Compare commits

..
Author SHA1 Message Date
skkim 94b39a44bd feat(ssulbox): 썰박스 상세에 공식 링크 오버레이 추가 2026-08-24 13:45:16 +09:00
skkim 3bcca23e97 Merge branch 'main': 공식 링크 오버레이·업체 직접입력 링크 반영, 랜딩 제거 유지 2026-08-24 11:20:57 +09:00
HyeongBaeYang 1128712170 Merge branch 'feature/video-official-site-overlay': 영상 종료 전 공식 링크 오버레이 2026-08-21 11:46:37 +09:00
HyeongBaeYangandClaude Fable 5 e328fc950c feat: 업체 직접 입력 시 공식 홈페이지 링크 입력란 추가
- BusinessNameInputModal에 선택 입력 URL 필드 추가 (프로토콜 미입력 시 https:// 보정)
- onManualInput 콜백 체인(officialSiteUrl) 확장
- POST /marketing 요청 body에 official_site_url 전달 (미입력 시 null)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DKTAqpFj8pbWzgvq7MRDHk
2026-08-21 10:56:39 +09:00
HyeongBaeYangandClaude Fable 5 547dd415c5 fix: 영상 링크 오버레이 문구를 '자세히 보기'로 변경
official_site_url이 네이버 플레이스/인스타그램 등 업체 대표 링크일 수 있어
중립적인 문구로 조정

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DKTAqpFj8pbWzgvq7MRDHk
2026-08-21 10:50:23 +09:00
HyeongBaeYangandClaude Fable 5 cea60e70db feat: 영상 종료 3초 전 공식 홈페이지 링크 오버레이 표시
- VideoDetailItem/VideoListItem에 official_site_url 필드 추가
- 플레이어 onTimeUpdate로 잔여 3초 감지, 링크 카드 오버레이 노출
- official_site_url이 null이면 오버레이 미렌더링

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DKTAqpFj8pbWzgvq7MRDHk
2026-08-21 10:45:15 +09:00
skkim 0d3167c1a2 fix: 공유하기 수정 2026-08-20 16:35:17 +09:00
skkim 8be95778f3 fix: 네이티브 공유 시 설명 텍스트 제거 2026-08-20 13:21:46 +09:00
skkim 17319e950e fix: 공유하기 및 UI 수정 2026-08-20 10:34:14 +09:00
skkimandCursor 4dff60c1ba refactor: main 머지로 복구된 랜딩을 다시 제거한다.
ADO2 콘텐츠를 첫 화면으로 되돌린다.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 16:31:36 +09:00
skkimandCursor 82b9fef3a1 chore: 튜토리얼 오버레이와 관련 문구를 제거
랜딩·업로드에서 자동 안내가 더 이상 뜨지 않게 한다.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 15:31:44 +09:00
skkimandCursor 4fe065378f Merge branch 'main' into feature-ssulbox
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 15:15:53 +09:00
skkim bdb581459d feat(social): 업로드 폼에 저장된 영상 SEO 메타데이터를 표시
값이 있으면 DB 결과를 바로 채우고, 없으면 video_id 기준으로 한 번만 생성한다.
2026-08-19 10:19:54 +09:00
skkim 63d60caabd fix: 이전 공유하기 기능 제거 2026-08-18 17:23:42 +09:00
skkim e400884eb7 fix: 공통으로 공유하기 사용하도록 변경 2026-08-18 14:56:38 +09:00
skkim 3566c1f7bc feat: 영상 공유·포스터 썸네일·좋아요 상태를 서버 연동으로 전환 2026-08-18 11:02:29 +09:00
skkim 9c0c3de35f UI 수정 2026-08-14 15:29:39 +09:00
skkim 3b8298bba2 fix(ssulbox): 업장 선택 후 변경 버튼 제거 및 사이드바 라벨 단순화 2026-08-13 11:29:50 +09:00
skkim fde7c8f6e1 style: 최소 폰트 크기를 14px 로 통일하고 하단 탭바 높이 상향 2026-08-12 17:26:05 +09:00
skkim 1f6921c587 fix: 썰박스 생성 소요 시간 안내를 약 5~6분으로 구체화 2026-08-12 17:26:00 +09:00
skkim cdddb913a0 Merge branch 'main' into feature-ssulbox 2026-08-12 15:42:15 +09:00
skkim 1cdb47ec2e perf: 이미지 미리보기를 축소 썸네일로 전환
- 원본 대신 400px 썸네일을 렌더해 디코딩/메모리 부담 감소
- 중복 파일은 추가하지 않고 안내
- 이미지 개수 카운터(n/100) 표시
- objectURL 해제 누락 지점 보완
2026-08-12 10:58:13 +09:00
skkim 23938871b0 feat: 이미지 업로드를 압축 후 순차 전송 방식으로 전환 2026-08-11 17:07:57 +09:00
skkim 18b5271110 fix: 로그인 유도 모달 개편과 공유 메뉴 방향·다운로드 파일명·정렬 수정 2026-08-11 14:57:35 +09:00
skkim 1c01dab748 fix: 영상 상세 모달을 social-posting-modal 구조로 통일하고 video 삐져나옴 버그 수정 2026-08-11 14:57:35 +09:00
skkim 40ebe2cca0 fix: 브랜드 분석 화면의 사이드바 collapsed 잔재 정리 2026-08-11 14:57:34 +09:00
skkim b9fd77fb51 refactor: 생성 완료 화면을 CompletionView 로 통일 2026-08-11 14:57:34 +09:00
skkim 3701490728 feat(ssulbox): 업장 검색을 ADO2 자동완성 방식으로 전환 2026-08-11 14:57:34 +09:00
skkim bda4c267dd refactor: 랜딩·튜토리얼·헤더 제거 2026-08-11 14:57:34 +09:00
skkim 741539a023 feat(ssulbox): 상세·공유 화면과 좋아요·댓글·업로드 연동 2026-08-11 14:57:34 +09:00
skkim 7b1e691715 refactor: 오버레이 닫기 동작을 useOverlayClose 로 통일 2026-08-11 14:57:33 +09:00
skkim 54e5d14127 feat: 모바일 하단 내비게이션·설정 패널 도입 2026-08-11 14:57:33 +09:00
skkim bb0ab91bcc feat(ssulbox): 썰박스 진입 탭·생성 플로우와 통합 콘텐츠 목록 분기 2026-08-11 14:57:33 +09:00
skkim c4c46db0d9 안내문구 수정 2026-07-28 16:06:24 +09:00
skkim f19cba7d75 fix: Meta 클릭 ID(fbc) 폴백 및 이벤트 ID 생성 폴백 추가 2026-07-28 12:00:34 +09:00
skkimandClaude Fable 5 f36fd5a3cb feat: Meta 픽셀 및 전환 추적 연동
- index.html에 Meta Pixel 스크립트 및 noscript 폴백 추가 (PageView 자동 추적)
- 전환 추적 유틸 추가 (trackViewContent, trackCompleteRegistration,
  trackFirstVideoCreated) — 서버 CAPI와 동일 event_id로 픽셀 발화해 중복제거
- 랜딩 진입 시 UTM 파라미터 first-touch 캡처 (localStorage 보존,
  가입 전환 시 서버로 전달 후 제거)
- 카카오 로그인 콜백에서 is_new_user 판정 시 CompleteRegistration 발화
  (토큰 리다이렉트 경로 + code 콜백 경로 모두 처리)
- 영상 생성 완료 시 FirstVideoCreated 발화
- KakaoCallbackResponse 타입을 백엔드 LoginResponse 구조에 맞게 수정
  (user 객체 제거, is_new_user 평탄화)
- logout이 refresh_token을 body로 전달하도록 수정, 실패해도
  로컬 데이터는 항상 삭제되도록 try/finally 처리

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-24 10:28:51 +09:00
skkim a853c714fd url입력 정제 추가 2026-07-22 15:52:45 +09:00
skkim 5512d90a9e 도메인 변경 2026-07-15 11:34:26 +09:00
skkim e2b22bd8e9 붙여넣기 시 url만 추출 기능 추가 2026-07-14 09:22:33 +09:00
skkim 5b7eba9540 ui 수정 2026-07-10 14:00:35 +09:00
skkim e7d6d89fe5 영상카드에 공유하기 좋아요 클릭 추가 2026-07-08 10:50:13 +09:00
skkim bd92eb2226 직접입력시 업종 추가 2026-07-03 16:00:37 +09:00
skkim 2f720dfa92 프로그래스바 수정, 이미지 분류 추가 및 UI 수정 2026-07-03 11:49:16 +09:00
skkim 8a39a34630 범용 프롬프트 적용 2026-06-29 15:06:25 +09:00
skkim 26ae588285 이미지 업로드 시 로딩화면 추가 2026-06-26 16:00:42 +09:00
skkim 6c499ae061 장르 선택 로직 개선 2026-06-26 11:50:08 +09:00
skkim 888ac4fa5e 인디케이터 추가 및 css코드 분리 2026-06-19 16:03:06 +09:00
skkim 429c8d4708 예약 업로드 충돌 시 실제 예약 시간 반환 2026-06-12 16:37:06 +09:00
skkim cb68b2da97 Merge branch 'feature-Bizinput' 2026-06-05 15:32:47 +09:00
skkim 3660290f1b 검색 기능 분리 및 튜토리얼 수정 2026-06-05 15:03:07 +09:00
skkim 8d7d0a74a6 직접입력 구조 변경 및 튜토리얼 추가 2026-06-02 16:02:24 +09:00
skkim cd7b1bf9f3 랜딩 페이지 영상 변경 2026-06-02 09:22:23 +09:00
skkim b18dd7aa4d 모바일에서 튜토리얼 버튼 위치 변경 2026-06-01 10:14:17 +09:00
skkim 7f1e2b83a9 튜토리얼 수정 및 아이콘 수정 2026-05-29 13:38:10 +09:00
skkim 1d855fd14c 업체 직접입력 기능 추가 2026-05-29 10:27:09 +09:00
skkim 0ea14da748 ADO2 콘텐츠, 상세 페이지 및 검색, 좋아요, 댓글, 공유하기 기능 추가 2026-05-27 15:27:03 +09:00
skkim f3195628d2 배경음악 재시도 오류 수정 및 subtitle 확인을 위한 엔드포인트 추가 2026-05-20 13:21:22 +09:00
skkim 9910d0146c 에러 수정 2026-05-15 09:47:54 +09:00
skkim 9697c40ed2 Merge branch 'main' of https://gitea.o2o.kr/castad/o2o-castad-frontend 2026-05-15 09:17:37 +09:00
skkim bf5fc05a25 에러 메시지 통일 및 UX 개선 2026-05-15 09:17:15 +09:00
skkim d3502fd421 에러메시지 수정 2026-05-13 16:59:24 +09:00
skkim f8ae482a16 배경음악 가사 표기 추가 및 파일정리 2026-05-13 14:37:57 +09:00
skkim 8a60d69467 페이지 설명, Open Graph 제목, 설명 추가 2026-05-12 17:18:04 +09:00
skkim 0a055a605c 가사 노출 형식 변경 2026-05-12 15:43:55 +09:00
skkim a155a98767 배경음악 기능 추가 및 예외 처리 수정 2026-05-12 15:22:19 +09:00
skkim cf27da30b4 링크 수정 2026-05-07 17:21:44 +09:00
skkim 8df5233fee Merge branch 'feature-credit' of https://gitea.o2o.kr/castad/o2o-castad-frontend into feature-credit 2026-05-07 15:48:14 +09:00
skkim 5796cce9c0 서비스약관, 개인정보처리방침 페이지 추가 및 푸터 링크 추가 2026-05-07 15:47:17 +09:00
skkim 310fde31d6 서비스약관, 개인정보처리방침 페이지 추가 2026-05-07 14:52:24 +09:00
skkim 324c78405a 업체명 검색시 오류메시지 추가 2026-05-06 17:30:05 +09:00
skkim 00ea49b7ed 크레딧 충전 기능 및 UI 수정 2026-05-04 13:47:38 +09:00
skkim 82dcda0038 임시 저장 2026-04-30 14:58:10 +09:00
skkim bdd52ed992 크레딧기능 추가 2026-04-28 14:32:55 +09:00
skkim 044fd21b2d 검색히스토리 추가 및 번역 수정 2026-04-24 15:50:05 +09:00
skkim 29cee13da7 프로그래스바 추가 및 UI 수정 2026-04-23 13:20:58 +09:00
skkim 6675b5301f 튜토리얼 수정 2026-04-21 15:24:26 +09:00
skkim 2b975a09eb 랜딩 페이지 UI 수정 2026-04-21 14:43:35 +09:00
skkim b1c3dd49e9 단어 수정 2026-04-16 17:11:48 +09:00
102 changed files with 21982 additions and 15948 deletions

No files matched your search

@@ -1,24 +0,0 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
@@ -1,233 +0,0 @@
import React, { useMemo } from 'react';
import { ArrowLeft, Sparkles, MapPin, Target, Zap, LayoutGrid, Users, Crown, TrendingUp } from 'lucide-react';
import { LALA_CABIN_DATA } from './constants';
import { GeometricChart } from './components/GeometricChart';
import { KeywordBubble } from './components/KeywordBubble';
import { BrandData, USP } from './types';
// Logic to calculate scores based on ICP (Ideal Customer Profile) signals
const calculateDynamicScores = (data: BrandData): USP[] => {
// 1. Extract Demand Signals from Targets (Needs + Triggers)
const marketSignals = data.targets.flatMap(t => [...t.needs, ...t.triggers]).map(s => s.replace(/\s+/g, ''));
// High value keywords that represent the "Core Value" of this specific property type
const coreKeywords = ['프라이빗', '감성', '독채', '캐빈', '조명', '불멍', 'Private', 'Mood'];
return data.usps.map(usp => {
let calculatedScore = 65; // Base score
const contentStr = (usp.label + usp.subLabel + usp.description).replace(/\s+/g, '');
// 2. Cross-reference USP with Market Signals
marketSignals.forEach(signal => {
if (contentStr.includes(signal)) calculatedScore += 4;
});
// 3. Boost based on Core Keywords (Weighted Importance)
coreKeywords.forEach(keyword => {
if (contentStr.includes(keyword)) calculatedScore += 6;
});
// 4. Special Boost based on specific Marketing Pillars (checking English SubLabels)
if (usp.subLabel === 'CONCEPT') calculatedScore += 10;
if (usp.subLabel === 'PRIVACY') calculatedScore += 8;
if (usp.subLabel === 'NIGHT MOOD') calculatedScore += 8;
if (usp.subLabel === 'PHOTO SPOT') calculatedScore += 5;
return {
...usp,
score: Math.min(Math.round(calculatedScore), 99) // Cap at 99
};
});
};
export default function App() {
const rawData = LALA_CABIN_DATA;
// Calculate scores on mount (or when data changes)
const scoredUSPs = useMemo(() => calculateDynamicScores(rawData), [rawData]);
// Find the top selling point
const topUSP = useMemo(() => [...scoredUSPs].sort((a, b) => b.score - a.score)[0], [scoredUSPs]);
return (
<div className="min-h-screen bg-brand-bg text-brand-text pb-24 selection:bg-brand-accent/30 font-sans">
{/* Top Navigation */}
<div className="p-6">
<button className="flex items-center gap-2 px-4 py-2 rounded-full border border-brand-muted/30 text-brand-muted hover:text-brand-accent hover:border-brand-accent transition-all text-sm group">
<ArrowLeft size={16} className="group-hover:-translate-x-1 transition-transform" />
<span>뒤로가기</span>
</button>
</div>
{/* Main Header */}
<div className="text-center mb-10 px-4">
<div className="flex justify-center mb-4">
<div className="relative">
<Sparkles className="text-brand-accent w-8 h-8 animate-pulse relative z-10" />
</div>
</div>
<h1 className="text-4xl font-bold mb-3 tracking-tight text-white">브랜드 인텔리전스</h1>
<p className="text-brand-muted text-lg max-w-xl mx-auto">
<span className="text-brand-accent font-semibold">AI 데이터 분석</span>을 통해 도출된 라라캐빈의 핵심 전략입니다.
</p>
</div>
{/* Grid Container */}
<div className="max-w-7xl mx-auto px-4 md:px-8 grid grid-cols-1 lg:grid-cols-2 gap-8">
{/* LEFT COLUMN: Identity & Text Analysis */}
<div className="space-y-6">
{/* Main Identity Card */}
<div className="bg-brand-card rounded-3xl p-8 border border-brand-muted/10 shadow-lg relative overflow-hidden group hover:border-brand-accent/20 transition-all duration-500">
<div className="absolute top-0 left-0 w-1.5 h-full bg-gradient-to-b from-brand-accent to-brand-purple"></div>
<div className="mb-4 flex items-center gap-2">
<span className="text-brand-accent font-bold text-sm uppercase tracking-wider flex items-center gap-2">
<LayoutGrid size={14} /> 브랜드 정체성
</span>
</div>
<h2 className="text-3xl font-bold mb-2 text-white tracking-tight">{rawData.name}</h2>
<div className="flex items-start gap-2 text-brand-muted text-sm mb-6">
<MapPin size={14} className="mt-0.5 shrink-0 text-brand-accent" />
<div>
<p>{rawData.address}</p>
<p className="opacity-70">{rawData.subAddress}</p>
</div>
</div>
<div className="space-y-5 text-gray-300 leading-relaxed border-t border-white/5 pt-5">
<div>
<h3 className="text-white font-semibold mb-2 text-sm text-brand-muted">입지 특성 분석</h3>
<p className="text-sm opacity-90 leading-6">{rawData.locationAnalysis}</p>
</div>
<div>
<h3 className="text-white font-semibold mb-2 text-sm text-brand-muted">컨셉 확장성</h3>
<p className="text-sm opacity-90 leading-6">{rawData.conceptAnalysis}</p>
</div>
</div>
</div>
{/* Positioning & Strategy Card */}
<div className="bg-brand-card rounded-3xl p-8 border border-brand-muted/10">
<h3 className="text-xl font-bold mb-6 flex items-center gap-2 text-white">
<Target size={20} className="text-brand-purple" /> 시장 포지셔닝
</h3>
<div className="grid grid-cols-1 gap-4">
<div className="bg-brand-bg/50 p-5 rounded-xl border border-brand-muted/20 hover:border-brand-accent/30 transition-colors group">
<span className="block text-xs text-brand-muted mb-1 group-hover:text-brand-accent transition-colors">카테고리 정의</span>
<span className="font-bold text-lg text-white">{rawData.positioning.category}</span>
</div>
<div className="bg-gradient-to-r from-brand-bg/50 to-brand-cardHover p-5 rounded-xl border border-brand-muted/20 border-l-4 border-l-brand-accent">
<span className="block text-xs text-brand-accent mb-1 font-semibold">핵심 가치 (Core Value)</span>
<span className="font-semibold text-white">{rawData.positioning.coreValue}</span>
</div>
</div>
</div>
{/* Target Audience Card */}
<div className="bg-brand-card rounded-3xl p-8 border border-brand-muted/10">
<h3 className="text-xl font-bold mb-6 flex items-center gap-2 text-white">
<Users size={20} className="text-brand-purple" /> 타겟 페르소나
</h3>
<div className="space-y-4">
{rawData.targets.map((target, idx) => (
<div key={idx} className="flex flex-col sm:flex-row sm:items-center gap-4 p-4 bg-brand-bg/30 rounded-xl border border-white/5 hover:border-brand-accent/20 transition-all group">
<div className="min-w-[120px]">
<div className="font-bold text-white group-hover:text-brand-accent transition-colors">{target.segment}</div>
<div className="text-xs text-brand-muted">{target.age}</div>
</div>
<div className="flex-1">
<div className="flex flex-wrap gap-1.5 mb-2">
{target.needs.map((need, i) => (
<span key={i} className="text-[10px] px-2 py-0.5 bg-brand-accent/10 text-brand-accent rounded-sm font-medium">{need}</span>
))}
</div>
<p className="text-xs text-gray-400 border-t border-white/5 pt-2 mt-2">
<span className="text-brand-muted">Trigger:</span> {target.triggers.join(', ')}
</p>
</div>
</div>
))}
</div>
</div>
</div>
{/* RIGHT COLUMN: Visuals & Keywords */}
<div className="space-y-6">
{/* Chart Card */}
<div className="bg-brand-card rounded-3xl p-8 border border-brand-muted/10 min-h-[500px] flex flex-col relative overflow-hidden">
<div className="flex justify-between items-center mb-2 z-10">
<h3 className="text-xl font-bold text-white">주요 셀링 포인트 (USP)</h3>
<div className="flex items-center gap-1 text-xs text-brand-accent bg-brand-accent/10 px-2 py-1 rounded">
<TrendingUp size={12} />
<span>AI Data Analysis</span>
</div>
</div>
<div className="flex-1 flex items-center justify-center relative z-10 -my-4">
<GeometricChart data={scoredUSPs} />
</div>
{/* Core Competitiveness Highlight */}
{topUSP && (
<div className="mt-2 mb-6 p-4 rounded-xl bg-gradient-to-r from-brand-accent/10 to-transparent border border-brand-accent/20 relative overflow-hidden">
<div className="absolute top-0 right-0 p-2 opacity-10">
<Crown size={64} className="text-brand-accent" />
</div>
<div className="relative z-10">
<div className="text-xs text-brand-accent font-bold uppercase tracking-wider mb-1 flex items-center gap-1">
<Crown size={12} /> Core Competitiveness
</div>
<div className="flex justify-between items-end">
<div>
<div className="text-lg font-bold text-white">{topUSP.label}</div>
<div className="text-xs text-brand-accent/80 font-mono tracking-wider">{topUSP.subLabel}</div>
</div>
{/* Score removed */}
</div>
</div>
</div>
)}
<div className="grid grid-cols-2 gap-3 z-10">
{scoredUSPs.filter(u => u.label !== topUSP.label).slice(0, 4).map((usp, idx) => (
<div key={idx} className="p-3 rounded-xl bg-brand-bg/40 border border-white/5 hover:bg-brand-bg/60 transition-colors">
<div className="flex justify-between items-start mb-1">
<div className="text-xs text-brand-muted font-bold uppercase tracking-tight">{usp.subLabel}</div>
{/* Score removed */}
</div>
<div className="text-sm font-bold text-white mb-1">{usp.label}</div>
<div className="text-xs text-gray-400 leading-tight line-clamp-1">{usp.description}</div>
</div>
))}
</div>
</div>
{/* Keywords Card */}
<div className="bg-brand-card rounded-3xl p-8 border border-brand-muted/10 relative overflow-hidden">
<h3 className="text-xl font-bold mb-6 text-center text-white">추천 타겟 키워드</h3>
<div className="flex flex-wrap justify-center gap-3 relative z-10">
{rawData.keywords.map((keyword, idx) => (
<KeywordBubble key={idx} text={keyword} />
))}
</div>
</div>
</div>
</div>
{/* Floating Action Button (Sticky Bottom) */}
<div className="fixed bottom-8 left-0 right-0 flex justify-center z-50 pointer-events-none">
<button className="pointer-events-auto bg-brand-purple hover:bg-brand-purpleHover text-white font-bold py-3 px-12 rounded-full shadow-2xl shadow-brand-purple/40 transform hover:scale-105 transition-all duration-300 flex items-center gap-2">
<Sparkles size={18} />
콘텐츠 생성
</button>
</div>
</div>
);
}
@@ -1,20 +0,0 @@
<div align="center">
<img width="1200" height="475" alt="GHBanner" src="https://github.com/user-attachments/assets/0aa67016-6eaf-458a-adb2-6e31a0763ed6" />
</div>
# Run and deploy your AI Studio app
This contains everything you need to run your app locally.
View your app in AI Studio: https://ai.studio/apps/drive/198bB4uG9EOOi0btQWINncwYJz7xEjWS3
## Run Locally
**Prerequisites:** Node.js
1. Install dependencies:
`npm install`
2. Set the `GEMINI_API_KEY` in [.env.local](.env.local) to your Gemini API key
3. Run the app:
`npm run dev`
@@ -1,159 +0,0 @@
import React from 'react';
import { USP } from '../types';
interface GeometricChartProps {
data: USP[];
}
export const GeometricChart: React.FC<GeometricChartProps> = ({ data }) => {
// Increased canvas size to prevent labels (especially on the right side like 'Privacy') from being cut off
const size = 500;
const center = size / 2;
const radius = 110; // Slightly increased radius for better visibility
const sides = data.length;
// Mint Color #94FBE0
const accentColor = "#94FBE0";
// Calculate polygon points
const getPoints = (r: number) => {
return data.map((_, i) => {
const angle = (Math.PI * 2 * i) / sides - Math.PI / 2;
const x = center + r * Math.cos(angle);
const y = center + r * Math.sin(angle);
return `${x},${y}`;
}).join(' ');
};
// Calculate data points based on score
const getDataPoints = () => {
return data.map((item, i) => {
const normalizedScore = item.score / 100;
const r = radius * normalizedScore;
const angle = (Math.PI * 2 * i) / sides - Math.PI / 2;
const x = center + r * Math.cos(angle);
const y = center + r * Math.sin(angle);
return `${x},${y}`;
}).join(' ');
};
// Calculate label positions (pushed out slightly further)
const labelRadius = radius + 55; // Increased padding for labels
const labels = data.map((item, i) => {
const angle = (Math.PI * 2 * i) / sides - Math.PI / 2;
const x = center + labelRadius * Math.cos(angle);
const y = center + labelRadius * Math.sin(angle);
// Adjust text anchor based on position
let anchor: 'start' | 'middle' | 'end' = 'middle';
if (x < center - 20) anchor = 'end';
if (x > center + 20) anchor = 'start';
return { x, y, text: item.label, sub: item.subLabel, anchor, score: item.score };
});
return (
<div className="flex flex-col items-center justify-center py-2 relative w-full h-full">
<svg viewBox={`0 0 ${size} ${size}`} className="w-full h-auto max-w-[500px]" style={{ overflow: 'visible' }}>
<defs>
<radialGradient id="polyGradient" cx="50%" cy="50%" r="50%" fx="50%" fy="50%">
<stop offset="0%" stopColor={accentColor} stopOpacity="0.3" />
<stop offset="100%" stopColor={accentColor} stopOpacity="0.05" />
</radialGradient>
</defs>
{/* Background Grids (Concentric) - Increased Opacity for Visibility */}
{[1, 0.75, 0.5, 0.25].map((scale, i) => (
<polygon
key={i}
points={getPoints(radius * scale)}
fill="none"
stroke={accentColor}
strokeOpacity={0.25 - (0.02 * i)}
strokeWidth="1"
strokeDasharray={i === 0 ? "0" : "4 2"}
/>
))}
{/* Axes Lines - Increased Opacity */}
{data.map((_, i) => {
const angle = (Math.PI * 2 * i) / sides - Math.PI / 2;
const x = center + radius * Math.cos(angle);
const y = center + radius * Math.sin(angle);
return (
<line
key={i}
x1={center}
y1={center}
x2={x}
y2={y}
stroke={accentColor}
strokeOpacity="0.25"
strokeWidth="1"
/>
);
})}
{/* Data Shape */}
<polygon
points={getDataPoints()}
fill="url(#polyGradient)"
stroke={accentColor}
strokeWidth="2.5"
strokeLinejoin="round"
/>
{/* Data Points (Dots) - Increased base size and highlight size */}
{data.map((item, i) => {
const normalizedScore = item.score / 100;
const r = radius * normalizedScore;
const angle = (Math.PI * 2 * i) / sides - Math.PI / 2;
const x = center + r * Math.cos(angle);
const y = center + r * Math.sin(angle);
const isHigh = item.score >= 90;
return (
<g key={i}>
{isHigh && (
<circle cx={x} cy={y} r="10" fill={accentColor} fillOpacity="0.4" />
)}
{/* Base dot is brighter (white) for all, slightly smaller for non-high */}
<circle cx={x} cy={y} r={isHigh ? 5 : 4} fill="#fff" />
</g>
)
})}
{/* Labels */}
{labels.map((l, i) => {
const isHigh = l.score >= 90;
return (
<g key={i}>
<text
x={l.x}
y={l.y - 7}
textAnchor={l.anchor}
fill={isHigh ? "#fff" : "#e2e8f0"}
fontSize={isHigh ? "14" : "12"}
fontWeight={isHigh ? "700" : "600"}
className="tracking-tight"
style={{ fontFamily: "sans-serif" }}
>
{l.text}
</text>
<text
x={l.x}
y={l.y + 9}
textAnchor={l.anchor}
fill={isHigh ? accentColor : "#94a3b8"}
fontSize={isHigh ? "11" : "10"}
fontWeight={isHigh ? "600" : "400"}
className="uppercase tracking-wider"
>
{l.sub}
</text>
</g>
);
})}
</svg>
</div>
);
};
@@ -1,13 +0,0 @@
import React from 'react';
interface KeywordBubbleProps {
text: string;
}
export const KeywordBubble: React.FC<KeywordBubbleProps> = ({ text }) => {
return (
<div className="bg-brand-cardHover/50 border border-brand-accent/20 rounded-full px-4 py-2 text-sm text-brand-text shadow-sm hover:border-brand-accent hover:text-brand-accent hover:bg-brand-accent/5 transition-all duration-300 cursor-default whitespace-nowrap">
# {text}
</div>
);
};
@@ -1,49 +0,0 @@
import { BrandData } from './types';
export const LALA_CABIN_DATA: BrandData = {
name: "라라캐빈 펜션",
address: "경기 가평군 조종면 와곡길 176",
subAddress: "[별관] 경기 가평군 조종면 운악리 175-6",
summary: "서울·경기 북부 근교 1~2시간대 숏브레이크 권역에 위치한 캐빈 감성 스테이. 조종면의 한적함과 프라이빗한 독채 구조를 강점으로 내세우며, '숲속 캐빈 무드'와 '야간 조명 감성'이 핵심입니다.",
locationAnalysis: "조종면은 청평/가평읍 대비 '한적함·프라이빗' 이미지가 강해 커플 및 소규모 힐링 고객에게 유리하며, 운악산 권역의 자연형 스테이 포지셔닝에 적합합니다.",
conceptAnalysis: "'라라캐빈'은 오두막(Cabin) 연상을 강하게 주며, 감성 목조/숲속/프라이빗 스테이로 스토리텔링 확장성이 큽니다. 별관의 동 분리 구조는 '세컨드 하우스' 느낌을 강화합니다.",
usps: [
{ label: "입지 환경", subLabel: "LOCATION", score: 85, description: "서울근교 한적한 조종면 자연권 숲속 드라이브" },
{ label: "브랜드 컨셉", subLabel: "CONCEPT", score: 95, description: "숙소 자체가 여행 목적이 되는 캐빈 감성" },
{ label: "프라이버시", subLabel: "PRIVACY", score: 90, description: "우리만 쓰는 느낌의 별관 분리동 독립 동선" },
{ label: "야간 무드", subLabel: "NIGHT MOOD", score: 92, description: "어두울수록 예쁜 스테이 장면과 불멍" },
{ label: "힐링 요소", subLabel: "HEALING", score: 88, description: "창밖 자연로딩, 숲뷰 산책 리셋" },
{ label: "포토 스팟", subLabel: "PHOTO SPOT", score: 94, description: "찍는 곳마다 커버샷 무드, 인스타 각" },
{ label: "숏브레이크", subLabel: "SHORT GETAWAY", score: 80, description: "1박2일 가볍게 떠나는 주말 리셋 여행" }
],
keywords: [
"가평 독채 펜션", "숲속 오두막", "감성 숙소", "불멍 스테이",
"서울근교 드라이브", "프라이빗 힐링", "커플 여행", "운악산 펜션",
"반려견 동반", "비오는날 감성"
],
targets: [
{
segment: "서울·경기 커플",
age: "25~39세",
needs: ["사진", "분위기", "프라이빗"],
triggers: ["숲속 캐빈 무드", "비 오는 날 감성", "밤 조명"]
},
{
segment: "소규모 우정여행",
age: "20~34세",
needs: ["예쁜 공간", "수다", "바베큐"],
triggers: ["인스타 각", "감성 포토존", "테이블 셋업"]
},
{
segment: "힐링 부부",
age: "30~50세",
needs: ["조용한 휴식", "숙면", "따뜻함"],
triggers: ["조용한 숲뷰", "따뜻한 캐빈", "기념일"]
}
],
positioning: {
category: "서울근교 숲속 캐빈 감성 스테이",
coreValue: "프라이빗한 휴식 + 사진이 되는 공간 + 밤 무드",
strategy: "시설 나열보다 '장면(Scenes)' 중심의 마케팅 전개"
}
};
@@ -1,56 +0,0 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>ADO2 Brand Analysis</title>
<script src="https://cdn.tailwindcss.com"></script>
<script>
tailwind.config = {
theme: {
extend: {
colors: {
brand: {
bg: '#011c1e',
card: '#083336',
cardHover: '#0b3f42',
accent: '#94FBE0',
purple: '#a855f7',
purpleHover: '#9333ea',
text: '#e2e8f0',
muted: '#94a3b8'
}
},
fontFamily: {
sans: ['Pretendard', 'Apple SD Gothic Neo', 'Malgun Gothic', 'sans-serif'],
}
}
}
}
</script>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap" rel="stylesheet">
<style>
body { font-family: 'Inter', sans-serif; background-color: #011c1e; color: white; }
/* Custom scrollbar for refined look */
::-webkit-scrollbar { width: 8px; }
::-webkit-scrollbar-track { background: #011c1e; }
::-webkit-scrollbar-thumb { background: #083336; border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: #94FBE0; }
</style>
<script type="importmap">
{
"imports": {
"react-dom/": "https://esm.sh/react-dom@^19.2.3/",
"react/": "https://esm.sh/react@^19.2.3/",
"react": "https://esm.sh/react@^19.2.3",
"lucide-react": "https://esm.sh/lucide-react@^0.563.0"
}
}
</script>
<link rel="stylesheet" href="/index.css">
</head>
<body>
<div id="root"></div>
<script type="module" src="/index.tsx"></script>
</body>
</html>
@@ -1,15 +0,0 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
const rootElement = document.getElementById('root');
if (!rootElement) {
throw new Error("Could not find root element to mount to");
}
const root = ReactDOM.createRoot(rootElement);
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
@@ -1,5 +0,0 @@
{
"name": "ADO2 Marketing Intelligence - Lala Cabin",
"description": "AI-powered marketing analysis dashboard for Lala Cabin Pension visualizing brand identity, target demographics, and key selling points.",
"requestFramePermissions": []
}
@@ -1,22 +0,0 @@
{
"name": "ado2-marketing-intelligence---lala-cabin",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"react-dom": "^19.2.3",
"react": "^19.2.3",
"lucide-react": "^0.563.0"
},
"devDependencies": {
"@types/node": "^22.14.0",
"@vitejs/plugin-react": "^5.0.0",
"typescript": "~5.8.2",
"vite": "^6.2.0"
}
}
@@ -1,29 +0,0 @@
{
"compilerOptions": {
"target": "ES2022",
"experimentalDecorators": true,
"useDefineForClassFields": false,
"module": "ESNext",
"lib": [
"ES2022",
"DOM",
"DOM.Iterable"
],
"skipLibCheck": true,
"types": [
"node"
],
"moduleResolution": "bundler",
"isolatedModules": true,
"moduleDetection": "force",
"allowJs": true,
"jsx": "react-jsx",
"paths": {
"@/*": [
"./*"
]
},
"allowImportingTsExtensions": true,
"noEmit": true
}
}
@@ -1,30 +0,0 @@
export interface USP {
label: string;
subLabel: string;
score: number; // 0-100
description: string;
}
export interface TargetPersona {
segment: string;
age: string;
needs: string[];
triggers: string[];
}
export interface BrandData {
name: string;
address: string;
subAddress: string;
summary: string;
locationAnalysis: string;
conceptAnalysis: string;
usps: USP[];
keywords: string[];
targets: TargetPersona[];
positioning: {
category: string;
coreValue: string;
strategy: string;
};
}
@@ -1,23 +0,0 @@
import path from 'path';
import { defineConfig, loadEnv } from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, '.', '');
return {
server: {
port: 3000,
host: '0.0.0.0',
},
plugins: [react()],
define: {
'process.env.API_KEY': JSON.stringify(env.GEMINI_API_KEY),
'process.env.GEMINI_API_KEY': JSON.stringify(env.GEMINI_API_KEY)
},
resolve: {
alias: {
'@': path.resolve(__dirname, '.'),
}
}
};
});
-10919
View File
File diff suppressed because it is too large. Load diff
+27 -2
View File
@@ -4,9 +4,31 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>CASTAD</title> <title>ADO2</title>
<!-- ① 페이지 설명 -->
<meta name="description" content="ADO2는 ㈜에이아이오투오의 AI 기반 마케팅 자동화 플랫폼입니다. 콘텐츠 제작부터 채널 배포까지 자동으로 처리합니다." />
<!-- ② Open Graph 제목 -->
<meta property="og:title" content="ADO2 - AI 마케팅 자동화 플랫폼" />
<!-- ③ Open Graph 설명 -->
<meta property="og:description" content="ADO2는 ㈜에이아이오투오의 AI 기반 마케팅 자동화 플랫폼입니다. 콘텐츠 제작부터 채널 배포까지 자동으로 처리합니다." />
<meta property="og:url" content="https://ado2.o2osolution.ai" />
<meta property="og:type" content="website" />
<link rel="icon" type="image/svg+xml" href="/favicon_32.svg" sizes="32x32"> <link rel="icon" type="image/svg+xml" href="/favicon_32.svg" sizes="32x32">
<link rel="icon" type="image/svg+xml" href="/favicon_48.svg" sizes="48x48"> <link rel="icon" type="image/svg+xml" href="/favicon_48.svg" sizes="48x48">
<!-- Meta Pixel Code -->
<script>
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window, document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '1572679738203392');
fbq('track', 'PageView');
</script>
<!-- End Meta Pixel Code -->
<script src="https://cdn.tailwindcss.com"></script> <script src="https://cdn.tailwindcss.com"></script>
<script> <script>
tailwind.config = { tailwind.config = {
@@ -153,9 +175,12 @@
} }
} }
</script> </script>
<link rel="stylesheet" href="/index.css">
</head> </head>
<body class="bg-[#121a1d]"> <body class="bg-[#121a1d]">
<!-- Meta Pixel noscript fallback (head의 noscript에는 img가 허용되지 않아 body에 위치) -->
<noscript><img height="1" width="1" style="display:none"
src="https://www.facebook.com/tr?id=1572679738203392&ev=PageView&noscript=1"
/></noscript>
<div id="root"></div> <div id="root"></div>
<script type="module" src="/src/index.tsx"></script> <script type="module" src="/src/index.tsx"></script>
</body> </body>
+42 -1
View File
@@ -16,6 +16,8 @@
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^22.14.0", "@types/node": "^22.14.0",
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@vitejs/plugin-react": "^5.0.0", "@vitejs/plugin-react": "^5.0.0",
"typescript": "~5.8.2", "typescript": "~5.8.2",
"vite": "^6.2.0" "vite": "^6.2.0"
@@ -52,6 +54,7 @@
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/code-frame": "^7.27.1", "@babel/code-frame": "^7.27.1",
"@babel/generator": "^7.28.5", "@babel/generator": "^7.28.5",
@@ -1288,10 +1291,32 @@
"integrity": "sha512-1N9SBnWYOJTrNZCdh/yJE+t910Y128BoyY+zBLWhL3r0TYzlTmFdXrPwHL9DyFZmlEXNQQolTZh3KHV31QDhyA==", "integrity": "sha512-1N9SBnWYOJTrNZCdh/yJE+t910Y128BoyY+zBLWhL3r0TYzlTmFdXrPwHL9DyFZmlEXNQQolTZh3KHV31QDhyA==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"undici-types": "~6.21.0" "undici-types": "~6.21.0"
} }
}, },
"node_modules/@types/react": {
"version": "19.2.18",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.18.tgz",
"integrity": "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"csstype": "^3.2.2"
}
},
"node_modules/@types/react-dom": {
"version": "19.2.4",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.4.tgz",
"integrity": "sha512-Bsc+QHgp+P/F02XDzNCY9jnZNCUuLki36KT7VKrTXXLdHf+vHMNZnW1rVu5DNW/rCK+fya3DATySbLM4yhtKUw==",
"dev": true,
"license": "MIT",
"peerDependencies": {
"@types/react": "^19.2.0"
}
},
"node_modules/@types/use-sync-external-store": { "node_modules/@types/use-sync-external-store": {
"version": "0.0.6", "version": "0.0.6",
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz", "resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.6.tgz",
@@ -1349,6 +1374,7 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"baseline-browser-mapping": "^2.9.0", "baseline-browser-mapping": "^2.9.0",
"caniuse-lite": "^1.0.30001759", "caniuse-lite": "^1.0.30001759",
@@ -1400,6 +1426,13 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"devOptional": true,
"license": "MIT"
},
"node_modules/d3-array": { "node_modules/d3-array": {
"version": "3.2.4", "version": "3.2.4",
"resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz", "resolved": "https://registry.npmjs.org/d3-array/-/d3-array-3.2.4.tgz",
@@ -1691,6 +1724,7 @@
} }
], ],
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@babel/runtime": "^7.28.4" "@babel/runtime": "^7.28.4"
}, },
@@ -1811,6 +1845,7 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=12" "node": ">=12"
}, },
@@ -1852,6 +1887,7 @@
"resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz", "resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz",
"integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==", "integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==",
"license": "MIT", "license": "MIT",
"peer": true,
"engines": { "engines": {
"node": ">=0.10.0" "node": ">=0.10.0"
} }
@@ -1861,6 +1897,7 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz", "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz",
"integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==", "integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"scheduler": "^0.27.0" "scheduler": "^0.27.0"
}, },
@@ -1907,6 +1944,7 @@
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz", "resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
"integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==", "integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@types/use-sync-external-store": "^0.0.6", "@types/use-sync-external-store": "^0.0.6",
"use-sync-external-store": "^1.4.0" "use-sync-external-store": "^1.4.0"
@@ -1969,7 +2007,8 @@
"version": "5.0.1", "version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==", "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
"license": "MIT" "license": "MIT",
"peer": true
}, },
"node_modules/redux-thunk": { "node_modules/redux-thunk": {
"version": "3.1.0", "version": "3.1.0",
@@ -2083,6 +2122,7 @@
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==", "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"devOptional": true, "devOptional": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"bin": { "bin": {
"tsc": "bin/tsc", "tsc": "bin/tsc",
"tsserver": "bin/tsserver" "tsserver": "bin/tsserver"
@@ -2166,6 +2206,7 @@
"integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==",
"dev": true, "dev": true,
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"esbuild": "^0.25.0", "esbuild": "^0.25.0",
"fdir": "^6.4.4", "fdir": "^6.4.4",
+4 -1
View File
@@ -5,7 +5,8 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "vite build", "typecheck": "tsc --noEmit",
"build": "tsc --noEmit && vite build",
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
@@ -17,6 +18,8 @@
}, },
"devDependencies": { "devDependencies": {
"@types/node": "^22.14.0", "@types/node": "^22.14.0",
"@types/react": "^19.2.0",
"@types/react-dom": "^19.2.0",
"@vitejs/plugin-react": "^5.0.0", "@vitejs/plugin-react": "^5.0.0",
"typescript": "~5.8.2", "typescript": "~5.8.2",
"vite": "^6.2.0" "vite": "^6.2.0"
@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8"?>
<svg id="Layer_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 660.69 145.69">
<!-- Generator: Adobe Illustrator 30.5.1, SVG Export Plug-In . SVG Version: 2.1.4 Build 3) -->
<defs>
<style>
.st0 {
fill: #fff;
}
</style>
</defs>
<g>
<g>
<path class="st0" d="M53.46,93.51l11.28-12.51h64.08l-31.22-63.81L32.69,93.51H15.09L90.17,5.91c2.48-2.89,6.19-5.64,10.73-5.64s7.29,2.48,8.8,5.64l43.45,87.6H53.46Z"/>
<path class="st0" d="M162.65,93.51l10.04-57.34h14.99l-7.84,44.83h42.22c23.38,0,43.18-16.78,43.18-38.5,0-16.64-12.51-28.33-31.35-28.33h-57.21l11.83-12.65h47.58c26.68,0,44.14,15.68,44.14,38.5,0,29.84-27.5,53.49-60.37,53.49h-57.21Z"/>
<path class="st0" d="M343.75,95.02c-36.17,0-54.45-12.1-54.45-38.37,0-38.09,23.24-56.65,71.23-56.65,36.17,0,54.46,11.96,54.46,38.23,0,38.09-23.1,56.79-71.23,56.79ZM358.33,12.51c-39.6,0-53.9,12.24-53.9,42.63,0,19.94,13.2,27.36,41.53,27.36,39.47,0,53.91-12.38,53.91-42.77,0-19.94-13.2-27.23-41.53-27.23Z"/>
<path class="st0" d="M417.47,93.51l4.81-27.23c2.89-16.5,15.68-24.48,36.58-24.48h40.15c16.91,0,23.79-5.78,23.79-15.68,0-9.08-9.08-11.96-26.4-11.96h-59.54l11.96-12.65h55.97c23.51,0,32.73,8.66,32.73,21.59,0,16.91-11,29.7-39.05,29.7h-40.15c-12.65,0-19.8,3.99-21.59,13.34l-2.47,14.85h94.75l-11.83,12.51h-99.7Z"/>
</g>
<g>
<path class="st0" d="M542.35,92.89c-2.38,0-4.15-1.38-4.15-3.61,0-3.07,2.69-4.84,5.68-4.84,2.46,0,4.3,1.31,4.3,3.53,0,3.07-2.69,4.92-5.84,4.92Z"/>
<path class="st0" d="M577.37,92.2l6.3-6.99h35.79l-17.43-35.63-36.25,42.62h-9.83l41.93-48.92c1.38-1.61,3.46-3.15,5.99-3.15s4.07,1.38,4.92,3.15l24.27,48.92h-55.68Z"/>
<path class="st0" d="M643.26,92.2l9.14-51.38h8.29l-9.14,51.38h-8.29Z"/>
</g>
</g>
<g>
<path class="st0" d="M.43,125.73c1.34-5.83,5.61-10.49,11.96-10.49,5.4,0,8.98,3.3,9.1,8.33,0,.17-.08.25-.23.25h-2.56c-.15,0-.23-.08-.23-.23-.17-3.74-2.48-5.9-6.18-5.9-4.69,0-7.56,3.67-8.65,8.31-1.31,5.71.33,11.09,6.32,11.09,3.43,0,6.17-1.81,7.52-6.23.03-.13.13-.2.27-.2h2.61c.17,0,.25.12.2.3-1.66,5.75-5.58,8.58-10.76,8.58-8.23,0-10.96-6.85-9.37-13.81Z"/>
<path class="st0" d="M25.26,129.28c1.02-4.34,4.26-7.77,9.1-7.77,5.75,0,8.31,4.74,7.04,10.19-1.02,4.34-4.24,7.77-9.08,7.77-5.76,0-8.33-4.74-7.05-10.19ZM38.31,131.48c.97-4.12-.25-7.86-4.07-7.86-3.17,0-5.13,2.61-5.9,5.88-.97,4.12.25,7.86,4.07,7.86,3.17,0,5.13-2.61,5.9-5.88Z"/>
<path class="st0" d="M44.55,138.85l1.83-7.57,2.08-9.2c.03-.15.13-.22.27-.22h2.5c.17,0,.25.1.22.27l-.7,2.76c1.24-1.86,3.43-3.43,6.01-3.43,3.38,0,5.7,2.48,4.66,7.04l-.74,3.25-1.61,7.15c-.03.15-.13.22-.27.22h-2.63c-.17,0-.25-.1-.2-.27l1.64-6.82.74-3.3c.74-3.3-.5-4.94-2.8-4.94-2.63,0-4.49,2.43-5.63,5.19l-.72,3.08-1.51,6.84c-.03.15-.13.22-.27.22h-2.66c-.15,0-.25-.1-.2-.27Z"/>
<path class="st0" d="M66.61,134.4l2.4-10.29h-1.96c-.17,0-.25-.1-.22-.29l.4-1.74c.03-.15.13-.22.27-.22h2.01l.89-4.1c.03-.15.13-.22.27-.22h2.66c.17,0,.25.1.22.27l-.99,4.05h3.97c.17,0,.25.1.22.27l-.42,1.76c-.03.13-.13.22-.27.22h-4.04l-2.35,10.22c-.45,1.98.08,2.78,1.56,2.78.59,0,1.26-.08,1.78-.2.18-.05.28.05.23.24l-.37,1.62c-.03.13-.1.2-.2.23-.75.22-1.71.38-2.58.38-2.35,0-4.37-1.26-3.48-4.99Z"/>
<path class="st0" d="M78.34,129.22c.92-4.04,3.95-7.71,8.98-7.71s7.96,3.69,6.8,9.15c-.02.13-.12.2-.25.2h-12.78c-.37,3.18.57,6.5,4.51,6.5,2.35,0,4.21-1.12,5.09-3.94.05-.13.15-.2.28-.2h2.41c.17,0,.25.12.2.29-1.17,3.99-4.07,5.96-8.01,5.96-6.68,0-8.38-5.39-7.24-10.25ZM91.3,128.82c.47-3-1.14-5.21-4.15-5.21-3.17,0-4.98,2.43-5.71,5.21h9.87Z"/>
<path class="st0" d="M97.15,138.85l1.83-7.57,2.08-9.2c.03-.15.13-.22.27-.22h2.5c.17,0,.25.1.22.27l-.7,2.76c1.24-1.86,3.43-3.43,6.01-3.43,3.38,0,5.7,2.48,4.66,7.04l-.74,3.25-1.61,7.15c-.03.15-.13.22-.27.22h-2.63c-.17,0-.25-.1-.2-.27l1.64-6.82.74-3.3c.74-3.3-.5-4.94-2.8-4.94-2.63,0-4.49,2.43-5.63,5.19l-.72,3.08-1.51,6.84c-.03.15-.13.22-.27.22h-2.66c-.15,0-.25-.1-.2-.27Z"/>
<path class="st0" d="M119.21,134.4l2.4-10.29h-1.96c-.17,0-.25-.1-.22-.29l.4-1.74c.03-.15.13-.22.27-.22h2.01l.89-4.1c.03-.15.13-.22.27-.22h2.66c.17,0,.25.1.22.27l-.99,4.05h3.97c.17,0,.25.1.22.27l-.42,1.76c-.03.13-.13.22-.27.22h-4.04l-2.35,10.22c-.45,1.98.08,2.78,1.56,2.78.59,0,1.26-.08,1.78-.2.18-.05.28.05.23.24l-.37,1.62c-.03.13-.1.2-.2.23-.75.22-1.71.38-2.58.38-2.35,0-4.37-1.26-3.48-4.99Z"/>
<path class="st0" d="M138.69,138.85l2.7-11.23,2.63-11.75c.03-.15.13-.22.27-.22h3.48c.15,0,.23.08.25.22l2.25,14.38.77,4.94,3.05-5.01,8.73-14.36c.07-.12.17-.17.3-.17h3.84c.15,0,.25.1.2.27l-2.76,11.69-2.53,11.28c-.03.15-.13.22-.27.22h-2.66c-.17,0-.25-.1-.22-.27l2.13-9.05,2.4-9.94-11.64,19.08c-.07.12-.17.17-.29.17h-2.11c-.15,0-.23-.08-.27-.22l-3.03-19.33-2.23,10.24-2.08,9.1c-.03.15-.13.22-.27.22h-2.41c-.17,0-.25-.1-.22-.27Z"/>
<path class="st0" d="M168.95,129.55c1.01-4.36,3.89-7.96,8.36-7.96,2.85,0,4.49,1.47,5.21,3.55l.67-3.07c.03-.15.13-.22.27-.22h2.6c.17,0,.25.1.22.27l-1.96,8.23-1.91,8.54c-.03.15-.13.22-.27.22h-2.51c-.15,0-.25-.1-.2-.27l.54-2.13c-1.36,1.59-3.15,2.65-5.34,2.65-4.99,0-6.87-4.66-5.66-9.82ZM181.38,130.98c.85-3.72.13-7.27-3.57-7.27-3.2,0-5.04,2.71-5.81,5.95-.92,4,.03,7.61,3.52,7.61,3,0,5.04-2.78,5.86-6.28Z"/>
<path class="st0" d="M187.85,138.85l2.04-8.54,1.83-8.23c.03-.15.13-.22.27-.22h2.56c.15,0,.25.1.2.27l-.79,3.07c1.74-2.29,4.07-3.5,6.42-3.5.37,0,.72.03,1.02.12.15.03.2.13.17.28l-.44,1.88c-.03.15-.13.2-.28.18-.27-.07-.59-.08-.9-.08-2.76,0-5.55,1.93-6.89,5.38l-2.14,9.45c-.03.15-.13.22-.27.22h-2.58c-.17,0-.27-.1-.22-.27Z"/>
<path class="st0" d="M202.32,138.87l2.71-11.38,2.58-11.61c.03-.15.13-.22.27-.22h2.58c.17,0,.27.1.22.27l-3.08,12.9,7.81-6.85c.1-.07.18-.12.3-.12h3.32c.22,0,.28.15.12.3l-7.04,5.93,3.94,10.74c.05.18-.02.29-.2.29h-2.68c-.13,0-.22-.05-.27-.2l-.8-2.51-2.33-6.4-2.98,2.61-1.39,6.3c-.03.15-.13.22-.27.22h-2.58c-.17,0-.25-.1-.22-.27Z"/>
<path class="st0" d="M219.82,129.22c.92-4.04,3.95-7.71,8.98-7.71s7.96,3.69,6.8,9.15c-.02.13-.12.2-.25.2h-12.78c-.37,3.18.57,6.5,4.51,6.5,2.35,0,4.21-1.12,5.09-3.94.05-.13.15-.2.28-.2h2.41c.17,0,.25.12.2.29-1.17,3.99-4.07,5.96-8.01,5.96-6.68,0-8.38-5.39-7.24-10.25ZM232.79,128.82c.47-3-1.14-5.21-4.15-5.21-3.17,0-4.98,2.43-5.71,5.21h9.87Z"/>
<path class="st0" d="M240.64,134.4l2.4-10.29h-1.96c-.17,0-.25-.1-.22-.29l.4-1.74c.03-.15.13-.22.27-.22h2.01l.89-4.1c.03-.15.13-.22.27-.22h2.66c.17,0,.25.1.22.27l-.99,4.05h3.97c.17,0,.25.1.22.27l-.42,1.76c-.03.13-.13.22-.27.22h-4.04l-2.35,10.22c-.45,1.98.08,2.78,1.56,2.78.59,0,1.26-.08,1.78-.2.18-.05.28.05.23.24l-.37,1.62c-.03.13-.1.2-.2.23-.75.22-1.71.38-2.58.38-2.35,0-4.37-1.26-3.48-4.99Z"/>
<path class="st0" d="M251.75,138.85l2.04-8.65,1.83-8.13c.03-.15.13-.22.27-.22h2.65c.17,0,.25.1.22.27l-1.94,8.06-1.94,8.71c-.02.15-.13.22-.27.22h-2.63c-.17,0-.25-.1-.22-.27ZM256.2,119.55l.65-2.73c.03-.15.13-.22.27-.22h2.61c.17,0,.25.1.22.27l-.64,2.75c-.03.13-.13.22-.27.22h-2.63c-.17,0-.25-.12-.22-.28Z"/>
<path class="st0" d="M260.47,138.85l1.83-7.57,2.08-9.2c.03-.15.13-.22.27-.22h2.5c.17,0,.25.1.22.27l-.7,2.76c1.24-1.86,3.43-3.43,6.01-3.43,3.38,0,5.7,2.48,4.66,7.04l-.74,3.25-1.61,7.15c-.03.15-.13.22-.27.22h-2.63c-.17,0-.25-.1-.2-.27l1.64-6.82.74-3.3c.74-3.3-.5-4.94-2.8-4.94-2.63,0-4.49,2.43-5.63,5.19l-.72,3.08-1.51,6.84c-.03.15-.13.22-.27.22h-2.66c-.15,0-.25-.1-.2-.27Z"/>
<path class="st0" d="M279.79,140.28c0-.15.1-.25.25-.25h2.58c.15,0,.23.08.25.25.03,2.09,1.71,3.28,4.04,3.28,3.1,0,4.71-1.78,5.63-5.71l.28-1.26c-1.34,1.56-3.12,2.58-5.31,2.58-5.06,0-6.85-4.72-5.7-9.68.99-4.31,3.89-7.89,8.34-7.89,2.88,0,4.54,1.44,5.26,3.54l.65-3.05c.03-.15.13-.22.27-.22h2.58c.17,0,.25.1.22.27l-2.04,8.63-1.61,7.12c-1.21,5.26-4,7.81-8.73,7.81-4.04,0-6.97-2.14-6.97-5.41ZM294.28,130.83c.82-3.6.13-7.12-3.59-7.12-3.23,0-5.08,2.7-5.83,5.93-.87,3.77-.02,7.42,3.54,7.42,3.02,0,5.09-2.78,5.88-6.23Z"/>
<path class="st0" d="M307.42,138.82l13.57-22.99c.07-.12.15-.17.28-.17h3.69c.15,0,.23.07.25.23l2.85,22.95c.02.17-.08.27-.23.27h-2.56c-.15,0-.23-.08-.25-.23l-.79-6.85h-9.53l-3.95,6.92c-.07.12-.15.17-.29.17h-2.88c-.18,0-.25-.12-.15-.3ZM323.99,129.52l-1.31-11.61-6.62,11.61h7.92Z"/>
<path class="st0" d="M332.8,132.49l.74-3.25,1.61-7.15c.03-.15.13-.22.27-.22h2.63c.17,0,.25.1.2.27l-1.64,6.82-.72,3.3c-.75,3.3.49,4.94,2.78,4.94,2.63,0,4.49-2.43,5.63-5.19l.72-3.08,1.51-6.84c.03-.15.13-.22.27-.22h2.66c.17,0,.25.1.22.27l-1.84,7.57-2.08,9.2c-.02.15-.12.22-.25.22h-2.51c-.15,0-.25-.1-.2-.27l.69-2.76c-1.24,1.86-3.43,3.43-6.01,3.43-3.38,0-5.71-2.48-4.66-7.04Z"/>
<path class="st0" d="M353.75,134.4l2.4-10.29h-1.96c-.17,0-.25-.1-.22-.29l.4-1.74c.03-.15.13-.22.27-.22h2.01l.89-4.1c.03-.15.13-.22.27-.22h2.66c.17,0,.25.1.22.27l-.99,4.05h3.97c.17,0,.25.1.22.27l-.42,1.76c-.03.13-.13.22-.27.22h-4.04l-2.35,10.22c-.45,1.98.08,2.78,1.56,2.78.59,0,1.26-.08,1.78-.2.18-.05.28.05.23.24l-.37,1.62c-.03.13-.1.2-.2.23-.75.22-1.71.38-2.58.38-2.35,0-4.37-1.26-3.49-4.99Z"/>
<path class="st0" d="M365.46,129.28c1.02-4.34,4.25-7.77,9.1-7.77,5.75,0,8.31,4.74,7.04,10.19-1.02,4.34-4.24,7.77-9.08,7.77-5.76,0-8.33-4.74-7.05-10.19ZM378.51,131.48c.97-4.12-.25-7.86-4.07-7.86-3.17,0-5.13,2.61-5.9,5.88-.97,4.12.25,7.86,4.07,7.86,3.17,0,5.13-2.61,5.9-5.88Z"/>
<path class="st0" d="M384.76,138.85l1.83-7.57,2.08-9.2c.03-.15.13-.22.27-.22h2.5c.17,0,.25.1.22.27l-.7,2.76c1.19-1.84,3.22-3.43,5.71-3.43,2.18,0,3.85,1.17,4.31,3.45,1.27-1.84,3.42-3.45,5.93-3.45,3.25,0,5.55,2.45,4.51,7.04l-.75,3.25-1.61,7.15c-.02.15-.12.22-.25.22h-2.63c-.17,0-.25-.1-.22-.27l1.64-6.82.74-3.3c.79-3.47-.49-4.94-2.46-4.94-2.24,0-3.84,2.04-4.98,4.52-.02.25-.05.55-.12.84l-.6,2.6-1.61,7.15c-.03.15-.13.22-.27.22h-2.63c-.15,0-.25-.1-.2-.27l1.64-6.82.74-3.3c.77-3.47-.49-4.94-2.48-4.94-2.41,0-4.09,2.41-5.23,5.19l-.72,3.08-1.51,6.84c-.03.15-.13.22-.27.22h-2.66c-.15,0-.25-.1-.2-.27Z"/>
<path class="st0" d="M415.88,129.55c1-4.36,3.89-7.96,8.36-7.96,2.85,0,4.49,1.47,5.21,3.55l.67-3.07c.03-.15.13-.22.27-.22h2.6c.17,0,.25.1.22.27l-1.96,8.23-1.91,8.54c-.03.15-.13.22-.27.22h-2.51c-.15,0-.25-.1-.2-.27l.54-2.13c-1.36,1.59-3.15,2.65-5.34,2.65-4.99,0-6.87-4.66-5.66-9.82ZM428.31,130.98c.85-3.72.13-7.27-3.57-7.27-3.2,0-5.04,2.71-5.81,5.95-.92,4,.03,7.61,3.52,7.61,3,0,5.04-2.78,5.86-6.28Z"/>
<path class="st0" d="M437.29,134.4l2.4-10.29h-1.96c-.17,0-.25-.1-.22-.29l.4-1.74c.03-.15.13-.22.27-.22h2.01l.89-4.1c.03-.15.13-.22.27-.22h2.66c.17,0,.25.1.22.27l-.99,4.05h3.97c.17,0,.25.1.22.27l-.42,1.76c-.03.13-.13.22-.27.22h-4.04l-2.35,10.22c-.45,1.98.08,2.78,1.56,2.78.59,0,1.26-.08,1.78-.2.18-.05.28.05.23.24l-.37,1.62c-.03.13-.1.2-.2.23-.75.22-1.71.38-2.58.38-2.35,0-4.37-1.26-3.49-4.99Z"/>
<path class="st0" d="M448.39,138.85l2.04-8.65,1.83-8.13c.03-.15.13-.22.27-.22h2.65c.17,0,.25.1.22.27l-1.94,8.06-1.94,8.71c-.02.15-.13.22-.27.22h-2.63c-.17,0-.25-.1-.22-.27ZM452.85,119.55l.65-2.73c.03-.15.13-.22.27-.22h2.61c.17,0,.25.1.22.27l-.64,2.75c-.03.13-.13.22-.27.22h-2.63c-.17,0-.25-.12-.22-.28Z"/>
<path class="st0" d="M458.71,129.28c1.02-4.34,4.25-7.77,9.1-7.77,5.75,0,8.31,4.74,7.04,10.19-1.02,4.34-4.24,7.77-9.08,7.77-5.76,0-8.33-4.74-7.05-10.19ZM471.76,131.48c.97-4.12-.25-7.86-4.07-7.86-3.17,0-5.13,2.61-5.9,5.88-.97,4.12.25,7.86,4.07,7.86,3.17,0,5.13-2.61,5.9-5.88Z"/>
<path class="st0" d="M478,138.85l1.83-7.57,2.08-9.2c.03-.15.13-.22.27-.22h2.5c.17,0,.25.1.22.27l-.7,2.76c1.24-1.86,3.43-3.43,6.01-3.43,3.38,0,5.7,2.48,4.66,7.04l-.74,3.25-1.61,7.15c-.03.15-.13.22-.27.22h-2.63c-.17,0-.25-.1-.2-.27l1.64-6.82.74-3.3c.74-3.3-.5-4.94-2.8-4.94-2.63,0-4.49,2.43-5.63,5.19l-.72,3.08-1.51,6.84c-.03.15-.13.22-.27.22h-2.66c-.15,0-.25-.1-.2-.27Z"/>
<path class="st0" d="M506.33,138.85l2.81-11.76,2.5-11.21c.03-.15.13-.22.27-.22h7.04c5.68,0,8.44,3.43,7.37,8.13-.9,3.89-4.31,6.28-9.6,6.28h-5.23l-1.98,8.83c-.03.15-.13.22-.27.22h-2.7c-.17,0-.25-.1-.22-.27ZM516.95,127.74c3.6,0,5.7-1.62,6.3-4.22.7-3.08-.79-5.51-4.52-5.51h-4.41l-2.33,9.73h4.96Z"/>
<path class="st0" d="M527.7,138.85l2.78-11.61,2.53-11.36c.03-.15.13-.22.27-.22h2.56c.17,0,.25.1.22.27l-2.7,11.28-2.61,11.69c-.03.15-.13.22-.27.22h-2.56c-.17,0-.27-.1-.22-.27Z"/>
<path class="st0" d="M537.92,129.55c1-4.36,3.89-7.96,8.36-7.96,2.85,0,4.49,1.47,5.21,3.55l.67-3.07c.03-.15.13-.22.27-.22h2.6c.17,0,.25.1.22.27l-1.96,8.23-1.91,8.54c-.03.15-.13.22-.27.22h-2.51c-.15,0-.25-.1-.2-.27l.54-2.13c-1.36,1.59-3.15,2.65-5.34,2.65-4.99,0-6.87-4.66-5.66-9.82ZM550.35,130.98c.85-3.72.13-7.27-3.57-7.27-3.2,0-5.04,2.71-5.81,5.95-.92,4,.03,7.61,3.52,7.61,3,0,5.04-2.78,5.86-6.28Z"/>
<path class="st0" d="M559.32,134.4l2.4-10.29h-1.96c-.17,0-.25-.1-.22-.29l.4-1.74c.03-.15.13-.22.27-.22h2.01l.89-4.1c.03-.15.13-.22.27-.22h2.66c.17,0,.25.1.22.27l-.99,4.05h3.97c.17,0,.25.1.22.27l-.42,1.76c-.03.13-.13.22-.27.22h-4.04l-2.35,10.22c-.45,1.98.08,2.78,1.56,2.78.59,0,1.26-.08,1.78-.2.18-.05.28.05.23.24l-.37,1.62c-.03.13-.1.2-.2.23-.75.22-1.71.38-2.58.38-2.35,0-4.37-1.26-3.49-4.99Z"/>
<path class="st0" d="M572.12,138.85l1.83-7.52,1.71-7.22h-2.45c-.17,0-.25-.1-.22-.29l.42-1.74c.03-.15.13-.22.27-.22h2.5l.37-1.56c.85-3.77,3.32-5.09,5.71-5.09.8,0,1.64.12,2.23.25.15.05.22.15.18.3l-.4,1.69c-.03.17-.13.22-.3.17-.45-.12-.97-.17-1.57-.17-1.36,0-2.4.85-2.9,3.08l-.32,1.32h3.79c.17,0,.25.1.22.27l-.4,1.76c-.03.13-.13.22-.27.22h-3.85l-1.66,7.22-1.64,7.57c-.03.15-.13.22-.27.22h-2.75c-.17,0-.25-.1-.22-.27Z"/>
<path class="st0" d="M584.65,129.28c1.02-4.34,4.25-7.77,9.1-7.77,5.75,0,8.31,4.74,7.04,10.19-1.02,4.34-4.24,7.77-9.08,7.77-5.76,0-8.33-4.74-7.05-10.19ZM597.7,131.48c.97-4.12-.25-7.86-4.07-7.86-3.17,0-5.13,2.61-5.9,5.88-.97,4.12.25,7.86,4.07,7.86,3.17,0,5.13-2.61,5.9-5.88Z"/>
<path class="st0" d="M603.95,138.85l2.04-8.54,1.83-8.23c.03-.15.13-.22.27-.22h2.56c.15,0,.25.1.2.27l-.79,3.07c1.74-2.29,4.07-3.5,6.42-3.5.37,0,.72.03,1.02.12.15.03.2.13.17.28l-.44,1.88c-.03.15-.13.2-.29.18-.27-.07-.59-.08-.9-.08-2.76,0-5.55,1.93-6.89,5.38l-2.14,9.45c-.03.15-.13.22-.27.22h-2.58c-.17,0-.27-.1-.22-.27Z"/>
<path class="st0" d="M618.42,138.85l1.83-7.57,2.08-9.2c.03-.15.13-.22.27-.22h2.5c.17,0,.25.1.22.27l-.7,2.76c1.19-1.84,3.22-3.43,5.71-3.43,2.18,0,3.85,1.17,4.31,3.45,1.27-1.84,3.42-3.45,5.93-3.45,3.25,0,5.55,2.45,4.51,7.04l-.75,3.25-1.61,7.15c-.02.15-.12.22-.25.22h-2.63c-.17,0-.25-.1-.22-.27l1.64-6.82.74-3.3c.79-3.47-.49-4.94-2.46-4.94-2.25,0-3.84,2.04-4.98,4.52-.02.25-.05.55-.12.84l-.6,2.6-1.61,7.15c-.03.15-.13.22-.27.22h-2.63c-.15,0-.25-.1-.2-.27l1.64-6.82.74-3.3c.77-3.47-.49-4.94-2.48-4.94-2.41,0-4.09,2.41-5.23,5.19l-.72,3.08-1.51,6.84c-.03.15-.13.22-.27.22h-2.66c-.15,0-.25-.1-.2-.27Z"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.7 KiB

-244
View File
@@ -1,244 +0,0 @@
{
"status": "completed",
"image_list": [
"https://ldb-phinf.pstatic.net/20260112_189/1768176025117RmItD_PNG/ChatGPT_Image_2026%B3%E2_1%BF%F9_9%C0%CF_%BF%C0%C8%C4_03_21_56.png",
"https://ldb-phinf.pstatic.net/20251215_290/1765776039787CALYj_JPEG/IMG_0060.JPG",
"https://ldb-phinf.pstatic.net/20251215_70/1765776016674Nbo0Q_JPEG/IMG_0067_%BA%B9%BB%E7.jpg",
"https://ldb-phinf.pstatic.net/20251215_136/17657760168457kDf6_JPEG/KakaoTalk_20251214_181208552_03_%BA%B9%BB%E7.jpg",
"https://ldb-phinf.pstatic.net/20251215_38/1765776039760cYgOj_JPEG/IMG_0044.JPG",
"https://ldb-phinf.pstatic.net/20251128_248/1764320049551B1gHl_JPEG/KakaoTalk_20251128_174635084_27.jpg",
"https://ldb-phinf.pstatic.net/20251128_209/1764320105053L8V2f_JPEG/KakaoTalk_20251128_174635084_17.jpg",
"https://ldb-phinf.pstatic.net/20241205_181/1733360083850LsEVv_JPEG/KakaoTalk_20241203_155353799_09.jpg",
"https://ldb-phinf.pstatic.net/20251128_209/1764320017959Rh3vs_JPEG/KakaoTalk_20251128_174635084_13.jpg",
"https://ldb-phinf.pstatic.net/20251128_102/1764320169035vluJN_JPEG/KakaoTalk_20251128_174635084_12.jpg",
"https://ldb-phinf.pstatic.net/20241129_249/17328584834569zWJT_JPEG/6S5A0642-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20241129_196/1732858501391FjLpd_JPEG/6S5A0657.jpg",
"https://ldb-phinf.pstatic.net/20241202_230/1733105198846QGbcW_JPEG/8.jpg",
"https://ldb-phinf.pstatic.net/20241202_94/1733105214373Q8ncR_JPEG/%B5%BF%B1%D7%B6%F3%B9%CC_%C3%A2%B9%AE_%B9%E6%B0%A1%C0%BB_2.jpg",
"https://ldb-phinf.pstatic.net/20231207_110/1701910802632rDM5r_JPEG/a_%28301%29-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20241202_7/1733106037765MNR8e_JPEG/9-1.jpg",
"https://ldb-phinf.pstatic.net/20240118_42/17055625561156LIx7_JPEG/6S5A0809-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240118_246/1705562556109bihHB_JPEG/6S5A1820-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20241202_259/1733104881690lDgnH_JPEG/3-2.jpg",
"https://ldb-phinf.pstatic.net/20231207_76/1701910651888PpVap_JPEG/%C6%EA%B5%E5%B6%F3%C0%CC%B7%EB.jpg",
"https://ldb-phinf.pstatic.net/20231207_242/1701910651863IAAlE_JPEG/%B0%AD%BE%C6%C1%F6_%BA%F1%C7%B0.jpg",
"https://ldb-phinf.pstatic.net/20241202_120/17331038087267aQ0S_JPEG/KakaoTalk_20241015_154536888_04.jpg",
"https://ldb-phinf.pstatic.net/20250710_164/17521338301365LRwl_JPEG/6S5A6748-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20250710_169/1752133830016fqFlL_JPEG/6S5A6760-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20231207_80/1701920469022ef7TW_JPEG/6S5A0614-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240603_140/17173835278369nntD_JPEG/6S5A6707.jpg",
"https://ldb-phinf.pstatic.net/20250710_173/1752133829861tPALd_JPEG/6S5A7136.jpg",
"https://ldb-phinf.pstatic.net/20241202_248/1733106037776BGjJx_JPEG/1-1.jpg",
"https://ldb-phinf.pstatic.net/20240603_275/1717383527874oJOpz_JPEG/DJI_0040-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20250710_153/1752133811173ba7oE_JPEG/6S5A6458.jpg",
"https://ldb-phinf.pstatic.net/20250710_185/1752133829868FyD76_JPEG/6S5A6815.jpg",
"https://ldb-phinf.pstatic.net/20250710_220/1752133829963w1aee_JPEG/6S5A6856.jpg",
"https://ldb-phinf.pstatic.net/20250710_228/1752133830002U65jg_JPEG/6S5A6864.jpg",
"https://ldb-phinf.pstatic.net/20250710_178/1752133829793fQQ2E_JPEG/6S5A7016-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20250710_279/1752133829838lTSC9_JPEG/6S5A7034-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20250710_179/1752133811452tOl7F_JPEG/6S5A6363.jpg",
"https://ldb-phinf.pstatic.net/20250710_75/1752133811152vd5ts_JPEG/6S5A6513.jpg",
"https://ldb-phinf.pstatic.net/20250710_147/1752133810693TfR5M_JPEG/6S5A6556.jpg",
"https://ldb-phinf.pstatic.net/20250710_202/1752133811177NRBDn_JPEG/6S5A6619-2.jpg",
"https://ldb-phinf.pstatic.net/20250710_196/1752133811066ufvpA_JPEG/6S5A6657.jpg",
"https://ldb-phinf.pstatic.net/20250710_280/1752133811307QCs3n_JPEG/6S5A6709.jpg",
"https://ldb-phinf.pstatic.net/20240603_85/1717383527884ST2DF_JPEG/6S5A6540.jpg",
"https://ldb-phinf.pstatic.net/20240603_249/1717383528285Om6dI_JPEG/6S5A6648.jpg",
"https://ldb-phinf.pstatic.net/20240603_288/1717383528022TxA4c_JPEG/6S5A6785.jpg",
"https://ldb-phinf.pstatic.net/20240909_284/1725865224424ux2W4_JPEG/6S5A9299-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20241129_87/1732858513628bWPt7_JPEG/6S5A9837-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20241202_50/1733105457578cGfYD_JPEG/6S5A9807-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240603_100/1717383527950q4yNf_JPEG/6S5A7056.jpg",
"https://ldb-phinf.pstatic.net/20240603_221/1717383527791s4ziP_JPEG/6S5A6673.jpg",
"https://ldb-phinf.pstatic.net/20241202_134/17331166295182o4vs_JPEG/47%C6%F2_%2829%29.jpg",
"https://ldb-phinf.pstatic.net/20241202_249/17331060371685uFQi_JPEG/3-1_%281%29.jpg",
"https://ldb-phinf.pstatic.net/20240909_238/1725865224397wnWE5_JPEG/DJI_0157.jpg",
"https://ldb-phinf.pstatic.net/20231206_34/1701833355386Nsg5j_JPEG/6S5A9995.jpg",
"https://ldb-phinf.pstatic.net/20241202_293/1733105206236d8l2f_JPEG/8-1.jpg",
"https://ldb-phinf.pstatic.net/20241202_224/1733105239528RLN59_JPEG/3-1-min.jpg",
"https://ldb-phinf.pstatic.net/20241202_31/1733116629874BYgpO_JPEG/47%C6%F2_%2823%29.jpg",
"https://ldb-phinf.pstatic.net/20241205_106/1733360083918ER1RI_JPEG/KakaoTalk_20241203_155353799_27.jpg",
"https://ldb-phinf.pstatic.net/20241129_126/17328584834200qVDw_JPEG/6S5A0645.jpg",
"https://ldb-phinf.pstatic.net/20240909_35/1725865128231ar2eM_PNG/KakaoTalk_20240710_163045662.png",
"https://ldb-phinf.pstatic.net/20241202_153/1733105180908PyVIC_JPEG/KakaoTalk_20231027_143438563_25-min.jpg",
"https://ldb-phinf.pstatic.net/20241129_128/1732858517984PFmrJ_JPEG/KakaoTalk_20241119_105023750.jpg",
"https://ldb-phinf.pstatic.net/20231207_124/1701910720268qeACJ_JPEG/%B9%D9%BA%A3%C5%A5.jpg",
"https://ldb-phinf.pstatic.net/20241202_55/173310545746333mf8_JPEG/6S5A9837-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20241202_11/1733106430749ovoeY_JPEG/37%C6%F2_%2820%29.jpg",
"https://ldb-phinf.pstatic.net/20231207_185/1701910772479mexsh_JPEG/a_%28282%29.jpg",
"https://ldb-phinf.pstatic.net/20240118_211/17055625561294XsN2_JPEG/6S5A1803-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240118_156/17055625560847R7SL_JPEG/6S5A0934-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20231207_179/17019107724184CCEU_JPEG/6S5A9906.jpg",
"https://ldb-phinf.pstatic.net/20231207_287/1701910772339cG7K0_JPEG/a_%28119%29.jpg",
"https://ldb-phinf.pstatic.net/20231207_40/1701910675360dvC1i_JPEG/%C8%AD%C0%E5%BD%C7_%281%29.jpg",
"https://ldb-phinf.pstatic.net/20231207_263/1701910675262pevKk_JPEG/%C8%AD%C0%E5%BD%C7_%284%29.jpg",
"https://ldb-phinf.pstatic.net/20231207_73/1701910651864xPI48_JPEG/%BB%E7%B6%F7_%BC%A4%C7%AA.jpg",
"https://ldb-phinf.pstatic.net/20231207_265/17019204486629hzae_JPEG/6S5A0645.jpg",
"https://ldb-phinf.pstatic.net/20241202_147/1733103809000xsMrG_JPEG/KakaoTalk_20241015_154532027_01.jpg",
"https://ldb-phinf.pstatic.net/20241202_77/1733103809037HSO4S_JPEG/KakaoTalk_20241015_154532027_02.jpg",
"https://ldb-phinf.pstatic.net/20241202_233/1733103809020IMEdL_JPEG/KakaoTalk_20241015_154532027_06.jpg",
"https://ldb-phinf.pstatic.net/20241202_53/1733103808802Wui9x_JPEG/KakaoTalk_20241015_154532027_04.jpg",
"https://ldb-phinf.pstatic.net/20241202_230/1733103808998dOq0b_JPEG/KakaoTalk_20241015_154532027_15.jpg",
"https://ldb-phinf.pstatic.net/20241202_122/1733103808509lOt9x_JPEG/KakaoTalk_20241015_154536888_13.jpg",
"https://ldb-phinf.pstatic.net/20241202_246/1733103809045RdnEP_JPEG/KakaoTalk_20241015_154536888_11.jpg",
"https://ldb-phinf.pstatic.net/20241202_287/1733103808656oB1xz_JPEG/KakaoTalk_20241015_154536888_06.jpg",
"https://ldb-phinf.pstatic.net/20241202_222/1733103808508hkf5K_JPEG/KakaoTalk_20241015_154536888_08.jpg",
"https://ldb-phinf.pstatic.net/20241202_229/1733103808818KGAps_JPEG/KakaoTalk_20241015_154536888_02.jpg",
"https://ldb-phinf.pstatic.net/20241202_12/1733103808751cVAsT_JPEG/KakaoTalk_20241015_154536888_03.jpg",
"https://ldb-phinf.pstatic.net/20240909_261/1725865224473Uo7V9_JPEG/6S5A9371-%C6%ED%C1%FD-%C6%ED%C1%FD-2.jpg",
"https://ldb-phinf.pstatic.net/20240909_22/1725865224495AL798_JPEG/6S5A9557-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240909_177/1725865224462eX1Pi_JPEG/DJI_0149-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240909_165/1725865224480S7c1j_JPEG/6S5A9468-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240909_85/1725865224421CNRrk_JPEG/DJI_0155.jpg",
"https://ldb-phinf.pstatic.net/20240909_62/1725865224361fP2d2_JPEG/6S5A9434.jpg",
"https://ldb-phinf.pstatic.net/20240909_155/1725865224363Xxt8y_JPEG/6S5A9431-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240909_13/1725865224457BGLGs_JPEG/6S5A9456.jpg",
"https://ldb-phinf.pstatic.net/20240603_162/1717383527882Vnrsk_JPEG/6S5A6786.jpg",
"https://ldb-phinf.pstatic.net/20240603_256/1717383527892WXOKA_JPEG/6S5A6896.jpg",
"https://ldb-phinf.pstatic.net/20240603_130/1717383527800oHSKA_JPEG/6S5A6904.jpg",
"https://ldb-phinf.pstatic.net/20240603_118/17173835277794IXlt_JPEG/6S5A6946.jpg",
"https://ldb-phinf.pstatic.net/20240603_257/1717383527822ITvHM_JPEG/6S5A6973.jpg",
"https://ldb-phinf.pstatic.net/20240603_170/1717383527880sTdFE_JPEG/DJI_0039-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240603_10/1717383527863CVLJ2_JPEG/DJI_0087-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240603_94/1717383527921sDeDB_JPEG/DJI_0091-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20231206_81/1701833426718D5Qwk_JPEG/b_%28119%29-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240118_153/17055625561274LAs5_JPEG/6S5A1460-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240118_8/1705562556139zGkjb_JPEG/6S5A1780.jpg",
"https://ldb-phinf.pstatic.net/20240118_57/1705562556129IR40O_JPEG/6S5A1199.jpg",
"https://ldb-phinf.pstatic.net/20240118_260/1705562556111cA7PG_JPEG/6S5A1927-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20231207_183/1701910720221oI66j_JPEG/%B9%D9%BA%A3%C5%A52.jpg",
"https://ldb-phinf.pstatic.net/20231207_247/1701910720113MBgKD_JPEG/%B9%D9%BA%A3%C5%A5_%282%29.jpg",
"https://ldb-phinf.pstatic.net/20231207_227/1701910720098FE7Si_JPEG/6S5A0001.jpg",
"https://ldb-phinf.pstatic.net/20231206_24/1701833408064fgoVj_JPEG/b_%2874%29.jpg",
"https://ldb-phinf.pstatic.net/20240603_100/1717383527883LWVq4_JPEG/6S5A6022-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240603_169/17173835278856AEUV_JPEG/6S5A5974-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240603_155/1717383527937gxiyc_JPEG/6S5A5988.jpg",
"https://ldb-phinf.pstatic.net/20231206_160/170183333003287LrV_JPEG/6S5A0243-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240603_217/1717383528190t41X5_JPEG/6S5A6027.jpg",
"https://ldb-phinf.pstatic.net/20240603_142/1717383527892jHtgI_JPEG/6S5A6643.jpg",
"https://ldb-phinf.pstatic.net/20240603_251/1717383527948jTN2a_JPEG/6S5A6125.jpg",
"https://ldb-phinf.pstatic.net/20240603_189/1717383527880wu4Bv_JPEG/6S5A6326.jpg",
"https://ldb-phinf.pstatic.net/20240603_14/1717383527794qCuuu_JPEG/6S5A6337.jpg",
"https://ldb-phinf.pstatic.net/20240603_220/1717383528017rKdOw_JPEG/6S5A6773.jpg"
],
"image_count": 119,
"m_id": 1,
"processed_info": {
"customer_name": "풀스테이 스테이펫 홍천",
"region": "",
"detail_region_info": "강원 홍천군 화촌면 답연밭길 5-2 스테이펫 홍천"
},
"marketing_analysis": {
"brand_identity": {
"location_feature_analysis": "강원 홍천 화촌면의 자연 친화적 입지는 도심 소음에서 벗어난 ‘조용한 숲세권’ 체류 니즈에 최적이며, 수도권에서 주말 이동이 가능한 거리감으로 숏브레이크 수요를 흡수하기 유리합니다.",
"concept_scalability": "‘스테이펫’ 콘셉트는 반려동물 동반 숙박을 넘어 펫 어메니티·펫 포토·펫 웰니스(산책 코스/케어 서비스)까지 확장 가능해, 체류 전 과정의 경험 가치를 패키지화하기 좋습니다."
},
"market_positioning": {
"category_definition": "자연 속 프라이빗 애견 동반 힐링 스테이",
"core_value": "반려동물과 ‘눈치 없이’ 온전히 쉬는 프라이빗한 쉼"
},
"target_persona": [
{
"persona": "주말 펫캉스 커플(반려견 1마리) – 조용한 자연에서 둘+한 마리의 리셋 여행을 찾는 2030",
"age": {
"min_age": 27,
"max_age": 39
},
"favor_target": [
"반려견 동반 가능 숙소",
"자연 뷰/산책하기 좋은 동선",
"청결한 침구와 탈취 관리",
"프라이빗한 공간 구성",
"감성 사진이 잘 나오는 무드"
],
"decision_trigger": "반려견 동반 + 프라이빗하게 쉴 수 있다는 확신(후기/시설 안내)"
},
{
"persona": "도심 탈출 1인/2인 힐링러 – 조용한 곳에서 휴식·독서를 즐기며 재충전하는 직장인",
"age": {
"min_age": 29,
"max_age": 45
},
"favor_target": [
"소음 적은 입지",
"자연 속 뷰",
"편안한 침대/휴식형 라운지",
"야간 감성 조명",
"체크인/이용 동선의 간편함"
],
"decision_trigger": "‘조용함’과 ‘자연 몰입’이 보장되는 입지/분위기"
},
{
"persona": "가족형 펫오너 – 반려견과 함께 안전하고 편하게 머물며 추억을 만드는 3040",
"age": {
"min_age": 33,
"max_age": 49
},
"favor_target": [
"반려견 안전 동선(미끄럼/울타리 등)",
"넓은 휴식 공간",
"바베큐 등 가족형 액티비티",
"주차/이동 편의",
"위생/청결 신뢰"
],
"decision_trigger": "가족 단위도 불편 없는 공간감 + 펫 프렌들리 정책"
}
],
"selling_points": [
{
"english_category": "PET FRIENDLY",
"korean_category": "애견 동반",
"description": "반려견과 함께하는 완전한 휴식",
"score": 95
},
{
"english_category": "HEALING",
"korean_category": "힐링 요소",
"description": "홍천 자연 속 리셋 스테이",
"score": 90
},
{
"english_category": "PRIVACY",
"korean_category": "프라이버시",
"description": "눈치 없이 즐기는 프라이빗 쉼",
"score": 88
},
{
"english_category": "SHORT GETAWAY",
"korean_category": "숏브레이크",
"description": "주말에 딱, 가볍게 떠나는 홍천",
"score": 82
},
{
"english_category": "NIGHT MOOD",
"korean_category": "야간 감성",
"description": "밤이 더 예쁜 감성 무드",
"score": 78
},
{
"english_category": "BBQ PARTY",
"korean_category": "바베큐",
"description": "자연을 곁들인 바베큐 한 판",
"score": 75
},
{
"english_category": "PHOTO SPOT",
"korean_category": "포토 스팟",
"description": "반려견 인생샷 남기는 공간",
"score": 73
}
],
"target_keywords": [
"홍천애견동반숙소",
"강원도애견동반펜션",
"스테이펫",
"펫캉스",
"반려견동반여행",
"홍천감성숙소",
"강원도힐링스테이",
"숲뷰숙소",
"주말여행추천",
"프라이빗스테이"
]
}
}
-244
View File
@@ -1,244 +0,0 @@
{
"status": "completed",
"image_list": [
"https://ldb-phinf.pstatic.net/20260112_189/1768176025117RmItD_PNG/ChatGPT_Image_2026%B3%E2_1%BF%F9_9%C0%CF_%BF%C0%C8%C4_03_21_56.png",
"https://ldb-phinf.pstatic.net/20251215_290/1765776039787CALYj_JPEG/IMG_0060.JPG",
"https://ldb-phinf.pstatic.net/20251215_70/1765776016674Nbo0Q_JPEG/IMG_0067_%BA%B9%BB%E7.jpg",
"https://ldb-phinf.pstatic.net/20251215_136/17657760168457kDf6_JPEG/KakaoTalk_20251214_181208552_03_%BA%B9%BB%E7.jpg",
"https://ldb-phinf.pstatic.net/20251215_38/1765776039760cYgOj_JPEG/IMG_0044.JPG",
"https://ldb-phinf.pstatic.net/20251128_248/1764320049551B1gHl_JPEG/KakaoTalk_20251128_174635084_27.jpg",
"https://ldb-phinf.pstatic.net/20251128_209/1764320105053L8V2f_JPEG/KakaoTalk_20251128_174635084_17.jpg",
"https://ldb-phinf.pstatic.net/20241205_181/1733360083850LsEVv_JPEG/KakaoTalk_20241203_155353799_09.jpg",
"https://ldb-phinf.pstatic.net/20251128_209/1764320017959Rh3vs_JPEG/KakaoTalk_20251128_174635084_13.jpg",
"https://ldb-phinf.pstatic.net/20251128_102/1764320169035vluJN_JPEG/KakaoTalk_20251128_174635084_12.jpg",
"https://ldb-phinf.pstatic.net/20241129_249/17328584834569zWJT_JPEG/6S5A0642-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20241129_196/1732858501391FjLpd_JPEG/6S5A0657.jpg",
"https://ldb-phinf.pstatic.net/20241202_230/1733105198846QGbcW_JPEG/8.jpg",
"https://ldb-phinf.pstatic.net/20241202_94/1733105214373Q8ncR_JPEG/%B5%BF%B1%D7%B6%F3%B9%CC_%C3%A2%B9%AE_%B9%E6%B0%A1%C0%BB_2.jpg",
"https://ldb-phinf.pstatic.net/20231207_110/1701910802632rDM5r_JPEG/a_%28301%29-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20241202_7/1733106037765MNR8e_JPEG/9-1.jpg",
"https://ldb-phinf.pstatic.net/20240118_42/17055625561156LIx7_JPEG/6S5A0809-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240118_246/1705562556109bihHB_JPEG/6S5A1820-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20241202_259/1733104881690lDgnH_JPEG/3-2.jpg",
"https://ldb-phinf.pstatic.net/20231207_76/1701910651888PpVap_JPEG/%C6%EA%B5%E5%B6%F3%C0%CC%B7%EB.jpg",
"https://ldb-phinf.pstatic.net/20231207_242/1701910651863IAAlE_JPEG/%B0%AD%BE%C6%C1%F6_%BA%F1%C7%B0.jpg",
"https://ldb-phinf.pstatic.net/20241202_120/17331038087267aQ0S_JPEG/KakaoTalk_20241015_154536888_04.jpg",
"https://ldb-phinf.pstatic.net/20250710_164/17521338301365LRwl_JPEG/6S5A6748-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20250710_169/1752133830016fqFlL_JPEG/6S5A6760-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20231207_80/1701920469022ef7TW_JPEG/6S5A0614-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240603_140/17173835278369nntD_JPEG/6S5A6707.jpg",
"https://ldb-phinf.pstatic.net/20250710_173/1752133829861tPALd_JPEG/6S5A7136.jpg",
"https://ldb-phinf.pstatic.net/20241202_248/1733106037776BGjJx_JPEG/1-1.jpg",
"https://ldb-phinf.pstatic.net/20240603_275/1717383527874oJOpz_JPEG/DJI_0040-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20250710_153/1752133811173ba7oE_JPEG/6S5A6458.jpg",
"https://ldb-phinf.pstatic.net/20250710_185/1752133829868FyD76_JPEG/6S5A6815.jpg",
"https://ldb-phinf.pstatic.net/20250710_220/1752133829963w1aee_JPEG/6S5A6856.jpg",
"https://ldb-phinf.pstatic.net/20250710_228/1752133830002U65jg_JPEG/6S5A6864.jpg",
"https://ldb-phinf.pstatic.net/20250710_178/1752133829793fQQ2E_JPEG/6S5A7016-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20250710_279/1752133829838lTSC9_JPEG/6S5A7034-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20250710_179/1752133811452tOl7F_JPEG/6S5A6363.jpg",
"https://ldb-phinf.pstatic.net/20250710_75/1752133811152vd5ts_JPEG/6S5A6513.jpg",
"https://ldb-phinf.pstatic.net/20250710_147/1752133810693TfR5M_JPEG/6S5A6556.jpg",
"https://ldb-phinf.pstatic.net/20250710_202/1752133811177NRBDn_JPEG/6S5A6619-2.jpg",
"https://ldb-phinf.pstatic.net/20250710_196/1752133811066ufvpA_JPEG/6S5A6657.jpg",
"https://ldb-phinf.pstatic.net/20250710_280/1752133811307QCs3n_JPEG/6S5A6709.jpg",
"https://ldb-phinf.pstatic.net/20240603_85/1717383527884ST2DF_JPEG/6S5A6540.jpg",
"https://ldb-phinf.pstatic.net/20240603_249/1717383528285Om6dI_JPEG/6S5A6648.jpg",
"https://ldb-phinf.pstatic.net/20240603_288/1717383528022TxA4c_JPEG/6S5A6785.jpg",
"https://ldb-phinf.pstatic.net/20240909_284/1725865224424ux2W4_JPEG/6S5A9299-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20241129_87/1732858513628bWPt7_JPEG/6S5A9837-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20241202_50/1733105457578cGfYD_JPEG/6S5A9807-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240603_100/1717383527950q4yNf_JPEG/6S5A7056.jpg",
"https://ldb-phinf.pstatic.net/20240603_221/1717383527791s4ziP_JPEG/6S5A6673.jpg",
"https://ldb-phinf.pstatic.net/20241202_134/17331166295182o4vs_JPEG/47%C6%F2_%2829%29.jpg",
"https://ldb-phinf.pstatic.net/20241202_249/17331060371685uFQi_JPEG/3-1_%281%29.jpg",
"https://ldb-phinf.pstatic.net/20240909_238/1725865224397wnWE5_JPEG/DJI_0157.jpg",
"https://ldb-phinf.pstatic.net/20231206_34/1701833355386Nsg5j_JPEG/6S5A9995.jpg",
"https://ldb-phinf.pstatic.net/20241202_293/1733105206236d8l2f_JPEG/8-1.jpg",
"https://ldb-phinf.pstatic.net/20241202_224/1733105239528RLN59_JPEG/3-1-min.jpg",
"https://ldb-phinf.pstatic.net/20241202_31/1733116629874BYgpO_JPEG/47%C6%F2_%2823%29.jpg",
"https://ldb-phinf.pstatic.net/20241205_106/1733360083918ER1RI_JPEG/KakaoTalk_20241203_155353799_27.jpg",
"https://ldb-phinf.pstatic.net/20241129_126/17328584834200qVDw_JPEG/6S5A0645.jpg",
"https://ldb-phinf.pstatic.net/20240909_35/1725865128231ar2eM_PNG/KakaoTalk_20240710_163045662.png",
"https://ldb-phinf.pstatic.net/20241202_153/1733105180908PyVIC_JPEG/KakaoTalk_20231027_143438563_25-min.jpg",
"https://ldb-phinf.pstatic.net/20241129_128/1732858517984PFmrJ_JPEG/KakaoTalk_20241119_105023750.jpg",
"https://ldb-phinf.pstatic.net/20231207_124/1701910720268qeACJ_JPEG/%B9%D9%BA%A3%C5%A7.jpg",
"https://ldb-phinf.pstatic.net/20241202_55/173310545746333mf8_JPEG/6S5A9837-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20241202_11/1733106430749ovoeY_JPEG/37%C6%F2_%2820%29.jpg",
"https://ldb-phinf.pstatic.net/20231207_185/1701910772479mexsh_JPEG/a_%28282%29.jpg",
"https://ldb-phinf.pstatic.net/20240118_211/17055625561294XsN2_JPEG/6S5A1803-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240118_156/17055625560847R7SL_JPEG/6S5A0934-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20231207_179/17019107724184CCEU_JPEG/6S5A9906.jpg",
"https://ldb-phinf.pstatic.net/20231207_287/1701910772339cG7K0_JPEG/a_%28119%29.jpg",
"https://ldb-phinf.pstatic.net/20231207_40/1701910675360dvC1i_JPEG/%C8%AD%C0%E5%BD%C7_%281%29.jpg",
"https://ldb-phinf.pstatic.net/20231207_263/1701910675262pevKk_JPEG/%C8%AD%C0%E5%BD%C7_%284%29.jpg",
"https://ldb-phinf.pstatic.net/20231207_73/1701910651864xPI48_JPEG/%BB%E7%B6%F7_%BC%A4%C7%AA.jpg",
"https://ldb-phinf.pstatic.net/20231207_265/17019204486629hzae_JPEG/6S5A0645.jpg",
"https://ldb-phinf.pstatic.net/20241202_147/1733103809000xsMrG_JPEG/KakaoTalk_20241015_154532027_01.jpg",
"https://ldb-phinf.pstatic.net/20241202_77/1733103809037HSO4S_JPEG/KakaoTalk_20241015_154532027_02.jpg",
"https://ldb-phinf.pstatic.net/20241202_233/1733103809020IMEdL_JPEG/KakaoTalk_20241015_154532027_06.jpg",
"https://ldb-phinf.pstatic.net/20241202_53/1733103808802Wui9x_JPEG/KakaoTalk_20241015_154532027_04.jpg",
"https://ldb-phinf.pstatic.net/20241202_230/1733103808998dOq0b_JPEG/KakaoTalk_20241015_154532027_15.jpg",
"https://ldb-phinf.pstatic.net/20241202_122/1733103808509lOt9x_JPEG/KakaoTalk_20241015_154536888_13.jpg",
"https://ldb-phinf.pstatic.net/20241202_246/1733103809045RdnEP_JPEG/KakaoTalk_20241015_154536888_11.jpg",
"https://ldb-phinf.pstatic.net/20241202_287/1733103808656oB1xz_JPEG/KakaoTalk_20241015_154536888_06.jpg",
"https://ldb-phinf.pstatic.net/20241202_222/1733103808508hkf5K_JPEG/KakaoTalk_20241015_154536888_08.jpg",
"https://ldb-phinf.pstatic.net/20241202_229/1733103808818KGAps_JPEG/KakaoTalk_20241015_154536888_02.jpg",
"https://ldb-phinf.pstatic.net/20241202_12/1733103808751cVAsT_JPEG/KakaoTalk_20241015_154536888_03.jpg",
"https://ldb-phinf.pstatic.net/20240909_261/1725865224473Uo7V9_JPEG/6S5A9371-%C6%ED%C1%FD-%C6%ED%C1%FD-2.jpg",
"https://ldb-phinf.pstatic.net/20240909_22/1725865224495AL798_JPEG/6S5A9557-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240909_177/1725865224462eX1Pi_JPEG/DJI_0149-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240909_165/1725865224480S7c1j_JPEG/6S5A9468-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240909_85/1725865224421CNRrk_JPEG/DJI_0155.jpg",
"https://ldb-phinf.pstatic.net/20240909_62/1725865224361fP2d2_JPEG/6S5A9434.jpg",
"https://ldb-phinf.pstatic.net/20240909_155/1725865224363Xxt8y_JPEG/6S5A9431-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240909_13/1725865224457BGLGs_JPEG/6S5A9456.jpg",
"https://ldb-phinf.pstatic.net/20240603_162/1717383527882Vnrsk_JPEG/6S5A6786.jpg",
"https://ldb-phinf.pstatic.net/20240603_256/1717383527892WXOKA_JPEG/6S5A6896.jpg",
"https://ldb-phinf.pstatic.net/20240603_130/1717383527800oHSKA_JPEG/6S5A6904.jpg",
"https://ldb-phinf.pstatic.net/20240603_118/17173835277794IXlt_JPEG/6S5A6946.jpg",
"https://ldb-phinf.pstatic.net/20240603_257/1717383527822ITvHM_JPEG/6S5A6973.jpg",
"https://ldb-phinf.pstatic.net/20240603_170/1717383527880sTdFE_JPEG/DJI_0039-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240603_10/1717383527863CVLJ2_JPEG/DJI_0087-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240603_94/1717383527921sDeDB_JPEG/DJI_0091-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20231206_81/1701833426718D5Qwk_JPEG/b_%28119%29-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240118_153/17055625561274LAs5_JPEG/6S5A1460-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240118_8/1705562556139zGkjb_JPEG/6S5A1780.jpg",
"https://ldb-phinf.pstatic.net/20240118_57/1705562556129IR40O_JPEG/6S5A1199.jpg",
"https://ldb-phinf.pstatic.net/20240118_260/1705562556111cA7PG_JPEG/6S5A1927-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20231207_183/1701910720221oI66j_JPEG/%B9%D9%BA%A3%C5%A52.jpg",
"https://ldb-phinf.pstatic.net/20231207_247/1701910720113MBgKD_JPEG/%B9%D9%BA%A3%C5%A5_%282%29.jpg",
"https://ldb-phinf.pstatic.net/20231207_227/1701910720098FE7Si_JPEG/6S5A0001.jpg",
"https://ldb-phinf.pstatic.net/20231206_24/1701833408064fgoVj_JPEG/b_%2874%29.jpg",
"https://ldb-phinf.pstatic.net/20240603_100/1717383527883LWVq4_JPEG/6S5A6022-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240603_169/17173835278856AEUV_JPEG/6S5A5974-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240603_155/1717383527937gxiyc_JPEG/6S5A5988.jpg",
"https://ldb-phinf.pstatic.net/20231206_160/170183333003287LrV_JPEG/6S5A0243-%C6%ED%C1%FD.jpg",
"https://ldb-phinf.pstatic.net/20240603_217/1717383528190t41X5_JPEG/6S5A6027.jpg",
"https://ldb-phinf.pstatic.net/20240603_142/1717383527892jHtgI_JPEG/6S5A6643.jpg",
"https://ldb-phinf.pstatic.net/20240603_251/1717383527948jTN2a_JPEG/6S5A6125.jpg",
"https://ldb-phinf.pstatic.net/20240603_189/1717383527880wu4Bv_JPEG/6S5A6326.jpg",
"https://ldb-phinf.pstatic.net/20240603_14/1717383527794qCuuu_JPEG/6S5A6337.jpg",
"https://ldb-phinf.pstatic.net/20240603_220/1717383528017rKdOw_JPEG/6S5A6773.jpg"
],
"image_count": 119,
"m_id": 1,
"processed_info": {
"customer_name": "Fullstay StayPet Hongcheon",
"region": "",
"detail_region_info": "5-2 Dapyeonbat-gil, Hwachon-myeon, Hongcheon-gun, Gangwon-do, Korea"
},
"marketing_analysis": {
"brand_identity": {
"location_feature_analysis": "Located in the nature-rich Hwachon-myeon area of Hongcheon, Gangwon-do, this property offers the ideal setting for a 'quiet forest retreat' away from urban noise. Its proximity to the Seoul metropolitan area makes it perfect for weekend short-break getaways.",
"concept_scalability": "The 'StayPet' concept extends beyond simple pet-friendly accommodation to include pet amenities, pet photo zones, and pet wellness experiences (walking trails/care services), enabling a comprehensive packaged experience throughout the entire stay."
},
"market_positioning": {
"category_definition": "Private Pet-Friendly Healing Stay in Nature",
"core_value": "A private retreat where you and your pet can relax without worry"
},
"target_persona": [
{
"persona": "Weekend Pet-cation Couples (with 1 dog) – Millennials seeking a reset trip for two + one furry friend in peaceful nature",
"age": {
"min_age": 27,
"max_age": 39
},
"favor_target": [
"Pet-friendly accommodation",
"Nature views / great walking trails",
"Clean bedding and odor management",
"Private space configuration",
"Aesthetic mood for great photos"
],
"decision_trigger": "Confidence in pet-friendly + private relaxation (verified through reviews and facility info)"
},
{
"persona": "Urban Escape Solo/Duo Healers – Working professionals recharging with quiet rest and reading in nature",
"age": {
"min_age": 29,
"max_age": 45
},
"favor_target": [
"Low-noise location",
"Nature views",
"Comfortable beds / relaxation lounge",
"Ambient night lighting",
"Simple check-in / easy access"
],
"decision_trigger": "Guaranteed 'quietness' and 'nature immersion' through location and atmosphere"
},
{
"persona": "Family Pet Owners – Families in their 30s-40s creating memories with their pets in a safe, comfortable stay",
"age": {
"min_age": 33,
"max_age": 49
},
"favor_target": [
"Pet safety features (non-slip floors / fencing)",
"Spacious relaxation areas",
"Family activities like BBQ",
"Parking / travel convenience",
"Hygiene / cleanliness assurance"
],
"decision_trigger": "Spacious enough for families + reliable pet-friendly policies"
}
],
"selling_points": [
{
"english_category": "PET FRIENDLY",
"korean_category": "Pet-Friendly",
"description": "A complete retreat with your beloved pet",
"score": 95
},
{
"english_category": "HEALING",
"korean_category": "Healing",
"description": "A reset stay in Hongcheon's natural surroundings",
"score": 90
},
{
"english_category": "PRIVACY",
"korean_category": "Privacy",
"description": "A private retreat — relax without a care",
"score": 88
},
{
"english_category": "SHORT GETAWAY",
"korean_category": "Short Getaway",
"description": "A quick weekend escape to Hongcheon",
"score": 82
},
{
"english_category": "NIGHT MOOD",
"korean_category": "Night Mood",
"description": "An aesthetic ambiance that shines at night",
"score": 78
},
{
"english_category": "BBQ PARTY",
"korean_category": "BBQ Party",
"description": "A BBQ feast surrounded by nature",
"score": 75
},
{
"english_category": "PHOTO SPOT",
"korean_category": "Photo Spot",
"description": "The perfect spot for unforgettable pet photos",
"score": 73
}
],
"target_keywords": [
"Hongcheon pet-friendly stay",
"Gangwon-do pet pension",
"StayPet",
"Pet-cation",
"Travel with pets",
"Hongcheon aesthetic stay",
"Gangwon healing retreat",
"Forest view accommodation",
"Weekend trip recommendation",
"Private stay"
]
}
}
+92
View File
@@ -0,0 +1,92 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>개인정보처리방침 - ADO2</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; line-height: 1.8; color: #333; max-width: 800px; margin: 0 auto; padding: 40px 20px; }
h1 { font-size: 28px; border-bottom: 2px solid #eee; padding-bottom: 12px; margin-bottom: 30px; }
h2 { font-size: 19px; margin-top: 40px; color: #111; }
p, li { font-size: 15px; color: #555; margin-bottom: 10px; }
ul { padding-left: 20px; }
.google-policy { background: #f0f7ff; border-left: 4px solid #4285f4; padding: 16px 20px; margin: 24px 0; border-radius: 4px; }
.google-policy p { color: #1a1a2e; margin: 0; }
.updated { color: #888; font-size: 14px; margin-bottom: 30px; }
</style>
</head>
<body>
<h1>개인정보처리방침 (Privacy Policy)</h1>
<p class="updated"><strong>시행일:</strong> 2026년 5월 7일 &nbsp;|&nbsp; <strong>최종 수정일:</strong> 2026년 5월 27일</p>
<p>㈜에이아이오투오(이하 "회사")는 AI 마케팅 자동화 서비스 ADO2(이하 "서비스")를 제공함에 있어 사용자의 개인정보를 중요시하며, 「개인정보 보호법」 등 관련 법령을 성실히 준수합니다.</p>
<h2>1. 수집하는 개인정보 항목 및 수집 방법</h2>
<p>회사는 서비스 제공을 위해 아래와 같은 개인정보를 수집합니다.</p>
<ul>
<li><strong>카카오 로그인을 통한 수집:</strong> 이름, 이메일 주소, 프로필 사진 — 서비스 회원 가입 및 로그인에 사용</li>
<li><strong>Google 사용자 프로필 :</strong> YouTube 채널 연동 시 연결된 구글 계정의 이름 및 프로필 사진 확인 — 채널 소유자 식별 목적으로만 사용</li>
<li><strong>YouTube Data API :</strong> 채널 정보, 동영상 목록, 재생목록 등 YouTube 계정 데이터 (읽기 전용)</li>
<li><strong>YouTube Data API :</strong> AI가 생성한 콘텐츠를 YouTube에 업로드하기 위한 동영상 관리 권한</li>
<li><strong>YouTube Analytics API :</strong> 채널 및 동영상의 조회수, 시청 시간 등 성과 지표 데이터 (읽기 전용)</li>
<li><strong>서비스 이용 과정에서 자동 수집:</strong> 접속 IP, 쿠키, 서비스 이용 기록</li>
</ul>
<h2>2. Google 사용자 데이터의 수집 및 이용 목적</h2>
<p>회사가 접근하는 Google 사용자 데이터는 아래 목적으로만 사용되며, 명시된 목적 외에는 사용하지 않습니다.</p>
<ul>
<li><strong>Google 사용자 프로필:</strong> YouTube 채널 연동 과정에서 연결 대상 구글 계정을 식별하는 용도로만 사용하며, 서비스 로그인에는 사용되지 않습니다.</li>
<li><strong>YouTube 계정 데이터 (읽기):</strong> 기존 채널 정보·동영상 현황을 분석하여 AI 콘텐츠 전략 수립에 활용합니다.</li>
<li><strong>YouTube 동영상 업로드:</strong> AI가 생성한 영상을 사용자의 YouTube 채널에 업로드합니다. 업로드는 반드시 사용자의 명시적 요청에 의해서만 실행됩니다.</li>
<li><strong>YouTube 분석 데이터:</strong> 채널 성과 지표를 분석하여 AI 마케팅 전략 수립 및 콘텐츠 최적화에 활용합니다.</li>
</ul>
<div class="google-policy">
<p><strong>[Google API 서비스 사용자 데이터 정책 준수]</strong><br><br>
㈜에이아이오투오가 운영하는 ADO2 서비스가 Google API로부터 수신한 정보의 사용 및 타 앱으로의 전송은,
<a href="https://developers.google.com/terms/api-services-user-data-policy" target="_blank">Google API 서비스 사용자 데이터 정책</a>의
제한적 사용(Limited Use) 요건을 포함한 모든 정책을 엄격히 준수합니다.<br><br>
특히, Google API로부터 수신한 데이터는 <strong>AI·ML 모델 학습에 사용되지 않으며</strong>, 사용자가 명시적으로 요청한 서비스 기능 제공 목적 외에는 사용·전송·공유되지 않습니다.</p>
</div>
<h2>3. Google 사용자 데이터의 제3자 공유</h2>
<p>회사는 Google API로부터 수신한 사용자 데이터를 아래 경우를 제외하고 어떠한 제3자에게도 판매하거나 공유하지 않습니다.</p>
<ul>
<li><strong>AI 콘텐츠 생성 처리:</strong> 서비스 제공에 필수적인 AI 생성 기능 수행을 위해 처리 서버로 전달될 수 있으며, 해당 처리는 서비스 제공 목적으로만 사용됩니다.</li>
<li><strong>법적 요구:</strong> 관련 법령에 의거한 수사기관 등의 적법한 요청이 있는 경우</li>
</ul>
<p>Google 사용자 데이터는 광고, 마케팅, 프로파일링 목적으로 사용되지 않습니다.</p>
<h2>4. Google 사용자 데이터의 저장 및 보안</h2>
<ul>
<li>Google OAuth 액세스 토큰 및 리프레시 토큰은 암호화된 상태로 보관됩니다.</li>
<li>Google API를 통해 읽어온 데이터는 서비스 기능 처리에 필요한 최소한의 시간 동안만 임시 보유하며, 처리 완료 후 삭제됩니다.</li>
<li>서버와의 모든 통신은 TLS(HTTPS)를 통해 암호화됩니다.</li>
<li>데이터 접근 권한은 서비스 운영에 필요한 최소 인원에게만 부여됩니다.</li>
</ul>
<h2>5. 개인정보의 보유 및 이용 기간 / 데이터 삭제</h2>
<p>원칙적으로 회원 탈퇴 또는 개인정보 수집·이용 목적이 달성된 후에는 해당 정보를 지체 없이 파기합니다. 단, 관련 법령에 따라 보존이 필요한 경우 해당 기간 동안 보관합니다.</p>
<ul>
<li>전자상거래 관련 기록: 5년 (전자상거래 등에서의 소비자보호에 관한 법률)</li>
<li>접속 로그 기록: 3개월 (통신비밀보호법)</li>
<li>Google 연동 토큰: 연동 해제 또는 회원 탈퇴 즉시 삭제</li>
</ul>
<p><strong>데이터 삭제 요청 방법:</strong> 아래 이메일(<a href="mailto:o2oteam@o2o.kr">o2oteam@o2o.kr</a>)로 요청하시면 <strong>영업일 기준 7일 이내</strong>에 처리 결과를 안내해 드립니다. Google 계정 연동 해제는 서비스 내 계정 설정에서 직접 처리하실 수 있으며, 해제 즉시 관련 토큰이 삭제됩니다.</p>
<h2>6. 정보주체의 권리 및 행사 방법</h2>
<p>사용자는 언제든지 자신의 개인정보에 대한 열람, 수정, 삭제, 처리 정지를 요청할 수 있습니다. 서비스 내 계정 설정에서 직접 처리하거나 아래 문의처로 연락해 주시기 바랍니다.</p>
<p>또한, <a href="https://myaccount.google.com/permissions" target="_blank">Google 계정 권한 관리 페이지</a>에서 ADO2 앱의 Google 데이터 접근 권한을 언제든지 직접 취소하실 수 있습니다.</p>
<h2>7. 개인정보 보호책임자 및 문의처</h2>
<p>개인정보 보호와 관련된 불만 처리 및 피해 구제에 관한 사항은 아래로 문의해 주시기 바랍니다.</p>
<ul>
<li><strong>회사명:</strong> ㈜에이아이오투오</li>
<li><strong>서비스명:</strong> ADO2</li>
<li><strong>이메일:</strong> <a href="mailto:o2oteam@o2o.kr">o2oteam@o2o.kr</a></li>
<li><strong>웹사이트:</strong> https://ado2.o2osolution.ai</li>
</ul>
<p style="margin-top:40px; font-size:14px; color:#999;">본 방침은 2026년 5월 7일부터 시행됩니다. 최종 수정일: 2026년 5월 27일</p>
</body>
</html>
+66
View File
@@ -0,0 +1,66 @@
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>서비스 약관 - ADO2</title>
<style>
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; line-height: 1.8; color: #333; max-width: 800px; margin: 0 auto; padding: 40px 20px; }
h1 { font-size: 28px; border-bottom: 2px solid #eee; padding-bottom: 12px; margin-bottom: 30px; }
h2 { font-size: 19px; margin-top: 40px; color: #111; }
p, li { font-size: 15px; color: #555; margin-bottom: 10px; }
ul { padding-left: 20px; }
.updated { color: #888; font-size: 14px; margin-bottom: 30px; }
</style>
</head>
<body>
<h1>서비스 이용약관 (Terms of Service)</h1>
<p class="updated"><strong>시행일:</strong> 2026년 5월 7일 &nbsp;|&nbsp; <strong>최종 수정일:</strong> 2026년 5월 21일</p>
<h2>제 1 조 (목적)</h2>
<p>본 약관은 ㈜에이아이오투오(이하 "회사")가 제공하는 AI 마케팅 자동화 서비스 ADO2(이하 "서비스")의 이용과 관련하여, 회사와 이용자(이하 "회원") 간의 권리, 의무 및 책임사항을 규정함을 목적으로 합니다.</p>
<h2>제 2 조 (용어의 정의)</h2>
<ul>
<li>"서비스"라 함은 회사가 제공하는 ADO2 AI 마케팅 자동화 플랫폼 및 관련 제반 기능을 의미합니다.</li>
<li>"회원"이라 함은 본 약관에 동의하고 회사와 이용계약을 체결하여 서비스를 이용하는 자를 말합니다.</li>
<li>"콘텐츠"라 함은 서비스 내에서 AI가 생성하거나 회원이 등록하는 텍스트, 이미지, 음악, 영상 등 일체의 자료를 말합니다.</li>
</ul>
<h2>제 3 조 (약관의 효력 및 변경)</h2>
<p>회사는 본 약관의 내용을 서비스 화면에 게시하며, 관련 법령을 위배하지 않는 범위에서 약관을 개정할 수 있습니다. 약관이 변경되는 경우 시행일 7일 전부터 공지합니다.</p>
<h2>제 4 조 (서비스의 제공 및 변경)</h2>
<p>회사는 AI 기반 마케팅 콘텐츠(가사, 이미지, 영상 등) 자동 생성, Google·YouTube 등 외부 플랫폼 연동, SNS 자동 배포 등의 서비스를 제공합니다. 운영상·기술상의 필요에 따라 서비스의 전부 또는 일부를 변경할 수 있습니다.</p>
<h2>제 5 조 (회원의 의무)</h2>
<ul>
<li>타인의 Google 계정 등 외부 서비스 계정을 무단으로 도용하여 서비스를 이용해서는 안 됩니다.</li>
<li>스팸 발송, API 한도 고의 초과, 허위 정보 등록 등 비정상적인 방법으로 서비스를 이용해서는 안 됩니다.</li>
<li>회사 또는 제3자의 지식재산권을 침해해서는 안 됩니다.</li>
</ul>
<h2>제 6 조 (외부 API 연동 및 데이터 활용)</h2>
<p>서비스는 Google, YouTube, Naver 등의 제3자 API를 활용하여 마케팅 자동화 기능을 제공합니다. 특히 YouTube 서비스 연동을 위해 YouTube Data API 및 YouTube Analytics API를 사용하며, 이를 통해 수집·처리되는 데이터는 <a href="/privacy.html">개인정보처리방침</a>에 따라 관리됩니다. 회원은 각 외부 서비스의 이용약관 및 정책을 준수할 의무가 있으며, 외부 API 제공사의 정책 변경으로 인한 서비스 제한에 대해 회사는 면책됩니다.</p>
<p>YouTube API 서비스 이용과 관련하여 <a href="https://www.youtube.com/t/terms" target="_blank">YouTube 이용약관</a> 및 <a href="https://policies.google.com/privacy" target="_blank">Google 개인정보처리방침</a>이 함께 적용됩니다.</p>
<h2>제 7 조 (AI 생성 콘텐츠의 권리)</h2>
<p>서비스 내에서 AI가 생성한 콘텐츠에 대한 권리 관계는 관련 법령 및 회사의 별도 정책에 따릅니다. 회원이 직접 입력한 정보(매장 URL, 상호명 등)를 기반으로 생성된 콘텐츠에 대한 책임은 회원에게 있습니다.</p>
<h2>제 8 조 (책임 제한)</h2>
<p>회사는 천재지변, 외부 플랫폼(Google, YouTube, Naver 등)의 장애, 통신 장애 등 불가항력으로 서비스를 제공할 수 없는 경우 책임이 면제됩니다.</p>
<h2>제 9 조 (준거법 및 재판관할)</h2>
<p>본 약관과 관련된 분쟁은 대한민국 법을 준거법으로 하며, 소송은 회사의 소재지를 관할하는 법원에 제소합니다.</p>
<h2>문의처</h2>
<ul>
<li><strong>회사명:</strong> ㈜에이아이오투오</li>
<li><strong>서비스명:</strong> ADO2</li>
<li><strong>이메일:</strong> o2oteam@o2o.kr</li>
<li><strong>웹사이트:</strong> https://ado2.o2osolution.ai</li>
</ul>
<p style="margin-top:40px; font-size:14px; color:#999;">본 약관은 2026년 5월 7일부터 시행됩니다.</p>
</body>
</html>
+55 -342
View File
@@ -1,24 +1,16 @@
import React, { useRef, useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import Header from './components/Header';
import HeroSection from './pages/Landing/HeroSection';
import WelcomeSection from './pages/Landing/WelcomeSection';
import DisplaySection from './pages/Landing/DisplaySection';
import LoadingSection from './pages/Analysis/LoadingSection';
import AnalysisResultSection from './pages/Analysis/AnalysisResultSection';
import LoginSection from './pages/Login/LoginSection';
import GenerationFlow from './pages/Dashboard/GenerationFlow'; import GenerationFlow from './pages/Dashboard/GenerationFlow';
import SocialConnectSuccess from './pages/Social/SocialConnectSuccess'; import SocialConnectSuccess from './pages/Social/SocialConnectSuccess';
import SocialConnectError from './pages/Social/SocialConnectError'; import SocialConnectError from './pages/Social/SocialConnectError';
import YouTubeOAuthCallback from './pages/Social/YouTubeOAuthCallback'; import YouTubeOAuthCallback from './pages/Social/YouTubeOAuthCallback';
import { crawlUrl, autocomplete, kakaoCallback, isLoggedIn, saveTokens, AutocompleteRequest } from './utils/api'; import VideoDetailPage from './components/VideoDetailPage';
import { CrawlingResponse } from './types/api'; import SsulDetailPage from './pages/Ssulbox/SsulDetailPage';
import { kakaoCallback, saveTokens, storeUtmFromUrl, trackViewContent, trackCompleteRegistration } from './utils/api';
import { clearSessionStorage } from './utils/storageKeys';
import { NAV } from './components/navItems';
type ViewMode = 'landing' | 'loading' | 'analysis' | 'login' | 'generation_flow';
const VIEW_MODE_KEY = 'castad_view_mode';
const ANALYSIS_DATA_KEY = 'castad_analysis_data';
const SESSION_KEY = 'castad_session_active'; const SESSION_KEY = 'castad_session_active';
// 새 탭/새 창에서 접근 시 localStorage 초기화 (sessionStorage로 현재 세션 확인) // 새 탭/새 창에서 접근 시 localStorage 초기화 (sessionStorage로 현재 세션 확인)
@@ -27,15 +19,7 @@ const initializeOnNewSession = () => {
if (!isExistingSession) { if (!isExistingSession) {
// 새 세션이면 localStorage 정리하고 세션 표시 // 새 세션이면 localStorage 정리하고 세션 표시
localStorage.removeItem(VIEW_MODE_KEY); clearSessionStorage();
localStorage.removeItem(ANALYSIS_DATA_KEY);
localStorage.removeItem('castad_wizard_step');
localStorage.removeItem('castad_active_item');
localStorage.removeItem('castad_song_task_id');
localStorage.removeItem('castad_image_task_id');
localStorage.removeItem('castad_song_generation');
localStorage.removeItem('castad_video_generation');
localStorage.removeItem('castad_video_ratio');
sessionStorage.setItem(SESSION_KEY, 'true'); sessionStorage.setItem(SESSION_KEY, 'true');
} }
}; };
@@ -44,63 +28,15 @@ const initializeOnNewSession = () => {
initializeOnNewSession(); initializeOnNewSession();
const App: React.FC = () => { const App: React.FC = () => {
const { t, i18n } = useTranslation(); const { t } = useTranslation();
const containerRef = useRef<HTMLElement>(null); const [initialTab, setInitialTab] = useState<string>(NAV.HOME);
// localStorage에서 저장된 상태 복원 (새 세션이면 이미 초기화됨)
const savedViewMode = localStorage.getItem(VIEW_MODE_KEY) as ViewMode | null;
const savedAnalysisData = localStorage.getItem(ANALYSIS_DATA_KEY);
// 저장된 분석 데이터 파싱 및 유효성 검사
const parseSavedAnalysisData = (): CrawlingResponse | null => {
if (!savedAnalysisData) return null;
try {
const data = JSON.parse(savedAnalysisData) as CrawlingResponse;
// 기본값 보장
if (data.marketing_analysis) {
data.marketing_analysis.brand_identity = data.marketing_analysis.brand_identity || {
location_feature_analysis: '',
concept_scalability: ''
};
data.marketing_analysis.market_positioning = data.marketing_analysis.market_positioning || {
category_definition: '',
core_value: ''
};
data.marketing_analysis.target_persona = data.marketing_analysis.target_persona || [];
data.marketing_analysis.selling_points = data.marketing_analysis.selling_points || [];
data.marketing_analysis.target_keywords = data.marketing_analysis.target_keywords || [];
}
if (data.processed_info) {
data.processed_info.customer_name = data.processed_info.customer_name || '알 수 없음';
data.processed_info.region = data.processed_info.region || '';
data.processed_info.detail_region_info = data.processed_info.detail_region_info || '';
}
data.image_list = data.image_list || [];
return data;
} catch {
localStorage.removeItem(ANALYSIS_DATA_KEY);
return null;
}
};
// 초기 viewMode 결정: 로그인 상태면 바로 generation_flow로
const getInitialViewMode = (): ViewMode => {
if (savedViewMode === 'generation_flow') return 'generation_flow';
if (isLoggedIn()) return 'generation_flow';
return 'landing';
};
const [viewMode, setViewMode] = useState<ViewMode>(getInitialViewMode());
const [initialTab, setInitialTab] = useState('새 프로젝트 만들기');
const [analysisData, setAnalysisData] = useState<CrawlingResponse | null>(
parseSavedAnalysisData()
);
const [error, setError] = useState<string | null>(null);
const [scrollProgress, setScrollProgress] = useState(0);
const [isProcessingCallback, setIsProcessingCallback] = useState(false); const [isProcessingCallback, setIsProcessingCallback] = useState(false);
// 카카오 로그인 콜백 처리 (URL에서 토큰 또는 code 파라미터 확인) // 카카오 로그인 콜백 처리 (URL에서 토큰 또는 code 파라미터 확인)
useEffect(() => { useEffect(() => {
// 광고 유입 UTM 파라미터 캡처 (콜백 처리로 URL이 정리되기 전에 최우선 실행)
storeUtmFromUrl();
const urlParams = new URLSearchParams(window.location.search); const urlParams = new URLSearchParams(window.location.search);
const accessToken = urlParams.get('access_token'); const accessToken = urlParams.get('access_token');
const refreshToken = urlParams.get('refresh_token'); const refreshToken = urlParams.get('refresh_token');
@@ -114,17 +50,21 @@ const App: React.FC = () => {
// 백엔드에서 토큰을 URL 파라미터로 전달한 경우 // 백엔드에서 토큰을 URL 파라미터로 전달한 경우
if (accessToken && refreshToken && !isProcessingCallback) { if (accessToken && refreshToken && !isProcessingCallback) {
setIsProcessingCallback(true); setIsProcessingCallback(true);
handleTokenCallback(accessToken, refreshToken); handleTokenCallback(accessToken, refreshToken, urlParams.get('is_new_user') === 'true');
} }
// 기존 code 방식 (Redirect URI가 프론트엔드인 경우) - Social OAuth는 제외 // 기존 code 방식 (Redirect URI가 프론트엔드인 경우) - Social OAuth는 제외
else if (code && !isProcessingCallback && !isSocialOAuthCallback) { else if (code && !isProcessingCallback && !isSocialOAuthCallback) {
setIsProcessingCallback(true); setIsProcessingCallback(true);
handleKakaoCallback(code); handleKakaoCallback(code);
} }
// 콜백이 아닌 일반 진입 — 광고 유입 추적
else {
trackViewContent();
}
}, []); }, []);
// 백엔드에서 토큰을 URL 파라미터로 전달받은 경우 처리 // 백엔드에서 토큰을 URL 파라미터로 전달받은 경우 처리
const handleTokenCallback = (accessToken: string, refreshToken: string) => { const handleTokenCallback = async (accessToken: string, refreshToken: string, isNewUser: boolean = false) => {
try { try {
// 토큰 저장 // 토큰 저장
saveTokens(accessToken, refreshToken); saveTokens(accessToken, refreshToken);
@@ -133,17 +73,24 @@ const App: React.FC = () => {
const url = new URL(window.location.href); const url = new URL(window.location.href);
url.searchParams.delete('access_token'); url.searchParams.delete('access_token');
url.searchParams.delete('refresh_token'); url.searchParams.delete('refresh_token');
url.searchParams.delete('is_new_user');
window.history.replaceState({}, document.title, url.pathname); window.history.replaceState({}, document.title, url.pathname);
const savedData = localStorage.getItem(ANALYSIS_DATA_KEY); // 신규 가입이면 Meta CompleteRegistration 전환 이벤트 발화
if (savedData) { // (서버가 계정당 최초 1회 판정 + UTM 저장, 실패해도 로그인 흐름에 영향 없음)
// 분석 데이터가 있으면 에셋 관리(step 1)부터 시작 if (isNewUser) {
// 이전에 저장된 wizard step이 URL 입력(-2) 등으로 남아있을 수 있으므로 초기화 await trackCompleteRegistration();
localStorage.removeItem('castad_wizard_step');
localStorage.removeItem('castad_active_item');
} }
setInitialTab('새 프로젝트 만들기');
setViewMode('generation_flow'); // 로그인 전 특정 화면(예: /video/{id})에서 유도된 로그인이면 그 경로로 복귀
const redirectPath = sessionStorage.getItem('castad_login_redirect');
sessionStorage.removeItem('castad_login_redirect');
if (redirectPath && redirectPath !== '/') {
window.location.href = redirectPath;
return;
}
// 그 외(사이드바 게이트 등)는 GenerationFlow 가 castad_login_next_item 으로 자체 복귀 처리
setInitialTab(NAV.HOME);
} catch (err) { } catch (err) {
console.error('Token callback failed:', err); console.error('Token callback failed:', err);
alert(t('app.loginFailed')); alert(t('app.loginFailed'));
@@ -156,6 +103,12 @@ const App: React.FC = () => {
try { try {
const response = await kakaoCallback(code); const response = await kakaoCallback(code);
// 신규 가입이면 Meta CompleteRegistration 전환 이벤트 발화
// (페이지 이동 전에 완료해야 요청이 유실되지 않음)
if (response.is_new_user) {
await trackCompleteRegistration();
}
// 로그인 성공 - 서버에서 받은 redirect_url로 이동 // 로그인 성공 - 서버에서 받은 redirect_url로 이동
window.location.href = response.redirect_url; window.location.href = response.redirect_url;
} catch (err) { } catch (err) {
@@ -171,202 +124,6 @@ const App: React.FC = () => {
} }
}; };
// viewMode 변경 시 localStorage에 저장
useEffect(() => {
localStorage.setItem(VIEW_MODE_KEY, viewMode);
}, [viewMode]);
// 스크롤 이벤트 핸들러 - 첫 번째 섹션에서 두 번째 섹션으로 넘어갈 때 0~1 값 계산
useEffect(() => {
const container = containerRef.current;
if (!container || viewMode !== 'landing') return;
const handleScroll = () => {
const scrollTop = container.scrollTop;
const sectionHeight = container.clientHeight;
// 첫 번째 섹션 스크롤 진행률 (0 ~ 1)
const progress = Math.min(1, Math.max(0, scrollTop / sectionHeight));
setScrollProgress(progress);
};
container.addEventListener('scroll', handleScroll);
return () => container.removeEventListener('scroll', handleScroll);
}, [viewMode]);
const scrollToSection = (index: number) => {
if (containerRef.current) {
const h = containerRef.current.clientHeight;
containerRef.current.scrollTo({
top: h * index,
behavior: 'smooth'
});
}
};
// 크롤링 응답 유효성 검사
const validateCrawlingResponse = (data: CrawlingResponse): boolean => {
// 필수 필드 존재 여부 확인
if (!data) return false;
if (!data.processed_info) return false;
if (!data.marketing_analysis) return false;
// marketing_analysis 내부 필드 기본값 보장
if (!data.marketing_analysis.brand_identity) {
data.marketing_analysis.brand_identity = {
location_feature_analysis: '',
concept_scalability: ''
};
}
if (!data.marketing_analysis.market_positioning) {
data.marketing_analysis.market_positioning = {
category_definition: '',
core_value: ''
};
}
if (!data.marketing_analysis.target_persona) {
data.marketing_analysis.target_persona = [];
}
if (!data.marketing_analysis.selling_points) {
data.marketing_analysis.selling_points = [];
}
if (!data.marketing_analysis.target_keywords) {
data.marketing_analysis.target_keywords = [];
}
// processed_info 내부 필드 기본값 보장
if (!data.processed_info.customer_name) {
data.processed_info.customer_name = '알 수 없음';
}
if (!data.processed_info.region) {
data.processed_info.region = '';
}
if (!data.processed_info.detail_region_info) {
data.processed_info.detail_region_info = '';
}
// image_list 기본값 보장
if (!data.image_list) {
data.image_list = [];
}
return true;
};
const handleStartAnalysis = async (url: string) => {
if (!url.trim()) return;
setViewMode('loading');
setError(null);
try {
const data = await crawlUrl(url);
// 응답 유효성 검사
if (!validateCrawlingResponse(data)) {
throw new Error(t('app.invalidUrl'));
}
setAnalysisData(data);
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(data));
setViewMode('analysis');
} catch (err) {
console.error('Crawling failed:', err);
const errorMessage = err instanceof Error ? err.message : t('app.analysisError');
setError(errorMessage);
setViewMode('landing');
}
};
// 업체명 자동완성으로 분석 시작
const handleAutocomplete = async (request: AutocompleteRequest) => {
setViewMode('loading');
setError(null);
try {
const data = await autocomplete(request);
// 응답 유효성 검사
if (!validateCrawlingResponse(data)) {
throw new Error(t('app.autocompleteError'));
}
setAnalysisData(data);
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(data));
setViewMode('analysis');
} catch (err) {
console.error('Autocomplete failed:', err);
const errorMessage = err instanceof Error ? err.message : t('app.autocompleteGeneralError');
setError(errorMessage);
setViewMode('landing');
}
};
// 테스트 데이터로 브랜드 분석 페이지 이동
const handleTestData = (data: CrawlingResponse) => {
const tagged = { ...data, _isTestData: true };
setAnalysisData(tagged);
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(tagged));
setViewMode('analysis');
};
// 언어 변경 시 테스트 데이터 다시 로드
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) => {
const tagged = { ...data, _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]);
const handleToLogin = async () => {
// 이미 로그인된 상태면 바로 generation_flow로 이동
if (isLoggedIn()) {
// 분석 데이터가 있으면 이전 wizard step 초기화 (에셋 관리부터 시작하도록)
const savedData = localStorage.getItem(ANALYSIS_DATA_KEY);
if (savedData) {
localStorage.removeItem('castad_wizard_step');
localStorage.removeItem('castad_active_item');
}
setInitialTab('새 프로젝트 만들기');
setViewMode('generation_flow');
return;
}
// 로그인 안 된 상태면 카카오 로그인 페이지로 리다이렉션
try {
const { getKakaoLoginUrl } = await import('./utils/api');
const response = await getKakaoLoginUrl();
window.location.href = response.auth_url;
} catch (err) {
console.error('Failed to get Kakao login URL:', err);
alert(t('app.loginUrlFailed'));
}
};
const handleLoginSuccess = () => {
setInitialTab('새 프로젝트 만들기');
setViewMode('generation_flow');
};
const handleGoBack = () => {
// localStorage 정리
localStorage.removeItem(VIEW_MODE_KEY);
localStorage.removeItem(ANALYSIS_DATA_KEY);
localStorage.removeItem('castad_wizard_step');
localStorage.removeItem('castad_active_item');
setViewMode('landing');
};
// Social OAuth 콜백 페이지 처리 // Social OAuth 콜백 페이지 처리
const pathname = window.location.pathname; const pathname = window.location.pathname;
@@ -383,6 +140,20 @@ const App: React.FC = () => {
return <SocialConnectError />; return <SocialConnectError />;
} }
// 영상 상세 페이지 (/video/{id}) — 인증 게이트는 VideoDetailPage 내부에서 처리
const videoDetailMatch = pathname.match(/^\/video\/([^/]+)$/);
if (videoDetailMatch) {
return <VideoDetailPage videoId={videoDetailMatch[1]} />;
}
// 썰박스 공유 페이지 (/ssul/{id}) — 위와 동일한 패턴, 비로그인 열람 가능.
// /video/{id} 와 경로를 나눈 이유: video.id 와 ssul_content.id 가 독립 시퀀스라
// 값이 겹치므로, 한 경로로 합치면 다른 종류의 콘텐츠가 열린다.
const ssulDetailMatch = pathname.match(/^\/ssul\/(\d+)$/);
if (ssulDetailMatch) {
return <SsulDetailPage contentId={ssulDetailMatch[1]} />;
}
// 카카오 콜백 처리 중 로딩 화면 표시 // 카카오 콜백 처리 중 로딩 화면 표시
if (isProcessingCallback) { if (isProcessingCallback) {
return ( return (
@@ -394,66 +165,8 @@ const App: React.FC = () => {
); );
} }
if (viewMode === 'loading') { // 그 외 전 경로는 ADO2 콘텐츠 갤러리를 첫 화면으로 하는 GenerationFlow 로 수렴
return <LoadingSection />; return <GenerationFlow initialActiveItem={initialTab} />;
}
if (viewMode === 'analysis' && analysisData) {
return (
<AnalysisResultSection
onBack={handleGoBack}
onGenerate={handleToLogin}
data={analysisData}
/>
);
}
if (viewMode === 'login') {
return <LoginSection onBack={() => setViewMode('analysis')} onLogin={handleLoginSuccess} />;
}
if (viewMode === 'generation_flow') {
return (
<GenerationFlow
onHome={handleGoBack}
initialActiveItem={initialTab}
initialImageList={analysisData?.image_list || []}
businessInfo={analysisData?.processed_info}
initialAnalysisData={analysisData}
/>
);
}
// 로그인된 상태에서 "시작하기" 버튼 클릭
const handleHeaderStart = () => {
setInitialTab('새 프로젝트 만들기');
setViewMode('generation_flow');
};
return (
<main className="landing-container" ref={containerRef}>
<Header onStartClick={handleHeaderStart} />
<section className="landing-section">
<HeroSection
onAnalyze={handleStartAnalysis}
onAutocomplete={handleAutocomplete}
onTestData={handleTestData}
onNext={() => scrollToSection(1)}
error={error}
scrollProgress={scrollProgress}
/>
</section>
<section className="landing-section">
<WelcomeSection
onStartClick={() => scrollToSection(0)}
onNext={() => scrollToSection(0)}
/>
</section>
<section className="landing-section">
<DisplaySection onStartClick={() => scrollToSection(0)} />
</section>
</main>
);
}; };
export default App; export default App;
+67
View File
@@ -0,0 +1,67 @@
import React, { useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { UserMeResponse } from '../types/api';
import { NAV_ITEMS, SETTINGS_ID } from './navItems';
import SettingsPanel from './SettingsPanel';
interface BottomNavProps {
activeItem: string;
onNavigate: (id: string) => void;
userInfo?: UserMeResponse | null;
onLogout?: () => void;
credits?: number | null;
isGuest: boolean;
onLoginClick: () => void;
}
const BottomNav: React.FC<BottomNavProps> = ({ activeItem, onNavigate, userInfo, onLogout, credits, isGuest, onLoginClick }) => {
const { t } = useTranslation();
const [settingsOpen, setSettingsOpen] = useState(false);
const settingsAnchorRef = useRef<HTMLButtonElement>(null);
const handleItemClick = (id: string) => {
if (id === SETTINGS_ID) {
setSettingsOpen(v => !v);
return;
}
onNavigate(id);
};
return (
<>
{settingsOpen && <div className="settings-backdrop" onClick={() => setSettingsOpen(false)} />}
{settingsOpen && (
<SettingsPanel
variant="bottom"
onClose={() => setSettingsOpen(false)}
onNavigate={onNavigate}
activeItem={activeItem}
userInfo={userInfo}
credits={credits}
isGuest={isGuest}
onLogout={onLogout}
onLoginClick={onLoginClick}
anchorRef={settingsAnchorRef}
/>
)}
<nav className="bottom-nav">
{NAV_ITEMS.map(item => {
const isActive = item.id === SETTINGS_ID ? settingsOpen : activeItem === item.id;
return (
<button
key={item.id}
ref={item.id === SETTINGS_ID ? settingsAnchorRef : undefined}
className={`bottom-nav-item ${isActive ? 'active' : ''}`}
onClick={() => handleItemClick(item.id)}
>
{item.icon}
<span>{t(item.labelKey)}</span>
</button>
);
})}
</nav>
</>
);
};
export default BottomNav;
+171
View File
@@ -0,0 +1,171 @@
import React, { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { useTranslation } from 'react-i18next';
import CitySelectModal, { REGIONS } from './CitySelectModal';
import { useOverlayClose } from '../hooks/useOverlayClose';
interface BusinessNameInputModalProps {
onClose: () => void;
onSubmit: (businessName: string, address: string, category: string, officialSiteUrl: string) => void;
}
const BusinessNameInputModal: React.FC<BusinessNameInputModalProps> = ({ onClose, onSubmit }) => {
const { t } = useTranslation();
const [businessName, setBusinessName] = useState('');
const [selectedCity, setSelectedCity] = useState('');
const [detailAddress, setDetailAddress] = useState('');
const [category, setCategory] = useState('');
const [officialSiteUrl, setOfficialSiteUrl] = useState('');
const [isCityModalOpen, setIsCityModalOpen] = useState(false);
const overlayCloseHandlers = useOverlayClose(onClose);
useEffect(() => {
document.body.style.overflow = 'hidden';
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
document.addEventListener('keydown', handleKeyDown);
return () => {
document.body.style.overflow = '';
document.removeEventListener('keydown', handleKeyDown);
};
}, [onClose]);
const handleCitySelect = (city: string) => {
const region = REGIONS.find(r => r.cities.includes(city));
// 특별시/광역시는 도 이름 없이 도시명만 사용
const prefix = region && region.label !== '특별시 / 광역시' ? `${region.label} ` : '';
setSelectedCity(`${prefix}${city}`);
};
const isValid = businessName.trim().length > 0 && selectedCity.length > 0 && detailAddress.trim().length > 0;
const handleSubmit = () => {
if (!isValid) return;
const fullAddress = `${selectedCity} ${detailAddress.trim()}`;
// 프로토콜 없이 입력하면 https:// 를 붙여서 전달
const trimmedUrl = officialSiteUrl.trim();
const normalizedUrl = trimmedUrl && !/^https?:\/\//i.test(trimmedUrl)
? `https://${trimmedUrl}`
: trimmedUrl;
onSubmit(businessName.trim(), fullAddress, category.trim(), normalizedUrl);
onClose();
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && isValid) handleSubmit();
};
// CitySelectModal의 selected prop용 — 도시명만 추출
const cityOnly = selectedCity.split(' ').pop() ?? '';
return createPortal(
<>
<div className="manual-modal-backdrop" {...overlayCloseHandlers}>
<div className="manual-modal" onClick={e => e.stopPropagation()}>
<div className="manual-modal-header">
<span className="manual-modal-title">{t('landing.hero.manualModalTitle')}</span>
<button className="manual-modal-close" onClick={onClose}>✕</button>
</div>
<p className="manual-modal-subtitle">{t('landing.hero.manualModalSubtitle')}</p>
<div className="manual-modal-body">
<div className="manual-modal-field">
<label className="manual-modal-label">{t('landing.hero.manualLabelName')}</label>
<input
type="text"
className="manual-modal-input"
placeholder={t('landing.hero.manualPlaceholderName')}
value={businessName}
onChange={e => setBusinessName(e.target.value)}
onKeyDown={handleKeyDown}
maxLength={50}
autoFocus
/>
</div>
<div className="manual-modal-field">
<label className="manual-modal-label">{t('landing.hero.manualLabelRegion')}</label>
<button
type="button"
className={`manual-modal-city-btn ${selectedCity ? 'selected' : ''}`}
onClick={() => setIsCityModalOpen(true)}
>
<span>{selectedCity || t('landing.hero.manualPlaceholderRegion')}</span>
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M6 9l6 6 6-6" />
</svg>
</button>
</div>
<div className="manual-modal-field">
<label className="manual-modal-label">{t('landing.hero.manualLabelDetail')}</label>
<input
type="text"
className="manual-modal-input"
placeholder={t('landing.hero.manualPlaceholderDetail')}
value={detailAddress}
onChange={e => setDetailAddress(e.target.value)}
onKeyDown={handleKeyDown}
maxLength={100}
/>
</div>
<div className="manual-modal-field">
<label className="manual-modal-label">{t('landing.hero.manualLabelCategory')}</label>
<input
type="text"
className="manual-modal-input"
placeholder={t('landing.hero.manualPlaceholderCategory')}
value={category}
onChange={e => setCategory(e.target.value)}
onKeyDown={handleKeyDown}
maxLength={30}
/>
</div>
<div className="manual-modal-field">
<label className="manual-modal-label">{t('landing.hero.manualLabelSiteUrl')}</label>
<input
type="url"
className="manual-modal-input"
placeholder={t('landing.hero.manualPlaceholderSiteUrl')}
value={officialSiteUrl}
onChange={e => setOfficialSiteUrl(e.target.value)}
onKeyDown={handleKeyDown}
maxLength={2048}
/>
</div>
<div className="manual-modal-actions">
<button type="button" className="manual-modal-cancel" onClick={onClose}>
{t('common.cancel')}
</button>
<button
type="button"
className="manual-modal-submit"
onClick={handleSubmit}
disabled={!isValid}
>
{t('landing.hero.manualAnalyzeButton')}
</button>
</div>
</div>
</div>
</div>
{isCityModalOpen && (
<CitySelectModal
selected={cityOnly}
onSelect={(city) => { handleCitySelect(city); setIsCityModalOpen(false); }}
onClose={() => setIsCityModalOpen(false)}
/>
)}
</>,
document.body
);
};
export default BusinessNameInputModal;
+162
View File
@@ -0,0 +1,162 @@
import React, { useState, useEffect } from 'react';
import { useOverlayClose } from '../hooks/useOverlayClose';
export const REGIONS: { label: string; cities: string[] }[] = [
{
label: '특별시 / 광역시',
cities: ['서울시', '부산시', '대구시', '인천시', '광주시', '대전시', '울산시', '세종시'],
},
{
label: '경기도',
cities: [
'수원시', '성남시', '고양시', '용인시', '부천시', '안산시', '안양시', '남양주시',
'화성시', '평택시', '의정부시', '시흥시', '파주시', '김포시', '광주시', '광명시',
'군포시', '하남시', '오산시', '이천시', '안성시', '구리시', '양주시', '포천시',
'여주시', '동두천시', '과천시', '가평군', '양평군', '연천군',
],
},
{
label: '강원도',
cities: [
'춘천시', '원주시', '강릉시', '동해시', '태백시', '속초시', '삼척시',
'홍천군', '횡성군', '영월군', '평창군', '정선군', '철원군', '화천군',
'양구군', '인제군', '고성군', '양양군',
],
},
{
label: '충청북도',
cities: [
'청주시', '충주시', '제천시',
'보은군', '옥천군', '영동군', '증평군', '진천군', '괴산군', '음성군', '단양군',
],
},
{
label: '충청남도',
cities: [
'천안시', '공주시', '보령시', '아산시', '서산시', '논산시', '계룡시', '당진시',
'금산군', '부여군', '서천군', '청양군', '홍성군', '예산군', '태안군',
],
},
{
label: '전라북도',
cities: [
'전주시', '군산시', '익산시', '정읍시', '남원시', '김제시',
'완주군', '진안군', '무주군', '장수군', '임실군', '순창군', '고창군', '부안군',
],
},
{
label: '전라남도',
cities: [
'목포시', '여수시', '순천시', '나주시', '광양시',
'담양군', '곡성군', '구례군', '고흥군', '보성군', '화순군', '장흥군', '강진군',
'해남군', '영암군', '무안군', '함평군', '영광군', '장성군', '완도군', '진도군', '신안군',
],
},
{
label: '경상북도',
cities: [
'포항시', '경주시', '김천시', '안동시', '구미시', '영주시', '영천시', '상주시', '문경시', '경산시',
'의성군', '청송군', '영양군', '영덕군', '청도군', '고령군', '성주군', '칠곡군',
'예천군', '봉화군', '울진군', '울릉군',
],
},
{
label: '경상남도',
cities: [
'창원시', '진주시', '통영시', '사천시', '김해시', '밀양시', '거제시', '양산시',
'의령군', '함안군', '창녕군', '고성군', '남해군', '하동군', '산청군', '함양군', '거창군', '합천군',
],
},
{
label: '제주도',
cities: ['제주시', '서귀포시'],
},
];
interface CitySelectModalProps {
selected: string;
onSelect: (city: string) => void;
onClose: () => void;
}
const CitySelectModal: React.FC<CitySelectModalProps> = ({ selected, onSelect, onClose }) => {
const [activeRegion, setActiveRegion] = useState<string | null>(
() => REGIONS.find(r => r.cities.includes(selected))?.label ?? null
);
useEffect(() => {
document.body.style.overflow = 'hidden';
return () => { document.body.style.overflow = ''; };
}, []);
const activeEntry = REGIONS.find(r => r.label === activeRegion);
const cities = activeEntry?.cities ?? [];
const handleSelect = (value: string) => {
onSelect(value === selected ? '' : value);
onClose();
};
const overlayCloseHandlers = useOverlayClose(onClose);
return (
<div className="city-modal-backdrop" {...overlayCloseHandlers}>
<div className="city-modal" onClick={e => e.stopPropagation()}>
<div className="city-modal-header">
<span className="city-modal-title">
{activeRegion ? (
<>
<button className="city-modal-back" onClick={() => setActiveRegion(null)}>←</button>
{activeRegion}
</>
) : '지역 선택'}
</span>
<button className="city-modal-close" onClick={onClose}>✕</button>
</div>
{activeRegion === null ? (
<div className="city-modal-grid">
{REGIONS.map(r => {
const isRegionSelected = selected === r.label;
const hasCitySelected = r.cities.includes(selected);
return (
<button
key={r.label}
className={`city-modal-region-item ${isRegionSelected || hasCitySelected ? 'has-selected' : ''}`}
onClick={() => setActiveRegion(r.label)}
>
<span>{r.label}</span>
{isRegionSelected && <span className="city-modal-region-badge">전체</span>}
{hasCitySelected && <span className="city-modal-region-badge">{selected}</span>}
<span className="city-modal-arrow">›</span>
</button>
);
})}
</div>
) : (
<div className="city-modal-item-wrap">
{activeRegion !== '특별시 / 광역시' && (
<button
className={`city-modal-item city-modal-item-all ${selected === activeRegion ? 'active' : ''}`}
onClick={() => handleSelect(activeRegion!)}
>
전체
</button>
)}
{cities.map(city => (
<button
key={city}
className={`city-modal-item ${selected === city ? 'active' : ''}`}
onClick={() => handleSelect(city)}
>
{city}
</button>
))}
</div>
)}
</div>
</div>
);
};
export default CitySelectModal;
+201
View File
@@ -0,0 +1,201 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
/**
* 생성 완료 화면의 공용 레이아웃 (ADO2 영상 · 썰박스 공통).
*
* **순수 표현 컴포넌트다** — 생성·폴링·다운로드 로직은 전혀 갖지 않는다.
* `CompletionContent`(ADO2)는 영상 생성과 자막 폴링까지 직접 수행하는 컨테이너라
* 그대로 재사용할 수 없었고, 그래서 화면만 여기로 분리했다.
*
* 양쪽의 차이는 정보 패널뿐이다:
* - ADO2 : 장르 · 해상도 → 가사 전문
* - 썰박스 : 시나리오 · 생성일시 → 시나리오 설명
* 그 차이를 `metaLines`/`detail` 슬롯으로 받는다.
*
* 마크업과 클래스명(`comp2-*`)은 기존 ADO2 완료 화면 그대로다. 클래스를 새로
* 만들지 않아야 [generation-flow.css](../styles/generation-flow.css) 의 반응형·
* 다크 팔레트가 두 화면에 동일하게 적용된다.
*/
/** 영상 영역이 무엇을 그릴지 */
export type CompletionVideoState =
/** 생성/렌더 진행 중 — 스피너 + 진행률 */
| 'loading'
/** 실패 — 메시지 + (있으면) 재시도 버튼 */
| 'error'
/** 재생 가능 */
| 'ready'
/** URL 을 아직 못 받았지만 진행 중도 실패도 아님 — 빈 자리만 유지 */
| 'empty';
interface CompletionViewProps {
videoState: CompletionVideoState;
videoUrl?: string | null;
/** `videoState === 'loading'` 일 때만 쓰인다 */
loadingText?: string;
/** 0~100. 표시용 값이며 크리핑 보간은 호출부 책임이다 */
progress?: number;
/** `videoState === 'error'` 일 때만 쓰인다 */
errorMessage?: string | null;
/** 없으면 재시도 버튼을 그리지 않는다 (썰박스는 이 화면에서 재시도가 없다) */
onRetry?: () => void;
/** 정보 패널 상단 파일명 */
fileName: string;
/** 메타 줄. 줄 사이에 구분선이 들어간다 */
metaLines: React.ReactNode[];
/** 메타 아래 상세 영역의 제목 */
detailLabel: string;
/** 상세 본문 (ADO2=가사 단락, 썰박스=시나리오 설명) */
detail: React.ReactNode;
onDownload: () => void;
downloadDisabled?: boolean;
/** 진행 중에는 '다운로드 중...' 처럼 바뀌므로 호출부가 문구를 정한다 */
downloadLabel: string;
onUpload: () => void;
uploadDisabled?: boolean;
/**
* 이 화면에 딸린 오버레이(SNS 업로드 모달 등).
*
* `.comp2-page` 안에 그려지므로 오버레이 쪽에서 타이포그래피 상속을
* 끊어야 한다 — `.social-posting-overlay` 의 `text-align` 참조.
*/
children?: React.ReactNode;
}
const CompletionView: React.FC<CompletionViewProps> = ({
videoState,
videoUrl,
loadingText,
progress = 0,
errorMessage,
onRetry,
fileName,
metaLines,
detailLabel,
detail,
onDownload,
downloadDisabled,
downloadLabel,
onUpload,
uploadDisabled,
children,
}) => {
const { t } = useTranslation();
return (
<main className="comp2-page">
<div className="comp2-title-row">
<h1 className="comp2-page-title">{t('completion.contentComplete')}</h1>
<p className="comp2-page-subtitle">{t('completion.contentCompleteDesc')}</p>
</div>
<div className="comp2-container">
<div className="comp2-grid">
{/* 왼쪽: 영상 */}
<div className="comp2-video-section">
<div className="comp2-video-wrapper">
{videoState === 'loading' ? (
<div className="comp2-video-loading">
<div className="loading-spinner">
<div className="loading-ring"></div>
<div className="loading-dot">
<div className="loading-dot-inner"></div>
</div>
</div>
<p className="comp2-loading-text">{loadingText}</p>
<div className="loading-progress-wrapper">
<div className="loading-progress-bar">
<div
className="loading-progress-fill"
style={{ width: `${progress}%` }}
/>
</div>
<span className="loading-progress-text">{Math.floor(progress)}%</span>
</div>
</div>
) : videoState === 'error' ? (
<div className="comp2-video-error">
<svg
className="comp2-error-icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
>
<circle cx="12" cy="12" r="10" />
<path d="M12 8v4M12 16h.01" />
</svg>
<p className="comp2-error-text">{errorMessage}</p>
{onRetry && (
<button onClick={onRetry} className="comp2-retry-btn">
{t('completion.retry')}
</button>
)}
</div>
) : videoState === 'ready' && videoUrl ? (
<video src={videoUrl} className="comp2-video-player" controls playsInline />
) : (
<div className="comp2-video-placeholder"></div>
)}
</div>
</div>
{/* 오른쪽: 콘텐츠 정보 */}
<div className="comp2-info-section">
<div className="comp2-info-header">
<span className="comp2-info-label">{t('completion.contentInfo')}</span>
</div>
<div className="comp2-file-info">
<h3 className="comp2-filename">{fileName}</h3>
</div>
<div className="comp2-info-content">
<div className="comp2-meta-grid">
{metaLines.map((line, i) => (
<React.Fragment key={i}>
<div className="comp2-meta-item">
<span className="comp2-meta-label">{line}</span>
</div>
<div className="comp2-meta-divider"></div>
</React.Fragment>
))}
<div className="comp2-lyrics-section">
<span className="comp2-meta-label">{detailLabel}</span>
{detail}
</div>
</div>
</div>
{/* 하단 버튼 */}
<div className="comp2-buttons">
<button
onClick={onDownload}
disabled={downloadDisabled}
className="comp2-btn comp2-btn-secondary"
>
{downloadLabel}
</button>
<button
onClick={onUpload}
disabled={uploadDisabled}
className="comp2-btn comp2-btn-primary"
>
{t('completion.uploadToSocial')}
</button>
</div>
</div>
</div>
</div>
{children}
</main>
);
};
export default CompletionView;
+128
View File
@@ -0,0 +1,128 @@
import React, { useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API_URL, toggleVideoLike, isLoggedIn } from '../utils/api';
import { buildContentShareUrl, tryNativeShare } from '../utils/nativeShare';
import { ContentType } from '../types/api';
import LoginPromptModal from './LoginPromptModal';
interface ContentCardSocialActionsProps {
videoId: number;
/**
* 콘텐츠 종류. video.id 와 ssul_content.id 가 겹치므로 좋아요 API 와
* 공유 URL(/video/{id} vs /ssul/{id}) 분기에 반드시 필요하다.
*/
contentType?: ContentType;
storeName: string;
region?: string;
title?: string | null;
description?: string | null;
commentCount: number;
initialLikeCount: number;
initialIsLiked?: boolean;
}
const ContentCardSocialActions: React.FC<ContentCardSocialActionsProps> = ({
videoId,
contentType = 'video',
storeName,
region,
title,
description,
commentCount,
initialLikeCount,
initialIsLiked = false,
}) => {
const { t } = useTranslation();
const [likeCount, setLikeCount] = useState(initialLikeCount);
const [isLiked, setIsLiked] = useState(initialIsLiked);
const [showLoginModal, setShowLoginModal] = useState(false);
const likeDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const shareUrl = buildContentShareUrl(API_URL, videoId, contentType);
const shareTitle = title || storeName || t('videoDetail.kakaoDefaultTitle');
const handleShareBtnClick = async (e: React.MouseEvent) => {
e.stopPropagation();
const handled = await tryNativeShare({
title: shareTitle,
url: shareUrl,
});
if (handled) {
return;
}
try {
await navigator.clipboard.writeText(shareUrl);
} catch {
// clipboard API 미지원 환경에서는 무시
}
};
const handleLikeClick = (e: React.MouseEvent) => {
e.stopPropagation();
if (!isLoggedIn()) {
setShowLoginModal(true);
return;
}
const prevLiked = isLiked;
const prevCount = likeCount;
setIsLiked(!prevLiked);
setLikeCount(prevLiked ? prevCount - 1 : prevCount + 1);
if (likeDebounceRef.current) clearTimeout(likeDebounceRef.current);
likeDebounceRef.current = setTimeout(async () => {
try {
const res = await toggleVideoLike(String(videoId), contentType);
setIsLiked(res.is_liked);
setLikeCount(res.like_count);
} catch (err) {
console.error('Failed to toggle like:', err);
setIsLiked(prevLiked);
setLikeCount(prevCount);
}
}, 500);
};
return (
<div className="content-card-social" onClick={(e) => e.stopPropagation()}>
<button
className={`content-card-like-btn ${isLiked ? 'liked' : ''}`}
onClick={handleLikeClick}
>
<svg width="15" height="15" viewBox="0 0 24 24" fill={isLiked ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="2">
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
</svg>
{likeCount}
</button>
<span className="content-card-comment">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
</svg>
{commentCount}
</span>
<button
className="content-card-share-btn"
onClick={handleShareBtnClick}
title={t('videoDetail.share')}
>
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="18" cy="5" r="3" /><circle cx="6" cy="12" r="3" /><circle cx="18" cy="19" r="3" />
<line x1="8.59" y1="13.51" x2="15.42" y2="17.49" /><line x1="15.41" y1="6.51" x2="8.59" y2="10.49" />
</svg>
</button>
{showLoginModal && (
<LoginPromptModal onClose={() => setShowLoginModal(false)} />
)}
</div>
);
};
export default ContentCardSocialActions;
+5
View File
@@ -10,6 +10,11 @@ const Footer: React.FC = () => {
<div className="footer-left"> <div className="footer-left">
<img src="/assets/images/ado2-sidebar-logo.svg" alt="ADO2" className="footer-logo" /> <img src="/assets/images/ado2-sidebar-logo.svg" alt="ADO2" className="footer-logo" />
<p className="footer-copyright">Copyright ⓒ O2O Inc. All rights reserved</p> <p className="footer-copyright">Copyright ⓒ O2O Inc. All rights reserved</p>
<div className="footer-links">
<a href="https://ado2.o2osolution.ai/privacy.html" rel="noopener noreferrer" className="footer-link">{t('footer.privacyPolicy')}</a>
<span className="footer-link-divider">|</span>
<a href="https://ado2.o2osolution.ai/terms.html" rel="noopener noreferrer" className="footer-link">{t('footer.termsOfService')}</a>
</div>
</div> </div>
<div className="footer-right"> <div className="footer-right">
<p className="footer-info">{t('footer.company')}</p> <p className="footer-info">{t('footer.company')}</p>
-64
View File
@@ -1,64 +0,0 @@
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { getKakaoLoginUrl, isLoggedIn } from '../utils/api';
import LanguageSwitch from './LanguageSwitch';
interface HeaderProps {
onStartClick?: () => void;
}
const Header: React.FC<HeaderProps> = ({ onStartClick }) => {
const { t } = useTranslation();
const [isLoading, setIsLoading] = useState(false);
const loggedIn = isLoggedIn();
const handleLogin = async () => {
if (isLoading) return;
setIsLoading(true);
try {
const response = await getKakaoLoginUrl();
window.location.href = response.auth_url;
} catch (err) {
console.error('Failed to get Kakao login URL:', err);
alert(t('header.loginFailedAlert'));
setIsLoading(false);
}
};
const handleStart = () => {
if (onStartClick) {
onStartClick();
}
};
return (
<header className="landing-header">
<div className="header-logo">
<img src="/assets/images/ado2-header-logo.svg" alt="ADO2" />
</div>
<div className="header-actions">
<LanguageSwitch />
{loggedIn ? (
<button
className="header-start-btn"
onClick={handleStart}
>
{t('header.start')}
</button>
) : (
<button
className="header-login-btn"
onClick={handleLogin}
disabled={isLoading}
>
{isLoading ? t('header.loading') : t('header.login')}
</button>
)}
</div>
</header>
);
};
export default Header;
+126
View File
@@ -0,0 +1,126 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { getKakaoLoginUrl } from '../utils/api';
import { useOverlayClose } from '../hooks/useOverlayClose';
interface LoginPromptModalProps {
onClose: () => void;
}
const LoginPromptModal: React.FC<LoginPromptModalProps> = ({ onClose }) => {
const { t } = useTranslation();
const overlayCloseHandlers = useOverlayClose(onClose);
const handleLogin = async () => {
try {
sessionStorage.setItem('castad_login_redirect', window.location.pathname);
const response = await getKakaoLoginUrl();
window.location.href = response.auth_url;
} catch (err) {
console.error('Failed to get Kakao login URL:', err);
}
};
return (
<div
style={{
position: 'fixed',
inset: 0,
background: 'rgba(0, 0, 0, 0.7)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
zIndex: 9999,
padding: '16px',
}}
{...overlayCloseHandlers}
>
<div
style={{
background: '#01282A',
border: '1px solid rgba(166, 255, 234, 0.15)',
borderRadius: '20px',
boxShadow: '0 24px 60px rgba(0, 0, 0, 0.5)',
padding: '44px 32px 36px',
width: '380px',
maxWidth: '100%',
textAlign: 'center',
position: 'relative',
}}
onClick={(e) => e.stopPropagation()}
>
<button
onClick={onClose}
aria-label="닫기"
style={{
position: 'absolute',
top: '16px',
right: '16px',
background: 'none',
border: 'none',
cursor: 'pointer',
color: '#9BCACC',
padding: '4px',
}}
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5">
<line x1="4" y1="4" x2="16" y2="16"/>
<line x1="16" y1="4" x2="4" y2="16"/>
</svg>
</button>
<div
style={{
width: '56px',
height: '56px',
margin: '0 auto 20px',
borderRadius: '50%',
background: 'rgba(166, 255, 234, 0.1)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}
>
<svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="#A6FFEA" strokeWidth="2">
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
<circle cx="12" cy="7" r="4" />
</svg>
</div>
<h2 style={{ color: '#FFFFFF', fontSize: '22px', fontWeight: 700, marginBottom: '10px', lineHeight: 1.4 }}>
{t('loginPrompt.title')}
</h2>
<p style={{ color: '#9BCACC', fontSize: '14px', lineHeight: 1.5, marginBottom: '28px', whiteSpace: 'pre-line' }}>
{t('loginPrompt.description')}
</p>
<button
onClick={handleLogin}
style={{
width: '100%',
padding: '15px',
background: '#FEE500',
color: '#3C1E1E',
border: 'none',
borderRadius: '10px',
fontSize: '16px',
fontWeight: 700,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '8px',
boxShadow: '0 4px 14px rgba(254, 229, 0, 0.25)',
}}
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fillRule="evenodd" clipRule="evenodd" d="M10 2C5.582 2 2 4.91 2 8.5c0 2.26 1.37 4.25 3.44 5.44L4.6 17.1a.3.3 0 0 0 .44.33l4.03-2.67c.3.03.62.04.93.04 4.418 0 8-2.91 8-6.5S14.418 2 10 2z" fill="#3C1E1E"/>
</svg>
{t('loginPrompt.loginBtn')}
</button>
</div>
</div>
);
};
export default LoginPromptModal;
+57
View File
@@ -0,0 +1,57 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
/** 생성할 콘텐츠 종류. 진입 화면에서 고르면 이후 플로우 전체가 갈린다. */
export type Pipeline = 'ado2' | 'ssul';
interface PipelineTabsProps {
value: Pipeline;
onChange: (value: Pipeline) => void;
}
const TABS: { id: Pipeline; labelKey: string; emoji?: string }[] = [
{ id: 'ado2', labelKey: 'pipelineTabs.ado2' },
{ id: 'ssul', labelKey: 'pipelineTabs.ssul', emoji: '📋' },
];
/**
* ADO2 / 썰박스 전환 탭 (밑줄 탭).
*
* 활성 탭 아래에만 밑줄이 얹히고, 색이 민트(ADO2) ↔ 앰버(썰박스)로 바뀐다.
* 스타일은 generation-flow.css 의 `.pipeline-tabs*` 참조.
*
* 접근성: castad 의 기존 탭(`.myinfo-tab` 등)에는 role/aria 가 없지만,
* 이 컴포넌트를 기점으로 표준 tablist 패턴을 도입한다.
*/
const PipelineTabs: React.FC<PipelineTabsProps> = ({ value, onChange }) => {
const { t } = useTranslation();
return (
<div
className="pipeline-tabs"
data-active={value}
role="tablist"
aria-label={t('pipelineTabs.ariaLabel')}
>
{TABS.map((tab) => (
<button
key={tab.id}
type="button"
role="tab"
aria-selected={value === tab.id}
className="pipeline-tab"
onClick={() => onChange(tab.id)}
>
{tab.emoji && (
<span className="pipeline-tab__emoji" aria-hidden="true">
{tab.emoji}
</span>
)}
{t(tab.labelKey)}
</button>
))}
</div>
);
};
export default PipelineTabs;
@@ -0,0 +1,58 @@
import React from 'react';
import { SearchHistoryItem } from './useSearchHistory';
interface SearchHistoryDropdownProps {
items: SearchHistoryItem[];
onSelect: (item: SearchHistoryItem) => void;
onDelete: (e: React.MouseEvent, value: string) => void;
className?: string;
itemClassName?: string;
titleClassName?: string;
addressClassName?: string;
}
const SearchHistoryDropdown: React.FC<SearchHistoryDropdownProps> = ({
items,
onSelect,
onDelete,
className = 'url-input-autocomplete-dropdown',
itemClassName = 'url-input-autocomplete-item',
titleClassName = 'url-input-autocomplete-title',
addressClassName = 'url-input-autocomplete-address',
}) => {
if (items.length === 0) return null;
return (
<div className={className}>
{items.map((item, index) => (
<div
key={index}
className={itemClassName}
style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}
>
<button
type="button"
style={{ flex: 1, textAlign: 'left', background: 'none', border: 'none', padding: 0, cursor: 'pointer' }}
onMouseDown={(e) => { e.preventDefault(); onSelect(item); }}
>
<div className={titleClassName}>{item.value}</div>
{item.roadAddress && (
<div className={addressClassName}>{item.roadAddress}</div>
)}
</button>
<button
type="button"
onMouseDown={(e) => onDelete(e, item.value)}
style={{ color:'#737983', background: 'none', border: 'none', cursor: 'pointer', padding: '0 4px', opacity: 0.8, flexShrink: 0 }}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
</svg>
</button>
</div>
))}
</div>
);
};
export default SearchHistoryDropdown;
@@ -0,0 +1,56 @@
import { useState, useEffect } from 'react';
export const SEARCH_HISTORY_KEY = 'castad_search_history';
export const SEARCH_HISTORY_MAX = 5;
export interface SearchHistoryItem {
type: 'url' | 'name';
value: string;
address?: string;
roadAddress?: string;
}
export const saveSearchHistory = (item: SearchHistoryItem) => {
try {
const saved = localStorage.getItem(SEARCH_HISTORY_KEY);
const history: SearchHistoryItem[] = saved ? JSON.parse(saved) : [];
const filtered = history.filter(h => h.value !== item.value);
const updated = [item, ...filtered].slice(0, SEARCH_HISTORY_MAX);
localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(updated));
} catch { /* ignore */ }
};
export const useSearchHistory = (searchType: 'url' | 'name') => {
const [history, setHistory] = useState<SearchHistoryItem[]>([]);
const [showHistory, setShowHistory] = useState(false);
useEffect(() => {
try {
const saved = localStorage.getItem(SEARCH_HISTORY_KEY);
if (saved) setHistory(JSON.parse(saved));
} catch { /* ignore */ }
}, []);
const filteredHistory = history.filter(h => h.type === searchType);
const deleteItem = (value: string) => {
const updated = history.filter(h => h.value !== value);
setHistory(updated);
localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(updated));
if (updated.filter(h => h.type === searchType).length === 0) {
setShowHistory(false);
}
};
const openHistory = (inputValue: string) => {
if (!inputValue && filteredHistory.length > 0) setShowHistory(true);
};
const closeHistory = () => setShowHistory(false);
const hideOnInput = (value: string) => {
if (value) setShowHistory(false);
};
return { filteredHistory, showHistory, openHistory, closeHistory, hideOnInput, deleteItem };
};
+353
View File
@@ -0,0 +1,353 @@
import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { searchAccommodation, cleanSearchTitle, AccommodationSearchItem, AutocompleteRequest } from '../utils/api';
import { useSearchHistory } from './SearchHistory/useSearchHistory';
import SearchHistoryDropdown from './SearchHistory/SearchHistoryDropdown';
import BusinessNameInputModal from './BusinessNameInputModal';
type SearchType = 'url' | 'name' | 'manual';
export type { SearchType };
const isValidUrl = (string: string): boolean => {
try {
const url = new URL(string);
return url.protocol === 'http:' || url.protocol === 'https:';
} catch {
return false;
}
};
// URL 형태로 판단되는 입력: 프로토콜/www. 시작 또는 도메인 형태(naver.me/xxx 등)
const isUrlLike = (value: string): boolean => {
const trimmed = value.trim();
return /^(https?:\/\/|www\.)/i.test(trimmed)
|| /^[a-z0-9-]+(\.[a-z0-9-]+)+([/?#]|$)/i.test(trimmed);
};
const sanitizeUrlInput = (value: string): string => {
return value.replace(/[^\x00-\x7F]/g, '');
};
// 텍스트 안에 포함된 첫 번째 URL을 추출 (없으면 null)
const extractUrl = (text: string): string | null => {
const match = text.match(/(https?:\/\/|www\.)[^\s]+/i);
return match ? match[0] : null;
};
interface SearchInputFormProps {
onAnalyze?: (value: string, type: SearchType) => void;
onAutocomplete?: (data: AutocompleteRequest) => void;
onManualInput?: (businessName: string, address: string, category: string, officialSiteUrl?: string) => void;
/** 직접입력 버튼 클릭 시 기본 동작(모달 열기)을 대체합니다. 제공 시 모달을 직접 관리해야 합니다. */
onManualButtonClick?: () => void;
error?: string | null;
}
const SearchInputForm: React.FC<SearchInputFormProps> = ({
onAnalyze,
onAutocomplete,
onManualInput,
onManualButtonClick,
error: externalError,
}) => {
const { t } = useTranslation();
const [inputValue, setInputValue] = useState('');
const [searchType] = useState<SearchType>('name');
const [isFocused, setIsFocused] = useState(false);
const [isManualModalOpen, setIsManualModalOpen] = useState(false);
const [localError, setLocalError] = useState('');
const [autocompleteResults, setAutocompleteResults] = useState<AccommodationSearchItem[]>([]);
const [isAutocompleteLoading, setIsAutocompleteLoading] = useState(false);
const [showAutocomplete, setShowAutocomplete] = useState(false);
const [selectedItem, setSelectedItem] = useState<AccommodationSearchItem | null>(null);
const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);
const { filteredHistory, showHistory, openHistory, closeHistory, hideOnInput, deleteItem } = useSearchHistory('name');
const debounceRef = useRef<NodeJS.Timeout | null>(null);
const autocompleteRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (autocompleteRef.current && !autocompleteRef.current.contains(event.target as Node)) {
setShowAutocomplete(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
const handleAutocompleteSearch = useCallback(async (query: string) => {
if (!query.trim()) {
setAutocompleteResults([]);
setShowAutocomplete(false);
return;
}
setIsAutocompleteLoading(true);
try {
const response = await searchAccommodation(query);
setAutocompleteResults(response.items || []);
setShowAutocomplete(response.items && response.items.length > 0);
} catch {
setAutocompleteResults([]);
setShowAutocomplete(false);
} finally {
setIsAutocompleteLoading(false);
}
}, []);
const handleSelectAutocomplete = (item: AccommodationSearchItem) => {
const cleanTitle = cleanSearchTitle(item.title);
setInputValue(cleanTitle);
setSelectedItem({ ...item, title: cleanTitle });
setShowAutocomplete(false);
setAutocompleteResults([]);
setHighlightedIndex(-1);
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (showAutocomplete && autocompleteResults.length > 0) {
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setHighlightedIndex(prev => prev < autocompleteResults.length - 1 ? prev + 1 : 0);
return;
case 'ArrowUp':
e.preventDefault();
setHighlightedIndex(prev => prev > 0 ? prev - 1 : autocompleteResults.length - 1);
return;
case 'Enter':
e.preventDefault();
if (highlightedIndex >= 0 && highlightedIndex < autocompleteResults.length) {
handleSelectAutocomplete(autocompleteResults[highlightedIndex]);
}
return;
case 'Escape':
e.preventDefault();
setShowAutocomplete(false);
setHighlightedIndex(-1);
return;
}
}
if (e.key === 'Enter') {
e.preventDefault();
}
};
const handleStart = () => {
const trimmed = inputValue.trim();
if (!trimmed) {
setLocalError(t('landing.hero.errorInputRequired'));
return;
}
if (isValidUrl(trimmed)) {
setLocalError('');
onAnalyze?.(trimmed, 'url');
return;
}
setLocalError('');
if (selectedItem && onAutocomplete) {
onAutocomplete({
address: selectedItem.address,
roadAddress: selectedItem.roadAddress,
title: selectedItem.title,
});
} else if (onAnalyze) {
onAnalyze(inputValue, searchType);
}
};
const applyInputChange = (value: string) => {
setInputValue(value);
setSelectedItem(null);
setHighlightedIndex(-1);
hideOnInput(value);
if (localError) setLocalError('');
if (debounceRef.current) clearTimeout(debounceRef.current);
if (isValidUrl(value)) {
setAutocompleteResults([]);
setShowAutocomplete(false);
} else {
debounceRef.current = setTimeout(() => handleAutocompleteSearch(value), 300);
}
};
// 모바일 키보드 클립보드 추천 등 paste 이벤트 없이 여러 글자가 한 번에 들어오는 경우 처리
const handleChange = (value: string) => {
const isBulkInsert = value.length - inputValue.length > 1;
if (isBulkInsert) {
const extracted = extractUrl(value);
if (extracted && extracted !== value.trim()) {
applyInputChange(sanitizeUrlInput(extracted));
return;
}
if (isUrlLike(value)) {
const sanitized = sanitizeUrlInput(value);
if (sanitized !== value) {
applyInputChange(sanitized);
return;
}
}
}
applyInputChange(value);
};
const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
const pastedText = e.clipboardData.getData('text');
// 붙여넣은 텍스트에 URL이 포함되어 있고 URL 외 다른 텍스트도 있으면 URL만 추출해서 입력창에 넣기
const extracted = extractUrl(pastedText);
if (extracted && extracted !== pastedText.trim()) {
e.preventDefault();
applyInputChange(sanitizeUrlInput(extracted));
return;
}
const input = e.currentTarget;
const start = input.selectionStart ?? inputValue.length;
const end = input.selectionEnd ?? inputValue.length;
const merged = inputValue.slice(0, start) + pastedText + inputValue.slice(end);
// 붙여넣은 후 완성될 전체 값이 URL 형태일 때만 비영문 문자 제거
if (!isUrlLike(merged)) return;
const sanitized = sanitizeUrlInput(merged);
if (sanitized === merged) return;
e.preventDefault();
applyInputChange(sanitized);
};
const handleManualButtonClick = () => {
if (onManualButtonClick) {
onManualButtonClick();
} else {
setIsManualModalOpen(true);
}
};
const error = externalError || localError;
return (
<div className="hero-form">
<div className={`hero-input-wrapper ${isFocused ? 'focused' : ''} ${error ? 'error' : ''} ${inputValue && !isFocused ? 'filled' : ''}`}>
{/* 유형 라벨 */}
{/* <div className="hero-dropdown-container">
<div className="hero-dropdown-trigger">
<span className="hero-dropdown-main">
{t('landing.hero.searchTypeLabel')}
</span>
</div>
</div> */}
{/* 입력 필드 */}
<div className="hero-input-container" ref={autocompleteRef}>
<input
type="text"
value={inputValue}
onChange={(e) => handleChange(e.target.value)}
onPaste={handlePaste}
onFocus={() => {
setIsFocused(true);
if (autocompleteResults.length > 0) setShowAutocomplete(true);
openHistory(inputValue);
}}
onBlur={() => { setIsFocused(false); setTimeout(() => closeHistory(), 150); }}
onKeyDown={handleKeyDown}
placeholder={t('landing.hero.placeholderCombined')}
className={`hero-input ${inputValue ? 'has-value' : ''}`}
/>
{/* 최근 검색 히스토리 */}
{showHistory && !showAutocomplete && (
<SearchHistoryDropdown
items={filteredHistory}
onSelect={(item) => {
closeHistory();
setInputValue(item.value);
if (item.type === 'name') {
setSelectedItem({ title: item.value, address: item.address || '', roadAddress: item.roadAddress || '' });
}
}}
onDelete={(e, value) => { e.preventDefault(); e.stopPropagation(); deleteItem(value); }}
className="hero-autocomplete-dropdown"
itemClassName="hero-autocomplete-item"
titleClassName="hero-autocomplete-title"
addressClassName="hero-autocomplete-address"
/>
)}
{/* 자동완성 결과 */}
{showAutocomplete && (
<div className="hero-autocomplete-dropdown">
{isAutocompleteLoading ? (
<div className="hero-autocomplete-loading">{t('landing.hero.searching')}</div>
) : (
autocompleteResults.map((item, index) => (
<button
key={index}
type="button"
className={`hero-autocomplete-item ${highlightedIndex === index ? 'highlighted' : ''}`}
onMouseDown={(e) => { e.preventDefault(); handleSelectAutocomplete(item); }}
onMouseEnter={() => setHighlightedIndex(index)}
>
<div className="hero-autocomplete-title" dangerouslySetInnerHTML={{ __html: item.title }} />
<div className="hero-autocomplete-address">{item.roadAddress || item.address}</div>
</button>
))
)}
</div>
)}
</div>
{/* 입력 clear 버튼 */}
{inputValue && (
<button
type="button"
className="hero-input-clear"
onClick={() => {
setInputValue('');
setSelectedItem(null);
setLocalError('');
setAutocompleteResults([]);
setShowAutocomplete(false);
}}
>
<img src="/assets/images/input-clear-icon.svg" alt="Clear" />
</button>
)}
</div>
<span className="hero-input-hint">{t('landing.hero.guideCombined')}</span>
{error && <p className="hero-error">{error}</p>}
<button onClick={handleStart} className="hero-button">
{t('landing.hero.analyzeButton')}
</button>
<div className="hero-divider"><span>또는</span></div>
<div className="hero-manual-card" onClick={handleManualButtonClick} role="button" tabIndex={0}
onKeyDown={(e) => e.key === 'Enter' && handleManualButtonClick()}>
<span className="hero-manual-card-title">{t('landing.hero.searchTypeManual')}</span>
<p className="hero-manual-button-desc">{t('landing.hero.manualButtonDesc')}</p>
</div>
{/* onManualButtonClick 미제공 시 모달을 내부에서 관리 */}
{!onManualButtonClick && isManualModalOpen && (
<BusinessNameInputModal
onClose={() => setIsManualModalOpen(false)}
onSubmit={(businessName, address, category, officialSiteUrl) => {
setIsManualModalOpen(false);
onManualInput?.(businessName, address, category, officialSiteUrl);
}}
/>
)}
</div>
);
};
export default SearchInputForm;
+141
View File
@@ -0,0 +1,141 @@
import React, { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { UserMeResponse } from '../types/api';
import LanguageSwitch from './LanguageSwitch';
import { NAV } from './navItems';
interface SettingsPanelProps {
variant: 'sidebar' | 'bottom';
onClose: () => void;
onNavigate: (id: string) => void;
activeItem: string;
userInfo?: UserMeResponse | null;
credits?: number | null;
isGuest: boolean;
isLoggingOut?: boolean;
onLogout?: () => void;
onLoginClick: () => void;
/** 팝업을 여는 설정 버튼 영역. 외부 클릭 닫기에서 제외해 재클릭 시 토글이 정상 동작하게 한다 */
anchorRef?: React.RefObject<HTMLElement | null>;
}
const SettingsPanel: React.FC<SettingsPanelProps> = ({
variant,
onClose,
onNavigate,
activeItem,
userInfo,
credits,
isGuest,
isLoggingOut,
onLogout,
onLoginClick,
anchorRef,
}) => {
const { t } = useTranslation();
const panelRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const handleClickOutside = (e: MouseEvent) => {
const target = e.target as Node;
if (anchorRef?.current?.contains(target)) return;
if (panelRef.current && !panelRef.current.contains(target)) {
onClose();
}
};
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
document.addEventListener('mousedown', handleClickOutside);
document.addEventListener('keydown', handleEscape);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
document.removeEventListener('keydown', handleEscape);
};
}, [onClose, anchorRef]);
return (
<div ref={panelRef} className={`settings-panel settings-panel--${variant}`}>
{/* 1) 프로필 — 패널 헤더 역할 */}
{!isGuest && (
<>
<div className="profile-section settings-panel-profile">
{userInfo?.profile_image_url || userInfo?.thumbnail_image_url ? (
<img
src={userInfo.thumbnail_image_url || userInfo.profile_image_url || ''}
alt="Profile"
className="profile-avatar"
/>
) : (
<div className="profile-avatar profile-avatar-default">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
<circle cx="12" cy="7" r="4" />
</svg>
</div>
)}
<div className="flex-1 min-w-0">
<p className="profile-name">{userInfo?.nickname || t('sidebar.defaultUser')}</p>
{credits !== null && credits !== undefined && (
<p className="profile-credits">{t('sidebar.credits', { count: credits })}</p>
)}
</div>
</div>
</>
)}
{/* 2) 메뉴 그룹 — 대시보드 */}
<button
className={`settings-panel-item ${activeItem === NAV.DASHBOARD ? 'active' : ''}`}
onClick={() => {
onNavigate(NAV.DASHBOARD);
onClose();
}}
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<rect x="3" y="3" width="7" height="9" /><rect x="14" y="3" width="7" height="5" />
<rect x="14" y="12" width="7" height="9" /><rect x="3" y="16" width="7" height="5" />
</svg>
<span>{t('sidebar.dashboard')}</span>
</button>
<div className="settings-panel-divider" />
{/* 3) 하단 그룹 — 언어 전환 / 로그아웃(로그인) / 고객의견 */}
<div className="settings-panel-language">
<LanguageSwitch isCollapsed={false} />
</div>
{isGuest ? (
<button className="settings-panel-item" onClick={onLoginClick}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4" /><polyline points="10 17 15 12 10 7" /><line x1="15" y1="12" x2="3" y2="12" />
</svg>
<span>{t('sidebar.login')}</span>
</button>
) : (
<button className="settings-panel-item" onClick={onLogout} disabled={isLoggingOut}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" /><polyline points="16 17 21 12 16 7" /><line x1="21" y1="12" x2="9" y2="12" />
</svg>
<span>{isLoggingOut ? t('sidebar.loggingOut') : t('sidebar.logout')}</span>
</button>
)}
<a
href="https://forms.gle/4a8mGebBYtdesvby9"
target="_blank"
rel="noopener noreferrer"
className="settings-panel-item"
title={t('sidebar.inquiry')}
>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
</svg>
<span>{t('sidebar.inquiry')}</span>
</a>
</div>
);
};
export default SettingsPanel;
+63 -157
View File
@@ -1,32 +1,30 @@
import React, { useState, useEffect } from 'react'; import React, { useRef, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { UserMeResponse } from '../types/api'; import { UserMeResponse } from '../types/api';
import { logout } from '../utils/api'; import { logout } from '../utils/api';
import LanguageSwitch from './LanguageSwitch'; import { NAV_ITEMS, SETTINGS_ID } from './navItems';
const TOP_NAV_ITEMS = NAV_ITEMS.filter(item => item.id !== SETTINGS_ID);
const SETTINGS_NAV_ITEM = NAV_ITEMS.find(item => item.id === SETTINGS_ID)!;
import SettingsPanel from './SettingsPanel';
interface SidebarItemProps { interface SidebarItemProps {
icon: React.ReactNode; icon: React.ReactNode;
label: string; label: string;
isActive?: boolean; isActive?: boolean;
isCollapsed: boolean;
isDisabled?: boolean;
onClick?: () => void; onClick?: () => void;
id?: string;
} }
const SidebarItem: React.FC<SidebarItemProps> = ({ icon, label, isActive, isCollapsed, isDisabled, onClick, id }) => { const SidebarItem: React.FC<SidebarItemProps> = ({ icon, label, isActive, onClick }) => {
return ( return (
<div <div
id={id} onClick={onClick}
onClick={isDisabled ? undefined : onClick} className={`sidebar-item ${isActive ? 'active' : ''}`}
className={`sidebar-item ${isActive ? 'active' : ''} ${isCollapsed ? 'collapsed' : ''} ${isDisabled ? 'disabled' : ''}`}
title={isCollapsed ? label : ""}
> >
<div className="sidebar-item-icon"> <div className="sidebar-item-icon">
{icon} {icon}
</div> </div>
{!isCollapsed && <span className="sidebar-item-label">{label}</span>} <span className="sidebar-item-label">{label}</span>
</div> </div>
); );
}; };
@@ -34,18 +32,20 @@ const SidebarItem: React.FC<SidebarItemProps> = ({ icon, label, isActive, isColl
interface SidebarProps { interface SidebarProps {
activeItem: string; activeItem: string;
onNavigate: (id: string) => void; onNavigate: (id: string) => void;
onHome?: () => void; onLogoClick?: () => void;
userInfo?: UserMeResponse | null; userInfo?: UserMeResponse | null;
onLogout?: () => void; onLogout?: () => void;
credits?: number | null;
isGuest: boolean;
onLoginClick: () => void;
} }
const Sidebar: React.FC<SidebarProps> = ({ activeItem, onNavigate, onHome, userInfo, onLogout }) => { const Sidebar: React.FC<SidebarProps> = ({ activeItem, onNavigate, onLogoClick, userInfo, onLogout, credits, isGuest, onLoginClick }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [isCollapsed, setIsCollapsed] = useState(false);
const [isMobileOpen, setIsMobileOpen] = useState(false);
const [isLoggingOut, setIsLoggingOut] = useState(false); const [isLoggingOut, setIsLoggingOut] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const settingsAnchorRef = useRef<HTMLDivElement>(null);
// 로그아웃 처리
const handleLogout = async () => { const handleLogout = async () => {
if (isLoggingOut) return; if (isLoggingOut) return;
setIsLoggingOut(true); setIsLoggingOut(true);
@@ -54,163 +54,69 @@ const Sidebar: React.FC<SidebarProps> = ({ activeItem, onNavigate, onHome, userI
onLogout?.(); onLogout?.();
} catch (error) { } catch (error) {
console.error('Logout failed:', error); console.error('Logout failed:', error);
// 에러가 나도 로컬 토큰은 이미 삭제됨, 홈으로 이동
onLogout?.(); onLogout?.();
} finally { } finally {
setIsLoggingOut(false); setIsLoggingOut(false);
} }
}; };
useEffect(() => { const handleItemClick = (id: string) => {
const handleResize = () => { if (id === SETTINGS_ID) {
if (window.innerWidth < 768) { setSettingsOpen(v => !v);
setIsMobileOpen(false); return;
}
};
handleResize();
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
const handleNavigate = (id: string) => {
onNavigate(id);
if (window.innerWidth < 768) {
setIsMobileOpen(false);
} }
onNavigate(id);
}; };
const menuItems = [
{ id: '대시보드', label: t('sidebar.dashboard'), disabled: false, icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><rect x="3" y="3" width="7" height="9"/><rect x="14" y="3" width="7" height="5"/><rect x="14" y="12" width="7" height="9"/><rect x="3" y="16" width="7" height="5"/></svg> },
{ id: '새 프로젝트 만들기', label: t('sidebar.newProject'), disabled: false, icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg> },
{ id: 'ADO2 콘텐츠', label: t('sidebar.ado2Contents'), disabled: false, icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/></svg> },
{ id: '내 콘텐츠', label: t('sidebar.myContents'), disabled: true, icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg> },
{ id: '콘텐츠 캘린더', label: '콘텐츠 캘린더', disabled: false, icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg> },
{ id: '내 정보', label: t('sidebar.myInfo'), disabled: false, icon: <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg> },
];
return ( return (
<> <div className="sidebar expanded">
{/* Mobile Menu Button */} <div className="sidebar-header">
<button <img
onClick={() => setIsMobileOpen(true)} onClick={onLogoClick}
className="mobile-menu-btn" src="/assets/images/ado2-sidebar-logo.svg"
> alt="ADO2"
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> className="sidebar-logo"
<line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="18" x2="21" y2="18"/>
</svg>
</button>
{/* Mobile Overlay */}
{isMobileOpen && (
<div
className="mobile-overlay"
onClick={() => setIsMobileOpen(false)}
/> />
)} </div>
{/* Sidebar */} <div className="sidebar-menu no-scrollbar">
<div className={`sidebar ${isCollapsed ? 'collapsed' : 'expanded'} ${isMobileOpen ? 'mobile-open' : 'mobile-closed'}`}> {TOP_NAV_ITEMS.map(item => (
<div className={`sidebar-header ${isCollapsed ? 'collapsed' : ''}`}> <SidebarItem
{!isCollapsed && ( key={item.id}
<img icon={item.icon}
onClick={onHome} label={t(item.labelKey)}
src="/assets/images/ado2-sidebar-logo.svg" isActive={activeItem === item.id}
alt="ADO2" onClick={() => handleItemClick(item.id)}
className="sidebar-logo" />
))}
</div>
<div className="sidebar-footer">
<div className="sidebar-settings-anchor" ref={settingsAnchorRef}>
<SidebarItem
icon={SETTINGS_NAV_ITEM.icon}
label={t(SETTINGS_NAV_ITEM.labelKey)}
isActive={settingsOpen}
onClick={() => handleItemClick(SETTINGS_NAV_ITEM.id)}
/>
{settingsOpen && (
<SettingsPanel
variant="sidebar"
onClose={() => setSettingsOpen(false)}
onNavigate={onNavigate}
activeItem={activeItem}
userInfo={userInfo}
credits={credits}
isGuest={isGuest}
isLoggingOut={isLoggingOut}
onLogout={handleLogout}
onLoginClick={onLoginClick}
anchorRef={settingsAnchorRef}
/> />
)} )}
<button
onClick={() => {
if (window.innerWidth < 768) {
setIsMobileOpen(false);
} else {
setIsCollapsed(!isCollapsed);
}
}}
className="p-1.5 text-gray-400 hover:text-white"
>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="18" x2="21" y2="18"/>
</svg>
</button>
</div>
<div className="sidebar-menu no-scrollbar">
{menuItems.map(item => (
<SidebarItem
key={item.id}
id={
item.id === '내 정보'
? 'sidebar-my-info'
: item.id === 'ADO2 콘텐츠'
? 'sidebar-ado2-contents'
: undefined
}
icon={item.icon}
label={item.label}
isCollapsed={isCollapsed}
isActive={activeItem === item.id}
isDisabled={item.disabled}
onClick={() => handleNavigate(item.id)}
/>
))}
</div>
<div className="sidebar-footer">
<div className="sidebar-language-switch">
<LanguageSwitch isCollapsed={isCollapsed} />
</div>
<div className={`profile-section ${isCollapsed ? 'collapsed' : ''}`}>
{userInfo?.profile_image_url || userInfo?.thumbnail_image_url ? (
<img
src={userInfo.thumbnail_image_url || userInfo.profile_image_url || ''}
alt="Profile"
className="profile-avatar"
/>
) : (
<div className="profile-avatar profile-avatar-default">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
<circle cx="12" cy="7" r="4"/>
</svg>
</div>
)}
{!isCollapsed && (
<div className="flex-1 min-w-0">
<p className="profile-name">{userInfo?.nickname || t('sidebar.defaultUser')}</p>
</div>
)}
</div>
<div className="sidebar-footer-actions">
<button
className={`logout-btn ${isCollapsed ? 'collapsed' : ''}`}
onClick={handleLogout}
disabled={isLoggingOut}
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/>
</svg>
{!isCollapsed && <span className="logout-btn-label">{isLoggingOut ? t('sidebar.loggingOut') : t('sidebar.logout')}</span>}
</button>
<a
href="https://forms.gle/4a8mGebBYtdesvby9"
target="_blank"
rel="noopener noreferrer"
className={`sidebar-inquiry-btn ${isCollapsed ? 'collapsed' : ''}`}
title="고객의견"
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
</svg>
{!isCollapsed && <span>고객의견</span>}
</a>
</div>
</div> </div>
</div> </div>
</> </div>
); );
}; };
+84 -68
View File
@@ -4,14 +4,13 @@ import { useTranslation } from 'react-i18next';
import { getSocialAccounts, uploadToSocial, waitForUploadComplete, TokenExpiredError, handleSocialReconnect, getAutoSeoYoutube } from '../utils/api'; import { getSocialAccounts, uploadToSocial, waitForUploadComplete, TokenExpiredError, handleSocialReconnect, getAutoSeoYoutube } from '../utils/api';
import { SocialAccount, VideoListItem, SocialUploadStatusResponse } from '../types/api'; import { SocialAccount, VideoListItem, SocialUploadStatusResponse } from '../types/api';
import UploadProgressModal, { UploadStatus } from './UploadProgressModal'; import UploadProgressModal, { UploadStatus } from './UploadProgressModal';
import { useTutorial } from './Tutorial/useTutorial'; import { useOverlayClose } from '../hooks/useOverlayClose';
import { TUTORIAL_KEYS } from './Tutorial/tutorialSteps';
import TutorialOverlay from './Tutorial/TutorialOverlay';
interface SocialPostingModalProps { interface SocialPostingModalProps {
isOpen: boolean; isOpen: boolean;
onClose: () => void; onClose: () => void;
video: VideoListItem | null; video: VideoListItem | null;
onGoToCalendar?: () => void;
} }
type PrivacyType = 'public' | 'unlisted' | 'private'; type PrivacyType = 'public' | 'unlisted' | 'private';
@@ -116,10 +115,10 @@ const MiniCalendar: React.FC<{
const SocialPostingModal: React.FC<SocialPostingModalProps> = ({ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
isOpen, isOpen,
onClose, onClose,
video video,
onGoToCalendar,
}) => { }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const tutorial = useTutorial();
const [socialAccounts, setSocialAccounts] = useState<SocialAccount[]>([]); const [socialAccounts, setSocialAccounts] = useState<SocialAccount[]>([]);
const [selectedChannel, setSelectedChannel] = useState<string>(''); const [selectedChannel, setSelectedChannel] = useState<string>('');
const [title, setTitle] = useState(''); const [title, setTitle] = useState('');
@@ -139,7 +138,10 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
const [videoMeta, setVideoMeta] = useState<{ width: number; height: number; duration: number } | null>(null); const [videoMeta, setVideoMeta] = useState<{ width: number; height: number; duration: number } | null>(null);
const channelDropdownRef = useRef<HTMLDivElement>(null); const channelDropdownRef = useRef<HTMLDivElement>(null);
const privacyDropdownRef = useRef<HTMLDivElement>(null); const privacyDropdownRef = useRef<HTMLDivElement>(null);
const hasBeenOpenedRef = useRef(false); const loadedForTaskIdRef = useRef<string | null>(null);
const loadedAtRef = useRef<number>(0);
const seoCache = useRef<Map<string, { title: string; description: string; tags: string }>>(new Map());
const SEO_CACHE_TTL = 50 * 60 * 1000;
// Upload progress modal state // Upload progress modal state
const [showUploadProgress, setShowUploadProgress] = useState(false); const [showUploadProgress, setShowUploadProgress] = useState(false);
@@ -150,6 +152,8 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
// 업로드 정보 (모달이 닫힌 후에도 유지) // 업로드 정보 (모달이 닫힌 후에도 유지)
const [uploadVideoTitle, setUploadVideoTitle] = useState<string>(''); const [uploadVideoTitle, setUploadVideoTitle] = useState<string>('');
const [uploadChannelName, setUploadChannelName] = useState<string>(''); const [uploadChannelName, setUploadChannelName] = useState<string>('');
const [uploadIsScheduled, setUploadIsScheduled] = useState(false);
const [uploadScheduledAt, setUploadScheduledAt] = useState<string | null>(null);
// 드롭다운 외부 클릭 시 닫기 // 드롭다운 외부 클릭 시 닫기
useEffect(() => { useEffect(() => {
@@ -176,39 +180,43 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
return () => { document.body.style.overflow = ''; }; return () => { document.body.style.overflow = ''; };
}, [isOpen]); }, [isOpen]);
// 모달 오픈/닫힘 시 튜토리얼 트리거 // 소셜 계정 로드 + SEO 자동 채움
useEffect(() => { useEffect(() => {
if (isOpen) { if (!isOpen) {
hasBeenOpenedRef.current = true; loadedForTaskIdRef.current = null;
if (!tutorial.hasSeen(TUTORIAL_KEYS.UPLOAD_MODAL)) { return;
const timer = setTimeout(() => { }
tutorial.startTutorial(TUTORIAL_KEYS.UPLOAD_MODAL);
}, 400); loadSocialAccounts();
return () => clearTimeout(timer);
if (video?.title) {
setTitle(video.title);
setDescription(video.description || '');
setTags((video.hashtags || []).join(','));
setIsLoadingAutoDescription(false);
return;
}
const now = Date.now();
const seoKey =
video?.type === 'ssul'
? `ssul:${video.video_id}`
: video?.task_id || null;
const expired = now - loadedAtRef.current > SEO_CACHE_TTL;
if (seoKey && (seoKey !== loadedForTaskIdRef.current || expired)) {
loadedForTaskIdRef.current = seoKey;
loadedAtRef.current = now;
loadAutocomplete(seoKey);
} else if (seoKey) {
const cached = seoCache.current.get(seoKey);
if (cached) {
setTitle(cached.title);
setDescription(cached.description);
setTags(cached.tags);
} }
} else if (hasBeenOpenedRef.current && !tutorial.hasSeen(TUTORIAL_KEYS.FEEDBACK)) {
hasBeenOpenedRef.current = false;
tutorial.startTutorial(TUTORIAL_KEYS.FEEDBACK);
} }
}, [isOpen]); }, [isOpen, video?.task_id, video?.type, video?.video_id, video?.title, video?.description, video?.hashtags]);
// SEO 생성 완료 시 UPLOAD_FORM 튜토리얼 트리거
useEffect(() => {
if (!isLoadingAutoDescription && isOpen && !tutorial.hasSeen(TUTORIAL_KEYS.UPLOAD_FORM)) {
const timer = setTimeout(() => {
tutorial.startTutorial(TUTORIAL_KEYS.UPLOAD_FORM);
}, 400);
return () => clearTimeout(timer);
}
}, [isLoadingAutoDescription]);
// 소셜 계정 로드
useEffect(() => {
if (isOpen) {
loadSocialAccounts();
loadAutocomplete();
}
}, [isOpen, video]);
const loadSocialAccounts = async () => { const loadSocialAccounts = async () => {
setIsLoadingAccounts(true); setIsLoadingAccounts(true);
@@ -217,7 +225,9 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
const activeAccounts = response.accounts?.filter(acc => acc.is_active) || []; const activeAccounts = response.accounts?.filter(acc => acc.is_active) || [];
setSocialAccounts(activeAccounts); setSocialAccounts(activeAccounts);
if (activeAccounts.length > 0) { if (activeAccounts.length > 0) {
setSelectedChannel(activeAccounts[0].platform_user_id); const lastUsed = localStorage.getItem('lastUsedSocialChannel');
const defaultAccount = activeAccounts.find(acc => acc.platform_user_id === lastUsed) || activeAccounts[0];
setSelectedChannel(defaultAccount.platform_user_id);
} }
} catch (error) { } catch (error) {
if (error instanceof TokenExpiredError) { if (error instanceof TokenExpiredError) {
@@ -231,25 +241,36 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
} }
}; };
const loadAutocomplete = async () => { /**
if (!video?.task_id) return; * 제목·설명·태그 자동 채움.
*
* `seoKey` 는 호출부가 만든 캐시 키다(ADO2=task_id, 썰박스=`ssul:{id}`).
* 백엔드에 보낼 식별자는 종류마다 다르다 — ADO2 는 task_id(UUID), 썰박스는
* ssul_content.id 문자열이며, 서버가 content_type 으로 어느 테이블을 볼지 가른다.
*/
const loadAutocomplete = async (seoKey: string) => {
if (!video) return;
const isSsul = video.type === 'ssul';
if (!isSsul && !video.task_id) return;
setIsLoadingAutoDescription(true); setIsLoadingAutoDescription(true);
try { try {
const requestPayload = { const requestPayload = {
task_id : video.task_id, content_type: video.type,
task_id: isSsul ? String(video.video_id) : video.task_id,
}; };
// Call autoSEO API
console.log('[Upload] Request payload:', requestPayload);
const autoSeoResponse = await getAutoSeoYoutube(requestPayload); const autoSeoResponse = await getAutoSeoYoutube(requestPayload);
// 각 필드가 있을 때만 덮어씌움 (기존 값 보호)
if (autoSeoResponse.title) setTitle(autoSeoResponse.title); if (autoSeoResponse.title) setTitle(autoSeoResponse.title);
if (autoSeoResponse.description) setDescription(autoSeoResponse.description); if (autoSeoResponse.description) setDescription(autoSeoResponse.description);
if (autoSeoResponse.keywords) setTags(autoSeoResponse.keywords.join(',')); if (autoSeoResponse.keywords) setTags(autoSeoResponse.keywords.join(','));
seoCache.current.set(seoKey, {
title: autoSeoResponse.title || '',
description: autoSeoResponse.description || '',
tags: autoSeoResponse.keywords?.join(',') || '',
});
} catch (error) { } catch (error) {
console.error('Failed to load autocomplete:', error); console.error('Failed to load autocomplete:', error);
// 실패해도 사용자에게 별도 알림 없이 조용히 처리
} finally { } finally {
setIsLoadingAutoDescription(false); setIsLoadingAutoDescription(false);
} }
@@ -298,6 +319,7 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
// 업로드 정보 저장 (모달이 닫힌 후에도 유지) // 업로드 정보 저장 (모달이 닫힌 후에도 유지)
setUploadVideoTitle(title.trim()); setUploadVideoTitle(title.trim());
setUploadChannelName(selectedAcc.display_name); setUploadChannelName(selectedAcc.display_name);
setUploadIsScheduled(publishTime === 'schedule');
setShowUploadProgress(true); setShowUploadProgress(true);
try { try {
@@ -318,6 +340,9 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
} }
const requestPayload = { const requestPayload = {
// 종류를 함께 보낸다 — 없으면 백엔드가 video 로 간주해, 썰박스 항목에서는
// id 가 겹치는 엉뚱한 ADO2 영상이 업로드된다.
content_type: video.type,
video_id: video.video_id, video_id: video.video_id,
social_account_id: selectedAcc.id, social_account_id: selectedAcc.id,
title: title.trim(), title: title.trim(),
@@ -335,16 +360,19 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
throw new Error(uploadResponse.message || t('social.uploadStartFailed')); throw new Error(uploadResponse.message || t('social.uploadStartFailed'));
} }
localStorage.setItem('lastUsedSocialChannel', selectedAcc.platform_user_id);
if (publishTime === 'schedule') { if (publishTime === 'schedule') {
// 예약 업로드: 폴링 없이 바로 완료 처리 // 예약 업로드: 폴링 없이 바로 완료 처리
setUploadStatus('completed'); setUploadStatus('completed');
setUploadProgress(100); setUploadProgress(100);
setUploadScheduledAt(uploadResponse.scheduled_at ?? null);
onClose(); onClose();
resetForm(); resetForm();
} else { } else {
// 즉시 업로드: 완료될 때까지 폴링 // 즉시 업로드: 완료될 때까지 폴링
const result = await waitForUploadComplete( const result = await waitForUploadComplete(
uploadResponse.upload_id, uploadResponse.upload_id.toString(),
(status, progress) => { (status, progress) => {
setUploadStatus(status as UploadStatus); setUploadStatus(status as UploadStatus);
setUploadProgress(progress || 0); setUploadProgress(progress || 0);
@@ -397,6 +425,8 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
setUploadErrorMessage(undefined); setUploadErrorMessage(undefined);
setUploadVideoTitle(''); setUploadVideoTitle('');
setUploadChannelName(''); setUploadChannelName('');
setUploadIsScheduled(false);
setUploadScheduledAt(null);
}; };
const handleClose = () => { const handleClose = () => {
@@ -404,6 +434,8 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
resetForm(); resetForm();
}; };
const overlayCloseHandlers = useOverlayClose(handleClose);
const selectedAccount = socialAccounts.find(acc => acc.platform_user_id === selectedChannel); const selectedAccount = socialAccounts.find(acc => acc.platform_user_id === selectedChannel);
const privacyOptions = [ const privacyOptions = [
@@ -425,7 +457,9 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
channelName={uploadChannelName || selectedAccount?.display_name || ''} channelName={uploadChannelName || selectedAccount?.display_name || ''}
youtubeUrl={uploadYoutubeUrl} youtubeUrl={uploadYoutubeUrl}
errorMessage={uploadErrorMessage} errorMessage={uploadErrorMessage}
isScheduled={publishTime === 'schedule'} isScheduled={uploadIsScheduled}
scheduledAt={uploadScheduledAt}
onGoToCalendar={onGoToCalendar}
/> />
); );
@@ -433,23 +467,13 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
return ( return (
<> <>
{showUploadProgress && uploadProgressModalElement} {showUploadProgress && uploadProgressModalElement}
{tutorial.isActive && (
<TutorialOverlay
hints={tutorial.hints}
currentIndex={tutorial.currentHintIndex}
onNext={tutorial.nextHint}
onPrev={tutorial.prevHint}
onSkip={tutorial.skipTutorial}
groupProgress={tutorial.groupProgress}
/>
)}
</> </>
); );
} }
return ( return (
<> <>
<div className="social-posting-overlay" onClick={handleClose}> <div className="social-posting-overlay" {...overlayCloseHandlers}>
<div className="social-posting-modal" onClick={(e) => e.stopPropagation()}> <div className="social-posting-modal" onClick={(e) => e.stopPropagation()}>
{/* Header */} {/* Header */}
<div className="social-posting-header"> <div className="social-posting-header">
@@ -520,7 +544,7 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
onClick={() => setIsChannelDropdownOpen(!isChannelDropdownOpen)} onClick={() => setIsChannelDropdownOpen(!isChannelDropdownOpen)}
> >
<div className="social-posting-channel-selected"> <div className="social-posting-channel-selected">
{selectedAccount && ( {selectedAccount ? (
<> <>
<img <img
src={getPlatformIcon(selectedAccount.platform)} src={getPlatformIcon(selectedAccount.platform)}
@@ -529,6 +553,8 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
/> />
<span>{selectedAccount.display_name}</span> <span>{selectedAccount.display_name}</span>
</> </>
) : (
<span className="social-posting-channel-placeholder">{t('social.selectChannel')}</span>
)} )}
</div> </div>
<svg className="social-posting-channel-arrow" viewBox="0 0 12 8" fill="none"> <svg className="social-posting-channel-arrow" viewBox="0 0 12 8" fill="none">
@@ -817,16 +843,6 @@ const SocialPostingModal: React.FC<SocialPostingModalProps> = ({
</div> </div>
</div> </div>
{uploadProgressModalElement} {uploadProgressModalElement}
{tutorial.isActive && (
<TutorialOverlay
hints={tutorial.hints}
currentIndex={tutorial.currentHintIndex}
onNext={tutorial.nextHint}
onPrev={tutorial.prevHint}
onSkip={tutorial.skipTutorial}
groupProgress={tutorial.groupProgress}
/>
)}
</> </>
); );
}; };
-298
View File
@@ -1,298 +0,0 @@
import React, { useEffect, useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { TutorialHint } from './tutorialSteps';
interface Rect {
top: number;
left: number;
width: number;
height: number;
}
interface TooltipPos {
top: number;
left: number;
}
interface TutorialOverlayProps {
hints: TutorialHint[];
currentIndex: number;
onNext: () => void;
onPrev: () => void;
onSkip: () => void;
groupProgress?: { groupTotal: number; groupOffset: number; isLastKeyInGroup: boolean } | null;
}
const PADDING = 8;
function getTargetRect(selector: string): Rect | null {
const el = document.querySelector(selector);
if (!el) return null;
const r = el.getBoundingClientRect();
return { top: r.top, left: r.left, width: r.width, height: r.height };
}
function getSpotlightRect(
rect: Rect,
padding: number,
override?: { top?: number; right?: number; bottom?: number; left?: number }
): Rect {
const pTop = override?.top ?? padding;
const pRight = override?.right ?? padding;
const pBottom = override?.bottom ?? padding;
const pLeft = override?.left ?? padding;
const left = Math.max(0, Math.floor(rect.left - pLeft));
const top = Math.max(0, Math.floor(rect.top - pTop));
const right = Math.min(window.innerWidth, Math.ceil(rect.left + rect.width + pRight));
const bottom = Math.min(window.innerHeight, Math.ceil(rect.top + rect.height + pBottom));
return {
top,
left,
width: Math.max(0, right - left),
height: Math.max(0, bottom - top),
};
}
function calcTooltipPos(rect: Rect, position: TutorialHint['position'], tooltipW = 300, tooltipH = 160): TooltipPos {
switch (position) {
case 'bottom':
return {
top: Math.min(rect.top + rect.height + PADDING, window.innerHeight - tooltipH - 8),
left: Math.min(Math.max(rect.left + rect.width / 2 - tooltipW / 2, 8), window.innerWidth - tooltipW - 8),
};
case 'top':
return {
top: Math.max(rect.top - tooltipH - PADDING, 8),
left: Math.min(Math.max(rect.left + rect.width / 2 - tooltipW / 2, 8), window.innerWidth - tooltipW - 8),
};
case 'right':
return {
top: Math.min(Math.max(rect.top + rect.height / 2 - tooltipH / 2, 8), window.innerHeight - tooltipH - 8),
left: Math.min(rect.left + rect.width + PADDING, window.innerWidth - tooltipW - 8),
};
case 'left':
return {
top: Math.min(Math.max(rect.top + rect.height / 2 - tooltipH / 2, 8), window.innerHeight - tooltipH - 8),
left: Math.max(rect.left - tooltipW - PADDING, 8),
};
}
}
const TutorialOverlay: React.FC<TutorialOverlayProps> = ({
hints,
currentIndex,
onNext,
onPrev,
onSkip,
groupProgress,
}) => {
const { t } = useTranslation();
const [targetRect, setTargetRect] = useState<Rect | null>(null);
const tooltipRef = React.useRef<HTMLDivElement>(null);
const [tooltipSize, setTooltipSize] = useState({ w: 300, h: 160 });
const hint = hints[currentIndex];
const isLast = currentIndex === hints.length - 1;
// 그룹이 있으면 그룹의 마지막 키 + 마지막 힌트일 때만 완료, 그룹 없으면 기존대로
const isFinish = isLast && (groupProgress ? groupProgress.isLastKeyInGroup : true);
const updateRect = useCallback(() => {
if (!hint) return;
setTargetRect(getTargetRect(hint.targetSelector));
}, [hint]);
useEffect(() => {
updateRect();
window.addEventListener('resize', updateRect);
window.addEventListener('scroll', updateRect, true);
return () => {
window.removeEventListener('resize', updateRect);
window.removeEventListener('scroll', updateRect, true);
};
}, [updateRect]);
useEffect(() => {
if (!hint) return;
let retryTimer: number | undefined;
let rectTimer: number | undefined;
let cleanupTarget: (() => void) | undefined;
const bindToTarget = (el: HTMLElement) => {
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
rectTimer = window.setTimeout(updateRect, 200);
const shouldClickAdvance = hint.clickToAdvance !== false;
if (shouldClickAdvance) {
el.style.cursor = 'pointer';
el.addEventListener('click', onNext);
cleanupTarget = () => {
el.style.cursor = '';
el.removeEventListener('click', onNext);
};
} else {
cleanupTarget = () => {};
}
};
const tryBind = (): boolean => {
const el = document.querySelector(hint.targetSelector) as HTMLElement | null;
if (!el) return false;
bindToTarget(el);
return true;
};
if (!tryBind()) {
retryTimer = window.setInterval(() => {
if (tryBind() && retryTimer) {
window.clearInterval(retryTimer);
retryTimer = undefined;
}
}, 80);
}
return () => {
if (retryTimer) window.clearInterval(retryTimer);
if (rectTimer) window.clearTimeout(rectTimer);
cleanupTarget?.();
};
}, [hint, updateRect, onNext]);
// 툴팁 DOM 크기 측정 — 힌트가 바뀔 때만 재측정
useEffect(() => {
const el = tooltipRef.current;
if (!el) return;
const { offsetWidth, offsetHeight } = el;
if (offsetWidth && offsetHeight) {
setTooltipSize(prev =>
prev.w === offsetWidth && prev.h === offsetHeight
? prev
: { w: offsetWidth, h: offsetHeight }
);
}
}, [currentIndex, hints]);
if (!hint) return null;
const spotlightPadding = hint.spotlightPadding ?? PADDING;
const spotlightRect = (targetRect && !hint.noSpotlight) ? getSpotlightRect(targetRect, spotlightPadding, hint.spotlightPaddingOverride) : null;
// 툴팁은 spotlightRect 기준으로 배치해야 스포트라이트와 겹치지 않음
const tooltipPos: TooltipPos = (spotlightRect ?? targetRect)
? calcTooltipPos((spotlightRect ?? targetRect)!, hint.position, tooltipSize.w, tooltipSize.h)
: {
top: window.innerHeight / 2 - tooltipSize.h / 2,
left: window.innerWidth / 2 - tooltipSize.w / 2,
};
return (
<div className="tutorial-overlay-root">
{spotlightRect ? (
<>
<div
className="tutorial-overlay-blocker"
style={{ top: 0, left: 0, right: 0, height: spotlightRect.top }}
/>
<div
className="tutorial-overlay-blocker"
style={{
top: spotlightRect.top,
left: 0,
width: spotlightRect.left,
height: spotlightRect.height,
}}
/>
<div
className="tutorial-overlay-blocker"
style={{
top: spotlightRect.top,
left: spotlightRect.left + spotlightRect.width,
right: 0,
height: spotlightRect.height,
}}
/>
<div
className="tutorial-overlay-blocker"
style={{
top: spotlightRect.top + spotlightRect.height,
left: 0,
right: 0,
bottom: 0,
}}
/>
<div
className="tutorial-spotlight-ring"
style={{
top: spotlightRect.top,
left: spotlightRect.left,
width: spotlightRect.width,
height: spotlightRect.height,
}}
/>
</>
) : null}
<div
ref={tooltipRef}
className={`tutorial-tooltip${hint.variant === 'bubble' ? ` tutorial-tooltip-bubble tutorial-tooltip-bubble--${hint.position}` : ''}`}
style={{ top: tooltipPos.top, left: tooltipPos.left }}
onClick={(e) => e.stopPropagation()}
>
<p className="tutorial-tooltip-title">{t(hint.titleKey)}</p>
<p className="tutorial-tooltip-desc">{t(hint.descriptionKey)}</p>
{hint.noteKey && (
<p className="tutorial-tooltip-note">{t(hint.noteKey)}</p>
)}
<div className="tutorial-tooltip-footer">
<span className="tutorial-tooltip-counter">
{groupProgress ? groupProgress.groupOffset + 1 : currentIndex + 1} / {groupProgress ? groupProgress.groupTotal : hints.length}
</span>
<div className="tutorial-tooltip-actions">
<button className="tutorial-btn-skip" onClick={onSkip}>
{t('tutorial.skip')}
</button>
{currentIndex > 0 && (
<button className="tutorial-btn-prev" onClick={onPrev}>
{t('tutorial.prev')}
</button>
)}
{(hint.clickToAdvance !== true || isFinish) && (
<button className="tutorial-btn-next" onClick={onNext}>
{isFinish ? t('tutorial.finish') : t('tutorial.next')}
</button>
)}
</div>
</div>
</div>
</div>
);
};
export default TutorialOverlay;
interface TutorialRestartPopupProps {
onConfirm: () => void;
onCancel: () => void;
}
export const TutorialRestartPopup: React.FC<TutorialRestartPopupProps> = ({ onConfirm, onCancel }) => {
const { t } = useTranslation();
return (
<div className="tutorial-restart-backdrop">
<div className="tutorial-restart-popup" onClick={(e) => e.stopPropagation()}>
<p className="tutorial-restart-title">{t('tutorial.restart.title')}</p>
<p className="tutorial-restart-desc">{t('tutorial.restart.desc')}</p>
<div className="tutorial-restart-actions">
<button className="tutorial-restart-cancel" onClick={onCancel}>
{t('tutorial.restart.cancel')}
</button>
<button className="tutorial-restart-confirm" onClick={onConfirm}>
{t('tutorial.restart.confirm')}
</button>
</div>
</div>
</div>
);
};
-425
View File
@@ -1,425 +0,0 @@
export interface TutorialHint {
targetSelector: string;
titleKey: string;
descriptionKey: string;
position: 'top' | 'bottom' | 'left' | 'right';
noteKey?: string;
variant?: 'bubble';
clickToAdvance?: boolean;
advanceSelector?: string;
noSpotlight?: boolean;
spotlightPadding?: number;
spotlightPaddingOverride?: { top?: number; right?: number; bottom?: number; left?: number };
}
export interface TutorialStepDef {
key: string;
hints: TutorialHint[];
}
export const TUTORIAL_KEYS = {
LANDING: 'landing',
ANALYSIS: 'analysis',
ASSET: 'asset',
SOUND: 'sound',
SOUND_LYRICS: 'soundLyrics',
SOUND_AUDIO: 'soundAudio',
GENERATING:'generating',
COMPLETION: 'completion',
MY_INFO: 'myInfo',
ADO2_CONTENTS: 'ado2Contents',
UPLOAD_MODAL: 'uploadModal',
UPLOAD_FORM: 'uploadForm',
DASHBOARD: 'dashboard',
CONTENT_CALENDAR: 'contentCalendar',
FEEDBACK: 'feedback',
} as const;
// 같은 페이지에 속하는 튜토리얼 키 그룹 — 진행 카운터를 합산해서 표시
export const TUTORIAL_PAGE_GROUPS: string[][] = [
[TUTORIAL_KEYS.SOUND, TUTORIAL_KEYS.SOUND_LYRICS, TUTORIAL_KEYS.SOUND_AUDIO],
[TUTORIAL_KEYS.GENERATING, TUTORIAL_KEYS.COMPLETION],
[TUTORIAL_KEYS.UPLOAD_MODAL, TUTORIAL_KEYS.UPLOAD_FORM],
];
export const tutorialSteps: TutorialStepDef[] = [
{
key: TUTORIAL_KEYS.LANDING,
hints: [
// {
// targetSelector: '.tutorial-center-anchor',
// titleKey: 'tutorial.landing.intro.title',
// descriptionKey: 'tutorial.landing.intro.desc',
// position: 'bottom',
// clickToAdvance: false,
// noSpotlight: true,
// },
{
targetSelector: '.hero-dropdown-trigger',
titleKey: 'tutorial.landing.dropdown.title',
descriptionKey: 'tutorial.landing.dropdown.desc',
position: 'left',
clickToAdvance: false,
noSpotlight: true,
variant: 'bubble',
},
{
targetSelector: '.hero-input-wrapper',
titleKey: 'tutorial.landing.field.title',
descriptionKey: 'tutorial.landing.field.desc',
position: 'right',
clickToAdvance: false,
noSpotlight: true,
variant: 'bubble',
},
{
targetSelector: '.hero-button',
titleKey: 'tutorial.landing.button.title',
descriptionKey: 'tutorial.landing.button.desc',
position: 'right',
clickToAdvance: false,
noSpotlight: true,
variant: 'bubble',
},
],
},
// {
// key: TUTORIAL_KEYS.ANALYSIS,
// hints: [
// {
// targetSelector: '.bi2-identity-card',
// titleKey: 'tutorial.analysis.identity.title',
// descriptionKey: 'tutorial.analysis.identity.desc',
// position: 'top',
// clickToAdvance: false,
// },
// {
// targetSelector: '.bi2-selling-card',
// titleKey: 'tutorial.analysis.selling.title',
// descriptionKey: 'tutorial.analysis.selling.desc',
// position: 'top',
// clickToAdvance: false,
// },
// {
// targetSelector: '.bi2-persona-grid',
// titleKey: 'tutorial.analysis.persona.title',
// descriptionKey: 'tutorial.analysis.persona.desc',
// position: 'top',
// clickToAdvance: false,
// },
// {
// targetSelector: '.bi2-keyword-tags',
// titleKey: 'tutorial.analysis.keywords.title',
// descriptionKey: 'tutorial.analysis.keywords.desc',
// position: 'top',
// clickToAdvance: false,
// },
// {
// targetSelector: '.bi2-generate-btn',
// titleKey: 'tutorial.analysis.generate.title',
// descriptionKey: 'tutorial.analysis.generate.desc',
// position: 'right',
// clickToAdvance: true,
// },
// ],
// },
{
key: TUTORIAL_KEYS.ASSET,
hints: [
{
targetSelector: '.asset-column.asset-column-left',
titleKey: 'tutorial.asset.image.title',
descriptionKey: 'tutorial.asset.image.desc',
position: 'left',
clickToAdvance: false,
},
{
targetSelector: '.asset-upload-zone',
titleKey: 'tutorial.asset.upload.title',
descriptionKey: 'tutorial.asset.upload.desc',
position: 'left',
clickToAdvance: false,
},
{
targetSelector: '.asset-ratio-section',
titleKey: 'tutorial.asset.ratio.title',
descriptionKey: 'tutorial.asset.ratio.desc',
position: 'left',
clickToAdvance: false,
},
{
targetSelector: '.asset-next-button',
titleKey: 'tutorial.asset.next.title',
descriptionKey: 'tutorial.asset.next.desc',
position: 'top',
clickToAdvance: true,
},
],
},
{
key: TUTORIAL_KEYS.SOUND,
hints: [
{
targetSelector: '.genre-grid',
titleKey: 'tutorial.sound.genre.title',
descriptionKey: 'tutorial.sound.genre.desc',
position: 'top',
clickToAdvance: false,
},
{
targetSelector: '.language-selector-wrapper',
titleKey: 'tutorial.sound.language.title',
descriptionKey: 'tutorial.sound.language.desc',
position: 'top',
clickToAdvance: false,
},
{
targetSelector: '.btn-generate-sound',
titleKey: 'tutorial.sound.generate.title',
descriptionKey: 'tutorial.sound.generate.desc',
position: 'right',
clickToAdvance: true,
},
],
},
{
key: TUTORIAL_KEYS.SOUND_LYRICS,
hints: [
{
targetSelector: '.lyrics-display',
titleKey: 'tutorial.sound.lyrics.title',
descriptionKey: 'tutorial.sound.lyrics.desc',
position: 'left',
clickToAdvance: false,
},
{
targetSelector: '.status-message-new',
titleKey: 'tutorial.sound.lyricsWait.title',
descriptionKey: 'tutorial.sound.lyricsWait.desc',
position: 'right',
clickToAdvance: false,
},
],
},
{
key: TUTORIAL_KEYS.SOUND_AUDIO,
hints: [
{
targetSelector: '.audio-player',
titleKey: 'tutorial.sound.audioPlayer.title',
descriptionKey: 'tutorial.sound.audioPlayer.desc',
position: 'left',
clickToAdvance: false,
},
{
targetSelector: '.btn-video-generate',
titleKey: 'tutorial.sound.video.title',
descriptionKey: 'tutorial.sound.video.desc',
position: 'top',
clickToAdvance: true,
},
],
},
{
key: TUTORIAL_KEYS.MY_INFO,
hints: [
{
targetSelector: '.youtube-connect-section',
titleKey: 'tutorial.myInfo.myInfo.title',
descriptionKey: 'tutorial.myInfo.myInfo.desc',
position: 'top',
clickToAdvance: false,
},
{
targetSelector: '.myinfo-social-btn',
titleKey: 'tutorial.myInfo.connect.title',
descriptionKey: 'tutorial.myInfo.connect.desc',
noteKey: 'tutorial.myInfo.connect.note',
position: 'top',
clickToAdvance: true,
},
{
targetSelector: '.myinfo-connected-accounts',
titleKey: 'tutorial.myInfo.connected.title',
descriptionKey: 'tutorial.myInfo.connected.desc',
position: 'top',
clickToAdvance: false,
},
{
targetSelector: '#sidebar-ado2-contents',
titleKey: 'tutorial.myInfo.ado2.title',
descriptionKey: 'tutorial.myInfo.ado2.desc',
position: 'right',
clickToAdvance: true,
},
],
},
{
key: TUTORIAL_KEYS.ADO2_CONTENTS,
hints: [
{
targetSelector: '.ado2-content-card',
titleKey: 'tutorial.ado2.list.title',
descriptionKey: 'tutorial.ado2.list.desc',
position: 'right',
clickToAdvance: false,
},
{
targetSelector: '.content-upload-btn',
titleKey: 'tutorial.ado2.download.title',
descriptionKey: 'tutorial.ado2.download.desc',
position: 'right',
clickToAdvance: false,
},
{
targetSelector: '.content-delete-btn',
titleKey: 'tutorial.ado2.delete.title',
descriptionKey: 'tutorial.ado2.delete.desc',
position: 'right',
clickToAdvance: false,
},
{
targetSelector: '.content-download-btn',
titleKey: 'tutorial.ado2.upload.title',
descriptionKey: 'tutorial.ado2.upload.desc',
position: 'right',
clickToAdvance: true,
},
],
},
{
key: TUTORIAL_KEYS.GENERATING,
hints:[
{
targetSelector: '.comp2-info-section',
titleKey: 'tutorial.completion.contentInfo.title',
descriptionKey: 'tutorial.completion.contentInfo.desc',
position: 'left',
},
{
targetSelector: '.comp2-video-section',
titleKey: 'tutorial.completion.generating.title',
descriptionKey: 'tutorial.completion.generating.desc',
position: 'right',
}
]
},
{
key: TUTORIAL_KEYS.COMPLETION,
hints: [
{
targetSelector: '.comp2-video-section',
titleKey: 'tutorial.completion.completion.title',
descriptionKey: 'tutorial.completion.completion.desc',
position: 'right',
clickToAdvance: false,
},
{
targetSelector: '#sidebar-my-info',
titleKey: 'tutorial.completion.myInfo.title',
descriptionKey: 'tutorial.completion.myInfo.desc',
position: 'right',
clickToAdvance: true,
},
],
},
{
key: TUTORIAL_KEYS.UPLOAD_MODAL,
hints: [
{
targetSelector: '.social-posting-content',
titleKey: 'tutorial.upload.seo.title',
descriptionKey: 'tutorial.upload.seo.desc',
position: 'right',
clickToAdvance: false,
},
],
},
{
key: TUTORIAL_KEYS.UPLOAD_FORM,
hints: [
{
targetSelector: '.social-posting-form',
titleKey: 'tutorial.upload.required.title',
descriptionKey: 'tutorial.upload.required.desc',
position: 'left',
clickToAdvance: false,
},
{
targetSelector: '.social-posting-radio-group',
titleKey: 'tutorial.upload.schedule.title',
descriptionKey: 'tutorial.upload.schedule.desc',
position: 'left',
clickToAdvance: false,
},
{
targetSelector: '.social-posting-btn:not(.cancel)',
titleKey: 'tutorial.upload.submit.title',
descriptionKey: 'tutorial.upload.submit.desc',
position: 'top',
clickToAdvance: true,
},
],
},
{
key: TUTORIAL_KEYS.DASHBOARD,
hints: [
{
targetSelector: '.stats-grid-8',
titleKey: 'tutorial.dashboard.metrics.title',
descriptionKey: 'tutorial.dashboard.metrics.desc',
position: 'bottom',
},
{
targetSelector: '.yoy-chart-card',
titleKey: 'tutorial.dashboard.chart.title',
descriptionKey: 'tutorial.dashboard.chart.desc',
position: 'right',
},
{
targetSelector: '.tutorial-center-anchor',
titleKey: 'tutorial.dashboard.more.title',
descriptionKey: 'tutorial.dashboard.more.desc',
position: 'bottom',
clickToAdvance: false,
},
],
},
{
key: TUTORIAL_KEYS.CONTENT_CALENDAR,
hints: [
{
targetSelector: '.calendar-grid-area',
titleKey: 'tutorial.contentCalendar.grid.title',
descriptionKey: 'tutorial.contentCalendar.grid.desc',
position: 'top',
clickToAdvance: true,
},
{
targetSelector: '.calendar-side-panel',
titleKey: 'tutorial.contentCalendar.panel.title',
descriptionKey: 'tutorial.contentCalendar.panel.desc',
position: 'left',
clickToAdvance: false,
},
],
},
{
key: TUTORIAL_KEYS.FEEDBACK,
hints: [
{
targetSelector: '.tutorial-center-anchor',
titleKey: 'tutorial.feedback.complete.title',
descriptionKey: 'tutorial.feedback.complete.desc',
position: 'bottom',
clickToAdvance: false,
},
{
targetSelector: '.sidebar-inquiry-btn',
titleKey: 'tutorial.feedback.title',
descriptionKey: 'tutorial.feedback.desc',
position: 'right',
},
],
},
];
-185
View File
@@ -1,185 +0,0 @@
import React, { useState, useCallback } from 'react';
import { tutorialSteps, TutorialHint, TUTORIAL_PAGE_GROUPS } from './tutorialSteps';
// 현재 키가 속한 그룹의 전체 힌트 수와 현재까지의 offset 반환
function getGroupProgress(key: string, currentIndex: number): { groupTotal: number; groupOffset: number; isLastKeyInGroup: boolean } | null {
const group = TUTORIAL_PAGE_GROUPS.find(g => g.includes(key));
if (!group) return null;
let offset = 0;
let total = 0;
for (const k of group) {
const step = tutorialSteps.find(s => s.key === k);
const count = step?.hints.length ?? 0;
if (k === key) offset = total;
total += count;
}
const isLastKeyInGroup = group[group.length - 1] === key;
return { groupTotal: total, groupOffset: offset + currentIndex, isLastKeyInGroup };
}
const SEEN_KEY = 'ado2_tutorial_seen';
const PROGRESS_KEY = 'ado2_tutorial_progress';
// 전역 단일 활성 튜토리얼 관리 — 새 튜토리얼 시작 시 이전 것을 skip 처리
let globalSkip: (() => void) | null = null;
function getSeenKeys(): string[] {
try {
return JSON.parse(localStorage.getItem(SEEN_KEY) || '[]');
} catch {
return [];
}
}
function markSeen(key: string) {
const seen = getSeenKeys();
if (!seen.includes(key)) {
localStorage.setItem(SEEN_KEY, JSON.stringify([...seen, key]));
}
clearProgress(key);
}
function saveProgress(key: string, index: number) {
try {
const progress = JSON.parse(localStorage.getItem(PROGRESS_KEY) || '{}');
progress[key] = index;
localStorage.setItem(PROGRESS_KEY, JSON.stringify(progress));
} catch {}
}
function loadProgress(key: string): number {
try {
const progress = JSON.parse(localStorage.getItem(PROGRESS_KEY) || '{}');
return progress[key] ?? 0;
} catch {
return 0;
}
}
function clearProgress(key: string) {
try {
const progress = JSON.parse(localStorage.getItem(PROGRESS_KEY) || '{}');
delete progress[key];
localStorage.setItem(PROGRESS_KEY, JSON.stringify(progress));
} catch {}
}
interface UseTutorialReturn {
isActive: boolean;
isRestartPopupVisible: boolean;
currentHintIndex: number;
hints: TutorialHint[];
tutorialKey: string | null;
groupProgress: { groupTotal: number; groupOffset: number; isLastKeyInGroup: boolean } | null;
startTutorial: (key: string, onComplete?: () => void, forceFromStart?: boolean) => void;
nextHint: () => void;
prevHint: () => void;
skipTutorial: () => void;
showRestartPopup: (key: string) => void;
confirmRestart: () => void;
cancelRestart: () => void;
hasSeen: (key: string) => boolean;
}
export function useTutorial(): UseTutorialReturn {
const [isActive, setIsActive] = useState(false);
const [isRestartPopupVisible, setIsRestartPopupVisible] = useState(false);
const [pendingRestartKey, setPendingRestartKey] = useState<string | null>(null);
const [currentHintIndex, setCurrentHintIndex] = useState(0);
const [hints, setHints] = useState<TutorialHint[]>([]);
const [tutorialKey, setTutorialKey] = useState<string | null>(null);
const onCompleteRef = React.useRef<(() => void) | undefined>(undefined);
const startTutorial = useCallback((key: string, onComplete?: () => void, forceFromStart?: boolean) => {
const step = tutorialSteps.find(s => s.key === key);
if (!step || step.hints.length === 0) return;
// 다른 인스턴스에서 활성화된 튜토리얼이 있으면 skip 처리
globalSkip?.();
const savedIndex = forceFromStart ? 0 : loadProgress(key);
const resumeIndex = savedIndex < step.hints.length ? savedIndex : 0;
onCompleteRef.current = onComplete;
setHints(step.hints);
setTutorialKey(key);
setCurrentHintIndex(resumeIndex);
setIsActive(true);
// 이 인스턴스의 skip을 전역에 등록
globalSkip = () => {
if (key) saveProgress(key, resumeIndex);
setIsActive(false);
setCurrentHintIndex(0);
globalSkip = null;
};
}, []);
const nextHint = useCallback(() => {
setCurrentHintIndex(prev => {
if (prev < hints.length - 1) {
const next = prev + 1;
if (tutorialKey) saveProgress(tutorialKey, next);
return next;
}
// 마지막 힌트 완료 → seen 기록 + 진행 상태 삭제
setIsActive(false);
if (tutorialKey) markSeen(tutorialKey);
globalSkip = null; // 완료된 튜토리얼은 globalSkip 해제
onCompleteRef.current?.();
onCompleteRef.current = undefined;
return 0;
});
}, [hints.length, tutorialKey]);
const prevHint = useCallback(() => {
setCurrentHintIndex(prev => Math.max(0, prev - 1));
}, []);
// 건너뛰기: 현재 진행 인덱스 저장 후 오버레이 닫기 → 다음 방문 시 이어서 표시
const skipTutorial = useCallback(() => {
if (tutorialKey) saveProgress(tutorialKey, currentHintIndex);
setIsActive(false);
setCurrentHintIndex(0);
}, [tutorialKey, currentHintIndex]);
// 튜토리얼 다시 보기: 팝업 표시만
const showRestartPopup = useCallback((key: string) => {
setPendingRestartKey(key);
setIsRestartPopupVisible(true);
}, []);
// 팝업에서 확인 → seen/progress 초기화 후 튜토리얼 시작
const confirmRestart = useCallback(() => {
setIsRestartPopupVisible(false);
if (pendingRestartKey) {
localStorage.removeItem(SEEN_KEY);
localStorage.removeItem(PROGRESS_KEY);
startTutorial(pendingRestartKey, undefined, true);
}
setPendingRestartKey(null);
}, [pendingRestartKey, startTutorial]);
// 팝업에서 취소
const cancelRestart = useCallback(() => {
setIsRestartPopupVisible(false);
setPendingRestartKey(null);
}, []);
const hasSeen = useCallback((key: string) => {
return getSeenKeys().includes(key);
}, []);
return {
isActive,
isRestartPopupVisible,
currentHintIndex,
hints,
tutorialKey,
groupProgress: tutorialKey ? getGroupProgress(tutorialKey, currentHintIndex) : null,
startTutorial,
nextHint,
prevHint,
skipTutorial,
showRestartPopup,
confirmRestart,
cancelRestart,
hasSeen,
};
}
+36 -3
View File
@@ -14,6 +14,8 @@ interface UploadProgressModalProps {
youtubeUrl?: string; youtubeUrl?: string;
errorMessage?: string; errorMessage?: string;
isScheduled?: boolean; isScheduled?: boolean;
scheduledAt?: string | null;
onGoToCalendar?: () => void;
} }
const UploadProgressModal: React.FC<UploadProgressModalProps> = ({ const UploadProgressModal: React.FC<UploadProgressModalProps> = ({
@@ -26,6 +28,8 @@ const UploadProgressModal: React.FC<UploadProgressModalProps> = ({
youtubeUrl, youtubeUrl,
errorMessage, errorMessage,
isScheduled = false, isScheduled = false,
scheduledAt,
onGoToCalendar,
}) => { }) => {
const { t } = useTranslation(); const { t } = useTranslation();
if (!isOpen) return null; if (!isOpen) return null;
@@ -146,14 +150,43 @@ const UploadProgressModal: React.FC<UploadProgressModalProps> = ({
{t('upload.viewOnYoutube')} {t('upload.viewOnYoutube')}
</a> </a>
)} )}
{/* Scheduled conflict notice */}
{status === 'completed' && isScheduled && scheduledAt && (
<div className="upload-progress-schedule-notice">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="12" cy="12" r="10" />
<line x1="12" y1="8" x2="12" y2="12" />
<line x1="12" y1="16" x2="12.01" y2="16" />
</svg>
<span>
{t('upload.scheduleConflict', {
time: new Date(scheduledAt).toLocaleString('ko-KR', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}),
})}
</span>
</div>
)}
</div> </div>
{/* Footer */} {/* Footer */}
<div className="upload-progress-footer"> <div className="upload-progress-footer">
{canClose ? ( {canClose ? (
<button className="upload-progress-btn primary" onClick={onClose}> <>
{status === 'completed' ? t('upload.confirm') : t('upload.close')} <button className="upload-progress-btn primary" onClick={onClose}>
</button> {status === 'completed' ? t('upload.confirm') : t('upload.close')}
</button>
{status === 'completed' && onGoToCalendar && (
<span className="upload-progress-calendar-link" onClick={() => { onClose(); onGoToCalendar(); }}>
{t('upload.goToCalendar')}
</span>
)}
</>
) : ( ) : (
<p className="upload-progress-note">{t('upload.doNotClose')}</p> <p className="upload-progress-note">{t('upload.doNotClose')}</p>
)} )}
+449
View File
@@ -0,0 +1,449 @@
import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import {
getVideoById,
getVideoComments,
postVideoComment,
deleteComment,
toggleVideoLike,
isLoggedIn,
getUserMe,
API_URL,
} from '../utils/api';
import { VideoDetailItem, CommentItem, UserMeResponse } from '../types/api';
import { buildVideoShareUrl, tryNativeShare } from '../utils/nativeShare';
import LoginPromptModal from './LoginPromptModal';
import { isSafeHttpUrl } from '../utils/url';
interface VideoDetailContentProps {
videoId: string;
isModal?: boolean;
onClose?: () => void;
}
const VideoDetailContent: React.FC<VideoDetailContentProps> = ({ videoId, isModal = false, onClose }) => {
const { t } = useTranslation();
const authed = isLoggedIn();
const [video, setVideo] = useState<VideoDetailItem | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [likeCount, setLikeCount] = useState(0);
const [isLiked, setIsLiked] = useState(false);
const [copied, setCopied] = useState(false);
const [isLandscape, setIsLandscape] = useState(false);
const [showSiteOverlay, setShowSiteOverlay] = useState(false);
const [showLoginModal, setShowLoginModal] = useState(false);
const [comments, setComments] = useState<CommentItem[]>([]);
const [commentsTotal, setCommentsTotal] = useState(0);
const [commentsPage, setCommentsPage] = useState(1);
const [commentsHasNext, setCommentsHasNext] = useState(false);
const [commentsLoading, setCommentsLoading] = useState(false);
const [commentInput, setCommentInput] = useState('');
const [commentSubmitting, setCommentSubmitting] = useState(false);
const commentTextareaRef = useRef<HTMLTextAreaElement>(null);
const [currentUser, setCurrentUser] = useState<UserMeResponse | null>(null);
const fetchComments = useCallback(async (page: number, append = false) => {
setCommentsLoading(true);
try {
const res = await getVideoComments(videoId, page, 20);
const sorted = [...res.items].sort(
(a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
);
setComments(prev => append ? [...prev, ...sorted] : sorted);
setCommentsTotal(res.total);
setCommentsHasNext(res.has_next);
setCommentsPage(page);
} catch (err) {
console.error('Failed to fetch comments:', err);
} finally {
setCommentsLoading(false);
}
}, [videoId]);
useEffect(() => {
const fetchVideo = async () => {
setLoading(true);
setError(null);
setShowSiteOverlay(false);
try {
const data = await getVideoById(videoId);
setVideo(data);
setLikeCount(data.like_count);
setIsLiked(data.is_liked_by_me);
} catch (err) {
console.error('Failed to fetch video:', err);
setError(t('ado2Contents.loadFailed'));
} finally {
setLoading(false);
}
};
fetchVideo();
fetchComments(1);
}, [videoId, fetchComments]);
useEffect(() => {
if (!authed) return;
getUserMe().then(setCurrentUser).catch((err) => {
console.error('Failed to fetch current user:', err);
});
}, [authed]);
const formatDate = (dateString: string) => {
const date = new Date(dateString);
return t('videoDetail.dateFormat', { year: date.getFullYear(), month: date.getMonth() + 1, day: date.getDate() });
};
const formatCommentDate = (dateString: string) => {
const date = new Date(dateString);
return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(date.getDate()).padStart(2, '0')}`;
};
const shareUrl = buildVideoShareUrl(API_URL, videoId);
const shareTitle = video?.title || video?.store_name || t('videoDetail.kakaoDefaultTitle');
const handleCopyLink = async () => {
try {
await navigator.clipboard.writeText(shareUrl);
} catch {
// clipboard API 미지원 환경에서는 무시
}
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const handleShareButtonClick = async () => {
const handled = await tryNativeShare({
title: shareTitle,
url: shareUrl,
});
if (handled) {
return;
}
await handleCopyLink();
};
const likeDebounceRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
const handleLike = () => {
if (!authed) { setShowLoginModal(true); return; }
// 1. UI 즉시 업데이트 (Optimistic)
setIsLiked(prev => !prev);
setLikeCount(prev => isLiked ? prev - 1 : prev + 1);
// 2. 기존 debounce 타이머 취소 후 재설정
if (likeDebounceRef.current) clearTimeout(likeDebounceRef.current);
likeDebounceRef.current = setTimeout(async () => {
const prevLiked = isLiked;
const prevCount = likeCount;
try {
await toggleVideoLike(videoId);
} catch (err) {
// 3. 실패 시 롤백
console.error('Failed to toggle like:', err);
setIsLiked(prevLiked);
setLikeCount(prevCount);
}
}, 500);
};
const handleHeaderAction = () => {
if (!isModal && !authed) { setShowLoginModal(true); return; }
onClose?.();
};
const handleCommentFocus = () => {
if (!authed) setShowLoginModal(true);
};
const handleCommentSubmit = async () => {
if (!authed) { setShowLoginModal(true); return; }
if (!commentInput.trim() || commentSubmitting) return;
setCommentSubmitting(true);
try {
await postVideoComment(videoId, commentInput.trim());
setCommentInput('');
if (commentTextareaRef.current) {
commentTextareaRef.current.style.height = 'auto';
}
await fetchComments(1);
} catch (err) {
console.error('Failed to post comment:', err);
} finally {
setCommentSubmitting(false);
}
};
const handleDeleteComment = async (commentId: number) => {
try {
await deleteComment(commentId);
await fetchComments(commentsPage);
} catch (err) {
console.error('Failed to delete comment:', err);
}
};
const renderCommentContent = (content: string | null, isDeleted: boolean) => {
if (isDeleted) return <span style={{ color: '#6B9EA0', fontStyle: 'italic' }}>{t('videoDetail.deletedComment')}</span>;
return content;
};
return (
<div className={isModal ? 'video-detail-modal-content' : 'video-detail-page-content'}>
{/* 헤더 */}
<div className="video-detail-header">
{isModal ? (
<>
<h2 className="video-detail-modal-title">{t('sidebar.ado2Contents')}</h2>
<button className="video-detail-close-btn" onClick={handleHeaderAction} aria-label={t('videoDetail.closeAriaLabel')}>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
</svg>
</button>
</>
) : (
<button className="video-detail-back-btn" onClick={handleHeaderAction}>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5">
<path d="M13 4l-6 6 6 6"/>
</svg>
{t('sidebar.ado2Contents')}
</button>
)}
</div>
<div className="video-detail-body">
{loading ? (
<div className="ado2-contents-loading">
<div className="loading-spinner"></div>
<p>{t('ado2Contents.loading')}</p>
</div>
) : error ? (
<div className="ado2-contents-error"><p>{error}</p></div>
) : video ? (
<div className={`video-detail-content ${isLandscape ? 'landscape' : ''}`}>
<div className="video-detail-player-wrap">
<video
src={video.result_movie_url}
controls
autoPlay
playsInline
controlsList="nodownload"
onContextMenu={(e) => e.preventDefault()}
className="video-detail-player"
onLoadedMetadata={(e) => {
const v = e.currentTarget;
setIsLandscape(v.videoWidth > v.videoHeight);
}}
onTimeUpdate={(e) => {
if (!video.official_site_url) return;
const v = e.currentTarget;
// 영상 종료 3초 전부터 공식 홈페이지 오버레이 노출
setShowSiteOverlay(
Number.isFinite(v.duration) && v.duration - v.currentTime <= 3
);
}}
/>
{showSiteOverlay && isSafeHttpUrl(video.official_site_url) && (
<a
href={video.official_site_url as string}
target="_blank"
rel="noopener noreferrer"
className="video-site-overlay"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="12" cy="12" r="10"/>
<line x1="2" y1="12" x2="22" y2="12"/>
<path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
</svg>
<span className="video-site-overlay-text">
<strong>{video.store_name}</strong>
{t('videoDetail.siteOverlayLabel')}
</span>
</a>
)}
</div>
<div className="video-detail-info">
<h2 className="video-detail-store">{video.store_name}</h2>
<p className="video-detail-date">{formatDate(video.created_at)}</p>
{/* 좋아요 + 링크 복사 */}
<div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
<button
className={`video-detail-like-btn ${isLiked ? 'liked' : ''}`}
onClick={handleLike}
disabled={false}
>
<svg width="16" height="16" viewBox="0 0 24 24" fill={isLiked ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="2">
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/>
</svg>
{likeCount}
</button>
<button
className="video-detail-copy-btn"
onClick={handleShareButtonClick}
title={t('videoDetail.share')}
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="18" cy="5" r="3"/><circle cx="6" cy="12" r="3"/><circle cx="18" cy="19" r="3"/>
<line x1="8.59" y1="13.51" x2="15.42" y2="17.49"/><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"/>
</svg>
{copied ? t('videoDetail.copied') : t('videoDetail.share')}
</button>
</div>
{/* 댓글 섹션 */}
<div className="video-detail-comments">
<div className="video-detail-comments-header">
<h3 className="video-detail-comments-title">{t('videoDetail.commentsTitle')}</h3>
<span className="video-detail-comments-count">{commentsTotal}</span>
</div>
{/* 댓글 작성자 프로필 (카카오 로그인 정보) */}
{authed && currentUser && (
<div className="video-detail-comment-profile">
{currentUser.profile_image_url && (
<img
src={currentUser.profile_image_url}
alt={currentUser.nickname}
className="video-detail-comment-avatar"
/>
)}
<span className="video-detail-comment-nickname">{currentUser.nickname}</span>
</div>
)}
<div className="video-detail-comment-input-wrap">
<textarea
ref={commentTextareaRef}
className="video-detail-comment-input"
placeholder={authed ? t('videoDetail.commentPlaceholder') : t('videoDetail.commentLoginRequired')}
maxLength={500}
rows={1}
value={commentInput}
onChange={(e) => {
setCommentInput(e.target.value);
e.target.style.height = 'auto';
e.target.style.height = `${e.target.scrollHeight}px`;
}}
onFocus={handleCommentFocus}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleCommentSubmit();
}
}}
disabled={!authed}
/>
<button
className="video-detail-comment-submit"
onClick={handleCommentSubmit}
disabled={!authed || !commentInput.trim() || commentSubmitting}
>
{commentSubmitting ? t('videoDetail.commentSubmitting') : t('videoDetail.commentSubmit')}
</button>
</div>
{comments.length === 0 && !commentsLoading ? (
<p className="video-detail-comments-empty">{t('videoDetail.noComments')}</p>
) : (
<ul className="video-detail-comment-list">
{comments.map((c) => (
<li key={c.id} className="video-detail-comment-item">
{c.profile_image_url && (
<img
src={c.profile_image_url}
alt={c.nickname || t('videoDetail.anonymous')}
className="video-detail-comment-avatar"
/>
)}
<div className="video-detail-comment-body">
<span className="video-detail-comment-nickname">
{c.nickname || t('videoDetail.anonymous')}
</span>
<p className="video-detail-comment-text">
{renderCommentContent(c.content, c.is_deleted)}
</p>
<div className="video-detail-comment-bottom">
<span className="video-detail-comment-date">{formatCommentDate(c.created_at)}</span>
{c.is_mine && !c.is_deleted && (
<button
className="video-detail-comment-delete"
onClick={() => handleDeleteComment(c.id)}
>
{t('videoDetail.deleteComment')}
</button>
)}
</div>
{/* 대댓글 (읽기 전용) */}
{c.replies && c.replies.length > 0 && (
<ul className="video-detail-reply-list">
{c.replies.map((r) => (
<li key={r.id} className="video-detail-reply-item">
{r.profile_image_url && (
<img
src={r.profile_image_url}
alt={r.nickname || t('videoDetail.anonymous')}
className="video-detail-comment-avatar small"
/>
)}
<div className="video-detail-comment-body">
<span className="video-detail-comment-nickname">
{r.nickname || t('videoDetail.anonymous')}
</span>
<p className="video-detail-comment-text">
{renderCommentContent(r.content, r.is_deleted)}
</p>
<div className="video-detail-comment-bottom">
<span className="video-detail-comment-date">{formatCommentDate(r.created_at)}</span>
{r.is_mine && !r.is_deleted && (
<button
className="video-detail-comment-delete"
onClick={() => handleDeleteComment(r.id)}
>
{t('videoDetail.deleteComment')}
</button>
)}
</div>
</div>
</li>
))}
</ul>
)}
</div>
</li>
))}
</ul>
)}
{commentsHasNext && (
<button
className="video-detail-comments-more"
onClick={() => fetchComments(commentsPage + 1, true)}
disabled={commentsLoading}
>
{commentsLoading ? t('videoDetail.loadingComments') : t('videoDetail.loadMoreComments')}
</button>
)}
</div>
</div>
</div>
) : null}
</div>
{showLoginModal && (
<LoginPromptModal onClose={() => setShowLoginModal(false)} />
)}
</div>
);
};
export default VideoDetailContent;
+38
View File
@@ -0,0 +1,38 @@
import React, { useEffect } from 'react';
import VideoDetailContent from './VideoDetailContent';
import { useOverlayClose } from '../hooks/useOverlayClose';
interface VideoDetailModalProps {
videoId: string;
onClose: () => void;
}
const VideoDetailModal: React.FC<VideoDetailModalProps> = ({ videoId, onClose }) => {
useEffect(() => {
// 모달 열릴 때 배경 스크롤 잠금
const prev = document.body.style.overflow;
document.body.style.overflow = 'hidden';
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
document.addEventListener('keydown', handleKeyDown);
return () => {
document.body.style.overflow = prev;
document.removeEventListener('keydown', handleKeyDown);
};
}, [onClose]);
const overlayCloseHandlers = useOverlayClose(onClose);
return (
<div className="video-detail-overlay" {...overlayCloseHandlers}>
<div className="video-detail-modal-box" onClick={(e) => e.stopPropagation()}>
<VideoDetailContent videoId={videoId} isModal={true} onClose={onClose} />
</div>
</div>
);
};
export default VideoDetailModal;
+21
View File
@@ -0,0 +1,21 @@
import React from 'react';
import VideoDetailContent from './VideoDetailContent';
interface VideoDetailPageProps {
videoId: string;
}
const VideoDetailPage: React.FC<VideoDetailPageProps> = ({ videoId }) => {
const handleBack = () => {
localStorage.setItem('castad_active_item', 'ADO2 콘텐츠');
window.location.href = '/';
};
return (
<div className="video-detail-page">
<VideoDetailContent videoId={videoId} isModal={false} onClose={handleBack} />
</div>
);
};
export default VideoDetailPage;
+58
View File
@@ -0,0 +1,58 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
interface WizardStepperProps {
currentStep: number; // 0-based. ADO2 는 wizardStep 0~3 과 일치
/**
* 단계 라벨. 생략하면 ADO2 기본 4단계를 쓴다(기존 호출부 무수정).
* 썰박스처럼 단계 구성이 다른 파이프라인이 직접 넘긴다.
*/
steps?: string[];
}
const WizardStepper: React.FC<WizardStepperProps> = ({ currentStep, steps: stepsProp }) => {
const { t } = useTranslation();
const steps = stepsProp ?? [
t('wizardSteps.brandAnalysis'),
t('wizardSteps.asset'),
t('wizardSteps.sound'),
t('wizardSteps.video'),
];
return (
<div className="wizard-stepper">
{steps.map((label, index) => {
const isDone = index < currentStep;
const isCurrent = index === currentStep;
const stateClass = isDone ? ' done' : isCurrent ? ' current' : ' pending';
return (
<React.Fragment key={index}>
{/* 노드: 2rem 고정 너비. 라벨은 absolute로 노드 중심 아래에 붙음 */}
<div className={`wizard-step${stateClass}`}>
<div className="wizard-stepper-node">
{isDone ? (
<svg width="14" height="14" viewBox="0 0 14 14" fill="none">
<path d="M2.5 7L5.5 10L11.5 4" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
</svg>
) : (
<span>{index + 1}</span>
)}
</div>
<span className="wizard-stepper-label">{label}</span>
</div>
{/* 연결선: flex:1로 남은 공간을 균등하게 채움 */}
{index < steps.length - 1 && (
<div className={`wizard-step-line${isDone ? ' done' : ''}`} />
)}
</React.Fragment>
);
})}
</div>
);
};
export default WizardStepper;
+93
View File
@@ -0,0 +1,93 @@
import React from 'react';
export const NAV = {
HOME: 'ADO2 콘텐츠',
NEW: '새 프로젝트 만들기',
MY: '내 정보',
DASHBOARD: '대시보드',
} as const;
export const SETTINGS_ID = '__settings__';
export const GATED_ITEMS: string[] = [NAV.NEW, NAV.MY, NAV.DASHBOARD];
export type MyInfoTab = 'contents' | 'calendar' | 'payment' | 'business';
export interface NavItemDef {
id: string;
labelKey: string;
icon: React.ReactNode;
}
export const NAV_ITEMS: NavItemDef[] = [
{
id: NAV.HOME,
labelKey: 'sidebar.ado2Contents',
icon: (
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
<polyline points="9 22 9 12 15 12 15 22" />
</svg>
),
},
{
id: NAV.NEW,
labelKey: 'sidebar.newProject',
icon: (
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<line x1="12" y1="5" x2="12" y2="19" />
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
),
},
{
id: NAV.MY,
labelKey: 'sidebar.myInfo',
icon: (
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2" />
<circle cx="12" cy="7" r="4" />
</svg>
),
},
{
id: SETTINGS_ID,
labelKey: 'sidebar.settings',
icon: (
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<circle cx="12" cy="12" r="3" />
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
</svg>
),
},
];
/** 구 activeItem(6메뉴 체제) → 새 4메뉴 체계 매핑 + 비로그인 게이트 강등을 함께 처리한다. */
export function sanitizeActiveItem(
raw: string | null,
isGuest: boolean
): { item: string; myInfoTab?: MyInfoTab } {
const gate = (result: { item: string; myInfoTab?: MyInfoTab }) =>
isGuest && GATED_ITEMS.includes(result.item) ? { item: NAV.HOME } : result;
switch (raw) {
case '대시보드':
return gate({ item: NAV.DASHBOARD });
case '내 콘텐츠':
return gate({ item: NAV.MY, myInfoTab: 'contents' });
case '콘텐츠 캘린더':
return gate({ item: NAV.MY, myInfoTab: 'calendar' });
case '비즈니스 설정':
return gate({ item: NAV.MY, myInfoTab: 'business' });
case NAV.MY:
return gate({ item: NAV.MY });
case NAV.NEW:
return gate({ item: NAV.NEW });
case NAV.DASHBOARD:
return gate({ item: NAV.DASHBOARD });
case NAV.HOME:
return { item: NAV.HOME };
default:
return { item: NAV.HOME };
}
}
+24
View File
@@ -0,0 +1,24 @@
import React, { useRef } from 'react';
/**
* 모달 오버레이(배경) 클릭 시에만 닫히도록 하는 핸들러 쌍.
* 모달 내부에서 텍스트를 드래그 선택하다가 마우스가 오버레이 위에서 놓이면
* click 이벤트의 타겟이 오버레이가 되어 의도치 않게 닫히는 문제를 막기 위해,
* mousedown과 click(mouseup) 타겟이 모두 오버레이 자신일 때만 닫는다.
*/
export function useOverlayClose(onClose: () => void) {
const mouseDownOnSelfRef = useRef(false);
const onMouseDown = (e: React.MouseEvent<HTMLElement>) => {
mouseDownOnSelfRef.current = e.target === e.currentTarget;
};
const onClick = (e: React.MouseEvent<HTMLElement>) => {
if (mouseDownOnSelfRef.current && e.target === e.currentTarget) {
onClose();
}
mouseDownOnSelfRef.current = false;
};
return { onMouseDown, onClick };
}
+1
View File
@@ -2,6 +2,7 @@
import React from 'react'; import React from 'react';
import ReactDOM from 'react-dom/client'; import ReactDOM from 'react-dom/client';
import './i18n'; import './i18n';
import './styles/index.css';
import App from './App'; import App from './App';
const rootElement = document.getElementById('root'); const rootElement = document.getElementById('root');
+282 -116
View File
@@ -1,4 +1,10 @@
{ {
"wizardSteps": {
"brandAnalysis": "Analysis",
"asset": "Image",
"sound": "Sound",
"video": "Video"
},
"header": { "header": {
"loginFailedAlert": "Failed to get login URL. Please try again.", "loginFailedAlert": "Failed to get login URL. Please try again.",
"start": "Get Started", "start": "Get Started",
@@ -12,95 +18,22 @@
"myContents": "My Contents", "myContents": "My Contents",
"myInfo": "My Info", "myInfo": "My Info",
"defaultUser": "User", "defaultUser": "User",
"credits": "Credits left: {{count}}",
"loggingOut": "Logging out...", "loggingOut": "Logging out...",
"logout": "Log Out", "logout": "Log Out",
"tutorialRestart": "Restart Tutorial" "inquiry": "Feedback",
}, "login": "Log In",
"tutorial": { "settings": "Settings"
"skip": "Skip",
"next": "Next",
"prev": "Back",
"finish": "Done",
"landing": {
"intro": { "title": "Welcome to ADO2 Tutorial", "desc": "We'll guide you through ADO2 step by step." },
"dropdown": { "title": "Choose Search Type", "desc": "Select URL or business name from the dropdown." },
"field": { "title": "Enter Search Term", "desc": "For URL, paste a Naver Maps share URL.\nFor business name, type the name and select from the list." },
"button": { "title": "Start Brand Analysis", "desc": "Click the button to let AI start analyzing your brand." }
},
"analysis": {
"identity": { "title": "Brand Identity", "desc": "Check the core values and market positioning AI analyzed for your brand." },
"selling": { "title": "Key Selling Points", "desc": "See your brand's strengths." },
"persona": { "title": "Target Customer Types", "desc": "AI analyzed what kind of customers visit this brand." },
"keywords": { "title": "Recommended Keywords", "desc": "Keywords your customers are likely to search for." },
"generate": { "title": "Generate Content", "desc": "Create video content based on the analysis.\nClick to sign in with Kakao and continue." }
},
"asset": {
"image": { "title": "Image List", "desc": "Photos from Naver Place. Tap 'Show more' to see the rest, or X to remove any." },
"upload": { "title": "Add Images", "desc": "You can freely add more images." },
"ratio": { "title": "Select Video Ratio", "desc": "Choose the ratio for the video to be generated." },
"next": { "title": "Next Step", "desc": "Proceed to the next step when ready." }
},
"sound": {
"genre": { "title": "Select Genre", "desc": "Pick a music genre that fits your brand." },
"language": { "title": "Select Language", "desc": "You can choose the language for the sound.\nWant to continue with Korean?" },
"generate": { "title": "Generate Sound", "desc": "Click the button and AI will generate lyrics and music in your chosen genre and language." },
"lyrics": { "title": "Lyrics Complete", "desc": "AI wrote lyrics in your selected language.\nCheck the generated lyrics." },
"lyricsWait": { "title": "Generating Music", "desc": "AI is composing music based on the lyrics.\nPlease wait a moment." },
"audioPlayer": { "title": "Preview the Music", "desc": "Music generation is complete.\nPress play to listen to the generated music." },
"video": { "title": "Generate Video", "desc": "Click the button to start generating your video." }
},
"myInfo": {
"myInfo": { "title": "My Info", "desc": "In My Info, you can manage your social connections and view connected accounts." },
"connect": { "title": "Connect Now", "desc": "Click the YouTube connect button to go to the connection page.", "note": "Instagram connection is coming soon." },
"connected": { "title": "Connected Accounts", "desc": "Your linked social accounts appear here.\nCheck after connecting." },
"ado2": { "title": "ADO2 Contents", "desc": "You can now upload the generated video.\nClick to navigate." }
},
"ado2": {
"list": { "title": "Generated Videos", "desc": "View all AI-created videos here." },
"download": { "title": "Download", "desc": "Download the video to your device." },
"delete": { "title": "Delete", "desc": "Remove videos you no longer need." },
"upload": { "title": "Upload to Social Media", "desc": "Select a video and upload it to social media." }
},
"completion": {
"contentInfo": { "title": "Content Info", "desc": "Check the title, genre, resolution, and lyrics of the generated content." },
"generating": { "title": "Generating Video", "desc": "AI is creating your video.\nPlease wait a moment." },
"completion": { "title": "Video Complete!", "desc": "Your video is ready. Want to take a look?" },
"myInfo": { "title": "Connect Social Account", "desc": "To upload your video to YouTube, connect your social account in My Info. Click to go there." }
},
"upload": {
"seo": { "title": "Title & Description", "desc": "AI is generating the title and description for your video. Please wait a moment." },
"required": { "title": "Required Fields", "desc": "Fields marked with * are required.\nPlease check them before uploading." },
"schedule": { "title": "Schedule Upload", "desc": "Post now or schedule for a specific time." },
"submit": { "title": "Start Upload", "desc": "Click the Post button to start uploading." }
},
"dashboard": {
"metrics": { "title": "Key Metrics", "desc": "Check views, subscribers, and other stats for content uploaded via ADO2." },
"chart": { "title": "Growth Chart", "desc": "Track your channel's growth over time." },
"more": { "title": "More Analytics", "desc": "Even more statistics are available at a glance on the dashboard." }
},
"contentCalendar": {
"grid": { "title": "Content Calendar", "desc": "View your content schedule by date.\nWhy not select today?" },
"panel": { "title": "Content List", "desc": "Check the detailed content schedule here." }
},
"feedback": {
"complete": { "title": "Tutorial Complete 🎉", "desc": "You've completed the full flow from brand analysis to YouTube upload.\nTo replay the tutorial, click the button in the top right." },
"title": "Customer Feedback",
"desc": "Share any issues or suggestions to help us improve."
},
"restart": {
"title": "Restart Tutorial?",
"desc": "The tutorial will restart from the current screen.",
"confirm": "Start",
"cancel": "Cancel"
}
}, },
"footer": { "footer": {
"company":"O2O Inc.", "company": "O2O Inc.",
"businessNumber": "Business Registration No. : 620-87-00810 | CEO : Ahn Sungmin", "businessNumber": "Business Registration No. : 620-87-00810 | CEO : Ahn Sungmin",
"headquarters": "HQ : 41593 Unicorn Lab Daegu A05, 5F, 111 Oksan-ro, Buk-gu, Daegu, Korea", "headquarters": "HQ : Unicorn Lab Daegu A05, 5F, 111 Oksan-ro, Buk-gu, Daegu, Korea",
"researchCenter": "R&D : 13453 Rooms 504-505 (East), KT Pangyo Bldg, 32 Geumto-ro, Sujeong-gu, Seongnam-si, Gyeonggi-do, Korea", "researchCenter": "R&D : Rooms 504-505 (East), KT Pangyo Bldg, 32 Geumto-ro, Sujeong-gu, Seongnam-si, Gyeonggi-do, Korea",
"phone": "Tel : 070-4260-8310 | 010-2755-6463", "phone": "Tel : 070-4260-8310 | 010-2755-6463",
"email": "Email : o2oteam@o2o.kr" "email": "Email : o2oteam@o2o.kr",
"privacyPolicy": "Privacy Policy",
"termsOfService": "Terms of Service"
}, },
"social": { "social": {
"title": "Social Media Posting", "title": "Social Media Posting",
@@ -122,7 +55,7 @@
"privacyPrivate": "Private", "privacyPrivate": "Private",
"publishTimeLabel": "Publish Time", "publishTimeLabel": "Publish Time",
"publishNow": "Publish Now", "publishNow": "Publish Now",
"publishSchedule": "Schedule (Coming Soon)", "publishSchedule": "Schedule",
"footerNote": "", "footerNote": "",
"footerNoteLink": "", "footerNoteLink": "",
"cancel": "Cancel", "cancel": "Cancel",
@@ -136,7 +69,29 @@
"uploadFailed": "Upload failed.", "uploadFailed": "Upload failed.",
"autoSeoTitle": "Auto-generating... (30–60 sec)", "autoSeoTitle": "Auto-generating... (30–60 sec)",
"autoSeoDescription": "Auto-generating... (30–60 sec)", "autoSeoDescription": "Auto-generating... (30–60 sec)",
"autoSeoTags": "Auto-generating... (30–60 sec)" "autoSeoTags": "Auto-generating... (30–60 sec)",
"youtubeCallback": {
"connecting": "Connecting YouTube...",
"pleaseWait": "Please wait a moment.",
"failed": "Connection Failed",
"errorAuthCancelled": "Google authentication was cancelled or failed.",
"errorNoCode": "Authorization code was not received.",
"errorProcessing": "An error occurred while processing the YouTube connection."
},
"connectError": {
"title": "{{platform}} Connection Failed",
"defaultError": "An unknown error occurred.",
"detail": "Please try again. If the problem persists, contact customer support.",
"retry": "Try Again"
},
"connectSuccess": {
"title": "{{name}} Connected",
"messageWithChannel": "{{platform}} account has been successfully connected.",
"messageWithoutChannel": "Account has been successfully connected.",
"verified": "Verified",
"countdown": "Redirecting in {{count}} seconds...",
"goNow": "Go Now"
}
}, },
"upload": { "upload": {
"title": "YouTube Upload", "title": "YouTube Upload",
@@ -152,23 +107,37 @@
"viewOnYoutube": "View on YouTube", "viewOnYoutube": "View on YouTube",
"confirm": "OK", "confirm": "OK",
"close": "Close", "close": "Close",
"doNotClose": "Upload is in progress. Do not close this window." "doNotClose": "Upload is in progress. Do not close this window.",
"goToCalendar": "View in Calendar",
"scheduleConflict": "Schedule adjusted to {{time}} due to a conflict."
}, },
"landing": { "landing": {
"hero": { "hero": {
"searchTypeBusinessName": "Business Name", "searchTypeLabel": "Business Name | URL",
"placeholderBusinessName": "Enter a business name", "placeholderCombined": "Enter a business name or Naver Maps/Place URL",
"guideUrl": "Search for a place on Naver Maps, tap Share,\nthen paste the URL here.", "guideCombined": "Paste a Naver Maps share URL, or enter a business name to automatically retrieve information.",
"guideBusinessName": "Search by business name to retrieve information.", "errorInputRequired": "Please enter a business name or URL.",
"errorUrlRequired": "Please enter a URL.", "errorInvalidUrl": "Invalid URL format. (e.g., https://naver.me/abcdef)",
"errorNameRequired": "Please enter a business name.",
"errorInvalidUrl": "Invalid URL format. (e.g., https://example.com)",
"analyzeButton": "Brand Analysis", "analyzeButton": "Brand Analysis",
"scrollMore": "Scroll to see more", "scrollMore": "Scroll to see more",
"testDataLoading": "Loading...", "searching": "Searching...",
"testData": "Test Data", "searchTypeManual": "Not on Naver? Enter manually",
"testDataLoadFailed": "Failed to load test data.", "manualButtonDesc": "Even businesses not listed on Naver Maps/Place\ncan get lyrics, music, and video production\njust by entering the name, region, and address.",
"searching": "Searching..." "manualModalTitle": "Enter Business Info Directly",
"manualModalSubtitle": "Even businesses not on Naver can get lyrics, music, and video production by filling in the details below.",
"manualAnalyzeButton": "Get Started",
"manualLabelName": "Business Name",
"manualLabelAddress": "Address",
"manualLabelRegion": "Region",
"manualLabelDetail": "Detail Address",
"manualLabelCategory": "Category",
"manualPlaceholderName": "Enter the business name",
"manualPlaceholderAddress": "Enter the address",
"manualPlaceholderRegion": "Select a region",
"manualPlaceholderDetail": "Enter detail address (e.g. Gangnam-gu Teheran-ro 123)",
"manualPlaceholderCategory": "Enter the business category (e.g. pension, cafe, salon)",
"manualLabelSiteUrl": "Website link (optional)",
"manualPlaceholderSiteUrl": "Enter the official website URL (e.g. https://example.com)"
}, },
"welcome": { "welcome": {
"title": "Welcome to ADO2.AI", "title": "Welcome to ADO2.AI",
@@ -198,24 +167,44 @@
"guideBusinessName": "Search by business name to retrieve information.", "guideBusinessName": "Search by business name to retrieve information.",
"searchButton": "Search", "searchButton": "Search",
"searching": "Searching...", "searching": "Searching...",
"testDataLoading": "Loading...", "searchTypeManual": "Manual Input",
"testData": "Test Data" "errorSelectFromList": "Please select a business from the list.",
"errorUrlRequired": "Please enter a URL.",
"errorNameRequired": "Please enter a business name.",
"errorInvalidUrl": "Invalid URL format. (e.g. https://example.com)",
"manualModalTitle": "Enter Business Info",
"manualLabelName": "Business Name",
"manualLabelAddress": "Address",
"manualLabelRegion": "Region",
"manualLabelDetail": "Detail Address",
"manualLabelCategory": "Category",
"manualPlaceholderName": "Enter the business name",
"manualPlaceholderAddress": "Enter the address",
"manualPlaceholderRegion": "Select a region",
"manualPlaceholderDetail": "Enter detail address (e.g. Gangnam-gu Teheran-ro 123)",
"manualPlaceholderCategory": "Enter the business category (e.g. pension, cafe, salon)"
}, },
"assetManagement": { "assetManagement": {
"title": "Brand Assets", "title": "Brand Assets",
"selectedImages": "Selected Images", "selectedImages": "Selected Images",
"imageAlt": "Image", "imageAlt": "Image",
"uploadBadge": "Uploaded", "uploadBadge": "Uploaded",
"previewUnavailable": "No preview",
"imageUpload": "Image Upload", "imageUpload": "Image Upload",
"dragAndDrop": "Drag and drop\nimages to upload", "dragAndDrop": "Drag & drop or\nclick to upload",
"videoRatio": "Video Ratio", "videoRatio": "Video Ratio",
"minImages": "Min. 5 images", "minImages": "Recommended 30+ images",
"youtubeShorts": "YouTube Shorts", "youtubeShorts": "YouTube Shorts",
"youtubeVideo": "YouTube Video", "youtubeVideo": "YouTube Video",
"back": "Go Back", "back": "Go Back",
"loadMore": "Load more", "loadMore": "Load more",
"uploadFailed": "Image upload failed.", "uploadFailed": "Image upload failed.",
"uploading": "Uploading... (30 sec – 2 min)", "uploadErrorTitle": "Image Upload Error",
"uploadErrorConfirm": "OK",
"duplicateSkippedTitle": "Duplicate Images Skipped",
"duplicateSkippedMessage": "Skipped {{count}} image(s) that were already added.",
"preparingPreviews": "Preparing previews ({{done}} / {{total}})",
"uploading": "Uploading... (30 sec – 1 min)",
"nextStep": "Next Step" "nextStep": "Next Step"
}, },
"soundStudio": { "soundStudio": {
@@ -228,19 +217,22 @@
"genreLabel": "Select Genre", "genreLabel": "Select Genre",
"genreAuto": "Auto Select", "genreAuto": "Auto Select",
"genreBallad": "Ballad", "genreBallad": "Ballad",
"languageLabel": "Language", "languageLabel": "Select Language",
"languageKorean": "Korean", "languageKorean": "Korean",
"lyricsColumn": "Lyrics", "lyricsColumn": "Lyrics",
"lyricsHint": "Select the lyrics area to edit", "lyricsHint": "Select the lyrics area to edit",
"lyricsPlaceholder": "Lyrics will be displayed when sound is generated.", "lyricsPlaceholder": "Lyrics will be displayed when sound is generated.",
"lyricsPlaceholderBGM": "Background music is generated without lyrics.",
"generateButton": "Generate Sound", "generateButton": "Generate Sound",
"regenerateButton": "Regenerate",
"regenerateHint": "Press the regenerate button to create new lyrics and music.",
"generating": "Generating...", "generating": "Generating...",
"generateVideo": "Generate Video", "generateVideo": "Generate Video",
"videoGenerating": "Generating Video", "videoGenerating": "Generating Video",
"noBusinessInfo": "No business information. Please try again.", "noBusinessInfo": "No business information. Please try again.",
"noImageUploadInfo": "No image upload information. Please go back to the previous step and try again.", "noImageUploadInfo": "No image upload information. Please go back to the previous step and try again.",
"generatingLyrics": "Generating lyrics...\n(30–60 sec)", "generatingLyrics": "Generating lyrics... (30–60 sec)",
"generatingSong": "Generating music...\n(1–2 min)", "generatingSong": "Generating music... (1–2 min)",
"songQueued": "Song generation queued...", "songQueued": "Song generation queued...",
"retryMessage": "Regenerating due to timeout... ({{count}}/{{max}})", "retryMessage": "Regenerating due to timeout... ({{count}}/{{max}})",
"lyricGenerationFailed": "Lyrics generation request failed.", "lyricGenerationFailed": "Lyrics generation request failed.",
@@ -251,7 +243,10 @@
"musicGenerationFailed": "Music generation failed.", "musicGenerationFailed": "Music generation failed.",
"multipleRetryFailed": "Music generation failed after multiple attempts. Please try again.", "multipleRetryFailed": "Music generation failed after multiple attempts. Please try again.",
"musicGenerationError": "An error occurred during music generation.", "musicGenerationError": "An error occurred during music generation.",
"songRegenerationError": "An error occurred during music regeneration." "songRegenerationError": "An error occurred during music regeneration.",
"creditsRemaining": "{{count}} left",
"creditsExhausted": "Not enough credits.",
"chargeCredits": "Top Up Credits"
}, },
"completion": { "completion": {
"back": "Go Back", "back": "Go Back",
@@ -259,6 +254,8 @@
"titleError": "Video Generation Failed", "titleError": "Video Generation Failed",
"titleComplete": "Content Creation Complete", "titleComplete": "Content Creation Complete",
"imageAndVideo": "Images & Video", "imageAndVideo": "Images & Video",
"checkingSubtitle": "Checking subtitle generation status...",
"waitingSubtitle": "Generating subtitles...",
"requestingGeneration": "Requesting video generation...", "requestingGeneration": "Requesting video generation...",
"generatingVideo": "Generating video...", "generatingVideo": "Generating video...",
"processingAfterRefresh": "Processing video... (recovered after refresh)", "processingAfterRefresh": "Processing video... (recovered after refresh)",
@@ -292,7 +289,18 @@
"videoNotReady": "The video is not ready yet.", "videoNotReady": "The video is not ready yet.",
"youtubeUploadMessage": "Uploading video to YouTube channel \"{{channelName}}\".\n\n(Upload feature coming soon)", "youtubeUploadMessage": "Uploading video to YouTube channel \"{{channelName}}\".\n\n(Upload feature coming soon)",
"deployComingSoon": "The deployment feature for the selected social channel is coming soon.", "deployComingSoon": "The deployment feature for the selected social channel is coming soon.",
"youtubeExpiredAlert": "YouTube authentication has expired. Redirecting to reconnect page." "youtubeExpiredAlert": "YouTube authentication has expired. Redirecting to reconnect page.",
"contentComplete": "Content Creation Complete",
"contentCompleteDesc": "Your optimized content has been created through AI analysis and editing",
"contentInfo": "File Name",
"genre": "Genre",
"resolution": "Resolution",
"lyrics": "Lyrics",
"sampleLyrics": "Loading lyrics...",
"noLyricsBGM": "Background music is generated without lyrics.",
"downloading": "Downloading...",
"download": "Download",
"uploadToSocial": "Upload"
}, },
"dashboard": { "dashboard": {
"title": "Dashboard", "title": "Dashboard",
@@ -365,13 +373,44 @@
"stayIntroReel": "Stay Meomum Introduction Reel", "stayIntroReel": "Stay Meomum Introduction Reel",
"newYearEvent": "New Year Special Event", "newYearEvent": "New Year Special Event",
"nightTimelapse": "Pension Night View Timelapse" "nightTimelapse": "Pension Night View Timelapse"
} },
"metricTotalViews": "Views",
"metricWatchTime": "Watch Time",
"metricAvgViewDuration": "Avg. Watch Duration",
"metricNewSubscribers": "New Subscribers",
"metricUploadedVideos": "Uploaded Videos",
"unitHours": "h",
"unitMinutes": "m",
"noDataInPeriod": "No data available for this period.",
"dataLoading": "Loading data...",
"noUploadsTitle": "No uploaded videos yet.",
"noUploadsDesc": "Upload videos via ADO2 to see real stats.",
"reconnectButton": "Reconnect →",
"connectButton": "Connect →",
"retryButton": "Retry →",
"selectAccount": "Select an account",
"modeAnnual": "Annual",
"modeMonthly": "Monthly",
"chartThisYear": "This Year",
"chartLastYear": "Last Year",
"chartThisMonth": "This Month",
"chartLastMonth": "Last Month",
"monthOverMonth": "Month-over-Month Growth",
"noAudienceData": "Not enough data to show real audience insights.",
"mockContentNotice": "The content shown below is sample data, not your actual content.",
"dataDelayTitle": "No data to display",
"dataDelayDesc": "There is no analytics data to display. YouTube may take up to 48 hours to reflect data after upload, and statistics are also not collected if the video was uploaded as private or has been deleted from YouTube.",
"sampleHide": "Hide Sample",
"sampleShow": "Show Sample",
"recentVideosDesc": "Showing stats for the latest 30 videos uploaded via ADO2.",
"channelStatsDesc": "Showing stats for the selected channel.",
"youtubeApiFailed": "Failed to call YouTube Analytics API."
}, },
"myInfo": { "myInfo": {
"title": "My Info", "title": "My Info",
"tabBasic": "Basic Info", "tabBasic": "Basic Info",
"tabPayment": "Payment Info", "tabPayment": "Payment Info",
"tabBusiness": "My Business & Social Channel Management", "tabBusiness": "Social Channel Management",
"basicPlaceholder": "Basic information settings are coming soon.", "basicPlaceholder": "Basic information settings are coming soon.",
"paymentPlaceholder": "Payment information settings are coming soon.", "paymentPlaceholder": "Payment information settings are coming soon.",
"myBusiness": "My Business", "myBusiness": "My Business",
@@ -386,7 +425,24 @@
"connected": "Connected", "connected": "Connected",
"disconnectAccount": "Disconnect", "disconnectAccount": "Disconnect",
"loadingAccounts": "Loading account information...", "loadingAccounts": "Loading account information...",
"youtubeExpiredAlert": "YouTube authentication has expired. Redirecting to reconnect page." "youtubeExpiredAlert": "YouTube authentication has expired. Redirecting to reconnect page.",
"creditsTitle": "Credit Balance",
"creditsLoading": "Loading...",
"creditsLabel": "Available Credits",
"creditsUnit": "credits",
"creditsDesc": "You can request a top-up from the admin if you run low on credits.",
"creditsChargeBtn": "Top Up",
"chargePopupTitle": "Credit Top-up Request",
"chargeAmountLabel": "Credits to Request",
"chargeNoteLabel": "Additional Notes",
"chargeNotePlaceholder": "Enter any message for the admin",
"chargeCancel": "Cancel",
"chargeSubmit": "Submit",
"chargeSubmitting": "Submitting...",
"chargeSuccess": "Your top-up request has been submitted!",
"chargeConfirm": "OK",
"tabContents": "My Contents",
"tabCalendar": "Calendar"
}, },
"ado2Contents": { "ado2Contents": {
"title": "ADO2 Contents", "title": "ADO2 Contents",
@@ -405,7 +461,14 @@
"delete": "Delete", "delete": "Delete",
"previous": "Previous", "previous": "Previous",
"next": "Next", "next": "Next",
"uploadToSocial": "Upload to social media" "uploadToSocial": "Upload",
"sortLatest": "Latest",
"sortOldest": "Oldest",
"sortLikes": "Most Liked",
"sortComments": "Most Commented",
"regionPlaceholder": "Select Region",
"searchPlaceholder": "Search by name",
"searchBtn": "Search"
}, },
"businessSettings": { "businessSettings": {
"title": "Business Settings", "title": "Business Settings",
@@ -427,14 +490,18 @@
"marketPositioning": "Market Positioning", "marketPositioning": "Market Positioning",
"coreValue": "Core Value", "coreValue": "Core Value",
"categoryDefinition": "Category Definition", "categoryDefinition": "Category Definition",
"targetPersona": "Target Persona", "targetPersona": "Key Customer Type",
"ageSuffix": "years old", "ageSuffix": "years old",
"sellingPoints": "Unique Selling Points (USP)", "sellingPoints": "Key Selling Points",
"recommendedKeywords": "Recommended Target Keywords", "recommendedKeywords": "Recommended Target Keywords",
"generateContent": "Generate Content", "generateContent": "Generate Content",
"pageDescBefore": " reveals ", "pageDescBefore": " reveals ",
"pageDescAfter": "'s core strategy.", "pageDescAfter": "'s core strategy.",
"loadingTitle": "Analyzing Brand" "loadingTitle": "Analyzing Brand",
"loadingStep1": "Collecting brand information...",
"loadingStep2": "Analyzing collected data...",
"loadingStep3": "Deriving key strategies...",
"loadingStep4": "Organizing results..."
}, },
"common": { "common": {
"back": "Go Back", "back": "Go Back",
@@ -446,15 +513,114 @@
"required": "*", "required": "*",
"unknown": "Unknown" "unknown": "Unknown"
}, },
"contentCalendar": {
"title": "Content Calendar",
"tabs": {
"all": "All",
"completed": "Done",
"scheduled": "Planned",
"failed": "Failed"
},
"status": {
"completed": "Done",
"scheduled": "Planned",
"failed": "Failed"
},
"months": [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
],
"days": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
],
"yearMonth": "{{month}} {{year}}",
"monthDay": "{{month}} {{day}}",
"loading": "Loading...",
"noResults": "No recent results",
"noResultsDesc": "Upload your content to social channels",
"myContents": "My Contents",
"cancel": "Cancel",
"retry": "Retry",
"cancelConfirm": "Are you sure you want to cancel this reservation?",
"cancelFailed": "Failed to cancel.",
"retryFailed": "Failed to retry.",
"completedCount": "Done {{count}}",
"scheduledCount": "Sched {{count}}",
"failedCount": "Fail {{count}}"
},
"loginPrompt": {
"title": "Login Required",
"loginBtn": "Login",
"description": "Sign in with Kakao in a few seconds\nto keep going."
},
"videoDetail": {
"dateFormat": "{{month}}/{{day}}/{{year}}",
"kakaoDefaultTitle": "ADO2 Video",
"kakaoDescription": "{{region}} · ADO2 AI Marketing Video",
"deletedComment": "(This comment has been deleted.)",
"closeAriaLabel": "Close",
"share": "Share",
"copied": "Copied!",
"siteOverlayLabel": "View more",
"commentsTitle": "Comments",
"commentPlaceholder": "Write a comment...",
"commentLoginRequired": "Please log in to write a comment",
"commentSubmitting": "Submitting",
"commentSubmit": "Submit",
"noComments": "No comments yet.",
"anonymous": "Anonymous",
"deleteComment": "Delete",
"loadMoreComments": "Load more comments",
"loadingComments": "Loading..."
},
"app": { "app": {
"loginProcessing": "Processing login...", "loginProcessing": "Processing login...",
"loginFailed": "Login processing failed. Please try again.", "loginFailed": "Login processing failed. Please try again.",
"kakaoLoginFailed": "Kakao login failed. Please try again.", "kakaoLoginFailed": "Kakao login failed. Please try again.",
"loginUrlFailed": "Failed to get login URL. Please try again.", "loginUrlFailed": "Failed to get login URL. Please try again.",
"invalidUrl": "Invalid URL. Please enter a Naver Map URL.", "invalidUrl": "Invalid URL. Please enter a Naver Map URL.",
"analysisError": "An error occurred during analysis. Please try again.", "analysisError": "No results found. Please check your input and try again.",
"autocompleteError": "Failed to retrieve business information.", "autocompleteError": "No results found. Please check your input and try again.",
"autocompleteGeneralError": "An error occurred while retrieving business information. Please try again.", "autocompleteGeneralError": "An error occurred while retrieving business information. Please try again.",
"pageComingSoon": "{{page}} page is coming soon." "pageComingSoon": "{{page}} page is coming soon."
},
"pipelineTabs": {
"ariaLabel": "Content type",
"ado2": "ADO2",
"ssul": "Ssulbox"
},
"ssulbox": {
"steps": {
"pick": "Select",
"making": "Generating",
"done": "Done"
},
"create": {
"step1": "STEP 1 · Pick a story",
"step2": "STEP 2 · Pick a place",
"searchPlaceholder": "Business name, or paste a Naver Map link",
"searchButton": "Search",
"searching": "Searching",
"cost": "Cost",
"costValue": "1 credit",
"submit": "Create Ssulbox",
"submitting": "Requesting…"
}
} }
} }
+326 -111
View File
@@ -1,4 +1,10 @@
{ {
"wizardSteps": {
"brandAnalysis": "분석",
"asset": "이미지",
"sound": "사운드",
"video": "영상"
},
"header": { "header": {
"loginFailedAlert": "로그인 URL을 가져오는데 실패했습니다. 다시 시도해주세요.", "loginFailedAlert": "로그인 URL을 가져오는데 실패했습니다. 다시 시도해주세요.",
"start": "시작하기", "start": "시작하기",
@@ -12,95 +18,22 @@
"myContents": "내 콘텐츠", "myContents": "내 콘텐츠",
"myInfo": "내 정보", "myInfo": "내 정보",
"defaultUser": "사용자", "defaultUser": "사용자",
"credits": "보유 크레딧: {{count}}",
"loggingOut": "로그아웃 중...", "loggingOut": "로그아웃 중...",
"logout": "로그아웃", "logout": "로그아웃",
"tutorialRestart": "튜토리얼 다시 보기" "inquiry": "고객의견",
}, "login": "로그인",
"tutorial": { "settings": "설정"
"skip": "건너뛰기",
"next": "다음",
"prev": "이전",
"finish": "완료",
"landing": {
"intro": { "title": "ADO2 튜토리얼 시작", "desc": "ADO2 사용 방법을 단계별로 안내해 드릴게요." },
"dropdown": { "title": "검색 방식 선택", "desc": "드롭다운에서 URL 또는 업체명 중 원하는 방식을 선택하세요." },
"field": { "title": "입력하기", "desc": "URL 방식이라면 네이버 지도 공유 URL,\n업체명 방식이라면 업체명을 입력하고 목록에서 선택하세요." },
"button": { "title": "브랜드 분석 시작", "desc": "버튼을 누르면 AI가 브랜드를 분석하기 시작해요." }
},
"analysis": {
"identity": { "title": "브랜드 정체성", "desc": "AI가 분석한 펜션의 핵심 가치와 시장 포지셔닝을 확인하세요." },
"selling": { "title": "주요 셀링 포인트", "desc": "펜션의 강점을 확인할 수 있어요." },
"persona": { "title": "주요 고객 유형", "desc": "어떤 고객이 이 펜션을 찾는지 분석했어요." },
"keywords": { "title": "추천 타겟 키워드", "desc": "고객이 검색할 가능성이 높은 키워드들이에요." },
"generate": { "title": "콘텐츠 생성", "desc": "분석 결과를 바탕으로 영상을 만들어 보세요.\n클릭하면 카카오 로그인으로 이동합니다." }
},
"asset": {
"image": { "title": "이미지 목록", "desc": "네이버 Place에서 가져 온 사진이에요. \n더보기를 누르면 나머지 사진도 볼 수 있고 X를 눌러 삭제 할 수 있어요." },
"upload": { "title": "이미지 추가", "desc": "이미지를 자유롭게 추가 할 수 있어요." },
"ratio": { "title": "영상 비율 선택", "desc": "생성 할 영상의 비율을 선택하세요." },
"next": { "title": "다음 단계로", "desc": "설정이 완료되면 다음 단계로 진행하세요." }
},
"sound": {
"genre": { "title": "장르 선택", "desc": "영상에 어울리는 음악 장르를 선택하세요." },
"language": { "title": "언어 선택", "desc": "사운드의 언어를 선택할 수 있어요. \n이미 선택된 한국어로 진행해볼까요?" },
"generate": { "title": "사운드 생성", "desc": "버튼을 클릭하면 AI가 선택한 장르와 언어로 가사와 음악을 생성해요."},
"lyrics": { "title": "가사 생성 완료", "desc": "AI가 선택한 언어로 가사를 만들었어요.\n생성된 가사를 확인하세요." },
"lyricsWait": { "title": "음악 생성 중", "desc": "가사를 바탕으로 AI가 음악을 만들고 있어요.\n잠시만 기다려 주세요." },
"audioPlayer": { "title": "음악 미리 듣기", "desc": "음악 생성이 완료되었어요.\n재생 버튼을 눌러 생성된 음악을 들어보세요." },
"video": { "title": "영상 생성", "desc": "버튼을 클릭해서 영상 생성을 시작하세요." }
},
"myInfo": {
"myInfo": { "title": "내 정보", "desc": "내 정보에서는 소셜 연결과 연결된 계정을 확인 할 수 있어요." },
"connect": { "title": "연결하기", "desc": "YouTube 연결 버튼을 누르면 연결 페이지로 이동합니다.", "note": "Instargram 연결은 오픈 예정입니다." },
"connected": { "title": "연결 계정", "desc": "연결된 소셜 계정 목록이에요. \n연결 후 여기서 확인할 수 있어요." },
"ado2": { "title": "ADO2 콘텐츠", "desc": "이제 생성된 영상을 업로드할 수 있어요. \n클릭해서 이동하세요." }
},
"ado2": {
"list": { "title": "생성된 영상 목록", "desc": "ADO2에서 만든 영상들을 확인할 수 있어요." },
"download": { "title": "다운로드", "desc": "영상을 다운로드 할 수 있어요." },
"delete": { "title": "삭제", "desc": "필요없는 영상을 삭제할 수 있어요." },
"upload": { "title": "소셜 업로드", "desc": "선택해서 소셜미디어에 업로드하세요." }
},
"completion": {
"contentInfo": { "title": "콘텐츠 정보", "desc": "콘텐츠의 제목,장르,규격,가사를 확인하세요." },
"generating": { "title": "영상 제작 중", "desc": "AI가 영상을 만들고 있어요. \n잠시만 기다려 주세요." },
"completion": { "title": "영상 완성!", "desc": "영상 제작이 완료되었어요. \n영상을 확인해 볼까요?" },
"myInfo": { "title": "소셜 계정 연동", "desc": "영상을 유튜브에 업로드하려면 내 정보에서 소셜 계정을 연동해야 해요. \n클릭해서 이동하세요." }
},
"upload": {
"seo": { "title": "제목 및 설명", "desc": "영상의 제목과 설명을 AI가 만들고 있어요. 잠시만 기다려 주세요." },
"required": { "title": "필수 항목", "desc": "영상을 업로드 하기 전 *는 필수 항목으로 \n반드시 확인해 주세요." },
"schedule": { "title": "업로드 예약", "desc": "지금 게시하거나 원하는 시간에 예약할 수 있어요." },
"submit": { "title": "업로드 시작", "desc": "게시 버튼을 눌러 업로드를 시작하세요." }
},
"dashboard": {
"metrics": { "title": "핵심 지표", "desc": "조회수, 구독자 등 ADO2로 업로드한 콘텐츠의 주요 통계를 확인하세요." },
"chart": { "title": "성장 추이 차트", "desc": "기간별 성장 추이를 그래프로 확인할 수 있어요." },
"more": { "title": "더 많은 통계", "desc": "그 외에도 다양한 통계를 대시보드에서 한눈에 확인할 수 있어요." }
},
"contentCalendar": {
"grid": { "title": "콘텐츠 캘린더", "desc": "날짜별로 콘텐츠 스케줄을 확인할 수 있어요. \n오늘 날짜를 선택해 볼까요?" },
"panel": { "title": "콘텐츠 목록", "desc": "자세한 콘텐츠 스케줄을 확인 할수 있어요." }
},
"feedback": {
"complete": { "title": "튜토리얼 완료 🎉", "desc": "유튜브 업로드까지 모든 과정을 완료했어요. \n튜토리얼을 다시보고 싶다면 우측 상단의 버튼을 눌러주세요." },
"title": "고객의견",
"desc": "서비스 이용 중 불편한 점이나 개선 의견을 보내주세요."
},
"restart": {
"title": "튜토리얼을 다시 시작할까요?",
"desc": "현재 화면부터 튜토리얼이 다시 시작됩니다.",
"confirm": "시작하기",
"cancel": "취소"
}
}, },
"footer": { "footer": {
"company":"㈜에이아이오투오", "company": "㈜에이아이오투오",
"businessNumber": "사업자 등록번호 : 620-87-00810 | 대표 : 안성민", "businessNumber": "사업자 등록번호 : 620-87-00810 | 대표 : 안성민",
"headquarters": "본사 : 41593 대구광역시 북구 옥산로 111, 5층 유니콘랩 대구 A05호", "headquarters": "본사 : 대구광역시 북구 옥산로 111, 5층 유니콘랩 대구 A05호",
"researchCenter": "연구소 : 13453 경기 성남시 수정구 금토로 32 (금토동) (주)KT 판교빌딩 504호~505호 (East)", "researchCenter": "연구소 : 경기 성남시 수정구 금토로 32 (금토동) (주)KT 판교빌딩 504호~505호 (East)",
"phone": "전화 : 070-4260-8310 | 010-2755-6463", "phone": "전화 : 070-4260-8310 | 010-2755-6463",
"email": "이메일 : o2oteam@o2o.kr" "email": "이메일 : o2oteam@o2o.kr",
"privacyPolicy": "개인정보처리방침",
"termsOfService": "서비스 약관"
}, },
"social": { "social": {
"title": "소셜 미디어 포스팅", "title": "소셜 미디어 포스팅",
@@ -136,7 +69,29 @@
"uploadFailed": "업로드에 실패했습니다.", "uploadFailed": "업로드에 실패했습니다.",
"autoSeoTitle": "자동으로 작성중입니다. (30~60초 소요)", "autoSeoTitle": "자동으로 작성중입니다. (30~60초 소요)",
"autoSeoDescription": "자동으로 작성중입니다. (30~60초 소요)", "autoSeoDescription": "자동으로 작성중입니다. (30~60초 소요)",
"autoSeoTags": "자동으로 작성중입니다. (30~60초 소요)" "autoSeoTags": "자동으로 작성중입니다. (30~60초 소요)",
"youtubeCallback": {
"connecting": "YouTube 연결 중...",
"pleaseWait": "잠시만 기다려주세요.",
"failed": "연결 실패",
"errorAuthCancelled": "Google 인증이 취소되었거나 실패했습니다.",
"errorNoCode": "인증 코드를 받지 못했습니다.",
"errorProcessing": "YouTube 연결 처리 중 오류가 발생했습니다."
},
"connectError": {
"title": "{{platform}} 연결 실패",
"defaultError": "알 수 없는 오류가 발생했습니다.",
"detail": "다시 시도해주세요. 문제가 지속되면 고객 지원에 문의해주세요.",
"retry": "다시 시도"
},
"connectSuccess": {
"title": "{{name}} 연결 완료",
"messageWithChannel": "{{platform}} 계정이 성공적으로 연결되었습니다.",
"messageWithoutChannel": "계정이 성공적으로 연결되었습니다.",
"verified": "인증됨",
"countdown": "{{count}}초 후 자동으로 이동합니다...",
"goNow": "지금 이동"
}
}, },
"upload": { "upload": {
"title": "YouTube 업로드", "title": "YouTube 업로드",
@@ -152,23 +107,37 @@
"viewOnYoutube": "YouTube에서 보기", "viewOnYoutube": "YouTube에서 보기",
"confirm": "확인", "confirm": "확인",
"close": "닫기", "close": "닫기",
"doNotClose": "업로드가 진행 중입니다. 창을 닫지 마세요." "doNotClose": "업로드가 진행 중입니다. 창을 닫지 마세요.",
"goToCalendar": "캘린더에서 확인",
"scheduleConflict": "예약 시간이 충돌하여 {{time}}으로 조정되었습니다."
}, },
"landing": { "landing": {
"hero": { "hero": {
"searchTypeBusinessName": "업체명", "searchTypeLabel": "업체명 | URL",
"placeholderBusinessName": "업체명을 입력하세요.", "placeholderCombined": "업체명 또는 URL을 입력하세요.",
"guideUrl": "네이버지도에서 장소를 검색하고 공유 선택, \n나오는 URL을 붙여 넣어 주세요.", "guideCombined": "네이버 지도 공유 URL을 붙여넣거나,\n업체명을 입력하면 자동으로 정보를 가져옵니다.",
"guideBusinessName": "업체명으로 검색하여 정보를 가져옵니다.", "errorInputRequired": "업체명 또는 URL을 입력해주세요.",
"errorUrlRequired": "URL을 입력해주세요.", "errorInvalidUrl": "올바른 URL 형식이 아닙니다. (예: https://naver.me/abcdef)",
"errorNameRequired": "업체명을 입력해주세요.",
"errorInvalidUrl": "올바른 URL 형식이 아닙니다. (예: https://example.com)",
"analyzeButton": "브랜드 분석", "analyzeButton": "브랜드 분석",
"scrollMore": "스크롤하여 더 보기", "scrollMore": "스크롤하여 더 보기",
"testDataLoading": "로딩 중...", "searching": "검색 중...",
"testData": "테스트 데이터", "searchTypeManual": "네이버에 없는 업체인가요? 직접 입력하기",
"testDataLoadFailed": "테스트 데이터를 불러오는데 실패했습니다.", "manualButtonDesc": "네이버 지도/플레이스에 등록되지 않은 업체도\n업체명·지역·상세주소만 입력하면\n가사·음악·영상 제작까지 가능합니다.",
"searching": "검색 중..." "manualModalTitle": "업체 정보 직접 입력",
"manualModalSubtitle": "네이버에 등록되지 않은 업체도 아래 정보만 입력하면 가사·음악·영상 제작까지 할 수 있어요.",
"manualAnalyzeButton": "시작하기",
"manualLabelName": "업체명",
"manualLabelAddress": "주소",
"manualLabelRegion": "지역",
"manualLabelDetail": "상세 주소",
"manualLabelCategory": "업종",
"manualPlaceholderName": "업체명을 입력하세요.",
"manualPlaceholderAddress": "주소를 입력하세요.",
"manualPlaceholderRegion": "지역을 선택하세요.",
"manualPlaceholderDetail": "상세 주소를 입력하세요. (예: 강남구 테헤란로 123)",
"manualPlaceholderCategory": "업종을 입력하세요. (예: 펜션, 카페, 미용실)",
"manualLabelSiteUrl": "홈페이지 링크 (선택)",
"manualPlaceholderSiteUrl": "공식 홈페이지 주소를 입력하세요. (예: https://example.com)"
}, },
"welcome": { "welcome": {
"title": "ADO2.AI에 오신 것을 환영합니다.", "title": "ADO2.AI에 오신 것을 환영합니다.",
@@ -198,24 +167,44 @@
"guideBusinessName": "업체명으로 검색하여 정보를 가져옵니다.", "guideBusinessName": "업체명으로 검색하여 정보를 가져옵니다.",
"searchButton": "검색하기", "searchButton": "검색하기",
"searching": "검색 중...", "searching": "검색 중...",
"testDataLoading": "로딩 중...", "searchTypeManual": "직접 입력",
"testData": "테스트 데이터" "errorSelectFromList": "목록에서 업체를 선택해 주세요.",
"errorUrlRequired": "URL을 입력해주세요.",
"errorNameRequired": "업체명을 입력해주세요.",
"errorInvalidUrl": "올바른 URL 형식이 아닙니다. (예: https://example.com)",
"manualModalTitle": "업체 정보 입력",
"manualLabelName": "업체명",
"manualLabelAddress": "주소",
"manualLabelRegion": "지역",
"manualLabelDetail": "상세 주소",
"manualLabelCategory": "업종",
"manualPlaceholderName": "업체명을 입력하세요.",
"manualPlaceholderAddress": "주소를 입력하세요.",
"manualPlaceholderRegion": "지역을 선택하세요.",
"manualPlaceholderDetail": "상세 주소를 입력하세요. (예: 강남구 테헤란로 123)",
"manualPlaceholderCategory": "업종을 입력하세요. (예: 펜션, 카페, 미용실)"
}, },
"assetManagement": { "assetManagement": {
"title": "브랜드 에셋", "title": "브랜드 에셋",
"selectedImages": "선택된 이미지", "selectedImages": "선택된 이미지",
"imageAlt": "이미지", "imageAlt": "이미지",
"uploadBadge": "업로드", "uploadBadge": "업로드",
"previewUnavailable": "미리보기 없음",
"imageUpload": "이미지 업로드", "imageUpload": "이미지 업로드",
"dragAndDrop": "이미지를 드래그하여\n업로드", "dragAndDrop": "이미지를 끌어다 놓거나\n클릭하여 업로드",
"videoRatio": "영상 비율", "videoRatio": "영상 비율",
"minImages": "최소 5장", "minImages": "권장 30장 이상",
"youtubeShorts": "유튜브 쇼츠", "youtubeShorts": "유튜브 쇼츠",
"youtubeVideo": "유튜브 일반", "youtubeVideo": "유튜브 일반",
"back": "뒤로가기", "back": "뒤로가기",
"loadMore": "더보기", "loadMore": "더보기",
"uploadFailed": "이미지 업로드에 실패했습니다.", "uploadFailed": "이미지 업로드에 실패했습니다.",
"uploading": "업로드 중 (30초~2분 소요)", "uploadErrorTitle": "이미지 업로드 초과",
"uploadErrorConfirm": "확인",
"duplicateSkippedTitle": "중복 이미지 제외",
"duplicateSkippedMessage": "이미 추가된 이미지 {{count}}장을 제외했습니다.",
"preparingPreviews": "미리보기 준비 중 ({{done}} / {{total}})",
"uploading": "업로드 중 (30~60초 소요)",
"nextStep": "다음 단계" "nextStep": "다음 단계"
}, },
"soundStudio": { "soundStudio": {
@@ -228,12 +217,15 @@
"genreLabel": "장르 선택", "genreLabel": "장르 선택",
"genreAuto": "자동 선택", "genreAuto": "자동 선택",
"genreBallad": "발라드", "genreBallad": "발라드",
"languageLabel": "언어", "languageLabel": "언어 선택",
"languageKorean": "한국어", "languageKorean": "한국어",
"lyricsColumn": "가사", "lyricsColumn": "가사",
"lyricsHint": "가사 영역을 선택해서 수정 가능해요", "lyricsHint": "가사 영역을 선택해서 수정 가능해요",
"lyricsPlaceholder": "사운드 생성 시 가사 표시됩니다.", "lyricsPlaceholder": "사운드 생성 시 가사 표시됩니다.",
"lyricsPlaceholderBGM": "배경음악은 가사 없이 생성됩니다.",
"generateButton": "사운드 생성", "generateButton": "사운드 생성",
"regenerateButton": "재생성 하기",
"regenerateHint": "재생성 버튼을 누르면 가사와 음악을 다시 만들 수 있어요.",
"generating": "생성 중...", "generating": "생성 중...",
"generateVideo": "영상 생성하기", "generateVideo": "영상 생성하기",
"videoGenerating": "영상 생성 중", "videoGenerating": "영상 생성 중",
@@ -251,7 +243,10 @@
"musicGenerationFailed": "음악 생성에 실패했습니다.", "musicGenerationFailed": "음악 생성에 실패했습니다.",
"multipleRetryFailed": "여러 번 시도했지만 음악 생성에 실패했습니다. 다시 시도해주세요.", "multipleRetryFailed": "여러 번 시도했지만 음악 생성에 실패했습니다. 다시 시도해주세요.",
"musicGenerationError": "음악 생성 중 오류가 발생했습니다.", "musicGenerationError": "음악 생성 중 오류가 발생했습니다.",
"songRegenerationError": "음악 재생성 중 오류가 발생했습니다." "songRegenerationError": "음악 재생성 중 오류가 발생했습니다.",
"creditsRemaining": "잔여 {{count}}",
"creditsExhausted": "크레딧이 부족합니다.",
"chargeCredits": "크레딧 충전하기"
}, },
"completion": { "completion": {
"back": "뒤로가기", "back": "뒤로가기",
@@ -259,6 +254,8 @@
"titleError": "영상 생성 실패", "titleError": "영상 생성 실패",
"titleComplete": "콘텐츠 제작 완료", "titleComplete": "콘텐츠 제작 완료",
"imageAndVideo": "이미지 및 영상", "imageAndVideo": "이미지 및 영상",
"checkingSubtitle": "자막 생성 상태를 확인하고 있습니다...",
"waitingSubtitle": "자막을 생성하고 있습니다...",
"requestingGeneration": "영상 생성을 요청하고 있습니다...", "requestingGeneration": "영상 생성을 요청하고 있습니다...",
"generatingVideo": "영상을 생성하고 있습니다...", "generatingVideo": "영상을 생성하고 있습니다...",
"processingAfterRefresh": "영상을 처리하고 있습니다... (새로고침 후 복구됨)", "processingAfterRefresh": "영상을 처리하고 있습니다... (새로고침 후 복구됨)",
@@ -292,7 +289,18 @@
"videoNotReady": "영상이 아직 준비되지 않았습니다.", "videoNotReady": "영상이 아직 준비되지 않았습니다.",
"youtubeUploadMessage": "YouTube 채널 \"{{channelName}}\"에 영상을 업로드합니다.\n\n(업로드 기능 준비 중)", "youtubeUploadMessage": "YouTube 채널 \"{{channelName}}\"에 영상을 업로드합니다.\n\n(업로드 기능 준비 중)",
"deployComingSoon": "선택한 소셜 채널에 배포 기능이 준비 중입니다.", "deployComingSoon": "선택한 소셜 채널에 배포 기능이 준비 중입니다.",
"youtubeExpiredAlert": "YouTube 인증이 만료되었습니다. 재연동 페이지로 이동합니다." "youtubeExpiredAlert": "YouTube 인증이 만료되었습니다. 재연동 페이지로 이동합니다.",
"contentComplete": "콘텐츠 제작 완료",
"contentCompleteDesc": "AI 분석 및 편집을 통해 최적화된 콘텐츠가 완성되었습니다",
"contentInfo": "파일명",
"genre": "장르",
"resolution": "규격",
"lyrics": "가사",
"sampleLyrics": "가사를 불러오는 중...",
"noLyricsBGM": "배경음악은 가사 없이 생성됩니다.",
"downloading": "다운로드 중...",
"download": "다운로드",
"uploadToSocial": "업로드"
}, },
"dashboard": { "dashboard": {
"title": "대시보드", "title": "대시보드",
@@ -365,13 +373,44 @@
"stayIntroReel": "스테이 머뭄 소개 릴스", "stayIntroReel": "스테이 머뭄 소개 릴스",
"newYearEvent": "신년 특가 이벤트 안내", "newYearEvent": "신년 특가 이벤트 안내",
"nightTimelapse": "펜션 야경 타임랩스" "nightTimelapse": "펜션 야경 타임랩스"
} },
"metricTotalViews": "조회수",
"metricWatchTime": "시청시간",
"metricAvgViewDuration": "평균 시청시간",
"metricNewSubscribers": "신규 구독자",
"metricUploadedVideos": "업로드 영상",
"unitHours": "시간",
"unitMinutes": "분",
"noDataInPeriod": "이 기간에 데이터가 없습니다.",
"dataLoading": "데이터 로딩 중...",
"noUploadsTitle": "아직 업로드된 영상이 없습니다.",
"noUploadsDesc": "ADO2에서 영상을 업로드하면 실제 통계가 표시됩니다.",
"reconnectButton": "재연동하러 가기 →",
"connectButton": "연동하러 가기 →",
"retryButton": "재시도 →",
"selectAccount": "계정을 선택하세요",
"modeAnnual": "연간",
"modeMonthly": "월간",
"chartThisYear": "올해",
"chartLastYear": "작년",
"chartThisMonth": "이번달",
"chartLastMonth": "지난달",
"monthOverMonth": "전월 대비 성장",
"noAudienceData": "누적 데이터가 부족하여 실제 시청자 정보가 없습니다.",
"mockContentNotice": "현재 표시된 콘텐츠는 실제 데이터가 아닌 샘플 데이터입니다.",
"dataDelayTitle": "표시할 데이터 없음",
"dataDelayDesc": "표시할 분석 데이터가 없습니다. 유튜브 정책상 업로드 후 최대 48시간이 지나야 데이터가 반영되며, 영상을 비공개로 업로드했거나 유튜브에서 삭제한 경우에도 통계가 집계되지 않습니다.",
"sampleHide": "Sample 숨기기",
"sampleShow": "Sample 보기",
"recentVideosDesc": "ADO2에서 업로드한 최근 30개의 영상 통계가 표시됩니다.",
"channelStatsDesc": "선택한 채널의 통계가 표시됩니다.",
"youtubeApiFailed": "YouTube Analytics API 호출에 실패했습니다."
}, },
"myInfo": { "myInfo": {
"title": "내 정보", "title": "내 정보",
"tabBasic": "기본 정보", "tabBasic": "기본 정보",
"tabPayment": "결제 정보", "tabPayment": "결제 정보",
"tabBusiness": "내 비즈니스 & 소셜 채널 관리", "tabBusiness": "소셜 채널 관리",
"basicPlaceholder": "기본 정보 설정 기능이 준비 중입니다.", "basicPlaceholder": "기본 정보 설정 기능이 준비 중입니다.",
"paymentPlaceholder": "결제 정보 설정 기능이 준비 중입니다.", "paymentPlaceholder": "결제 정보 설정 기능이 준비 중입니다.",
"myBusiness": "내 비즈니스", "myBusiness": "내 비즈니스",
@@ -386,7 +425,24 @@
"connected": "연결됨", "connected": "연결됨",
"disconnectAccount": "연결 해제", "disconnectAccount": "연결 해제",
"loadingAccounts": "계정 정보를 불러오는 중...", "loadingAccounts": "계정 정보를 불러오는 중...",
"youtubeExpiredAlert": "YouTube 인증이 만료되었습니다. 재연동 페이지로 이동합니다." "youtubeExpiredAlert": "YouTube 인증이 만료되었습니다. 재연동 페이지로 이동합니다.",
"creditsTitle": "크레딧 현황",
"creditsLoading": "로딩 중...",
"creditsLabel": "보유 크레딧",
"creditsUnit": "크레딧",
"creditsDesc": "크레딧이 부족하면 관리자에게 충전 요청할 수 있습니다.",
"creditsChargeBtn": "충전하기",
"chargePopupTitle": "크레딧 충전 요청",
"chargeAmountLabel": "충전 크레딧",
"chargeNoteLabel": "기타 내용",
"chargeNotePlaceholder": "관리자에게 전달할 내용을 입력해주세요",
"chargeCancel": "취소",
"chargeSubmit": "요청하기",
"chargeSubmitting": "요청 중...",
"chargeSuccess": "충전 요청이 완료 되었습니다!",
"chargeConfirm": "확인",
"tabContents": "내 콘텐츠",
"tabCalendar": "콘텐츠 캘린더"
}, },
"ado2Contents": { "ado2Contents": {
"title": "ADO2 콘텐츠", "title": "ADO2 콘텐츠",
@@ -405,7 +461,14 @@
"delete": "삭제", "delete": "삭제",
"previous": "이전", "previous": "이전",
"next": "다음", "next": "다음",
"uploadToSocial": "소셜 미디어에 업로드" "uploadToSocial": "업로드",
"sortLatest": "최신순",
"sortOldest": "오래된순",
"sortLikes": "좋아요 많은순",
"sortComments": "댓글 많은순",
"regionPlaceholder": "지역 선택",
"searchPlaceholder": "업체명 검색",
"searchBtn": "검색"
}, },
"businessSettings": { "businessSettings": {
"title": "비즈니스 설정", "title": "비즈니스 설정",
@@ -434,7 +497,11 @@
"generateContent": "콘텐츠 생성", "generateContent": "콘텐츠 생성",
"pageDescBefore": "을 통해 도출된 ", "pageDescBefore": "을 통해 도출된 ",
"pageDescAfter": "의 핵심 전략입니다.", "pageDescAfter": "의 핵심 전략입니다.",
"loadingTitle": "브랜드 분석 중" "loadingTitle": "브랜드 분석 중",
"loadingStep1": "브랜드 정보를 수집하는 중...",
"loadingStep2": "수집한 데이터를 분석하는 중...",
"loadingStep3": "핵심 전략을 도출하는 중...",
"loadingStep4": "결과를 정리하는 중..."
}, },
"common": { "common": {
"back": "뒤로가기", "back": "뒤로가기",
@@ -446,15 +513,163 @@
"required": "*", "required": "*",
"unknown": "알 수 없음" "unknown": "알 수 없음"
}, },
"contentCalendar": {
"title": "콘텐츠 캘린더",
"tabs": {
"all": "전체",
"completed": "완료",
"scheduled": "예약",
"failed": "실패"
},
"status": {
"completed": "완료",
"scheduled": "예약",
"failed": "실패"
},
"months": [
"1월",
"2월",
"3월",
"4월",
"5월",
"6월",
"7월",
"8월",
"9월",
"10월",
"11월",
"12월"
],
"days": [
"일",
"월",
"화",
"수",
"목",
"금",
"토"
],
"yearMonth": "{{year}}년 {{month}}",
"monthDay": "{{month}} {{day}}일",
"loading": "불러오는 중...",
"noResults": "최근 결과 없음",
"noResultsDesc": "제작한 콘텐츠를 소셜 채널에 업로드해 보세요",
"myContents": "내 콘텐츠",
"cancel": "취소",
"retry": "재시도",
"cancelConfirm": "예약을 취소하시겠습니까?",
"cancelFailed": "취소에 실패했습니다.",
"retryFailed": "재시도에 실패했습니다.",
"completedCount": "완료 {{count}}",
"scheduledCount": "예약 {{count}}",
"failedCount": "실패 {{count}}"
},
"loginPrompt": {
"title": "로그인이 필요합니다.",
"loginBtn": "로그인",
"description": "카카오 계정으로 간편하게 로그인하고\n이어서 진행해보세요."
},
"videoDetail": {
"dateFormat": "{{year}}년 {{month}}월 {{day}}일",
"kakaoDefaultTitle": "ADO2 영상",
"kakaoDescription": "{{region}} · ADO2 AI 마케팅 영상",
"deletedComment": "(삭제된 댓글입니다.)",
"closeAriaLabel": "닫기",
"share": "공유하기",
"copied": "복사됨!",
"siteOverlayLabel": "자세히 보기",
"commentsTitle": "댓글",
"commentPlaceholder": "댓글을 입력하세요...",
"commentLoginRequired": "로그인 후 댓글을 작성할 수 있습니다",
"commentSubmitting": "작성 중",
"commentSubmit": "작성",
"noComments": "아직 댓글이 없습니다.",
"anonymous": "익명",
"deleteComment": "삭제",
"loadMoreComments": "댓글 더 보기",
"loadingComments": "불러오는 중..."
},
"app": { "app": {
"loginProcessing": "로그인 처리 중...", "loginProcessing": "로그인 처리 중...",
"loginFailed": "로그인 처리에 실패했습니다. 다시 시도해주세요.", "loginFailed": "로그인 처리에 실패했습니다. 다시 시도해주세요.",
"kakaoLoginFailed": "카카오 로그인에 실패했습니다. 다시 시도해주세요.", "kakaoLoginFailed": "카카오 로그인에 실패했습니다. 다시 시도해주세요.",
"loginUrlFailed": "로그인 URL을 가져오는데 실패했습니다. 다시 시도해주세요.", "loginUrlFailed": "로그인 URL을 가져오는데 실패했습니다. 다시 시도해주세요.",
"invalidUrl": "유효하지 않은 URL입니다. 네이버 지도 URL을 입력해주세요.", "invalidUrl": "유효하지 않은 URL입니다. 네이버 지도 URL을 입력해주세요.",
"analysisError": "분석 중 오류가 발생했습니다. 다시 시도해주세요.", "analysisError": "검색 정보를 찾을 수 없습니다. 입력 정보를 다시 확인해주세요.",
"autocompleteError": "업체 정보 조회에 실패했습니다.", "autocompleteError": "검색 정보를 찾을 수 없습니다. 입력 정보를 다시 확인해주세요.",
"autocompleteGeneralError": "업체 정보 조회 중 오류가 발생했습니다. 다시 시도해주세요.", "autocompleteGeneralError": "업체 정보 조회 중 오류가 발생했습니다. 다시 시도해주세요.",
"pageComingSoon": "{{page}} 페이지 준비 중입니다." "pageComingSoon": "{{page}} 페이지 준비 중입니다."
},
"pipelineTabs": {
"ariaLabel": "생성할 콘텐츠 종류",
"ado2": "ADO2",
"ssul": "썰박스"
},
"ssulbox": {
"steps": {
"pick": "선택",
"making": "생성",
"done": "완성"
},
"create": {
"step1": "STEP 1 · 시나리오 선택",
"step2": "STEP 2 · 업장 검색",
"searchPlaceholder": "업체명 또는 URL을 입력하세요.",
"searchButton": "검색",
"searching": "검색 중",
"placeLoading": "가게를 찾는 중… (몇 초 걸려요)",
"hintUrlOk": "네이버 링크로 이 가게를 직접 크롤링합니다.",
"hintDefault": "업체의 사진과 정보를 크롤링해 썰박스에 사용합니다.",
"hintScenario": "{{name}} 시나리오로 약 5~6분 소요됩니다.",
"noResult": "검색 결과가 없어요. 이름을 바꾸거나 네이버 지도 링크를 붙여넣어 주세요.",
"cost": "생성 비용",
"costValue": "1 크레딧",
"submit": "썰박스 만들기",
"submitting": "요청 중…"
},
"making": {
"title": "썰박스를 만들고 있어요",
"step1": "대본 생성 중",
"step2": "스토리보드 구성 중",
"step3": "이미지·목소리 생성 중",
"step4": "영상 합성 중",
"takesTime": "약 5~6분 소요됩니다.",
"failTitle": "생성에 실패했어요",
"failDefault": "잠시 후 다시 시도해주세요.",
"refunded": "차감된 크레딧은 환불되었습니다.",
"retry": "다시 만들기"
},
"result": {
"title": "썰박스가 완성됐어요",
"download": "다운로드",
"downloading": "다운로드 중...",
"loadFailed": "영상을 불러오지 못했어요. 내 콘텐츠에서 확인해주세요.",
"scenarioLabel": "시나리오",
"createdLabel": "생성일시"
},
"viewer": {
"untitled": "이름 없는 콘텐츠"
},
"error": {
"createFailed": "생성 요청에 실패했어요. 잠시 후 다시 시도해주세요."
},
"scenario": {
"joseon": {
"name": "조선왕",
"desc": "조선 27대 왕들의 실화 썰"
},
"samgukji": {
"name": "삼국지",
"desc": "위·촉·오 영웅 28인의 야사"
},
"greek": {
"name": "그리스·로마신화",
"desc": "올림포스 신·영웅들의 전설"
},
"odyssey": {
"name": "오디세이",
"desc": "오디세우스 10년 귀향 대모험"
}
}
} }
} }
+1 -29
View File
@@ -1,11 +1,7 @@
import React from 'react';
import React, { useEffect } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { CrawlingResponse, TargetPersona } from '../../types/api'; import { CrawlingResponse, TargetPersona } from '../../types/api';
import { GeometricChart } from './GeometricChart'; import { GeometricChart } from './GeometricChart';
import { useTutorial } from '../../components/Tutorial/useTutorial';
import { TUTORIAL_KEYS } from '../../components/Tutorial/tutorialSteps';
import TutorialOverlay from '../../components/Tutorial/TutorialOverlay';
interface AnalysisResultSectionProps { interface AnalysisResultSectionProps {
onBack: () => void; onBack: () => void;
@@ -15,19 +11,8 @@ interface AnalysisResultSectionProps {
const AnalysisResultSection: React.FC<AnalysisResultSectionProps> = ({ onBack, onGenerate, data }) => { const AnalysisResultSection: React.FC<AnalysisResultSectionProps> = ({ onBack, onGenerate, data }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const tutorial = useTutorial();
const { processed_info, marketing_analysis } = data; const { processed_info, marketing_analysis } = data;
useEffect(() => {
const timer = setTimeout(() => {
if (!tutorial.hasSeen(TUTORIAL_KEYS.ANALYSIS)) {
tutorial.startTutorial(TUTORIAL_KEYS.ANALYSIS);
}
}, 600);
return () => clearTimeout(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const brandIdentity = marketing_analysis?.brand_identity; const brandIdentity = marketing_analysis?.brand_identity;
const marketPositioning = marketing_analysis?.market_positioning; const marketPositioning = marketing_analysis?.market_positioning;
const targetPersonas = marketing_analysis?.target_persona || []; const targetPersonas = marketing_analysis?.target_persona || [];
@@ -38,7 +23,6 @@ const AnalysisResultSection: React.FC<AnalysisResultSectionProps> = ({ onBack, o
const sortedSellingPoints = [...sellingPoints].sort((a, b) => b.score - a.score); const sortedSellingPoints = [...sellingPoints].sort((a, b) => b.score - a.score);
return ( return (
<>
<div className="bi2-page"> <div className="bi2-page">
{/* Header */} {/* Header */}
<div className="bi2-header"> <div className="bi2-header">
@@ -190,18 +174,6 @@ const AnalysisResultSection: React.FC<AnalysisResultSectionProps> = ({ onBack, o
</button> </button>
</div> </div>
</div> </div>
{tutorial.isActive && (
<TutorialOverlay
hints={tutorial.hints}
currentIndex={tutorial.currentHintIndex}
onNext={tutorial.nextHint}
onPrev={tutorial.prevHint}
onSkip={tutorial.skipTutorial}
groupProgress={tutorial.groupProgress}
/>
)}
</>
); );
}; };
+55 -3
View File
@@ -1,15 +1,56 @@
import React from 'react'; import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
const LoadingSection: React.FC = () => { interface LoadingSectionProps {
onComplete?: () => void;
isComplete?: boolean;
}
const LoadingSection: React.FC<LoadingSectionProps> = ({ onComplete, isComplete }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [progress, setProgress] = useState(0);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
useEffect(() => {
intervalRef.current = setInterval(() => {
setProgress(prev => {
if (prev >= 100) {
if (intervalRef.current) clearInterval(intervalRef.current);
return 100;
}
const increment = prev < 70 ? 0.5 : prev < 90 ? 0.2 : 0.1;
return Math.min(prev + increment, 100);
});
}, 200);
return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
};
}, []);
useEffect(() => {
if (!isComplete) return;
if (intervalRef.current) clearInterval(intervalRef.current);
setProgress(100);
const timer = setTimeout(() => {
onComplete?.();
}, 400);
return () => clearTimeout(timer);
}, [isComplete]);
const getStepMessage = (p: number) => {
if (p < 30) return t('analysis.loadingStep1');
if (p < 50) return t('analysis.loadingStep2');
if (p < 80) return t('analysis.loadingStep3');
return t('analysis.loadingStep4');
};
return ( return (
<div className="loading-container"> <div className="loading-container">
<div className="loading-content"> <div className="loading-content">
{/* Logo */} {/* Logo */}
<div className="loading-logo"> <div className="loading-logo">
<img src="/assets/images/ado2-loading-logo.svg" alt="ADO2" /> <img src="/assets/images/ADO2_with Slogan_white.svg" alt="ADO2" />
</div> </div>
{/* Loading Spinner and Text */} {/* Loading Spinner and Text */}
@@ -23,6 +64,17 @@ const LoadingSection: React.FC = () => {
className="loading-spinner-icon" className="loading-spinner-icon"
/> />
</div> </div>
<div className="loading-progress-wrapper">
<div className="loading-progress-bar">
<div
className="loading-progress-fill"
style={{ width: `${progress}%` }}
/>
</div>
<span className="loading-progress-text">{Math.floor(progress)}%</span>
</div>
<p className="loading-step-message">{getStepMessage(progress)}</p>
</div> </div>
</div> </div>
</div> </div>
+153 -191
View File
@@ -1,16 +1,22 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { getVideosList, deleteVideo } from '../../utils/api'; import { getAllVideos } from '../../utils/api';
import { VideoListItem } from '../../types/api'; import { VideoListItem } from '../../types/api';
import SocialPostingModal from '../../components/SocialPostingModal'; import VideoDetailModal from '../../components/VideoDetailModal';
import CitySelectModal from '../../components/CitySelectModal';
import ContentCardSocialActions from '../../components/ContentCardSocialActions';
import SsulViewerModal from '../Ssulbox/SsulViewerModal';
interface ADO2ContentsPageProps { interface ADO2ContentsPageProps {
onBack: () => void; onBack?: () => void;
} }
const ADO2ContentsPage: React.FC<ADO2ContentsPageProps> = ({ onBack }) => { const ADO2ContentsPage: React.FC<ADO2ContentsPageProps> = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const [selectedVideoId, setSelectedVideoId] = useState<number | null>(null);
// 썰박스는 별도 뷰어를 쓴다 — VideoDetailModal 은 video_id 로 조회하므로
// 썰박스 id 를 넘기면 id 가 겹치는 다른 영상이 열린다.
const [selectedSsul, setSelectedSsul] = useState<VideoListItem | null>(null);
const [videos, setVideos] = useState<VideoListItem[]>([]); const [videos, setVideos] = useState<VideoListItem[]>([]);
const [total, setTotal] = useState(0); const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@@ -19,130 +25,105 @@ const ADO2ContentsPage: React.FC<ADO2ContentsPageProps> = ({ onBack }) => {
const [hasNext, setHasNext] = useState(false); const [hasNext, setHasNext] = useState(false);
const [hasPrev, setHasPrev] = useState(false); const [hasPrev, setHasPrev] = useState(false);
const [totalPages, setTotalPages] = useState(1); const [totalPages, setTotalPages] = useState(1);
const [deleteModalOpen, setDeleteModalOpen] = useState(false);
const [deleteTargetId, setDeleteTargetId] = useState<number | null>(null);
const [isDeleting, setIsDeleting] = useState(false);
const [uploadModalOpen, setUploadModalOpen] = useState(false);
const [uploadTargetVideo, setUploadTargetVideo] = useState<VideoListItem | null>(null);
const pageSize = 12; const pageSize = 20;
const [sortBy, setSortBy] = useState<'created_at' | 'like_count' | 'comment_count'>('created_at');
const [order, setOrder] = useState<'desc' | 'asc'>('desc');
const [searchInput, setSearchInput] = useState('');
const [storeName, setStoreName] = useState('');
const [region, setRegion] = useState('');
const [showCityModal, setShowCityModal] = useState(false);
useEffect(() => { useEffect(() => {
fetchVideos(); fetchVideos();
}, [page]); }, [page, sortBy, order, storeName, region]);
const fetchVideos = async () => { const fetchVideos = async () => {
setLoading(true); setLoading(true);
setError(null); setError(null);
try { try {
const response = await getVideosList(page, pageSize); const response = await getAllVideos(page, pageSize, sortBy, storeName, order, region);
console.log('[ADO2] API response:', response); setVideos(response.items);
console.log('[ADO2] First video item:', response.items[0]);
// result_movie_url이 있는 비디오만 필터링 (빈/더미 데이터 제외)
const validVideos = response.items.filter(video => video.result_movie_url && video.result_movie_url.trim() !== '');
setVideos(validVideos);
setTotal(response.total); setTotal(response.total);
setTotalPages(response.total_pages); setTotalPages(response.total_pages);
setHasNext(response.has_next); setHasNext(response.has_next);
setHasPrev(response.has_prev); setHasPrev(response.has_prev);
} catch (err) { } catch (err) {
console.error('Failed to fetch videos:', err); console.error('Failed to fetch all videos:', err);
setError(t('ado2Contents.loadFailed')); setError(t('ado2Contents.loadFailed'));
} finally { } finally {
setLoading(false); setLoading(false);
} }
}; };
const handleCardClick = (videoId: number) => {
setSelectedVideoId(videoId);
};
const formatDate = (dateString: string) => { const formatDate = (dateString: string) => {
const date = new Date(dateString); const date = new Date(dateString);
const year = date.getFullYear(); const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0'); const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0'); return `${year}.${month}.${day}`;
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${year}.${month}.${day}・${hours}:${minutes}`;
};
const formatTitle = (storeName: string, dateString: string) => {
const date = new Date(dateString);
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${storeName} ${month}/${day} ${hours}:${minutes}`;
};
const handleDownload = async (videoUrl: string, storeName: string) => {
try {
const response = await fetch(videoUrl);
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${storeName}.mp4`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (err) {
console.error('Download failed:', err);
alert(t('ado2Contents.downloadFailed'));
}
};
const handleDeleteClick = (videoId: number) => {
setDeleteTargetId(videoId);
setDeleteModalOpen(true);
};
const handleUploadClick = (video: VideoListItem) => {
console.log('[ADO2] Upload clicked - video object:', video);
console.log('[ADO2] video.video_id:', video.video_id);
setUploadTargetVideo(video);
setUploadModalOpen(true);
};
const handleUploadModalClose = () => {
setUploadModalOpen(false);
setUploadTargetVideo(null);
};
const handleDeleteCancel = () => {
setDeleteModalOpen(false);
setDeleteTargetId(null);
};
const handleDeleteConfirm = async () => {
if (!deleteTargetId) return;
setIsDeleting(true);
try {
await deleteVideo(deleteTargetId);
// 삭제 성공 시 로컬 상태에서 즉시 제거 (UI 즉시 반영)
// fetchVideos()를 호출하지 않음 - 서버 캐시 또는 동기화 지연으로 인해
// 삭제된 항목이 다시 나타날 수 있기 때문
setVideos(prev => prev.filter(video => video.video_id !== deleteTargetId));
setTotal(prev => Math.max(0, prev - 1));
setDeleteModalOpen(false);
setDeleteTargetId(null);
} catch (err) {
console.error('Delete failed:', err);
alert(t('ado2Contents.deleteFailed'));
} finally {
setIsDeleting(false);
}
}; };
return ( return (
<div className="ado2-contents-page"> <div className="ado2-contents-page">
{/* Header */}
<div className="ado2-contents-header"> <div className="ado2-contents-header">
<h1 className="ado2-contents-title">{t('ado2Contents.title')}</h1> <h1 className="ado2-contents-title">{t('sidebar.ado2Contents')}</h1>
<span className="ado2-contents-count">{t('ado2Contents.totalCount', { count: total })}</span> <span className="ado2-contents-count">{t('ado2Contents.totalCount', { count: total })}</span>
</div> </div>
{/* Content Grid */} <div className="ado2-contents-filters">
<select
className="ado2-filter-select"
value={`${sortBy}__${order}`}
onChange={(e) => {
const [sb, ord] = e.target.value.split('__') as [typeof sortBy, typeof order];
setSortBy(sb);
setOrder(ord);
setPage(1);
}}
>
<option value="created_at__desc">{t('ado2Contents.sortLatest')}</option>
<option value="created_at__asc">{t('ado2Contents.sortOldest')}</option>
<option value="like_count__desc">{t('ado2Contents.sortLikes')}</option>
<option value="comment_count__desc">{t('ado2Contents.sortComments')}</option>
</select>
<button
type="button"
className={`ado2-region-pill ${region ? 'active' : ''}`}
onClick={() => setShowCityModal(true)}
>
{region || t('ado2Contents.regionPlaceholder')}
{region && (
<span className="ado2-region-clear" onClick={(e) => { e.stopPropagation(); setRegion(''); setPage(1); }}>✕</span>
)}
</button>
<form
className="ado2-filter-search"
onSubmit={(e) => {
e.preventDefault();
setStoreName(searchInput);
setPage(1);
}}
>
<input
type="text"
className="ado2-filter-input"
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
placeholder={t('ado2Contents.searchPlaceholder')}
/>
<button type="submit" className="ado2-filter-btn">
{t('ado2Contents.searchBtn')}
</button>
</form>
</div>
{loading ? ( {loading ? (
<div className="ado2-contents-loading"> <div className="ado2-contents-loading">
<div className="loading-spinner"></div> <div className="loading-spinner"></div>
@@ -161,89 +142,86 @@ const ADO2ContentsPage: React.FC<ADO2ContentsPageProps> = ({ onBack }) => {
<> <>
<div className="ado2-contents-grid"> <div className="ado2-contents-grid">
{videos.map((video) => ( {videos.map((video) => (
<div key={video.task_id} className="ado2-content-card"> // key·상세 열기 모두 (type, video_id) 로 다뤄야 한다 —
{/* Video Thumbnail */} // video_id 는 종류별 독립 시퀀스라 값이 겹친다.
<div className="content-card-thumbnail"> <div
{video.result_movie_url ? ( key={`${video.type}-${video.video_id}`}
className="ado2-content-card"
style={{ cursor: 'pointer' }}
onClick={() =>
video.type === 'ssul'
? setSelectedSsul(video)
: handleCardClick(video.video_id)
}
role="button"
tabIndex={0}
onKeyDown={(e) =>
e.key === 'Enter' &&
(video.type === 'ssul'
? setSelectedSsul(video)
: handleCardClick(video.video_id))
}
>
<div className="content-card-thumbnail ado2-gallery-thumbnail-wrap">
{video.poster_url ? (
<img
src={video.poster_url}
alt={video.store_name}
loading="lazy"
decoding="async"
className="content-video-preview"
/>
) : video.thumbnail_url ? (
<img
src={video.thumbnail_url}
alt={video.store_name}
style={{ width: '100%', height: '100%', objectFit: 'cover' }}
/>
) : video.result_movie_url ? (
<video <video
src={video.result_movie_url} src={video.result_movie_url}
className="content-video-preview" className="content-video-preview"
preload="metadata"
muted muted
playsInline playsInline
onMouseEnter={(e) => e.currentTarget.play()}
onMouseLeave={(e) => {
e.currentTarget.pause();
e.currentTarget.currentTime = 0;
}}
/> />
) : ( ) : (
<div className="content-no-video"> <div className="content-no-video" />
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5"> )}
<rect x="2" y="2" width="20" height="20" rx="2.18" ry="2.18"/> {/* 호버 오버레이 */}
<line x1="7" y1="2" x2="7" y2="22"/> <div className="ado2-gallery-overlay">
<line x1="17" y1="2" x2="17" y2="22"/> <div className="ado2-gallery-play-btn">
<line x1="2" y1="12" x2="22" y2="12"/> <svg width="28" height="28" viewBox="0 0 24 24" fill="currentColor">
<line x1="2" y1="7" x2="7" y2="7"/> <polygon points="5,3 19,12 5,21"/>
<line x1="2" y1="17" x2="7" y2="17"/>
<line x1="17" y1="17" x2="22" y2="17"/>
<line x1="17" y1="7" x2="22" y2="7"/>
</svg> </svg>
</div> </div>
)} </div>
</div> </div>
{/* Card Info */}
<div className="content-card-info"> <div className="content-card-info">
<div className="content-card-text"> <div className="content-card-text">
<h3 className="content-card-title"> <h3 className="content-card-title">{video.store_name}</h3>
{formatTitle(video.store_name, video.created_at)} <div className="content-card-meta">
</h3> <p className="content-card-date">{formatDate(video.created_at)}</p>
<p className="content-card-date"> {/* 좋아요·댓글 API 가 type 을 받으므로 썰박스에도 노출한다.
{formatDate(video.created_at)} contentType 이 없으면 id 가 겹치는 다른 영상에 반영된다. */}
</p> <ContentCardSocialActions
</div> videoId={video.video_id}
contentType={video.type}
{/* Action Buttons */} storeName={video.store_name}
<div className="content-card-actions"> region={video.region}
<button title={video.title}
className="content-download-btn" description={video.description}
onClick={() => handleUploadClick(video)} commentCount={video.comment_count ?? 0}
disabled={!video.result_movie_url} initialLikeCount={video.like_count ?? 0}
> initialIsLiked={video.is_liked_by_me}
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5"> />
<path d="M10 13V3M10 3l-4 4M10 3l4 4"/> </div>
<path d="M3 15v2h14v-2"/>
</svg>
<span>{t('ado2Contents.uploadToSocial')}</span>
</button>
<button
className="content-upload-btn"
onClick={() => handleDownload(video.result_movie_url, video.store_name)}
disabled={!video.result_movie_url}
title={t('ado2Contents.download')}
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5">
<path d="M10 3v10M10 13l-4-4M10 13l4-4"/>
<path d="M3 15v2h14v-2"/>
</svg>
</button>
<button
className="content-delete-btn"
onClick={() => handleDeleteClick(video.video_id)}
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5">
<path d="M3 5h14M8 5V3h4v2M6 5v12h8V5"/>
<line x1="8" y1="8" x2="8" y2="14"/>
<line x1="12" y1="8" x2="12" y2="14"/>
</svg>
</button>
</div> </div>
</div> </div>
</div> </div>
))} ))}
</div> </div>
{/* Pagination - 항상 표시 */}
<div className="ado2-contents-pagination"> <div className="ado2-contents-pagination">
<button <button
className="pagination-btn" className="pagination-btn"
@@ -264,38 +242,22 @@ const ADO2ContentsPage: React.FC<ADO2ContentsPageProps> = ({ onBack }) => {
</> </>
)} )}
{/* 삭제 확인 모달 */} <SsulViewerModal item={selectedSsul} onClose={() => setSelectedSsul(null)} />
{deleteModalOpen && (
<div className="delete-modal-overlay" onClick={handleDeleteCancel}> {selectedVideoId !== null && (
<div className="delete-modal" onClick={(e: React.MouseEvent) => e.stopPropagation()}> <VideoDetailModal
<h2 className="delete-modal-title">{t('ado2Contents.deleteConfirmTitle')}</h2> videoId={String(selectedVideoId)}
<p className="delete-modal-description">{t('ado2Contents.deleteConfirmDesc')}</p> onClose={() => setSelectedVideoId(null)}
<div className="delete-modal-actions"> />
<button
className="delete-modal-btn cancel"
onClick={handleDeleteCancel}
disabled={isDeleting}
>
{t('ado2Contents.cancel')}
</button>
<button
className="delete-modal-btn confirm"
onClick={handleDeleteConfirm}
disabled={isDeleting}
>
{isDeleting ? t('ado2Contents.deleting') : t('ado2Contents.delete')}
</button>
</div>
</div>
</div>
)} )}
{/* 소셜 미디어 업로드 모달 */} {showCityModal && (
<SocialPostingModal <CitySelectModal
isOpen={uploadModalOpen} selected={region}
onClose={handleUploadModalClose} onSelect={(city) => { setRegion(city); setPage(1); }}
video={uploadTargetVideo} onClose={() => setShowCityModal(false)}
/> />
)}
</div> </div>
); );
}; };
+195 -35
View File
@@ -3,13 +3,19 @@ import React, { useRef, useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { ImageItem, ImageUrlItem } from '../../types/api'; import { ImageItem, ImageUrlItem } from '../../types/api';
import { uploadImages } from '../../utils/api'; import { uploadImages } from '../../utils/api';
import { isImageInputFile } from '../../utils/imageCompression.ts';
import { MAX_IMAGES_PER_UPLOAD_TASK } from '../../utils/imageUpload.ts';
import { splitDuplicateFiles } from '../../utils/imageDedup.ts';
interface AssetManagementContentProps { interface AssetManagementContentProps {
onNext: (imageTaskId: string) => void; onNext: (imageTaskId: string) => void;
onBack?: () => void; onBack?: () => void;
imageList: ImageItem[]; imageList: ImageItem[];
onRemoveImage: (index: number) => void; onRemoveImage: (index: number) => void;
onAddImages: (files: File[]) => void; onAddImages: (
files: File[],
onProgress: (done: number, total: number) => void
) => Promise<void>;
} }
type VideoRatio = 'vertical' | 'horizontal'; type VideoRatio = 'vertical' | 'horizontal';
@@ -26,9 +32,12 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
const { t } = useTranslation(); const { t } = useTranslation();
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
const [isUploading, setIsUploading] = useState(false); const [isUploading, setIsUploading] = useState(false);
const [uploadError, setUploadError] = useState<string | null>(null); const [uploadProgress, setUploadProgress] = useState(0);
// 업로드 실패와 중복 제외 안내가 같은 다이얼로그 마크업을 공유한다.
const [dialog, setDialog] = useState<{ title: string; message: string } | null>(null);
const [videoRatio, setVideoRatio] = useState<VideoRatio>('vertical'); const [videoRatio, setVideoRatio] = useState<VideoRatio>('vertical');
const [displayCount, setDisplayCount] = useState(IMAGES_PER_PAGE); const [displayCount, setDisplayCount] = useState(IMAGES_PER_PAGE);
const [thumbnailProgress, setThumbnailProgress] = useState<{ done: number; total: number } | null>(null);
useEffect(() => { useEffect(() => {
const savedRatio = localStorage.getItem('castad_video_ratio') as VideoRatio; const savedRatio = localStorage.getItem('castad_video_ratio') as VideoRatio;
@@ -37,20 +46,42 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
} }
}, []); }, []);
useEffect(() => {
if (!dialog) return;
const handleEscape = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
event.preventDefault();
setDialog(null);
}
};
window.addEventListener('keydown', handleEscape);
return () => window.removeEventListener('keydown', handleEscape);
}, [dialog]);
const handleVideoRatioChange = (ratio: VideoRatio) => { const handleVideoRatioChange = (ratio: VideoRatio) => {
setVideoRatio(ratio); setVideoRatio(ratio);
localStorage.setItem('castad_video_ratio', ratio); localStorage.setItem('castad_video_ratio', ratio);
}; };
const getImageSrc = (item: ImageItem): string => { const getImageSrc = (item: ImageItem): string | null => {
return item.type === 'url' ? item.url : item.preview; return item.type === 'url' ? item.preview_url : item.preview;
}; };
const handleNextWithUpload = async () => { const handleNextWithUpload = async () => {
if (imageList.length === 0) return; if (imageList.length === 0) return;
setIsUploading(true); setIsUploading(true);
setUploadError(null); setUploadProgress(0);
setDialog(null);
const interval = setInterval(() => {
setUploadProgress(prev => {
if (prev >= 99) return prev;
return prev + (prev < 50 ? 0.6 : prev < 80 ? 0.3 : prev < 90 ? 0.15 : 0.11);
});
}, 200);
try { try {
const urlImages: ImageUrlItem[] = imageList const urlImages: ImageUrlItem[] = imageList
@@ -63,13 +94,47 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
if (urlImages.length > 0 || fileImages.length > 0) { if (urlImages.length > 0 || fileImages.length > 0) {
const response = await uploadImages(urlImages, fileImages); const response = await uploadImages(urlImages, fileImages);
clearInterval(interval);
setUploadProgress(100);
// 이미지 변경 시 이전 음악/영상 생성 결과 초기화 — 반드시 재생성하도록 강제
localStorage.removeItem('castad_song_generation');
localStorage.removeItem('castad_song_completion');
localStorage.removeItem('castad_song_task_id');
localStorage.removeItem('castad_video_generation');
localStorage.removeItem('castad_video_complete');
onNext(response.task_id); onNext(response.task_id);
} }
} catch (error) { } catch (error) {
clearInterval(interval);
console.error('Image upload failed:', error); console.error('Image upload failed:', error);
setUploadError(error instanceof Error ? error.message : t('assetManagement.uploadFailed')); setDialog({
title: t('assetManagement.uploadErrorTitle'),
message: error instanceof Error ? error.message : t('assetManagement.uploadFailed'),
});
} finally { } finally {
setIsUploading(false); setIsUploading(false);
setUploadProgress(0);
}
};
const runAddImages = async (files: File[]) => {
const { newFiles, duplicateCount } = splitDuplicateFiles(imageList, files);
if (newFiles.length > 0) {
setThumbnailProgress({ done: 0, total: newFiles.length });
try {
await onAddImages(newFiles, (done, total) => setThumbnailProgress({ done, total }));
} finally {
setThumbnailProgress(null);
}
}
// 썸네일 생성 오버레이에 가려지지 않도록 작업이 끝난 뒤에 안내한다.
if (duplicateCount > 0) {
setDialog({
title: t('assetManagement.duplicateSkippedTitle'),
message: t('assetManagement.duplicateSkippedMessage', { count: duplicateCount }),
});
} }
}; };
@@ -81,10 +146,8 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
const handleDrop = (e: React.DragEvent) => { const handleDrop = (e: React.DragEvent) => {
e.preventDefault(); e.preventDefault();
e.stopPropagation(); e.stopPropagation();
const files = Array.from(e.dataTransfer.files).filter((file: File) => const files = Array.from(e.dataTransfer.files).filter(isImageInputFile);
file.type.startsWith('image/') if (files.length > 0) void runAddImages(files);
);
if (files.length > 0) onAddImages(files);
}; };
const handleFileSelect = () => { const handleFileSelect = () => {
@@ -94,7 +157,7 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => { const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const files = e.target.files; const files = e.target.files;
if (files && files.length > 0) { if (files && files.length > 0) {
onAddImages(Array.from(files)); void runAddImages(Array.from(files));
e.target.value = ''; e.target.value = '';
} }
}; };
@@ -104,6 +167,79 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
return ( return (
<main className="asset-page"> <main className="asset-page">
{thumbnailProgress && (
<div className="asset-upload-overlay">
<div className="asset-upload-overlay-content">
<div className="loading-spinner">
<div className="loading-ring"></div>
<div className="loading-dot">
<div className="loading-dot-inner"></div>
</div>
</div>
<p className="comp2-loading-text">
{t('assetManagement.preparingPreviews', {
done: thumbnailProgress.done,
total: thumbnailProgress.total,
})}
</p>
</div>
</div>
)}
{isUploading && (
<div className="asset-upload-overlay">
<div className="asset-upload-overlay-content">
<div className="loading-spinner">
<div className="loading-ring"></div>
<div className="loading-dot">
<div className="loading-dot-inner"></div>
</div>
</div>
<p className="comp2-loading-text">{t('assetManagement.uploading')}</p>
<div className="loading-progress-wrapper">
<div className="loading-progress-bar">
<div
className="loading-progress-fill"
style={{ width: `${uploadProgress}%` }}
/>
</div>
<span className="loading-progress-text">{Math.floor(uploadProgress)}%</span>
</div>
</div>
</div>
)}
{dialog && (
<div
className="asset-upload-error-overlay"
onClick={() => setDialog(null)}
>
<div
className="asset-upload-error-dialog"
role="alertdialog"
aria-modal="true"
aria-labelledby="asset-upload-error-title"
aria-describedby="asset-upload-error-message"
onClick={(event) => event.stopPropagation()}
>
<h2 id="asset-upload-error-title" className="asset-upload-error-title">
{dialog.title}
</h2>
<p id="asset-upload-error-message" className="asset-upload-error-message">
{dialog.message}
</p>
<button
type="button"
className="asset-upload-error-confirm"
onClick={() => setDialog(null)}
autoFocus
>
{t('assetManagement.uploadErrorConfirm')}
</button>
</div>
</div>
)}
{/* Fixed Header - 뒤로가기 버튼 */} {/* Fixed Header - 뒤로가기 버튼 */}
<div className="asset-sticky-header"> <div className="asset-sticky-header">
{onBack && ( {onBack && (
@@ -127,6 +263,13 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
<div className="asset-section-header-left"> <div className="asset-section-header-left">
<h3 className="asset-section-title">{t('assetManagement.selectedImages')}</h3> <h3 className="asset-section-title">{t('assetManagement.selectedImages')}</h3>
<span className="asset-section-subtitle">{t('assetManagement.minImages')}</span> <span className="asset-section-subtitle">{t('assetManagement.minImages')}</span>
<span
className={`asset-section-count${
imageList.length > MAX_IMAGES_PER_UPLOAD_TASK ? ' asset-section-count-over' : ''
}`}
>
{imageList.length} / {MAX_IMAGES_PER_UPLOAD_TASK}
</span>
</div> </div>
<button onClick={handleFileSelect} className="asset-mobile-upload-btn"> <button onClick={handleFileSelect} className="asset-mobile-upload-btn">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none"> <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
@@ -140,26 +283,46 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
<div className="asset-image-list"> <div className="asset-image-list">
{visibleImages.length > 0 && ( {visibleImages.length > 0 && (
<div className="asset-image-grid"> <div className="asset-image-grid">
{visibleImages.map((item, i) => ( {visibleImages.map((item, i) => {
<div key={i} className="asset-image-item"> const src = getImageSrc(item);
<img const fileName = item.type === 'file' ? item.file.name : '';
src={getImageSrc(item)} return (
alt={`${t('assetManagement.imageAlt')} ${i + 1}`} <div key={i} className="asset-image-item">
/> {src ? (
{item.type === 'file' && ( <img
<div className="asset-image-badge">{t('assetManagement.uploadBadge')}</div> src={src}
)} alt={`${t('assetManagement.imageAlt')} ${i + 1}`}
<button referrerPolicy="no-referrer"
onClick={() => onRemoveImage(i)} loading="lazy"
className="asset-image-remove" decoding="async"
> />
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5"> ) : (
<line x1="18" y1="6" x2="6" y2="18"/> <div className="asset-image-placeholder" title={fileName}>
<line x1="6" y1="6" x2="18" y2="18"/> <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
</svg> <rect x="3" y="3" width="18" height="18" rx="2"/>
</button> <circle cx="8.5" cy="8.5" r="1.5"/>
</div> <path d="M21 15l-5-5L5 21"/>
))} </svg>
<span className="asset-image-placeholder-name">
{fileName || t('assetManagement.previewUnavailable')}
</span>
</div>
)}
{item.type === 'file' && (
<div className="asset-image-badge">{t('assetManagement.uploadBadge')}</div>
)}
<button
onClick={() => onRemoveImage(i)}
className="asset-image-remove"
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<line x1="18" y1="6" x2="6" y2="18"/>
<line x1="6" y1="6" x2="18" y2="18"/>
</svg>
</button>
</div>
);
})}
</div> </div>
)} )}
</div> </div>
@@ -225,9 +388,6 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
{/* Fixed Footer - 다음 단계 버튼 */} {/* Fixed Footer - 다음 단계 버튼 */}
<div className="asset-sticky-footer"> <div className="asset-sticky-footer">
{uploadError && (
<p className="text-red-500 text-sm mb-2">{uploadError}</p>
)}
<button <button
onClick={handleNextWithUpload} onClick={handleNextWithUpload}
disabled={imageList.length === 0 || isUploading} disabled={imageList.length === 0 || isUploading}
@@ -240,7 +400,7 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
<input <input
ref={fileInputRef} ref={fileInputRef}
type="file" type="file"
accept="image/*" accept="image/*,.heic,.heif"
multiple multiple
onChange={handleFileChange} onChange={handleFileChange}
className="hidden" className="hidden"
@@ -1,21 +0,0 @@
import React from 'react';
import Sidebar from '../../components/Sidebar';
import AssetManagementContent from './AssetManagementContent';
interface AssetManagementSectionProps {
onBack: () => void;
}
const AssetManagementSection: React.FC<AssetManagementSectionProps> = ({ onBack }) => {
return (
<div className="flex w-full h-screen bg-[#002224] text-white overflow-hidden">
<Sidebar />
<div className="flex-1 overflow-y-auto">
<AssetManagementContent onBack={onBack} onNext={() => {}} />
</div>
</div>
);
};
export default AssetManagementSection;
+168 -151
View File
@@ -1,17 +1,16 @@
import React, { useState, useEffect, useRef } from 'react'; import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { generateVideo, waitForVideoComplete } from '../../utils/api'; import { generateVideo, waitForVideoComplete, getSubtitleStatus, waitForSubtitleComplete, trackFirstVideoCreated } from '../../utils/api';
import SocialPostingModal from '../../components/SocialPostingModal'; import SocialPostingModal from '../../components/SocialPostingModal';
import { useTutorial } from '../../components/Tutorial/useTutorial'; import CompletionView from '../../components/CompletionView';
import { TUTORIAL_KEYS } from '../../components/Tutorial/tutorialSteps';
import TutorialOverlay from '../../components/Tutorial/TutorialOverlay';
interface CompletionContentProps { interface CompletionContentProps {
onBack: () => void; onBack: () => void;
songTaskId: string | null; songTaskId: string | null;
onVideoStatusChange?: (status: 'idle' | 'generating' | 'complete' | 'error') => void; onVideoStatusChange?: (status: 'idle' | 'generating' | 'complete' | 'error') => void;
onVideoProgressChange?: (progress: number) => void; onVideoProgressChange?: (progress: number) => void;
onGoToCalendar?: () => void;
} }
type VideoStatus = 'idle' | 'generating' | 'polling' | 'complete' | 'error'; type VideoStatus = 'idle' | 'generating' | 'polling' | 'complete' | 'error';
@@ -32,7 +31,8 @@ const CompletionContent: React.FC<CompletionContentProps> = ({
onBack, onBack,
songTaskId, songTaskId,
onVideoStatusChange, onVideoStatusChange,
onVideoProgressChange onVideoProgressChange,
onGoToCalendar,
}) => { }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [videoStatus, setVideoStatus] = useState<VideoStatus>('idle'); const [videoStatus, setVideoStatus] = useState<VideoStatus>('idle');
@@ -40,21 +40,9 @@ const CompletionContent: React.FC<CompletionContentProps> = ({
const [errorMessage, setErrorMessage] = useState<string | null>(null); const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [statusMessage, setStatusMessage] = useState(''); const [statusMessage, setStatusMessage] = useState('');
const [renderProgress, setRenderProgress] = useState(0); const [renderProgress, setRenderProgress] = useState(0);
const [displayProgress, setDisplayProgress] = useState(0);
const hasStartedGeneration = useRef(false); const hasStartedGeneration = useRef(false);
const displayIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
const tutorial = useTutorial();
// 영상 생성 중 튜토리얼 트리거 (생성 상태 안내 -> 콘텐츠 정보 -> 내 정보 이동)
useEffect(() => {
const isComplete = videoStatus === 'complete';
const isProcessing = videoStatus === 'generating' || videoStatus === 'polling';
if (isProcessing && !tutorial.isActive && !tutorial.hasSeen(TUTORIAL_KEYS.GENERATING)) {
tutorial.startTutorial(TUTORIAL_KEYS.GENERATING);
} else if (isComplete && !tutorial.isActive && !tutorial.hasSeen(TUTORIAL_KEYS.COMPLETION)) {
tutorial.startTutorial(TUTORIAL_KEYS.COMPLETION);
}
}, [videoStatus, tutorial]);
// 소셜 미디어 포스팅 모달 // 소셜 미디어 포스팅 모달
const [showSocialModal, setShowSocialModal] = useState(false); const [showSocialModal, setShowSocialModal] = useState(false);
@@ -83,6 +71,31 @@ const CompletionContent: React.FC<CompletionContentProps> = ({
} }
}, [renderProgress, onVideoProgressChange]); }, [renderProgress, onVideoProgressChange]);
useEffect(() => {
if (displayIntervalRef.current) clearInterval(displayIntervalRef.current);
if (renderProgress === 100) {
setDisplayProgress(100);
return;
}
// renderProgress에 도달한 후에도 99%까지 서서히 크리핑
const CREEP_MAX = 99;
displayIntervalRef.current = setInterval(() => {
setDisplayProgress(prev => {
const target = Math.max(prev, renderProgress);
if (prev >= CREEP_MAX) return prev;
const increment = prev < 70 ? 0.2 : prev < 90 ? 0.04 : 0.01;
return Math.min(prev + increment, Math.max(target, Math.min(prev + increment, CREEP_MAX)));
});
}, 100);
return () => {
if (displayIntervalRef.current) clearInterval(displayIntervalRef.current);
};
}, [renderProgress]);
const saveToStorage = (videoTaskId: string, currentSongTaskId: string, status: VideoStatus, url: string | null, dbId?: number) => { const saveToStorage = (videoTaskId: string, currentSongTaskId: string, status: VideoStatus, url: string | null, dbId?: number) => {
const data: SavedVideoState = { const data: SavedVideoState = {
videoTaskId, videoTaskId,
@@ -143,10 +156,19 @@ const CompletionContent: React.FC<CompletionContentProps> = ({
hasStartedGeneration.current = true; hasStartedGeneration.current = true;
setVideoStatus('generating'); setVideoStatus('generating');
setStatusMessage(t('completion.requestingGeneration')); setStatusMessage(t('completion.checkingSubtitle'));
setErrorMessage(null); setErrorMessage(null);
try { try {
// 자막 완료 여부 확인 후 미완료면 폴링
const subtitleStatus = await getSubtitleStatus(songTaskId);
if (subtitleStatus.status !== 'completed') {
setStatusMessage(t('completion.waitingSubtitle'));
await waitForSubtitleComplete(songTaskId);
}
setStatusMessage(t('completion.requestingGeneration'));
const savedRatio = localStorage.getItem('castad_video_ratio'); const savedRatio = localStorage.getItem('castad_video_ratio');
const orientation = (savedRatio === 'horizontal' || savedRatio === 'vertical') ? savedRatio : 'vertical'; const orientation = (savedRatio === 'horizontal' || savedRatio === 'vertical') ? savedRatio : 'vertical';
@@ -226,6 +248,9 @@ const CompletionContent: React.FC<CompletionContentProps> = ({
setVideoStatus('complete'); setVideoStatus('complete');
setStatusMessage(''); setStatusMessage('');
saveToStorage(videoTaskId, currentSongTaskId, 'complete', videoUrlFromResponse, videoId); saveToStorage(videoTaskId, currentSongTaskId, 'complete', videoUrlFromResponse, videoId);
// Meta FirstVideoCreated 전환 이벤트 발화 (서버가 계정당 최초 1회 판정, 실패해도 무시)
trackFirstVideoCreated();
} else { } else {
throw new Error(t('completion.videoUrlMissing')); throw new Error(t('completion.videoUrlMissing'));
} }
@@ -254,6 +279,7 @@ const CompletionContent: React.FC<CompletionContentProps> = ({
setVideoUrl(completeVideo.videoUrl); setVideoUrl(completeVideo.videoUrl);
if (completeVideo.videoDbId) setVideoDbId(completeVideo.videoDbId); if (completeVideo.videoDbId) setVideoDbId(completeVideo.videoDbId);
setVideoStatus('complete'); setVideoStatus('complete');
setShowComplete(true);
hasStartedGeneration.current = true; hasStartedGeneration.current = true;
return; return;
} }
@@ -265,6 +291,7 @@ const CompletionContent: React.FC<CompletionContentProps> = ({
setVideoUrl(savedState.videoUrl); setVideoUrl(savedState.videoUrl);
if (savedState.videoDbId) setVideoDbId(savedState.videoDbId); if (savedState.videoDbId) setVideoDbId(savedState.videoDbId);
setVideoStatus('complete'); setVideoStatus('complete');
setShowComplete(true);
hasStartedGeneration.current = true; hasStartedGeneration.current = true;
} else if (savedState.status === 'polling') { } else if (savedState.status === 'polling') {
setVideoStatus('polling'); setVideoStatus('polling');
@@ -296,15 +323,32 @@ const CompletionContent: React.FC<CompletionContentProps> = ({
} }
}, []); }, []);
const handleDownload = () => { const [isDownloading, setIsDownloading] = useState(false);
if (videoUrl) {
const handleDownload = async () => {
if (!videoUrl || isDownloading) return;
setIsDownloading(true);
try {
const response = await fetch(videoUrl);
const blob = await response.blob();
const blobUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = blobUrl;
link.download = getFileName();
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(blobUrl);
} catch {
const link = document.createElement('a'); const link = document.createElement('a');
link.href = videoUrl; link.href = videoUrl;
link.download = 'castad_video.mp4'; link.download = getFileName();
link.target = '_blank'; link.target = '_blank';
document.body.appendChild(link); document.body.appendChild(link);
link.click(); link.click();
document.body.removeChild(link); document.body.removeChild(link);
} finally {
setIsDownloading(false);
} }
}; };
@@ -321,11 +365,20 @@ const CompletionContent: React.FC<CompletionContentProps> = ({
setVideoStatus('idle'); setVideoStatus('idle');
setVideoUrl(null); setVideoUrl(null);
setErrorMessage(null); setErrorMessage(null);
setShowComplete(false);
clearStorage(); clearStorage();
startVideoGeneration(); startVideoGeneration();
}; };
const isLoading = videoStatus === 'generating' || videoStatus === 'polling'; const [showComplete, setShowComplete] = useState(false);
useEffect(() => {
if (displayProgress < 100) return;
const timer = setTimeout(() => setShowComplete(true), 500);
return () => clearTimeout(timer);
}, [displayProgress]);
const isLoading = videoStatus === 'generating' || videoStatus === 'polling' || (videoStatus === 'complete' && !showComplete);
// 비디오 해상도 계산 // 비디오 해상도 계산
const getVideoResolution = () => { const getVideoResolution = () => {
@@ -339,134 +392,98 @@ const CompletionContent: React.FC<CompletionContentProps> = ({
return `${businessName}.mp4`; return `${businessName}.mp4`;
}; };
/**
* 가사 단락 파싱.
*
* `[Verse]` 처럼 대괄호만 있는 줄을 섹션 머리로 보고, 뒤따르는 줄들을 그 섹션에
* 묶는다. 태그 없이 시작하는 가사도 있어 첫 섹션은 태그 없이 열릴 수 있다.
*/
const renderLyrics = () => {
if (!songCompletionData) {
return <p className="comp2-lyrics-text">{t('completion.sampleLyrics')}</p>;
}
if (!songCompletionData.lyrics) {
return <p className="comp2-lyrics-text">{t('completion.noLyricsBGM')}</p>;
}
const lines = songCompletionData.lyrics.split('\n').filter((l: string) => l.trim());
const sections: { tag: string | null; lines: string[] }[] = [];
lines.forEach((line: string) => {
const tagMatch = line.trim().match(/^\[(.+)\]$/);
if (tagMatch) {
sections.push({ tag: `[${tagMatch[1]}]`, lines: [] });
} else if (sections.length === 0) {
sections.push({ tag: null, lines: [line] });
} else {
sections[sections.length - 1].lines.push(line);
}
});
return (
<div className="comp2-lyrics-paragraphs">
{sections
.filter((s) => s.lines.length > 0)
.map((section, i) => (
<div key={i} className="comp2-lyrics-para-section">
{section.tag && <span className="comp2-lyrics-tag">{section.tag}</span>}
<p className="comp2-lyrics-text">{section.lines.join('\n')}</p>
</div>
))}
</div>
);
};
return ( return (
<main className="comp2-page"> <CompletionView
<div className="comp2-header"> videoState={
<button onClick={onBack} className="comp2-back-btn"> isLoading
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> ? 'loading'
<path d="M15 18l-6-6 6-6" /> : videoStatus === 'error'
</svg> ? 'error'
<span>{t('completion.back')}</span> : videoUrl
</button> ? 'ready'
</div> : 'empty'
}
<div className="comp2-title-row"> videoUrl={videoUrl}
<h1 className="comp2-page-title">{t('completion.contentComplete', { defaultValue: '콘텐츠 제작 완료' })}</h1> loadingText={statusMessage}
<p className="comp2-page-subtitle">{t('completion.contentCompleteDesc', { defaultValue: 'AI 분석 및 편집을 통해 최적화된 콘텐츠가 완성되었습니다' })}</p> progress={displayProgress}
</div> errorMessage={errorMessage}
onRetry={handleRetry}
<div className="comp2-container"> fileName={getFileName()}
<div className="comp2-grid"> metaLines={[
{/* 왼쪽: 영상 */} `${t('completion.genre')} : ${songCompletionData?.genre || 'K-POP'}`,
<div className="comp2-video-section"> `${t('completion.resolution')} : ${getVideoResolution()}`,
<div className="comp2-video-wrapper"> ]}
{isLoading ? ( detailLabel={t('completion.lyrics')}
<div className="comp2-video-loading"> detail={renderLyrics()}
<div className="loading-spinner"> onDownload={handleDownload}
<div className="loading-ring"></div> downloadDisabled={videoStatus !== 'complete' || !videoUrl || isDownloading}
<div className="loading-dot"> downloadLabel={isDownloading ? t('completion.downloading') : t('completion.download')}
<div className="loading-dot-inner"></div> onUpload={handleOpenSocialConnect}
</div> uploadDisabled={videoStatus !== 'complete' || !videoDbId}
</div> >
<p className="comp2-loading-text">{statusMessage}</p> {/* 소셜 미디어 포스팅 모달 (기존 SocialPostingModal 컴포넌트 사용) */}
</div> <SocialPostingModal
) : videoStatus === 'error' ? ( isOpen={showSocialModal}
<div className="comp2-video-error"> onClose={handleCloseSocialConnect}
<svg className="comp2-error-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> onGoToCalendar={onGoToCalendar}
<circle cx="12" cy="12" r="10" /> video={
<path d="M12 8v4M12 16h.01" /> videoUrl && videoDbId
</svg> ? {
<p className="comp2-error-text">{errorMessage}</p> // ADO2 파이프라인 완료 화면이므로 항상 영상이다
<button onClick={handleRetry} className="comp2-retry-btn"> type: 'video',
{t('completion.retry')} video_id: videoDbId,
</button> store_name: songCompletionData?.businessName || '',
</div> region: '',
) : videoUrl ? ( task_id: songTaskId || '',
<video result_movie_url: videoUrl,
src={videoUrl} created_at: new Date().toISOString(),
className="comp2-video-player" like_count: 0,
controls comment_count: 0,
playsInline is_liked_by_me: false,
/> }
) : ( : null
<div className="comp2-video-placeholder"></div> }
)} />
</div> </CompletionView>
</div>
{/* 오른쪽: 콘텐츠 정보 */}
<div className="comp2-info-section">
<div className="comp2-info-header">
<span className="comp2-info-label">{t('completion.contentInfo', { defaultValue: '콘텐츠 정보' })}</span>
</div>
<div className="comp2-info-content">
<div className="comp2-file-info">
<h3 className="comp2-filename">{getFileName()}</h3>
{/* <p className="comp2-filesize">19.6MB</p> */}
</div>
<div className="comp2-meta-grid">
<div className="comp2-meta-item">
<span className="comp2-meta-label">{t('completion.genre', { defaultValue: '장르' })} : {songCompletionData?.genre || 'K-POP'}</span>
</div>
<div className="comp2-meta-divider"></div>
<div className="comp2-meta-item">
<span className="comp2-meta-label">{t('completion.resolution', { defaultValue: '규격' })} : {getVideoResolution()}</span>
</div>
<div className="comp2-meta-divider"></div>
<div className="comp2-lyrics-section">
<span className="comp2-meta-label">{t('completion.lyrics', { defaultValue: '가사' })}</span>
<p className="comp2-lyrics-text">
{songCompletionData?.lyrics || t('completion.sampleLyrics', { defaultValue: '가사를 불러오는 중...' })}
</p>
</div>
</div>
</div>
{/* 하단 버튼 */}
<div className="comp2-buttons">
<button
onClick={handleDownload}
disabled={videoStatus !== 'complete' || !videoUrl}
className="comp2-btn comp2-btn-secondary"
>
{t('completion.download', { defaultValue: '다운로드' })}
</button>
<button
onClick={handleOpenSocialConnect}
disabled={videoStatus !== 'complete' || !videoDbId}
className="comp2-btn comp2-btn-primary"
>
{t('completion.uploadToSocial', { defaultValue: '소셜 채널 업로드' })}
</button>
</div>
</div>
</div>
</div>
{/* 소셜 미디어 포스팅 모달 (기존 SocialPostingModal 컴포넌트 사용) */}
<SocialPostingModal
isOpen={showSocialModal}
onClose={handleCloseSocialConnect}
video={videoUrl && videoDbId ? {
video_id: videoDbId,
store_name: songCompletionData?.businessName || '',
region: '',
task_id: songTaskId || '',
result_movie_url: videoUrl,
created_at: new Date().toISOString(),
} : null}
/>
{tutorial.isActive && (
<TutorialOverlay
hints={tutorial.hints}
currentIndex={tutorial.currentHintIndex}
onNext={tutorial.nextHint}
onPrev={tutorial.prevHint}
onSkip={tutorial.skipTutorial}
groupProgress={tutorial.groupProgress}
/>
)}
</main>
); );
}; };
+112 -88
View File
@@ -1,5 +1,6 @@
import React, { useState, useEffect, useCallback, useRef } from 'react'; import React, { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { UploadHistoryItem } from '../../types/api'; import { UploadHistoryItem } from '../../types/api';
import { getUploadHistory, cancelUpload, retryUpload } from '../../utils/api'; import { getUploadHistory, cancelUpload, retryUpload } from '../../utils/api';
@@ -53,28 +54,30 @@ const statusColor = (status: UploadStatus) => {
} }
}; };
// 상태 라벨 // 상태 라벨 (컴포넌트 내부에서 t()로 처리)
const statusLabel = (status: UploadStatus) => { const statusLabelKey = (status: UploadStatus) => {
switch (status) { switch (status) {
case 'completed': return '완료'; case 'completed': return 'contentCalendar.status.completed';
case 'scheduled': case 'scheduled':
case 'pending': return '예약'; case 'pending': return 'contentCalendar.status.scheduled';
case 'failed': return '실패'; case 'failed': return 'contentCalendar.status.failed';
default: return status; default: return status;
} }
}; };
interface ContentCalendarContentProps { interface ContentCalendarContentProps {
onNavigate?: (id: string) => void; onNavigate?: (id: string) => void;
/** 내 정보 탭 안에 임베드될 때: 탭 라벨과 중복되는 자체 제목을 숨기고 여백을 줄인다 */
embedded?: boolean;
} }
const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavigate }) => { const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavigate, embedded }) => {
const { t } = useTranslation();
const today = new Date(); const today = new Date();
const [year, setYear] = useState(today.getFullYear()); const [year, setYear] = useState(today.getFullYear());
const [month, setMonth] = useState(today.getMonth()); const [month, setMonth] = useState(today.getMonth());
const [activeTab, setActiveTab] = useState<TabType>('전체'); const [activeTab, setActiveTab] = useState<TabType>('전체');
const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT); const [isMobile, setIsMobile] = useState(window.innerWidth < MOBILE_BREAKPOINT);
const [sheetOpen, setSheetOpen] = useState(false);
// allItems: 캘린더 도트용 (전체) // allItems: 캘린더 도트용 (전체)
// panelItems: 오른쪽 패널용 (탭 필터) // panelItems: 오른쪽 패널용 (탭 필터)
const [allItems, setAllItems] = useState<UploadHistoryItem[]>([]); const [allItems, setAllItems] = useState<UploadHistoryItem[]>([]);
@@ -192,18 +195,23 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
setTimeout(() => { setTimeout(() => {
const el = dateRefs.current[dateKey]; const el = dateRefs.current[dateKey];
const panel = panelRef.current; const panel = panelRef.current;
if (el && panel) { if (!el) return;
// 패널이 자체 스크롤을 가진 경우(데스크톱 사이드 패널)만 내부 스크롤.
// 모바일은 목록이 캘린더 아래에 그대로 펼쳐지므로 페이지 스크롤로 이동한다.
if (panel && panel.scrollHeight > panel.clientHeight) {
const panelTop = panel.getBoundingClientRect().top; const panelTop = panel.getBoundingClientRect().top;
const elTop = el.getBoundingClientRect().top; const elTop = el.getBoundingClientRect().top;
const offset = elTop - panelTop + panel.scrollTop - 12; // 12px 여백 const offset = elTop - panelTop + panel.scrollTop - 12; // 12px 여백
panel.scrollTo({ top: offset, behavior: 'smooth' }); panel.scrollTo({ top: offset, behavior: 'smooth' });
} else {
el.scrollIntoView({ behavior: 'smooth', block: 'center' });
} }
}, 50); }, 50);
}; };
// 취소 // 취소
const handleCancel = async (uploadId: number) => { const handleCancel = async (uploadId: number) => {
if (!window.confirm('예약을 취소하시겠습니까?')) return; if (!window.confirm(t('contentCalendar.cancelConfirm'))) return;
// 낙관적 업데이트: 먼저 UI에서 제거 // 낙관적 업데이트: 먼저 UI에서 제거
setAllItems(prev => prev.filter(i => i.upload_id !== uploadId)); setAllItems(prev => prev.filter(i => i.upload_id !== uploadId));
setPanelItems(prev => prev.filter(i => i.upload_id !== uploadId)); setPanelItems(prev => prev.filter(i => i.upload_id !== uploadId));
@@ -212,7 +220,7 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
} catch { } catch {
// 실패 시 다시 불러오기 // 실패 시 다시 불러오기
refreshAll(); refreshAll();
alert('취소에 실패했습니다.'); alert(t('contentCalendar.cancelFailed'));
} }
}; };
@@ -222,7 +230,7 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
await retryUpload(uploadId); await retryUpload(uploadId);
refreshAll(); refreshAll();
} catch { } catch {
alert('재시도에 실패했습니다.'); alert(t('contentCalendar.retryFailed'));
} }
}; };
@@ -234,10 +242,11 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`; return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
}; };
// 날짜 표시 (M월 D) // 날짜 표시
const formatDateLabel = (key: string) => { const formatDateLabel = (key: string) => {
const [, m, d] = key.split('-'); const [, m, d] = key.split('-');
return `${parseInt(m)}월 ${parseInt(d)}`; const months = t('contentCalendar.months', { returnObjects: true }) as string[];
return t('contentCalendar.monthDay', { month: months[parseInt(m) - 1], day: parseInt(d) });
}; };
const buildCalendarDays = (): CalendarDay[] => { const buildCalendarDays = (): CalendarDay[] => {
@@ -266,9 +275,15 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
}; };
const calendarDays = buildCalendarDays(); const calendarDays = buildCalendarDays();
const monthNames = ['1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월']; const monthNames = t('contentCalendar.months', { returnObjects: true }) as string[];
const dayLabels = ['일','월','화','수','목','금','토']; const dayLabels = t('contentCalendar.days', { returnObjects: true }) as string[];
const tabs: TabType[] = ['전체','완료','예약','실패']; const tabs: TabType[] = ['전체','완료','예약','실패'];
const tabLabels: Record<TabType, string> = {
'전체': t('contentCalendar.tabs.all'),
'완료': t('contentCalendar.tabs.completed'),
'예약': t('contentCalendar.tabs.scheduled'),
'실패': t('contentCalendar.tabs.failed'),
};
// ── 캘린더 그리드 ────────────────────────────────────────────── // ── 캘린더 그리드 ──────────────────────────────────────────────
const renderCalendarGrid = () => { const renderCalendarGrid = () => {
@@ -387,24 +402,24 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
{summary.completed > 0 && ( {summary.completed > 0 && (
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: '#1ba64f', flexShrink: 0 }} /> <div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: '#1ba64f', flexShrink: 0 }} />
<span style={{ fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 11, color: '#01191a', lineHeight: 1, whiteSpace: 'nowrap' }}> <span style={{ fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 12, color: '#01191a', lineHeight: 1, whiteSpace: 'nowrap' }}>
완료 {summary.completed} {t('contentCalendar.completedCount', { count: summary.completed })}
</span> </span>
</div> </div>
)} )}
{summary.scheduled > 0 && ( {summary.scheduled > 0 && (
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: '#2563eb', flexShrink: 0 }} /> <div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: '#2563eb', flexShrink: 0 }} />
<span style={{ fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 11, color: '#01191a', lineHeight: 1, whiteSpace: 'nowrap' }}> <span style={{ fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 12, color: '#01191a', lineHeight: 1, whiteSpace: 'nowrap' }}>
예약 {summary.scheduled} {t('contentCalendar.scheduledCount', { count: summary.scheduled })}
</span> </span>
</div> </div>
)} )}
{summary.failed > 0 && ( {summary.failed > 0 && (
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
<div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: '#e15252', flexShrink: 0 }} /> <div style={{ width: 8, height: 8, borderRadius: '50%', backgroundColor: '#e15252', flexShrink: 0 }} />
<span style={{ fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 11, color: '#01191a', lineHeight: 1, whiteSpace: 'nowrap' }}> <span style={{ fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 12, color: '#01191a', lineHeight: 1, whiteSpace: 'nowrap' }}>
실패 {summary.failed} {t('contentCalendar.failedCount', { count: summary.failed })}
</span> </span>
</div> </div>
)} )}
@@ -419,7 +434,7 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
// ── 탭 바 ──────────────────────────────────────────────────── // ── 탭 바 ────────────────────────────────────────────────────
const renderTabs = () => ( const renderTabs = () => (
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}> <div style={{ display: 'flex', gap: 8, alignItems: 'center', justifyContent: 'center', width: '100%' }}>
{tabs.map(tab => ( {tabs.map(tab => (
<button <button
key={tab} key={tab}
@@ -432,7 +447,7 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
letterSpacing: '-0.096px', lineHeight: '22px', whiteSpace: 'nowrap', letterSpacing: '-0.096px', lineHeight: '22px', whiteSpace: 'nowrap',
}} }}
> >
{tab} {tabLabels[tab]}
</button> </button>
))} ))}
</div> </div>
@@ -442,9 +457,9 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
const renderStats = () => ( const renderStats = () => (
<div style={{ display: 'flex', gap: 16, alignItems: 'center' }}> <div style={{ display: 'flex', gap: 16, alignItems: 'center' }}>
{[ {[
{ label: '예약', value: totalStats.scheduled }, { label: t('contentCalendar.tabs.scheduled'), value: totalStats.scheduled },
{ label: '완료', value: totalStats.completed }, { label: t('contentCalendar.tabs.completed'), value: totalStats.completed },
{ label: '실패', value: totalStats.failed }, { label: t('contentCalendar.tabs.failed'), value: totalStats.failed },
].map((item, idx) => ( ].map((item, idx) => (
<React.Fragment key={item.label}> <React.Fragment key={item.label}>
{idx > 0 && <div style={{ width: 0, height: 14, borderLeft: '1px solid #379599' }} />} {idx > 0 && <div style={{ width: 0, height: 14, borderLeft: '1px solid #379599' }} />}
@@ -483,7 +498,7 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
color: '#e5f1f2', letterSpacing: '-0.096px', lineHeight: '22px', color: '#e5f1f2', letterSpacing: '-0.096px', lineHeight: '22px',
margin: 0, whiteSpace: 'nowrap', margin: 0, whiteSpace: 'nowrap',
}}> }}>
{year}년 {monthNames[month]} {t('contentCalendar.yearMonth', { year, month: monthNames[month] })}
</p> </p>
<button <button
onClick={handleNextMonth} onClick={handleNextMonth}
@@ -526,32 +541,41 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
backgroundColor: statusColor(item.status as UploadStatus), flexShrink: 0, backgroundColor: statusColor(item.status as UploadStatus), flexShrink: 0,
}} /> }} />
<span style={{ <span style={{
fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 13, fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 14,
color: statusColor(item.status as UploadStatus), lineHeight: 1, color: statusColor(item.status as UploadStatus), lineHeight: 1,
}}> }}>
{statusLabel(item.status as UploadStatus)} {t(statusLabelKey(item.status as UploadStatus))}
</span> </span>
<span style={{ <span style={{
fontFamily: 'Pretendard, sans-serif', fontWeight: 400, fontSize: 13, fontFamily: 'Pretendard, sans-serif', fontWeight: 400, fontSize: 14,
color: '#9bcacc', lineHeight: 1, marginLeft: 'auto', color: '#9bcacc', lineHeight: 1, marginLeft: 'auto',
}}> }}>
{formatTime(item)} {formatTime(item)}
</span> </span>
</div> </div>
{/* 채널 아이콘 + 제목 */} {/* 채널 아이콘 + 채널명 */}
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}> <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<PlatformIcon platform={item.platform} size={18} /> <PlatformIcon platform={item.platform} size={16} />
<span style={{ <span style={{
fontFamily: 'Pretendard, sans-serif', fontWeight: 600, fontSize: 14, fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 12,
color: '#e5f1f2', lineHeight: 1.4, color: '#9bcacc', lineHeight: 1.4,
overflow: 'hidden', display: '-webkit-box', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis',
WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
}}> }}>
{item.title} {item.platform_username || item.platform_user_id || item.channel_name}
</span> </span>
</div> </div>
{/* 제목 */}
<span style={{
fontFamily: 'Pretendard, sans-serif', fontWeight: 600, fontSize: 14,
color: '#e5f1f2', lineHeight: 1.4,
overflow: 'hidden', display: '-webkit-box',
WebkitLineClamp: 2, WebkitBoxOrient: 'vertical',
}}>
{item.title}
</span>
{/* 실패 메시지 */} {/* 실패 메시지 */}
{isFailed && item.error_message && ( {isFailed && item.error_message && (
<p style={{ <p style={{
@@ -571,11 +595,11 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
style={{ style={{
height: 30, padding: '0 12px', borderRadius: 8, height: 30, padding: '0 12px', borderRadius: 8,
border: '1px solid #379599', backgroundColor: 'transparent', border: '1px solid #379599', backgroundColor: 'transparent',
fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 13, fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 14,
color: '#9bcacc', cursor: 'pointer', color: '#9bcacc', cursor: 'pointer',
}} }}
> >
취소 {t('contentCalendar.cancel')}
</button> </button>
)} )}
{isFailed && ( {isFailed && (
@@ -584,11 +608,11 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
style={{ style={{
height: 30, padding: '0 12px', borderRadius: 8, height: 30, padding: '0 12px', borderRadius: 8,
border: 'none', backgroundColor: '#a65eff', border: 'none', backgroundColor: '#a65eff',
fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 13, fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 14,
color: '#ffffff', cursor: 'pointer', color: '#ffffff', cursor: 'pointer',
}} }}
> >
재시도 {t('contentCalendar.retry')}
</button> </button>
)} )}
</div> </div>
@@ -598,11 +622,12 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
}; };
// ── 패널 콘텐츠 ──────────────────────────────────────────── // ── 패널 콘텐츠 ────────────────────────────────────────────
const renderPanelContent = () => { // inline=true (모바일): 자체 스크롤 없이 페이지 흐름에 그대로 펼친다
const renderPanelContent = (inline = false) => {
if (panelLoading) { if (panelLoading) {
return ( return (
<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}> <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', minHeight: inline ? 120 : undefined }}>
<span style={{ color: '#9bcacc', fontFamily: 'Pretendard, sans-serif', fontSize: 14 }}>불러오는 중...</span> <span style={{ color: '#9bcacc', fontFamily: 'Pretendard, sans-serif', fontSize: 14 }}>{t('contentCalendar.loading')}</span>
</div> </div>
); );
} }
@@ -611,23 +636,24 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
<div style={{ <div style={{
flex: 1, display: 'flex', flexDirection: 'column', flex: 1, display: 'flex', flexDirection: 'column',
alignItems: 'center', justifyContent: 'center', gap: 24, padding: 16, alignItems: 'center', justifyContent: 'center', gap: 24, padding: 16,
minHeight: inline ? 160 : undefined,
}}> }}>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'center', textAlign: 'center' }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'center', textAlign: 'center' }}>
<p style={{ <p style={{
fontFamily: 'Pretendard, sans-serif', fontWeight: 700, fontSize: 16, fontFamily: 'Pretendard, sans-serif', fontWeight: 700, fontSize: 16,
color: '#e5f1f2', letterSpacing: '-0.096px', lineHeight: '22px', margin: 0, color: '#e5f1f2', letterSpacing: '-0.096px', lineHeight: '22px', margin: 0,
}}> }}>
최근 결과 없음 {t('contentCalendar.noResults')}
</p> </p>
<p style={{ <p style={{
fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 12, fontFamily: 'Pretendard, sans-serif', fontWeight: 500, fontSize: 12,
color: '#9bcacc', letterSpacing: '-0.072px', lineHeight: 1, margin: 0, color: '#9bcacc', letterSpacing: '-0.072px', lineHeight: 1, margin: 0,
}}> }}>
제작한 콘텐츠를 소셜 채널에 업로드해 보세요 {t('contentCalendar.noResultsDesc')}
</p> </p>
</div> </div>
<button <button
onClick={() => onNavigate?.('ADO2 콘텐츠')} onClick={() => onNavigate?.('내 콘텐츠')}
style={{ style={{
height: 34, padding: '0 10px', borderRadius: 8, border: 'none', height: 34, padding: '0 10px', borderRadius: 8, border: 'none',
backgroundColor: '#a65eff', cursor: 'pointer', backgroundColor: '#a65eff', cursor: 'pointer',
@@ -635,7 +661,7 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
color: '#ffffff', color: '#ffffff',
}} }}
> >
ADO2 콘텐츠 {t('contentCalendar.myContents')}
</button> </button>
</div> </div>
); );
@@ -644,7 +670,11 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
<div <div
ref={panelRef} ref={panelRef}
className="calendar-panel-scroll" className="calendar-panel-scroll"
style={{ flex: 1, overflowY: 'auto', padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 20, maxHeight: 700 }} style={{
flex: 1, padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 20,
overflowY: inline ? 'visible' : 'auto',
maxHeight: inline ? undefined : 700,
}}
> >
{sortedDateKeys.map(dateKey => ( {sortedDateKeys.map(dateKey => (
<div <div
@@ -673,17 +703,19 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
return ( return (
<div style={{ <div style={{
display: 'flex', flexDirection: 'column', alignItems: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center',
paddingTop: 24, paddingBottom: 20, width: '100%', paddingTop: embedded ? 0 : 24, paddingBottom: 20, width: '100%',
boxSizing: 'border-box', position: 'relative', boxSizing: 'border-box', position: 'relative',
}}> }}>
<div style={{ width: '100%', paddingBottom: 24, paddingLeft: 20, paddingRight: 20, boxSizing: 'border-box' }}> {!embedded && (
<p style={{ <div style={{ width: '100%', paddingBottom: 24, paddingLeft: 20, paddingRight: 20, boxSizing: 'border-box' }}>
fontFamily: 'Pretendard, sans-serif', fontWeight: 700, fontSize: 30, <p style={{
color: '#ffffff', letterSpacing: '-0.18px', lineHeight: 1.3, margin: 0, fontFamily: 'Pretendard, sans-serif', fontWeight: 700, fontSize: 30,
}}> color: '#ffffff', letterSpacing: '-0.18px', lineHeight: 1.3, margin: 0,
콘텐츠 캘린더 }}>
</p> {t('contentCalendar.title')}
</div> </p>
</div>
)}
<div style={{ <div style={{
display: 'flex', flexDirection: 'column', gap: 16, display: 'flex', flexDirection: 'column', gap: 16,
@@ -698,34 +730,24 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
{renderCalendarGrid()} {renderCalendarGrid()}
</div> </div>
{/* 바텀시트 */} {/* 업로드 목록 — 캘린더 바로 아래에 펼쳐 둔다(바텀시트로 감추지 않음).
<div style={{ position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 100, display: 'flex', flexDirection: 'column' }}> 좌우 여백 없음: 위 캘린더 그리드와 가로 폭을 맞춘다 */}
<div style={{ width: '100%', marginTop: 16, boxSizing: 'border-box' }}>
<div style={{ <div style={{
backgroundColor: '#01393b', backgroundColor: '#01393b',
borderTop: '1px solid #046266', border: '1px solid #046266',
borderRadius: '20px 20px 0 0', borderRadius: 20,
overflow: 'hidden', overflow: 'hidden',
}}> }}>
<div
onClick={() => setSheetOpen(o => !o)}
style={{ display: 'flex', justifyContent: 'center', padding: '8px 0', cursor: 'pointer' }}
>
<div style={{ width: 49, height: 4, backgroundColor: '#9bcacc', borderRadius: 999 }} />
</div>
<div style={{ <div style={{
borderBottom: sheetOpen ? '1px solid #046266' : 'none', borderBottom: '1px solid #046266',
height: 50, display: 'flex', alignItems: 'center', padding: '0 16px', height: 50, display: 'flex', alignItems: 'center', padding: '0 16px',
}}> }}>
{renderTabs()} {renderTabs()}
</div> </div>
{sheetOpen && ( {renderPanelContent(true)}
<div style={{ height: 400, overflowY: 'auto', backgroundColor: '#01393b', display: 'flex', flexDirection: 'column' }}>
{renderPanelContent()}
</div>
)}
</div> </div>
</div> </div>
<div style={{ height: sheetOpen ? 516 : 116 }} />
</div> </div>
); );
} }
@@ -736,26 +758,28 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
return ( return (
<div style={{ <div style={{
display: 'flex', flexDirection: 'column', alignItems: 'center', display: 'flex', flexDirection: 'column', alignItems: 'center',
padding: '32px', padding: embedded ? '0' : '32px',
width: '100%', width: '100%',
minWidth: 1400, minWidth: 1400,
height: '100%', boxSizing: 'border-box', height: embedded ? 'auto' : '100%', boxSizing: 'border-box',
}}> }}>
<div style={{ width: '100%', maxWidth: 1440, paddingBottom: 32, flexShrink: 0 }}> {!embedded && (
<p style={{ <div style={{ width: '100%', maxWidth: 1440, paddingBottom: 32, flexShrink: 0 }}>
fontFamily: 'Pretendard, sans-serif', fontWeight: 700, fontSize: 30, <p style={{
color: '#ffffff', letterSpacing: '-0.18px', lineHeight: 1.3, margin: 0, fontFamily: 'Pretendard, sans-serif', fontWeight: 700, fontSize: 30,
}}> color: '#ffffff', letterSpacing: '-0.18px', lineHeight: 1.3, margin: 0,
콘텐츠 캘린더 }}>
</p> {t('contentCalendar.title')}
</div> </p>
</div>
)}
<div style={{ <div style={{
display: 'grid', display: 'grid',
gridTemplateColumns: 'minmax(0,1fr) minmax(0,1fr) minmax(0,1fr) minmax(0,1fr) minmax(0,1fr) minmax(0,1fr) minmax(0,1fr) minmax(0,1fr) 340px', gridTemplateColumns: 'minmax(0,1fr) minmax(0,1fr) minmax(0,1fr) minmax(0,1fr) minmax(0,1fr) minmax(0,1fr) minmax(0,1fr) minmax(0,1fr) 340px',
gap: 16, gap: 16,
width: '100%', maxWidth: 1440, width: '100%', maxWidth: 1440,
flex: 1, minHeight: 0, flex: 1, minHeight: embedded ? 'calc(100vh - 220px)' : 0,
}}> }}>
{/* 캘린더 영역 */} {/* 캘린더 영역 */}
<div className="calendar-grid-area" style={{ <div className="calendar-grid-area" style={{
@@ -774,7 +798,7 @@ const ContentCalendarContent: React.FC<ContentCalendarContentProps> = ({ onNavig
</div> </div>
{loading ? ( {loading ? (
<div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}> <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<span style={{ color: '#9bcacc', fontFamily: 'Pretendard, sans-serif', fontSize: 14 }}>불러오는 중...</span> <span style={{ color: '#9bcacc', fontFamily: 'Pretendard, sans-serif', fontSize: 14 }}>{t('contentCalendar.loading')}</span>
</div> </div>
) : renderCalendarGrid()} ) : renderCalendarGrid()}
</div> </div>
+83 -63
View File
@@ -81,29 +81,29 @@ interface ConnectedAccount {
// ===================================================== // =====================================================
const MOCK_CONTENT_METRICS: ContentMetric[] = [ const MOCK_CONTENT_METRICS: ContentMetric[] = [
{ id: 'total-views', label: '조회수', value: 240000, unit: 'count', trend: 3800, trendDirection: 'up' }, { id: 'total-views', label: 'dashboard.metricTotalViews', value: 240000, unit: 'count', trend: 3800, trendDirection: 'up' },
{ id: 'total-watch-time', label: '시청시간', value: 85.3, unit: 'hours', trend: 21.5, trendDirection: 'up' }, { id: 'total-watch-time', label: 'dashboard.metricWatchTime', value: 85.3, unit: 'hours', trend: 21.5, trendDirection: 'up' },
{ id: 'avg-view-duration',label: '평균 시청시간', value: 41, unit: 'minutes', trend: 2.4, trendDirection: 'up' }, { id: 'avg-view-duration',label: 'dashboard.metricAvgViewDuration', value: 41, unit: 'minutes', trend: 2.4, trendDirection: 'up' },
{ id: 'new-subscribers', label: '신규 구독자', value: 483, unit: 'count', trend: 50, trendDirection: 'up' }, { id: 'new-subscribers', label: 'dashboard.metricNewSubscribers', value: 483, unit: 'count', trend: 50, trendDirection: 'up' },
{ id: 'likes', label: '좋아요', value: 15800, unit: 'count', trend: 180, trendDirection: 'up' }, { id: 'likes', label: 'dashboard.metricLikes', value: 15800, unit: 'count', trend: 180, trendDirection: 'up' },
{ id: 'comments', label: '댓글', value: 2500, unit: 'count', trend: 50, trendDirection: 'down' }, { id: 'comments', label: 'dashboard.metricComments', value: 2500, unit: 'count', trend: 50, trendDirection: 'down' },
{ id: 'shares', label: '공유', value: 840, unit: 'count', trend: 15, trendDirection: 'up' }, { id: 'shares', label: 'dashboard.metricShares', value: 840, unit: 'count', trend: 15, trendDirection: 'up' },
{ id: 'uploaded-videos', label: '업로드 영상', value: 17, unit: 'count', trend: 4, trendDirection: 'up' }, { id: 'uploaded-videos', label: 'dashboard.metricUploadedVideos', value: 17, unit: 'count', trend: 4, trendDirection: 'up' },
]; ];
const MOCK_MONTHLY_DATA: MonthlyData[] = [ const MOCK_MONTHLY_DATA: MonthlyData[] = [
{ month: '1월', thisYear: 18000, lastYear: 14500 }, { month: 'dashboard.months.jan', thisYear: 18000, lastYear: 14500 },
{ month: '2월', thisYear: 19500, lastYear: 15800 }, { month: 'dashboard.months.feb', thisYear: 19500, lastYear: 15800 },
{ month: '3월', thisYear: 21000, lastYear: 17200 }, { month: 'dashboard.months.mar', thisYear: 21000, lastYear: 17200 },
{ month: '4월', thisYear: 18500, lastYear: 16800 }, { month: 'dashboard.months.apr', thisYear: 18500, lastYear: 16800 },
{ month: '5월', thisYear: 24000, lastYear: 19500 }, { month: 'dashboard.months.may', thisYear: 24000, lastYear: 19500 },
{ month: '6월', thisYear: 27500, lastYear: 21000 }, { month: 'dashboard.months.jun', thisYear: 27500, lastYear: 21000 },
{ month: '7월', thisYear: 32000, lastYear: 23500 }, { month: 'dashboard.months.jul', thisYear: 32000, lastYear: 23500 },
{ month: '8월', thisYear: 29500, lastYear: 24800 }, { month: 'dashboard.months.aug', thisYear: 29500, lastYear: 24800 },
{ month: '9월', thisYear: 31000, lastYear: 26200 }, { month: 'dashboard.months.sep', thisYear: 31000, lastYear: 26200 },
{ month: '10월', thisYear: 28500, lastYear: 25500 }, { month: 'dashboard.months.oct', thisYear: 28500, lastYear: 25500 },
{ month: '11월', thisYear: 34000, lastYear: 27800 }, { month: 'dashboard.months.nov', thisYear: 34000, lastYear: 27800 },
{ month: '12월', thisYear: 38000, lastYear: 29500 }, { month: 'dashboard.months.dec', thisYear: 38000, lastYear: 29500 },
]; ];
const MOCK_DAILY_DATA: DailyData[] = Array.from({ length: 30 }, (_, i) => { const MOCK_DAILY_DATA: DailyData[] = Array.from({ length: 30 }, (_, i) => {
@@ -201,18 +201,16 @@ const formatNumber = (num: number): string => {
return num.toString(); return num.toString();
}; };
// unit에 따라 value를 표시용 문자열로 변환 (언어별 suffix는 호출부에서 처리) const formatValue = (value: number, unit: string, unitHours: string, unitMinutes: string): string => {
const formatValue = (value: number, unit: string): string => { if (unit === 'hours') return value.toFixed(1) + unitHours;
if (unit === 'hours') return value.toFixed(1) + '시간'; if (unit === 'minutes') return Math.round(value) + unitMinutes;
if (unit === 'minutes') return Math.round(value) + '분';
return formatNumber(Math.round(value)); return formatNumber(Math.round(value));
}; };
// unit에 따라 trend 절댓값을 표시용 문자열로 변환 const formatTrend = (trend: number, unit: string, unitHours: string, unitMinutes: string): string => {
const formatTrend = (trend: number, unit: string): string => {
const abs = Math.abs(trend); const abs = Math.abs(trend);
if (unit === 'hours') return abs.toFixed(1) + '시간'; if (unit === 'hours') return abs.toFixed(1) + unitHours;
if (unit === 'minutes') return Math.round(abs) + '분'; if (unit === 'minutes') return Math.round(abs) + unitMinutes;
return formatNumber(Math.round(abs)); return formatNumber(Math.round(abs));
}; };
@@ -239,19 +237,22 @@ const TrendIcon: React.FC<{ direction: 'up' | 'down' }> = ({ direction }) => (
); );
const StatCard: React.FC<ContentMetric> = ({ label, value, unit, trend, trendDirection }) => { const StatCard: React.FC<ContentMetric> = ({ label, value, unit, trend, trendDirection }) => {
const { t } = useTranslation();
const unitHours = t('dashboard.unitHours');
const unitMinutes = t('dashboard.unitMinutes');
const isNeutral = trend === 0 || trendDirection === '-'; const isNeutral = trend === 0 || trendDirection === '-';
const isUp = trendDirection === 'up'; const isUp = trendDirection === 'up';
return ( return (
<div className="stat-card"> <div className="stat-card">
<span className="stat-label">{label}</span> <span className="stat-label">{t(label)}</span>
<h3 className="stat-value">{formatValue(value, unit)}</h3> <h3 className="stat-value">{formatValue(value, unit, unitHours, unitMinutes)}</h3>
<div className="stat-trend-wrapper"> <div className="stat-trend-wrapper">
{isNeutral ? ( {isNeutral ? (
<span className="stat-trend neutral">─</span> <span className="stat-trend neutral">─</span>
) : ( ) : (
<span className={`stat-trend ${isUp ? 'up' : 'down'}`}> <span className={`stat-trend ${isUp ? 'up' : 'down'}`}>
<TrendIcon direction={isUp ? 'up' : 'down'} /> <TrendIcon direction={isUp ? 'up' : 'down'} />
{isUp ? '+' : '-'}{formatTrend(trend, unit)} {isUp ? '+' : '-'}{formatTrend(trend, unit, unitHours, unitMinutes)}
</span> </span>
)} )}
</div> </div>
@@ -276,11 +277,12 @@ const YearOverYearChart: React.FC<{
currentLabel: string; currentLabel: string;
previousLabel: string; previousLabel: string;
mode: 'day' | 'month'; mode: 'day' | 'month';
}> = ({ data, currentLabel, previousLabel, mode }) => { noDataLabel: string;
}> = ({ data, currentLabel, previousLabel, mode, noDataLabel }) => {
if (data.length === 0) { if (data.length === 0) {
return ( return (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '200px', opacity: 0.4 }}> <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '200px', opacity: 0.4 }}>
<span>이 기간에 데이터가 없습니다.</span> <span>{noDataLabel}</span>
</div> </div>
); );
} }
@@ -362,14 +364,14 @@ const YearOverYearChart: React.FC<{
// Icon Components // Icon Components
// ===================================================== // =====================================================
const YouTubeIcon: React.FC<{ className?: string }> = ({ className }) => ( const YouTubeIcon: React.FC<{ className?: string; style?: React.CSSProperties }> = ({ className, style }) => (
<svg className={className || "platform-tab-icon"} viewBox="0 0 24 24" fill="currentColor"> <svg className={className || "platform-tab-icon"} style={style} viewBox="0 0 24 24" fill="currentColor">
<path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z" /> <path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z" />
</svg> </svg>
); );
const InstagramIcon: React.FC<{ className?: string }> = ({ className }) => ( const InstagramIcon: React.FC<{ className?: string; style?: React.CSSProperties }> = ({ className, style }) => (
<svg className={className || "platform-tab-icon"} viewBox="0 0 24 24" fill="currentColor"> <svg className={className || "platform-tab-icon"} style={style} viewBox="0 0 24 24" fill="currentColor">
<path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 1 0 0 12.324 6.162 6.162 0 0 0 0-12.324zM12 16a4 4 0 1 1 0-8 4 4 0 0 1 0 8zm6.406-11.845a1.44 1.44 0 1 0 0 2.881 1.44 1.44 0 0 0 0-2.881z" /> <path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 1 0 0 12.324 6.162 6.162 0 0 0 0-12.324zM12 16a4 4 0 1 1 0-8 4 4 0 0 1 0 8zm6.406-11.845a1.44 1.44 0 1 0 0 2.881 1.44 1.44 0 0 0 0-2.881z" />
</svg> </svg>
); );
@@ -573,7 +575,7 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
return; return;
} }
if (errorData.code === 'YOUTUBE_API_FAILED') { if (errorData.code === 'YOUTUBE_API_FAILED') {
setError({ code: 'YOUTUBE_API_FAILED', message: 'YouTube Analytics API 호출에 실패했습니다.' }); setError({ code: 'YOUTUBE_API_FAILED', message: t('dashboard.youtubeApiFailed') });
setDashboardData(null); setDashboardData(null);
return; return;
} }
@@ -606,7 +608,7 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
if (isLoading) { if (isLoading) {
return ( return (
<div className="flex justify-center items-center h-screen"> <div className="flex justify-center items-center h-screen">
<div className="text-lg">{t('데이터 로딩 중...')}</div> <div className="text-lg">{t('dashboard.dataLoading')}</div>
</div> </div>
); );
} }
@@ -614,12 +616,13 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
// hasUploads === false이고 error 없음: 업로드 영상 없음 → 전체 mock 데이터 표시 + 안내 배너 // hasUploads === false이고 error 없음: 업로드 영상 없음 → 전체 mock 데이터 표시 + 안내 배너
const isEmptyState = dashboardData?.hasUploads === false && !dashboardData?.error; const isEmptyState = dashboardData?.hasUploads === false && !dashboardData?.error;
// 블러 조건: 1)계정 미연결 2)업로드 영상 없음 3)데이터 없음 4)에러 있음
const isBlurred = accounts.length === 0 || isEmptyState || !dashboardData || !!error;
// showMockData=true면 전체 mock 강제, 아니면 API 우선 / isEmptyState 시 mock 폴백 // showMockData=true면 전체 mock 강제, 아니면 API 우선 / isEmptyState 시 mock 폴백
const useReal = !showMockData && !isEmptyState; const useReal = !showMockData && !isEmptyState;
const contentMetrics = (useReal && dashboardData?.contentMetrics?.length) ? dashboardData.contentMetrics : MOCK_CONTENT_METRICS; const hasRealContentMetrics = useReal && !!dashboardData?.contentMetrics?.some((m: ContentMetric) => m.value > 0);
const contentMetrics = hasRealContentMetrics ? dashboardData!.contentMetrics : MOCK_CONTENT_METRICS;
// 블러 조건: 1)계정 미연결 2)업로드 영상 없음 3)데이터 없음 4)에러 있음 5)실제 지표 없음
const isBlurred = accounts.length === 0 || isEmptyState || !dashboardData || !!error || !hasRealContentMetrics;
const topContent = (useReal && dashboardData?.topContent?.length) ? dashboardData.topContent : MOCK_TOP_CONTENT; const topContent = (useReal && dashboardData?.topContent?.length) ? dashboardData.topContent : MOCK_TOP_CONTENT;
const hasRealAgeGroups = useReal && !!dashboardData?.audienceData?.ageGroups?.some(g => g.percentage > 0); const hasRealAgeGroups = useReal && !!dashboardData?.audienceData?.ageGroups?.some(g => g.percentage > 0);
const hasRealGender = useReal && ((dashboardData?.audienceData?.gender?.male ?? 0) + (dashboardData?.audienceData?.gender?.female ?? 0)) > 0; const hasRealGender = useReal && ((dashboardData?.audienceData?.gender?.male ?? 0) + (dashboardData?.audienceData?.gender?.female ?? 0)) > 0;
@@ -631,15 +634,15 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
const chartData: ChartDataPoint[] = mode === 'month' const chartData: ChartDataPoint[] = mode === 'month'
? ((useReal && dashboardData?.monthlyData?.length) ? ((useReal && dashboardData?.monthlyData?.length)
? dashboardData.monthlyData.map((d: MonthlyData) => ({ label: d.month, current: d.thisYear, previous: d.lastYear })) ? dashboardData.monthlyData.map((d: MonthlyData) => ({ label: d.month, current: d.thisYear, previous: d.lastYear }))
: MOCK_MONTHLY_DATA.map((d: MonthlyData) => ({ label: d.month, current: d.thisYear, previous: d.lastYear }))) : MOCK_MONTHLY_DATA.map((d: MonthlyData) => ({ label: t(d.month), current: d.thisYear, previous: d.lastYear })))
: ((useReal && dashboardData?.dailyData?.length) : ((useReal && dashboardData?.dailyData?.length)
? dashboardData.dailyData.map((d: DailyData) => ({ label: d.date, current: d.thisPeriod, previous: d.lastPeriod })) ? dashboardData.dailyData.map((d: DailyData) => ({ label: d.date, current: d.thisPeriod, previous: d.lastPeriod }))
: MOCK_DAILY_DATA.map((d: DailyData) => ({ label: d.date, current: d.thisPeriod, previous: d.lastPeriod }))); : MOCK_DAILY_DATA.map((d: DailyData) => ({ label: d.date, current: d.thisPeriod, previous: d.lastPeriod })));
// mode별 차트 레이블 // mode별 차트 레이블
const chartCurrentLabel = mode === 'month' ? '올해' : '이번달'; const chartCurrentLabel = mode === 'month' ? t('dashboard.chartThisYear') : t('dashboard.chartThisMonth');
const chartPreviousLabel = mode === 'month' ? '작년' : '지난달'; const chartPreviousLabel = mode === 'month' ? t('dashboard.chartLastYear') : t('dashboard.chartLastMonth');
const chartSectionTitle = mode === 'month' ? t('dashboard.yearOverYear') : '전월 대비 성장'; const chartSectionTitle = mode === 'month' ? t('dashboard.yearOverYear') : t('dashboard.monthOverMonth');
const lastUpdated = new Date().toLocaleDateString('ko-KR', { const lastUpdated = new Date().toLocaleDateString('ko-KR', {
year: 'numeric', year: 'numeric',
@@ -657,8 +660,24 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
<path d="M15 10l4.553-2.069A1 1 0 0121 8.87v6.26a1 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" strokeLinecap="round" strokeLinejoin="round" /> <path d="M15 10l4.553-2.069A1 1 0 0121 8.87v6.26a1 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" strokeLinecap="round" strokeLinejoin="round" />
</svg> </svg>
<div> <div>
<p style={{ color: '#a6ffea', fontSize: '20px', fontWeight: 600, marginBottom: '2px' }}>아직 업로드된 영상이 없습니다.</p> <p style={{ color: '#a6ffea', fontSize: '20px', fontWeight: 600, marginBottom: '2px' }}>{t('dashboard.noUploadsTitle')}</p>
<p style={{ color: 'rgba(255,255,255,0.5)', fontSize: '16px' }}>ADO2에서 영상을 업로드하면 실제 통계가 표시됩니다.</p> <p style={{ color: 'rgba(255,255,255,0.5)', fontSize: '16px' }}>{t('dashboard.noUploadsDesc')}</p>
</div>
</div>
</div>
)}
{/* 48시간 지연 안내 배너 */}
{dashboardData && !isEmptyState && !hasRealContentMetrics && !showMockData && (
<div className="mb-4 p-4 border-l-4 rounded" style={{ background: 'rgba(255,210,100,0.06)', borderColor: '#ffd264' }}>
<div className="flex items-center gap-3">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#ffd264" strokeWidth="2" style={{ flexShrink: 0 }}>
<circle cx="12" cy="12" r="10" />
<path d="M12 6v6l4 2" strokeLinecap="round" strokeLinejoin="round" />
</svg>
<div>
<p style={{ color: '#ffd264', fontSize: '16px', fontWeight: 600, marginBottom: '2px' }}>{t('dashboard.dataDelayTitle')}</p>
<p style={{ color: 'rgba(255,255,255,0.5)', fontSize: '14px' }}>{t('dashboard.dataDelayDesc')}</p>
</div> </div>
</div> </div>
</div> </div>
@@ -679,7 +698,7 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
onClick={() => onNavigate?.('내 정보')} onClick={() => onNavigate?.('내 정보')}
className="ml-4 px-4 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700 whitespace-nowrap" className="ml-4 px-4 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700 whitespace-nowrap"
> >
재연동하러 가기 → {t('dashboard.reconnectButton')}
</button> </button>
)} )}
{error.code === 'YOUTUBE_NOT_CONNECTED' && ( {error.code === 'YOUTUBE_NOT_CONNECTED' && (
@@ -687,7 +706,7 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
onClick={() => onNavigate?.('내 정보')} onClick={() => onNavigate?.('내 정보')}
className="ml-4 px-4 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700 whitespace-nowrap" className="ml-4 px-4 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700 whitespace-nowrap"
> >
연동하러 가기 → {t('dashboard.connectButton')}
</button> </button>
)} )}
{(error.code === 'YOUTUBE_API_FAILED' || error.code === 'DASHBOARD_DATA_ERROR') && ( {(error.code === 'YOUTUBE_API_FAILED' || error.code === 'DASHBOARD_DATA_ERROR') && (
@@ -695,7 +714,7 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
onClick={() => { setError(null); setRetryTrigger((n: number) => n + 1); }} onClick={() => { setError(null); setRetryTrigger((n: number) => n + 1); }}
className="ml-4 px-4 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700 whitespace-nowrap" className="ml-4 px-4 py-2 bg-yellow-600 text-white rounded hover:bg-yellow-700 whitespace-nowrap"
> >
재시도 → {t('dashboard.retryButton')}
</button> </button>
)} )}
</div> </div>
@@ -721,7 +740,7 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
borderRadius: '8px', borderRadius: '8px',
color: 'rgba(255,255,255,0.85)', color: 'rgba(255,255,255,0.85)',
padding: '5px 10px', padding: '5px 10px',
fontSize: '13px', fontSize: '14px',
cursor: 'pointer', cursor: 'pointer',
minWidth: '160px', minWidth: '160px',
}} }}
@@ -738,7 +757,7 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
</span> </span>
</> </>
) : ( ) : (
<span style={{ flex: 1, color: 'rgba(255,255,255,0.4)' }}>계정을 선택하세요</span> <span style={{ flex: 1, color: 'rgba(255,255,255,0.4)' }}>{t('dashboard.selectAccount')}</span>
); );
})()} })()}
<svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.5)" strokeWidth="2" style={{ flexShrink: 0, marginLeft: 'auto' }}> <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.5)" strokeWidth="2" style={{ flexShrink: 0, marginLeft: 'auto' }}>
@@ -769,7 +788,7 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
display: 'flex', alignItems: 'center', gap: '8px', display: 'flex', alignItems: 'center', gap: '8px',
padding: '8px 12px', padding: '8px 12px',
cursor: 'pointer', cursor: 'pointer',
fontSize: '13px', fontSize: '14px',
background: acc.id === selectedAccountId ? 'rgba(255,255,255,0.08)' : 'transparent', background: acc.id === selectedAccountId ? 'rgba(255,255,255,0.08)' : 'transparent',
color: 'rgba(255,255,255,0.85)', color: 'rgba(255,255,255,0.85)',
}} }}
@@ -800,20 +819,20 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
<div className="flex items-center justify-between mb-4"> <div className="flex items-center justify-between mb-4">
<div> <div>
<h2 className="dashboard-section-title" style={{ marginBottom: '2px' }}>{t('dashboard.contentPerformance')}</h2> <h2 className="dashboard-section-title" style={{ marginBottom: '2px' }}>{t('dashboard.contentPerformance')}</h2>
<p style={{ fontSize: '14px', color: 'rgba(255,255,255,0.4)', margin: 0 }}>ADO2에서 업로드한 최근 30개의 영상 통계가 표시됩니다.</p> <p style={{ fontSize: '14px', color: 'rgba(255,255,255,0.4)', margin: 0 }}>{t('dashboard.recentVideosDesc')}</p>
</div> </div>
<div className="mode-toggle"> <div className="mode-toggle">
<button <button
className={`mode-btn ${mode === 'month' ? 'active' : ''}`} className={`mode-btn ${mode === 'month' ? 'active' : ''}`}
onClick={() => setMode('month')} onClick={() => setMode('month')}
> >
연간 {t('dashboard.modeAnnual')}
</button> </button>
<button <button
className={`mode-btn ${mode === 'day' ? 'active' : ''}`} className={`mode-btn ${mode === 'day' ? 'active' : ''}`}
onClick={() => setMode('day')} onClick={() => setMode('day')}
> >
월간 {t('dashboard.modeMonthly')}
</button> </button>
</div> </div>
</div> </div>
@@ -850,6 +869,7 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
currentLabel={chartCurrentLabel} currentLabel={chartCurrentLabel}
previousLabel={chartPreviousLabel} previousLabel={chartPreviousLabel}
mode={mode} mode={mode}
noDataLabel={t('dashboard.noDataInPeriod')}
/> />
</div> </div>
</div> </div>
@@ -874,7 +894,7 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
<AnimatedSection delay={1000} className="audience-section"> <AnimatedSection delay={1000} className="audience-section">
<div style={{ marginBottom: '16px' }}> <div style={{ marginBottom: '16px' }}>
<h2 className="dashboard-section-title" style={{ marginBottom: '2px' }}>{t('dashboard.audienceInsights')}</h2> <h2 className="dashboard-section-title" style={{ marginBottom: '2px' }}>{t('dashboard.audienceInsights')}</h2>
<p style={{ fontSize: '14px', color: 'rgba(255,255,255,0.4)', margin: 0 }}>선택한 채널의 통계가 표시됩니다.</p> <p style={{ fontSize: '14px', color: 'rgba(255,255,255,0.4)', margin: 0 }}>{t('dashboard.channelStatsDesc')}</p>
</div> </div>
<div style={{ position: 'relative' }}> <div style={{ position: 'relative' }}>
<div className="audience-cards" style={!hasRealAudienceData && !showMockData ? { filter: 'blur(4px)', pointerEvents: 'none', userSelect: 'none' } : {}}> <div className="audience-cards" style={!hasRealAudienceData && !showMockData ? { filter: 'blur(4px)', pointerEvents: 'none', userSelect: 'none' } : {}}>
@@ -907,7 +927,7 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
padding: '20px 28px', padding: '20px 28px',
}}> }}>
<p style={{ color: 'rgba(255,255,255,0.85)', fontSize: '16px', fontWeight: 500, margin: 0, textAlign: 'center' }}> <p style={{ color: 'rgba(255,255,255,0.85)', fontSize: '16px', fontWeight: 500, margin: 0, textAlign: 'center' }}>
누적 데이터가 부족하여 실제 시청자 정보가 없습니다. {t('dashboard.noAudienceData')}
</p> </p>
</div> </div>
</div> </div>
@@ -920,8 +940,8 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
onClick={() => setShowMockData(prev => !prev)} onClick={() => setShowMockData(prev => !prev)}
style={{ style={{
position: 'fixed', position: 'fixed',
bottom: '24px', top: '10px',
right: '24px', right: '5px',
zIndex: 9999, zIndex: 9999,
display: 'flex', display: 'flex',
alignItems: 'center', alignItems: 'center',
@@ -943,7 +963,7 @@ const DashboardContent: React.FC<DashboardContentProps> = ({ onNavigate }) => {
: <><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></> : <><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></>
} }
</svg> </svg>
{showMockData ? 'Sample 숨기기' : 'Sample 보기'} {showMockData ? t('dashboard.sampleHide') : t('dashboard.sampleShow')}
</button> </button>
</div> </div>
); );
+471 -201
View File
@@ -1,43 +1,75 @@
import React, { useEffect, useRef, useState } from 'react'; import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import Sidebar from '../../components/Sidebar'; import Sidebar from '../../components/Sidebar';
import BottomNav from '../../components/BottomNav';
import LoginPromptModal from '../../components/LoginPromptModal';
import AssetManagementContent from './AssetManagementContent'; import AssetManagementContent from './AssetManagementContent';
import SoundStudioContent from './SoundStudioContent'; import SoundStudioContent from './SoundStudioContent';
import CompletionContent from './CompletionContent'; import CompletionContent from './CompletionContent';
import DashboardContent from './DashboardContent'; import DashboardContent from './DashboardContent';
import BusinessSettingsContent from './BusinessSettingsContent';
import UrlInputContent from './UrlInputContent'; import UrlInputContent from './UrlInputContent';
import ADO2ContentsPage from './ADO2ContentsPage'; import ADO2ContentsPage from './ADO2ContentsPage';
import MyInfoContent from './MyInfoContent'; import MyInfoContent from './MyInfoContent';
import ContentCalendarContent from './ContentCalendarContent';
import LoadingSection from '../Analysis/LoadingSection'; import LoadingSection from '../Analysis/LoadingSection';
import AnalysisResultSection from '../Analysis/AnalysisResultSection'; import AnalysisResultSection from '../Analysis/AnalysisResultSection';
import { ImageItem, CrawlingResponse, UserMeResponse } from '../../types/api'; import { ImageItem, type ImageListItem, CrawlingResponse, UserMeResponse } from '../../types/api';
import { crawlUrl, autocomplete, AutocompleteRequest, getUserMe, clearTokens } from '../../utils/api'; import { crawlUrl, autocomplete, marketingAnalysis, AutocompleteRequest, getUserMe, getUserCredits, clearTokens, getActiveSsulTask, waitForSsulComplete, isLoggedIn } from '../../utils/api';
import { useTutorial } from '../../components/Tutorial/useTutorial'; import WizardStepper from '../../components/WizardStepper';
import { TUTORIAL_KEYS } from '../../components/Tutorial/tutorialSteps'; import { NAV, GATED_ITEMS, sanitizeActiveItem, MyInfoTab } from '../../components/navItems';
import TutorialOverlay, { TutorialRestartPopup } from '../../components/Tutorial/TutorialOverlay'; import { useIsMobile } from '../../utils/useIsMobile';
import { createPreviewThumbnail } from '../../utils/imageCompression';
const WIZARD_STEP_KEY = 'castad_wizard_step'; import { saveSearchHistory } from '../../components/SearchHistory/useSearchHistory';
const ACTIVE_ITEM_KEY = 'castad_active_item';
const SONG_TASK_ID_KEY = 'castad_song_task_id';
const IMAGE_TASK_ID_KEY = 'castad_image_task_id';
const ANALYSIS_DATA_KEY = 'castad_analysis_data';
// 다른 컴포넌트에서 사용하는 storage key들 (초기화용) /** 파일 이미지의 썸네일 objectURL 을 일괄 해제한다. preview 가 null 인 항목은 건너뛴다. */
const SONG_GENERATION_KEY = 'castad_song_generation'; const revokeAllPreviews = (items: ImageItem[]) => {
const VIDEO_GENERATION_KEY = 'castad_video_generation'; items.forEach(item => {
const VIDEO_COMPLETE_KEY = 'castad_video_complete'; // 완료된 영상 정보 if (item.type === 'file' && item.preview) {
URL.revokeObjectURL(item.preview);
}
});
};
import { Pipeline } from '../../components/PipelineTabs';
import { Scen } from '../Ssulbox/ssulData';
import SsulMakingContent, { SsulJob } from '../Ssulbox/SsulMakingContent';
import SsulResultContent from '../Ssulbox/SsulResultContent';
import {
K,
clearProjectStorage,
clearSessionStorage,
} from '../../utils/storageKeys';
// 모든 프로젝트 관련 localStorage 초기화 const WIZARD_STEP_KEY = K.WIZARD_STEP;
const clearAllProjectStorage = () => { const ACTIVE_ITEM_KEY = K.ACTIVE_ITEM;
localStorage.removeItem(WIZARD_STEP_KEY); const SONG_TASK_ID_KEY = K.SONG_TASK_ID;
localStorage.removeItem(SONG_TASK_ID_KEY); const IMAGE_TASK_ID_KEY = K.IMAGE_TASK_ID;
localStorage.removeItem(IMAGE_TASK_ID_KEY); const ANALYSIS_DATA_KEY = K.ANALYSIS_DATA;
localStorage.removeItem(SONG_GENERATION_KEY);
localStorage.removeItem(VIDEO_GENERATION_KEY); /**
localStorage.removeItem(VIDEO_COMPLETE_KEY); * 랜딩 CTA 에서 썰박스를 고르고 로그인하러 갈 때 남기는 1회성 프리셋.
* 카카오 로그인은 외부 리다이렉트 왕복이고 initializeOnNewSession 이
* localStorage 만 지우므로 sessionStorage 를 쓴다.
*/
const PENDING_PIPELINE_KEY = 'castad_pending_pipeline';
/** 비로그인 게이트 클릭 시 "로그인 후 열어줄 메뉴"를 남기는 1회성 프리셋. 카카오 왕복을 견뎌야 해서 sessionStorage */
const LOGIN_NEXT_ITEM_KEY = 'castad_login_next_item';
/** 썰박스 진행 단계. ADO2 의 wizardStep(-2~3) 과 별도 축이다 */
type SsulStep = 'entry' | 'making' | 'result';
/** 썰박스 스텝퍼 라벨(i18n 키)과 0-based 인덱스 */
const SSUL_STEP_LABELS = [
'ssulbox.steps.pick',
'ssulbox.steps.making',
'ssulbox.steps.done',
] as const;
const SSUL_STEP_INDEX: Record<SsulStep, number> = {
entry: 0,
making: 1,
result: 2,
}; };
interface BusinessInfo { interface BusinessInfo {
@@ -47,9 +79,9 @@ interface BusinessInfo {
} }
interface GenerationFlowProps { interface GenerationFlowProps {
onHome: () => void; onHome?: () => void;
initialActiveItem?: string; initialActiveItem?: string;
initialImageList?: string[]; initialImageList?: ImageListItem[];
businessInfo?: BusinessInfo; businessInfo?: BusinessInfo;
initialAnalysisData?: CrawlingResponse | null; initialAnalysisData?: CrawlingResponse | null;
} }
@@ -64,7 +96,7 @@ interface GenerationFlowProps {
const GenerationFlow: React.FC<GenerationFlowProps> = ({ const GenerationFlow: React.FC<GenerationFlowProps> = ({
onHome, onHome,
initialActiveItem = '대시보드', initialActiveItem = NAV.HOME,
initialImageList = [], initialImageList = [],
businessInfo, businessInfo,
initialAnalysisData initialAnalysisData
@@ -88,7 +120,20 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
} }
}; };
const [activeItem, setActiveItem] = useState(savedActiveItem || initialActiveItem); const isGuest = !isLoggedIn();
/** activeItem 초기화: 로그인 복귀 메뉴(최우선) → 저장된 값 → 초기값, 마지막에 구 이름 마이그레이션+게스트 강등 */
const getInitialNav = () => {
const loginNext = sessionStorage.getItem(LOGIN_NEXT_ITEM_KEY);
if (loginNext && isLoggedIn()) {
sessionStorage.removeItem(LOGIN_NEXT_ITEM_KEY);
return sanitizeActiveItem(loginNext, isGuest);
}
return sanitizeActiveItem(savedActiveItem || initialActiveItem, isGuest);
};
const initialNav = getInitialNav();
const [activeItem, setActiveItem] = useState(initialNav.item);
// 초기 위저드 단계 결정 // 초기 위저드 단계 결정
const getInitialWizardStep = (): number => { const getInitialWizardStep = (): number => {
@@ -108,21 +153,78 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
}; };
const [wizardStep, setWizardStep] = useState(getInitialWizardStep()); const [wizardStep, setWizardStep] = useState(getInitialWizardStep());
/**
* 초기 파이프라인 결정 — 우선순위를 지켜야 한다.
*
* 2번이 없으면 위 getInitialWizardStep() 의 "분석 데이터가 있으면 step 1부터"
* 강제 로직과 충돌한다. ADO2 분석을 마치고 돌아온 상태에서 파이프라인만
* 'ssul' 로 남아 있으면, 썰박스 화면인데 ADO2 위저드 단계가 그려진다.
*/
const getInitialPipeline = (): Pipeline => {
// 1) 랜딩 CTA 프리셋 (1회성). 카카오 로그인 리다이렉트 왕복을 견뎌야 해서 sessionStorage
const pending = sessionStorage.getItem(PENDING_PIPELINE_KEY);
if (pending === 'ssul' || pending === 'ado2') {
sessionStorage.removeItem(PENDING_PIPELINE_KEY);
return pending;
}
// 2) 분석 데이터가 있으면 ADO2 흐름 한가운데이므로 강제
if (initialAnalysisData || savedAnalysisData) return 'ado2';
// 3) 저장된 선택
const saved = localStorage.getItem(K.PIPELINE);
return saved === 'ssul' ? 'ssul' : 'ado2';
};
const [pipeline, setPipeline] = useState<Pipeline>(getInitialPipeline);
/** 썰박스 전용 진행 축. wizardStep 숫자 축은 확장하지 않는다 */
const [ssulStep, setSsulStep] = useState<SsulStep>('entry');
const [ssulJob, setSsulJob] = useState<SsulJob | null>(null);
/** 언마운트·로그아웃·재시도 시 진행 중인 폴링을 멈추는 플래그 */
const ssulCancelledRef = useRef(false);
const changePipeline = (next: Pipeline) => {
setPipeline(next);
localStorage.setItem(K.PIPELINE, next);
};
/** 진입 화면(탭이 보이는 단계) 여부. 두 파이프라인이 공유한다 */
const isEntry = pipeline === 'ado2' ? wizardStep === -2 : ssulStep === 'entry';
const [songTaskId, setSongTaskId] = useState<string | null>(savedSongTaskId); const [songTaskId, setSongTaskId] = useState<string | null>(savedSongTaskId);
const [imageTaskId, setImageTaskId] = useState<string | null>(savedImageTaskId); const [imageTaskId, setImageTaskId] = useState<string | null>(savedImageTaskId);
const [videoGenerationStatus, setVideoGenerationStatus] = useState<'idle' | 'generating' | 'complete' | 'error'>('idle'); const [videoGenerationStatus, setVideoGenerationStatus] = useState<'idle' | 'generating' | 'complete' | 'error'>('idle');
const [videoGenerationProgress, setVideoGenerationProgress] = useState(0); const [videoGenerationProgress, setVideoGenerationProgress] = useState(0);
const [analysisData, setAnalysisData] = useState<CrawlingResponse | null>(parseAnalysisData()); const [analysisData, setAnalysisData] = useState<CrawlingResponse | null>(parseAnalysisData());
const [analysisError, setAnalysisError] = useState<string | null>(null); const [analysisError, setAnalysisError] = useState<string | null>(null);
const [isAnalysisComplete, setIsAnalysisComplete] = useState(false);
const [userInfo, setUserInfo] = useState<UserMeResponse | null>(null); const [userInfo, setUserInfo] = useState<UserMeResponse | null>(null);
const tutorial = useTutorial(); const [credits, setCredits] = useState<number | null>(null);
const [myInfoInitialTab, setMyInfoInitialTab] = useState<MyInfoTab | undefined>(initialNav.myInfoTab);
// 로그인 직후 사용자 정보 조회 const refreshCredits = useCallback(async () => {
if (!isLoggedIn()) return;
try {
const { credits } = await getUserCredits();
setCredits(credits);
} catch (e) {
console.error('Failed to refresh credits:', e);
}
}, []);
// 사운드 스튜디오, 영상 완성 진입 시 크레딧 갱신
useEffect(() => { useEffect(() => {
if (wizardStep === 2 || wizardStep === 3) {
refreshCredits();
}
}, [wizardStep]);
// 로그인 직후 사용자 정보 + 크레딧 조회 (비로그인이면 요청 자체를 하지 않는다 — 401 → 강제 리다이렉트 방지)
useEffect(() => {
if (!isLoggedIn()) return;
const fetchUserInfo = async () => { const fetchUserInfo = async () => {
try { try {
const data = await getUserMe(); const [data, creditsData] = await Promise.all([getUserMe(), getUserCredits()]);
setUserInfo(data); setUserInfo(data);
setCredits(creditsData.credits);
} catch (error) { } catch (error) {
console.error('Failed to fetch user info:', error); console.error('Failed to fetch user info:', error);
} }
@@ -133,10 +235,9 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
// 로그아웃 핸들러 // 로그아웃 핸들러
const handleLogout = () => { const handleLogout = () => {
clearTokens(); clearTokens();
localStorage.removeItem('castad_view_mode'); // 세션 키를 전부 지운다. 이전에는 view_mode/analysis/wizard/active_item 만 지워
localStorage.removeItem('castad_analysis_data'); // 생성 중이던 song·video 상태가 남았고, 다른 계정으로 로그인하면 그대로 복원됐다.
localStorage.removeItem(WIZARD_STEP_KEY); clearSessionStorage();
localStorage.removeItem(ACTIVE_ITEM_KEY);
window.location.href = '/'; window.location.href = '/';
}; };
@@ -146,12 +247,21 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
// URL 이미지를 ImageItem 형태로 변환하여 초기화 // URL 이미지를 ImageItem 형태로 변환하여 초기화
const getInitialImageList = (): ImageItem[] => { const getInitialImageList = (): ImageItem[] => {
if (analysisData?.image_list && analysisData.image_list.length > 0) { if (analysisData?.image_list && analysisData.image_list.length > 0) {
return analysisData.image_list.map(url => ({ type: 'url', url })); return analysisData.image_list.map(item => ({ type: 'url' as const, url: item.original, preview_url: item.preview }));
} }
return initialImageList.map(url => ({ type: 'url', url })); return initialImageList.map(item => ({ type: 'url' as const, url: item.original, preview_url: item.preview }));
}; };
const [imageList, setImageList] = useState<ImageItem[]>(getInitialImageList()); const [imageList, setImageList] = useState<ImageItem[]>(getInitialImageList());
const imageListRef = useRef<ImageItem[]>(imageList);
imageListRef.current = imageList;
// 의존성 배열에 imageList 를 넣으면 이미지를 추가할 때마다 cleanup 이 돌아
// 방금 만든 썸네일이 즉시 revoke 된다. 반드시 빈 배열이어야 한다.
useEffect(() => {
return () => revokeAllPreviews(imageListRef.current);
}, []);
const prevAnalysisMIdRef = useRef<number | null | undefined>(analysisData?.m_id); const prevAnalysisMIdRef = useRef<number | null | undefined>(analysisData?.m_id);
// analysisData 변경 시 m_id가 바뀐 경우(새로운 분석)에만 imageList 업데이트 // analysisData 변경 시 m_id가 바뀐 경우(새로운 분석)에만 imageList 업데이트
@@ -160,7 +270,9 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
console.log('[GenerationFlow] analysisData updated, m_id:', analysisData?.m_id); console.log('[GenerationFlow] analysisData updated, m_id:', analysisData?.m_id);
if (analysisData?.image_list && analysisData.image_list.length > 0) { if (analysisData?.image_list && analysisData.image_list.length > 0) {
if (prevAnalysisMIdRef.current !== analysisData.m_id) { if (prevAnalysisMIdRef.current !== analysisData.m_id) {
setImageList(analysisData.image_list.map(url => ({ type: 'url', url }))); // 목록을 통째로 교체하므로 기존 파일 썸네일을 먼저 해제한다.
revokeAllPreviews(imageListRef.current);
setImageList(analysisData.image_list.map(item => ({ type: 'url' as const, url: item.original, preview_url: item.preview })));
} }
} }
prevAnalysisMIdRef.current = analysisData?.m_id; prevAnalysisMIdRef.current = analysisData?.m_id;
@@ -169,34 +281,53 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
const handleRemoveImage = (index: number) => { const handleRemoveImage = (index: number) => {
setImageList(prev => { setImageList(prev => {
const item = prev[index]; const item = prev[index];
// 파일 이미지인 경우 메모리 해제 // 파일 이미지인 경우 썸네일 메모리 해제 (생성 실패 시 preview 는 null)
if (item.type === 'file') { if (item.type === 'file' && item.preview) {
URL.revokeObjectURL(item.preview); URL.revokeObjectURL(item.preview);
} }
return prev.filter((_, i) => i !== index); return prev.filter((_, i) => i !== index);
}); });
}; };
const handleAddImages = (files: File[]) => { const handleAddImages = async (
const newImages: ImageItem[] = files.map(file => ({ files: File[],
type: 'file', onProgress: (done: number, total: number) => void
file, ) => {
preview: URL.createObjectURL(file), const total = files.length;
})); const newImages: ImageItem[] = [];
// 새로 업로드된 이미지를 배열 앞에 추가 (최신 이미지가 상단에 표시)
onProgress(0, total);
// 반드시 순차 처리한다. Promise.all 로 동시에 돌리면 원본 크기 비트맵이
// 한꺼번에 메모리에 올라가, 이 작업이 없애려던 문제가 그대로 재현된다.
for (const file of files) {
const preview = await createPreviewThumbnail(file);
newImages.push({ type: 'file', file, preview });
onProgress(newImages.length, total);
// 진행률이 실제로 화면에 그려지도록 매 장마다 렌더링 기회를 넘긴다.
await new Promise(resolve => setTimeout(resolve, 0));
}
// 장마다 setState 하면 그리드가 N 번 재조정된다. 전부 끝난 뒤 한 번만 반영한다.
// 새로 추가된 이미지를 배열 앞에 둔다 (최신 이미지가 상단에 표시)
setImageList(prev => [...newImages, ...prev]); setImageList(prev => [...newImages, ...prev]);
}; };
// 홈 버튼(로고) 클릭 시 모든 상태 초기화 후 홈으로 이동 // 홈 버튼(로고) 클릭 시 프로젝트 상태를 비우고 ADO2 콘텐츠로 돌아간다.
const handleHome = () => { const handleHome = () => {
clearAllProjectStorage(); clearProjectStorage();
localStorage.removeItem(ANALYSIS_DATA_KEY); localStorage.removeItem(ANALYSIS_DATA_KEY);
setWizardStep(-2); setWizardStep(-2);
setSongTaskId(null); setSongTaskId(null);
setImageTaskId(null); setImageTaskId(null);
setAnalysisData(null); setAnalysisData(null);
revokeAllPreviews(imageListRef.current);
setImageList([]); setImageList([]);
onHome(); if (onHome) {
onHome();
return;
}
setActiveItem(NAV.HOME);
}; };
// 위저드 단계 이동 // 위저드 단계 이동
@@ -208,6 +339,7 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
// 업체명 자동완성으로 분석 시작 // 업체명 자동완성으로 분석 시작
const handleAutocomplete = async (request: AutocompleteRequest) => { const handleAutocomplete = async (request: AutocompleteRequest) => {
goToWizardStep(-1); // 로딩 상태로 goToWizardStep(-1); // 로딩 상태로
setIsAnalysisComplete(false);
setAnalysisError(null); setAnalysisError(null);
try { try {
@@ -215,11 +347,11 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
console.log('[Autocomplete] Response m_id:', data.m_id); console.log('[Autocomplete] Response m_id:', data.m_id);
// 기본값 보장 // 기본값 보장
if (data.marketing_analysis) { // if (data.marketing_analysis) {
data.marketing_analysis.tags = data.marketing_analysis.tags || []; // data.marketing_analysis.tags = data.marketing_analysis.tags || [];
data.marketing_analysis.facilities = data.marketing_analysis.facilities || []; // data.marketing_analysis.facilities = data.marketing_analysis.facilities || [];
data.marketing_analysis.report = data.marketing_analysis.report || ''; // data.marketing_analysis.report = data.marketing_analysis.report || '';
} // }
if (data.processed_info) { if (data.processed_info) {
data.processed_info.customer_name = data.processed_info.customer_name || '알 수 없음'; data.processed_info.customer_name = data.processed_info.customer_name || '알 수 없음';
data.processed_info.region = data.processed_info.region || ''; data.processed_info.region = data.processed_info.region || '';
@@ -229,25 +361,40 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
setAnalysisData(data); setAnalysisData(data);
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(data)); localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(data));
goToWizardStep(0); // 브랜드 분석 결과로 saveSearchHistory({ type: 'name', value: request.title.replace(/<[^>]*>/g, ''), address: request.address, roadAddress: request.roadAddress });
setIsAnalysisComplete(true);
} catch (err) { } catch (err) {
console.error('Autocomplete error:', err); console.error('Autocomplete error:', err);
setAnalysisError(err instanceof Error ? err.message : t('app.autocompleteError')); setAnalysisError(t('app.autocompleteError'));
goToWizardStep(-2); // URL 입력으로 돌아가기 goToWizardStep(-2); // URL 입력으로 돌아가기
} }
}; };
// 테스트용 랜덤 m_id 생성 (99 ~ 300) // 업체명·주소 수동 입력으로 마케팅 분석 API 호출
const generateRandomMId = (): number => { const handleManualInput = async (businessName: string, address: string, category: string, officialSiteUrl?: string) => {
return Math.floor(Math.random() * (300 - 99 + 1)) + 99; goToWizardStep(-1);
}; setIsAnalysisComplete(false);
setAnalysisError(null);
// 테스트 데이터로 브랜드 분석 페이지 이동 try {
const handleTestData = (data: CrawlingResponse) => { const data = await marketingAnalysis(businessName, address, category, officialSiteUrl);
const tagged = { ...data, m_id: generateRandomMId(), _isTestData: true };
setAnalysisData(tagged); if (data.processed_info) {
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(tagged)); data.processed_info.customer_name = data.processed_info.customer_name || businessName;
goToWizardStep(0); // 브랜드 분석 결과로 data.processed_info.region = data.processed_info.region || '';
data.processed_info.detail_region_info = data.processed_info.detail_region_info || '';
}
data.image_list = data.image_list || [];
setAnalysisData(data);
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(data));
saveSearchHistory({ type: 'name', value: businessName, address, roadAddress: address });
setIsAnalysisComplete(true);
} catch (err) {
console.error('Marketing analysis error:', err);
setAnalysisError(t('app.autocompleteError'));
goToWizardStep(-2);
}
}; };
// 언어 변경 시 테스트 데이터 다시 로드 // 언어 변경 시 테스트 데이터 다시 로드
@@ -262,7 +409,7 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
.then(res => res.json()) .then(res => res.json())
.then((data: CrawlingResponse) => { .then((data: CrawlingResponse) => {
// 언어 변경 시에는 기존 m_id 유지 // 언어 변경 시에는 기존 m_id 유지
const tagged = { ...data, m_id: parsed.m_id || generateRandomMId(), _isTestData: true }; const tagged = { ...data, m_id: parsed.m_id, _isTestData: true };
setAnalysisData(tagged); setAnalysisData(tagged);
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(tagged)); localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(tagged));
}) })
@@ -275,6 +422,7 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
if (!url.trim()) return; if (!url.trim()) return;
goToWizardStep(-1); // 로딩 상태로 goToWizardStep(-1); // 로딩 상태로
setIsAnalysisComplete(false);
setAnalysisError(null); setAnalysisError(null);
try { try {
@@ -282,11 +430,11 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
console.log('[Crawl] Response m_id:', data.m_id); console.log('[Crawl] Response m_id:', data.m_id);
// 기본값 보장 // 기본값 보장
if (data.marketing_analysis) { // if (data.marketing_analysis) {
data.marketing_analysis.tags = data.marketing_analysis.tags || []; // data.marketing_analysis.tags = data.marketing_analysis.tags || [];
data.marketing_analysis.facilities = data.marketing_analysis.facilities || []; // data.marketing_analysis.facilities = data.marketing_analysis.facilities || [];
data.marketing_analysis.report = data.marketing_analysis.report || ''; // data.marketing_analysis.report = data.marketing_analysis.report || '';
} // }
if (data.processed_info) { if (data.processed_info) {
data.processed_info.customer_name = data.processed_info.customer_name || '알 수 없음'; data.processed_info.customer_name = data.processed_info.customer_name || '알 수 없음';
data.processed_info.region = data.processed_info.region || ''; data.processed_info.region = data.processed_info.region || '';
@@ -296,11 +444,11 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
setAnalysisData(data); setAnalysisData(data);
localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(data)); localStorage.setItem(ANALYSIS_DATA_KEY, JSON.stringify(data));
goToWizardStep(0); // 브랜드 분석 결과로 saveSearchHistory({ type: 'url', value: url });
setIsAnalysisComplete(true);
} catch (err) { } catch (err) {
console.error('Crawling failed:', err); console.error('Crawling failed:', err);
const errorMessage = err instanceof Error ? err.message : t('app.analysisError'); setAnalysisError(t('app.analysisError'));
setAnalysisError(errorMessage);
goToWizardStep(-2); // URL 입력으로 돌아가기 goToWizardStep(-2); // URL 입력으로 돌아가기
} }
}; };
@@ -320,44 +468,137 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
localStorage.setItem(ACTIVE_ITEM_KEY, activeItem); localStorage.setItem(ACTIVE_ITEM_KEY, activeItem);
}, [activeItem]); }, [activeItem]);
// wizardStep 변경 시 튜토리얼 트리거 (사이드바 메뉴 화면에서는 제외) const [loginGateOpen, setLoginGateOpen] = useState(false);
const SIDEBAR_ITEMS = ['대시보드', 'ADO2 콘텐츠', '내 정보', '콘텐츠 캘린더'];
useEffect(() => {
if (tutorial.isActive) tutorial.skipTutorial();
if (SIDEBAR_ITEMS.includes(activeItem)) return;
const timer = setTimeout(() => {
if (wizardStep === 1 && !tutorial.hasSeen(TUTORIAL_KEYS.ASSET)) {
tutorial.startTutorial(TUTORIAL_KEYS.ASSET);
} else if (wizardStep === 2 && !tutorial.hasSeen(TUTORIAL_KEYS.SOUND)) {
tutorial.startTutorial(TUTORIAL_KEYS.SOUND);
}
}, 600);
return () => clearTimeout(timer);
}, [wizardStep, activeItem]);
// activeItem 변경 시 튜토리얼 트리거 /** 내 정보의 특정 탭으로 딥링크 이동. 비로그인이면 로그인 관문을 띄운다 */
useEffect(() => { const goToMyInfoTab = (tab: MyInfoTab) => {
if (tutorial.isActive) tutorial.skipTutorial(); if (!isLoggedIn()) {
if (activeItem === '내 정보' && !tutorial.hasSeen(TUTORIAL_KEYS.MY_INFO)) { sessionStorage.setItem(LOGIN_NEXT_ITEM_KEY, NAV.MY);
tutorial.startTutorial(TUTORIAL_KEYS.MY_INFO); setLoginGateOpen(true);
} else if (activeItem === 'ADO2 콘텐츠' && !tutorial.hasSeen(TUTORIAL_KEYS.ADO2_CONTENTS)) { return;
tutorial.startTutorial(TUTORIAL_KEYS.ADO2_CONTENTS);
} else if (activeItem === '대시보드' && !tutorial.hasSeen(TUTORIAL_KEYS.DASHBOARD)) {
tutorial.startTutorial(TUTORIAL_KEYS.DASHBOARD);
} else if (activeItem === '콘텐츠 캘린더' && !tutorial.hasSeen(TUTORIAL_KEYS.CONTENT_CALENDAR)) {
tutorial.startTutorial(TUTORIAL_KEYS.CONTENT_CALENDAR);
} }
}, [activeItem]); setMyInfoInitialTab(tab);
setActiveItem(NAV.MY);
};
// 결제 탭으로 바로 이동하는 핸들러 (크레딧 충전하기 버튼용)
const handleGoToPayment = () => {
goToMyInfoTab('payment');
};
/**
* 썰박스 잡 폴링을 시작한다.
*
* 폴링 소유가 GenerationFlow 인 이유: SsulMakingContent 가 들고 있으면
* 사이드바로 이동하는 순간 언마운트되면서 폴링이 끊긴다.
* 잡은 화면보다 오래 살아야 한다.
*/
const watchSsulTask = useCallback(
(taskId: number, scenario: Scen) => {
ssulCancelledRef.current = false;
setSsulJob({ taskId, scenario, status: 'queued', step: 0, error: null });
waitForSsulComplete(
taskId,
(task) => {
if (ssulCancelledRef.current) return;
setSsulJob({
taskId,
scenario,
status: task.status,
step: task.step,
error: task.error,
});
},
() => ssulCancelledRef.current
)
.then(() => {
if (ssulCancelledRef.current) return;
localStorage.removeItem(K.SSUL_TASK_ID);
setSsulStep('result');
})
.catch((e: Error) => {
if (ssulCancelledRef.current || e.message === 'CANCELLED') return;
localStorage.removeItem(K.SSUL_TASK_ID);
setSsulJob((prev) =>
prev ? { ...prev, status: 'error', error: e.message } : prev
);
})
.finally(() => {
if (ssulCancelledRef.current) return;
// 완료든 실패든 잔액을 갱신한다. 실패 시 백엔드가 환불하므로
// 갱신하지 않으면 사이드바 잔액이 낡은 값으로 굳는다.
refreshCredits();
});
},
[refreshCredits]
);
/** 생성 요청이 접수됐을 때 */
const handleSsulJobStarted = (taskId: number, scenario: Scen) => {
localStorage.setItem(K.SSUL_TASK_ID, String(taskId));
setSsulStep('making');
// 생성 시작 시점에 크레딧이 선차감되므로 사이드바 잔액을 즉시 갱신
refreshCredits();
watchSsulTask(taskId, scenario);
};
/** 실패 후 처음부터 */
const handleSsulRetry = () => {
ssulCancelledRef.current = true;
localStorage.removeItem(K.SSUL_TASK_ID);
setSsulJob(null);
setSsulStep('entry');
};
/**
* 새로고침·새 탭 진입 시 진행 중인 잡을 복구한다.
*
* 권위는 서버(`/ssul/tasks/active`)다. localStorage 의 SSUL_TASK_ID 는 힌트일 뿐이고,
* initializeOnNewSession 이 새 탭에서 그것을 지우기 때문에 서버를 물어야 한다.
*/
useEffect(() => {
if (!isLoggedIn()) return;
let alive = true;
getActiveSsulTask().then((task) => {
if (!alive || !task) return;
changePipeline('ssul');
setSsulStep('making');
watchSsulTask(task.id, task.scenario as Scen);
});
return () => {
alive = false;
};
// 마운트 시 1회만 — watchSsulTask 는 refreshCredits 에만 의존한다
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
/** 언마운트 시 폴링 중단 (로그아웃·화면 전환) */
useEffect(() => {
return () => {
ssulCancelledRef.current = true;
};
}, []);
// 네비게이션 핸들러 - "새 프로젝트 만들기" 클릭 시 기존 프로젝트 데이터 초기화 // 네비게이션 핸들러 - "새 프로젝트 만들기" 클릭 시 기존 프로젝트 데이터 초기화
const handleNavigate = (item: string) => { const handleNavigate = (item: string) => {
if (item === '새 프로젝트 만들기') { if (!isLoggedIn() && GATED_ITEMS.includes(item)) {
sessionStorage.setItem(LOGIN_NEXT_ITEM_KEY, item);
setLoginGateOpen(true);
return;
}
setMyInfoInitialTab(undefined);
if (item === NAV.NEW) {
// 기존 프로젝트 데이터 초기화 // 기존 프로젝트 데이터 초기화
clearAllProjectStorage(); clearProjectStorage();
localStorage.removeItem(ANALYSIS_DATA_KEY); localStorage.removeItem(ANALYSIS_DATA_KEY);
// URL 입력 단계로 명시적 저장 (다음 진입 시 올바른 단계 복원) // URL 입력 단계로 명시적 저장 (다음 진입 시 올바른 단계 복원)
localStorage.setItem(WIZARD_STEP_KEY, '-2'); localStorage.setItem(WIZARD_STEP_KEY, '-2');
setWizardStep(-2); setWizardStep(-2);
// 파이프라인도 기본값으로 되돌린다. clearProjectStorage() 가 K.PIPELINE 을
// 지우므로 state 만 남으면 저장소와 어긋난다.
setPipeline('ado2');
setSsulStep('entry');
setSongTaskId(null); setSongTaskId(null);
setImageTaskId(null); setImageTaskId(null);
setAnalysisData(null); setAnalysisData(null);
@@ -367,24 +608,53 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
setAnalysisError(null); setAnalysisError(null);
} }
setActiveItem(item); setActiveItem(item);
refreshCredits();
}; };
// 새 프로젝트 만들기 - 단계별 컨텐츠 렌더링 // 새 프로젝트 만들기 - 단계별 컨텐츠 렌더링
const renderWizardContent = () => { const renderWizardContent = () => {
// 진입 화면은 두 파이프라인이 공유하므로 switch 밖에서 먼저 처리한다.
// ADO2 는 wizardStep -2, 썰박스는 ssulStep 'entry' 가 여기 해당한다.
if (isEntry) {
return (
<UrlInputContent
pipeline={pipeline}
onPipelineChange={changePipeline}
onAnalyze={handleStartAnalysis}
onAutocomplete={handleAutocomplete}
onManualInput={handleManualInput}
error={analysisError}
onSsulJobStarted={handleSsulJobStarted}
onGoToPayment={handleGoToPayment}
/>
);
}
// 썰박스는 자체 축으로 진행한다
if (pipeline === 'ssul') {
switch (ssulStep) {
case 'making':
return (
<SsulMakingContent job={ssulJob} onRetry={handleSsulRetry} />
);
case 'result':
return ssulJob ? (
<SsulResultContent taskId={ssulJob.taskId} scenario={ssulJob.scenario} />
) : null;
default:
return null;
}
}
switch (wizardStep) { switch (wizardStep) {
case -2:
// URL 입력 단계
return (
<UrlInputContent
onAnalyze={handleStartAnalysis}
onAutocomplete={handleAutocomplete}
onTestData={handleTestData}
error={analysisError}
/>
);
case -1: case -1:
// 로딩 단계 // 로딩 단계
return <LoadingSection />; return (
<LoadingSection
isComplete={isAnalysisComplete}
onComplete={() => goToWizardStep(0)}
/>
);
case 0: case 0:
// 브랜드 분석 결과 단계 // 브랜드 분석 결과 단계
if (!analysisData) { if (!analysisData) {
@@ -404,8 +674,8 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
onBack={() => goToWizardStep(0)} onBack={() => goToWizardStep(0)}
onNext={(taskId: string) => { onNext={(taskId: string) => {
// Clear video generation state to start fresh // Clear video generation state to start fresh
localStorage.removeItem(VIDEO_GENERATION_KEY); localStorage.removeItem(K.VIDEO_GENERATION);
localStorage.removeItem(VIDEO_COMPLETE_KEY); localStorage.removeItem(K.VIDEO_COMPLETE);
setVideoGenerationStatus('idle'); setVideoGenerationStatus('idle');
setVideoGenerationProgress(0); setVideoGenerationProgress(0);
@@ -430,15 +700,10 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
businessInfo={currentBusinessInfo} businessInfo={currentBusinessInfo}
imageTaskId={imageTaskId} imageTaskId={imageTaskId}
mId={analysisData?.m_id ?? 0} mId={analysisData?.m_id ?? 0}
industry={analysisData?.industry ?? ''}
videoGenerationStatus={videoGenerationStatus} videoGenerationStatus={videoGenerationStatus}
videoGenerationProgress={videoGenerationProgress} videoGenerationProgress={videoGenerationProgress}
onStatusChange={(status: string) => { onGoToPayment={handleGoToPayment}
if (status === 'generating_song' && !tutorial.hasSeen(TUTORIAL_KEYS.SOUND_LYRICS)) {
setTimeout(() => tutorial.startTutorial(TUTORIAL_KEYS.SOUND_LYRICS), 400);
} else if (status === 'complete' && !tutorial.hasSeen(TUTORIAL_KEYS.SOUND_AUDIO)) {
setTimeout(() => tutorial.startTutorial(TUTORIAL_KEYS.SOUND_AUDIO), 400);
}
}}
/> />
); );
case 3: case 3:
@@ -447,8 +712,8 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
onBack={() => { onBack={() => {
// 뒤로가기 시 비디오 생성 상태 초기화 // 뒤로가기 시 비디오 생성 상태 초기화
// 새 노래 생성 후 다시 영상 생성할 수 있도록 // 새 노래 생성 후 다시 영상 생성할 수 있도록
localStorage.removeItem(VIDEO_GENERATION_KEY); localStorage.removeItem(K.VIDEO_GENERATION);
localStorage.removeItem(VIDEO_COMPLETE_KEY); localStorage.removeItem(K.VIDEO_COMPLETE);
setVideoGenerationStatus('idle'); setVideoGenerationStatus('idle');
setVideoGenerationProgress(0); setVideoGenerationProgress(0);
goToWizardStep(2); goToWizardStep(2);
@@ -456,6 +721,7 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
songTaskId={songTaskId} songTaskId={songTaskId}
onVideoStatusChange={setVideoGenerationStatus} onVideoStatusChange={setVideoGenerationStatus}
onVideoProgressChange={setVideoGenerationProgress} onVideoProgressChange={setVideoGenerationProgress}
onGoToCalendar={() => goToMyInfoTab('calendar')}
/> />
); );
default: default:
@@ -465,27 +731,45 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
const renderContent = () => { const renderContent = () => {
switch (activeItem) { switch (activeItem) {
case '대시보드': case NAV.DASHBOARD:
return <DashboardContent onNavigate={handleNavigate} />;
case '비즈니스 설정':
return <BusinessSettingsContent />;
case 'ADO2 콘텐츠':
return ( return (
<ADO2ContentsPage <DashboardContent
onBack={() => setActiveItem('새 프로젝트 만들기')} onNavigate={(id) => (id === NAV.MY ? goToMyInfoTab('business') : handleNavigate(id))}
/> />
); );
case '콘텐츠 캘린더': case NAV.HOME:
return <ContentCalendarContent onNavigate={handleNavigate} />; return <ADO2ContentsPage />;
case '내 정보': case NAV.MY:
return <MyInfoContent />; return <MyInfoContent initialTab={myInfoInitialTab} onNavigate={handleNavigate} />;
case '새 프로젝트 만들기': case NAV.NEW:
// 브랜드 분석(0)과 로딩(-1)은 전체 화면으로 표시 // 진입 화면(탭)과 ADO2 로딩(-1)은 스텝퍼 없이 전체 화면으로 표시
if (wizardStep === 0 || wizardStep === -1) { if (isEntry || (pipeline === 'ado2' && wizardStep === -1)) {
return renderWizardContent(); return renderWizardContent();
} }
// 썰박스는 자체 3단계 스텝퍼를 쓴다
if (pipeline === 'ssul') {
return (
<div className="wizard-page-container">
<WizardStepper
steps={SSUL_STEP_LABELS.map((key) => t(key))}
currentStep={SSUL_STEP_INDEX[ssulStep]}
/>
{renderWizardContent()}
</div>
);
}
// 브랜드 분석(0)은 전체 화면 스크롤이지만 스텝퍼는 표시
if (wizardStep === 0) {
return (
<>
<WizardStepper currentStep={wizardStep} />
{renderWizardContent()}
</>
);
}
return ( return (
<div className="wizard-page-container"> <div className="wizard-page-container">
<WizardStepper currentStep={wizardStep} />
{renderWizardContent()} {renderWizardContent()}
</div> </div>
); );
@@ -498,89 +782,75 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
} }
}; };
// 로딩 화면에서만 Sidebar 숨김 // 로딩 화면에서만 Sidebar/BottomNav 숨김
const showSidebar = wizardStep !== -1; const showSidebar = wizardStep !== -1;
// 브랜드 분석(0)일 때는 전체 페이지 스크롤 // 브랜드 분석(0)일 때는 전체 페이지 스크롤
const isBrandAnalysis = activeItem === '새 프로젝트 만들기' && wizardStep === 0; const isBrandAnalysis = activeItem === NAV.NEW && wizardStep === 0;
// 스크롤이 필요한 페이지: 대시보드, 비즈니스 설정, 브랜드 분석(0), ADO2 콘텐츠, 내 정보 // 위저드 진행 중에도 탭바를 노출한다. 각 단계의 고정 CTA 는 모바일에서
const needsScroll = activeItem === '대시보드' || activeItem === '비즈니스 설정' || activeItem === 'ADO2 콘텐츠' || activeItem === '내 정보' || activeItem === '콘텐츠 캘린더' || isBrandAnalysis; // 탭바 높이만큼 띄우도록 CSS(@media max-width:767px)에서 처리한다.
const showBottomNav = showSidebar;
// 스크롤이 필요한 페이지: 새 프로젝트 만들기(위저드) 외 전부 + 브랜드 분석(0)
const needsScroll = activeItem !== NAV.NEW || isBrandAnalysis;
// 현재 화면에 맞는 튜토리얼 키 반환 (없으면 null) const isMobile = useIsMobile();
const getCurrentTutorialKey = (): string | null => {
if (activeItem === '내 정보') return TUTORIAL_KEYS.MY_INFO;
if (activeItem === 'ADO2 콘텐츠') return TUTORIAL_KEYS.ADO2_CONTENTS;
if (activeItem === '대시보드') return TUTORIAL_KEYS.DASHBOARD;
if (activeItem === '콘텐츠 캘린더') return TUTORIAL_KEYS.CONTENT_CALENDAR;
if (activeItem === '새 프로젝트 만들기') {
if (wizardStep === 1) return TUTORIAL_KEYS.ASSET;
if (wizardStep === 2) return TUTORIAL_KEYS.SOUND;
}
return null;
};
const handleTutorialRestart = () => { const nav = isMobile
tutorial.showRestartPopup(getCurrentTutorialKey()!); ? (showBottomNav && (
}; <BottomNav
activeItem={activeItem}
const tutorialUI = ( onNavigate={handleNavigate}
<> userInfo={userInfo}
{getCurrentTutorialKey() && ( onLogout={handleLogout}
<button credits={credits}
className="tutorial-restart-fab" isGuest={isGuest}
onClick={handleTutorialRestart} onLoginClick={() => setLoginGateOpen(true)}
title={t('sidebar.tutorialRestart')}
>
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">
<circle cx="12" cy="12" r="10"/>
<path d="M12 8v4l3 3"/>
</svg>
<span>{t('sidebar.tutorialRestart')}</span>
</button>
)}
{tutorial.isActive && (
<TutorialOverlay
hints={tutorial.hints}
currentIndex={tutorial.currentHintIndex}
onNext={tutorial.nextHint}
onPrev={tutorial.prevHint}
onSkip={tutorial.skipTutorial}
groupProgress={tutorial.groupProgress}
/> />
)} ))
{tutorial.isRestartPopupVisible && ( : (showSidebar && (
<TutorialRestartPopup <Sidebar
onConfirm={tutorial.confirmRestart} activeItem={activeItem}
onCancel={tutorial.cancelRestart} onNavigate={handleNavigate}
onLogoClick={handleHome}
userInfo={userInfo}
onLogout={handleLogout}
credits={credits}
isGuest={isGuest}
onLoginClick={() => setLoginGateOpen(true)}
/> />
)} ));
</>
const loginGateModal = loginGateOpen && (
<LoginPromptModal
onClose={() => {
sessionStorage.removeItem(LOGIN_NEXT_ITEM_KEY);
setLoginGateOpen(false);
}}
/>
); );
// 브랜드 분석일 때는 전체 화면 스크롤 // 브랜드 분석일 때는 전체 화면 스크롤
if (isBrandAnalysis) { if (isBrandAnalysis) {
return ( return (
<div className="analysis-page-wrapper"> <div className="analysis-page-wrapper">
{showSidebar && ( {!isMobile && nav}
<Sidebar activeItem={activeItem} onNavigate={handleNavigate} onHome={handleHome} userInfo={userInfo} onLogout={handleLogout} /> <main className={`analysis-page-main ${showBottomNav ? 'has-bottom-nav' : ''}`}>
)}
<main className="analysis-page-main">
{renderContent()} {renderContent()}
</main> </main>
{tutorialUI} {isMobile && nav}
{loginGateModal}
</div> </div>
); );
} }
return ( return (
<div className={`flex w-full bg-[#002224] text-white ${needsScroll ? 'min-h-[100dvh]' : 'h-[100dvh] overflow-hidden'}`}> <div className={`flex w-full bg-[#002224] text-white ${needsScroll ? 'min-h-[100dvh]' : 'h-[100dvh] overflow-hidden'}`}>
{showSidebar && ( {!isMobile && nav}
<Sidebar activeItem={activeItem} onNavigate={handleNavigate} onHome={handleHome} userInfo={userInfo} onLogout={handleLogout} /> <div className={`flex-1 relative pl-0 md:pl-0 bg-[#001a1c] ${needsScroll ? 'overflow-auto' : 'h-full overflow-hidden'} ${showBottomNav ? 'has-bottom-nav' : ''}`}>
)}
{tutorialUI}
<div className={`flex-1 relative pl-0 md:pl-0 ${needsScroll ? 'overflow-auto' : 'h-full overflow-hidden'}`}>
{renderContent()} {renderContent()}
</div> </div>
{isMobile && nav}
{loginGateModal}
</div> </div>
); );
}; };
+433
View File
@@ -0,0 +1,433 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { getVideosList, deleteVideo, deleteSsulContent } from '../../utils/api';
import { VideoListItem } from '../../types/api';
import SocialPostingModal from '../../components/SocialPostingModal';
import VideoDetailModal from '../../components/VideoDetailModal';
import ContentCardSocialActions from '../../components/ContentCardSocialActions';
import SsulViewerModal from '../Ssulbox/SsulViewerModal';
import { useOverlayClose } from '../../hooks/useOverlayClose';
const VideoPreviewCard: React.FC<{ src: string; className?: string }> = ({ src, className }) => {
const videoRef = useRef<HTMLVideoElement>(null);
const isPlayingRef = useRef(false);
const pendingPlayRef = useRef(false);
useEffect(() => {
const video = videoRef.current;
if (!video) return;
const observer = new IntersectionObserver(
([entry]) => {
if (entry.isIntersecting) {
video.preload = 'auto';
} else {
video.preload = 'none';
}
},
{ threshold: 0.1 }
);
observer.observe(video);
return () => observer.disconnect();
}, []);
const safePlay = useCallback((video: HTMLVideoElement) => {
const playPromise = video.play();
if (playPromise !== undefined) {
playPromise
.then(() => { isPlayingRef.current = true; })
.catch((error) => {
if (error.name !== 'AbortError') console.error(error);
});
}
}, []);
const handleCanPlay = useCallback(() => {
if (!pendingPlayRef.current || !videoRef.current) return;
pendingPlayRef.current = false;
safePlay(videoRef.current);
}, [safePlay]);
const handleMouseEnter = useCallback(() => {
const video = videoRef.current;
if (!video) return;
if (video.readyState >= 3) {
safePlay(video);
} else {
pendingPlayRef.current = true;
}
}, [safePlay]);
const handleMouseLeave = useCallback(() => {
const video = videoRef.current;
if (!video) return;
pendingPlayRef.current = false;
if (isPlayingRef.current) {
video.pause();
video.currentTime = 0;
isPlayingRef.current = false;
}
}, []);
return (
<video
ref={videoRef}
src={src}
className={className}
muted
playsInline
preload="none"
onCanPlay={handleCanPlay}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
/>
);
};
interface MyContentsPageProps {
onBack?: () => void;
onNavigate?: (item: string) => void;
/** 내 정보 탭 안에 임베드될 때: 탭 라벨과 중복되는 자체 제목을 숨긴다 */
embedded?: boolean;
}
const MyContentsPage: React.FC<MyContentsPageProps> = ({ onNavigate, embedded }) => {
const { t } = useTranslation();
const [videos, setVideos] = useState<VideoListItem[]>([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [page, setPage] = useState(1);
const [hasNext, setHasNext] = useState(false);
const [hasPrev, setHasPrev] = useState(false);
const [totalPages, setTotalPages] = useState(1);
const [deleteModalOpen, setDeleteModalOpen] = useState(false);
const [deleteTarget, setDeleteTarget] = useState<VideoListItem | null>(null);
const [isDeleting, setIsDeleting] = useState(false);
const [uploadModalOpen, setUploadModalOpen] = useState(false);
const [uploadTargetVideo, setUploadTargetVideo] = useState<VideoListItem | null>(null);
const [selectedVideoId, setSelectedVideoId] = useState<number | null>(null);
// 썰박스는 별도 뷰어를 쓴다 — VideoDetailModal 은 video_id 로 조회하므로
// 썰박스 id 를 넘기면 id 가 겹치는 다른 영상이 열린다.
const [selectedSsul, setSelectedSsul] = useState<VideoListItem | null>(null);
const pageSize = 12;
useEffect(() => {
fetchVideos();
}, [page]);
const fetchVideos = async () => {
setLoading(true);
setError(null);
try {
const response = await getVideosList(page, pageSize);
const validVideos = response.items.filter(video => video.result_movie_url && video.result_movie_url.trim() !== '');
setVideos(validVideos);
setTotal(response.total);
setTotalPages(response.total_pages);
setHasNext(response.has_next);
setHasPrev(response.has_prev);
} catch (err) {
console.error('Failed to fetch videos:', err);
setError(t('ado2Contents.loadFailed'));
} finally {
setLoading(false);
}
};
const formatDate = (dateString: string) => {
const date = new Date(dateString);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${year}.${month}.${day}`;
};
const formatTitle = (storeName: string, dateString: string) => {
const date = new Date(dateString);
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${storeName} ${month}/${day} ${hours}:${minutes}`;
};
const handleDownload = async (videoUrl: string, storeName: string) => {
try {
const response = await fetch(videoUrl);
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${storeName}.mp4`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (err) {
console.error('Download failed:', err);
alert(t('ado2Contents.downloadFailed'));
}
};
// 아이템 전체를 저장한다 — id 만 들면 종류를 잃어 어느 삭제 API 를 부를지 알 수 없다
// (video.id 와 ssul_content.id 는 값이 겹치는 독립 시퀀스).
const handleDeleteClick = (video: VideoListItem) => {
setDeleteTarget(video);
setDeleteModalOpen(true);
};
const handleUploadClick = (video: VideoListItem) => {
setUploadTargetVideo(video);
setUploadModalOpen(true);
};
const handleUploadModalClose = () => {
setUploadModalOpen(false);
setUploadTargetVideo(null);
};
const handleDeleteCancel = () => {
setDeleteModalOpen(false);
setDeleteTarget(null);
};
const deleteModalOverlayHandlers = useOverlayClose(handleDeleteCancel);
const handleDeleteConfirm = async () => {
if (!deleteTarget) return;
setIsDeleting(true);
try {
// 종류별 삭제 API 가 다르다. deleteVideo 는 Video.id 로 지우므로
// 썰박스 id 를 넘기면 id 가 겹치는 엉뚱한 ADO2 영상이 삭제된다.
if (deleteTarget.type === 'ssul') {
await deleteSsulContent(deleteTarget.video_id);
} else {
await deleteVideo(deleteTarget.video_id);
}
setVideos(prev =>
prev.filter(
video =>
!(video.type === deleteTarget.type && video.video_id === deleteTarget.video_id)
)
);
setTotal(prev => Math.max(0, prev - 1));
setDeleteModalOpen(false);
setDeleteTarget(null);
} catch (err) {
console.error('Delete failed:', err);
alert(t('ado2Contents.deleteFailed'));
} finally {
setIsDeleting(false);
}
};
return (
<div className={`ado2-contents-page ${embedded ? 'ado2-contents-page--embedded' : ''}`}>
{/* Header */}
<div className="ado2-contents-header">
{!embedded && <h1 className="ado2-contents-title">{t('sidebar.myContents')}</h1>}
<span className="ado2-contents-count">{t('ado2Contents.totalCount', { count: total })}</span>
</div>
{/* Content Grid */}
{loading ? (
<div className="ado2-contents-loading">
<div className="loading-spinner"></div>
<p>{t('ado2Contents.loading')}</p>
</div>
) : error ? (
<div className="ado2-contents-error">
<p>{error}</p>
<button onClick={fetchVideos} className="retry-btn">{t('ado2Contents.retry')}</button>
</div>
) : videos.length === 0 ? (
<div className="ado2-contents-empty">
<p>{t('ado2Contents.noContent')}</p>
</div>
) : (
<>
<div className="ado2-contents-grid">
{videos.map((video) => (
// key 는 (type, video_id) 쌍이어야 한다 — task_id 는 썰박스에 없고(빈 문자열)
// video_id 는 종류별 독립 시퀀스라 값이 겹친다.
<div key={`${video.type}-${video.video_id}`} className="ado2-content-card">
{/* Video Thumbnail */}
<div
className="content-card-thumbnail"
style={{ cursor: 'pointer' }}
onClick={() =>
video.type === 'ssul'
? setSelectedSsul(video)
: setSelectedVideoId(video.video_id)
}
>
{video.poster_url ? (
<img
src={video.poster_url}
alt={video.store_name}
loading="lazy"
decoding="async"
className="content-video-preview"
/>
) : video.result_movie_url ? (
<VideoPreviewCard
src={video.result_movie_url}
className="content-video-preview"
/>
) : (
<div className="content-no-video">
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
<rect x="2" y="2" width="20" height="20" rx="2.18" ry="2.18"/>
<line x1="7" y1="2" x2="7" y2="22"/>
<line x1="17" y1="2" x2="17" y2="22"/>
<line x1="2" y1="12" x2="22" y2="12"/>
<line x1="2" y1="7" x2="7" y2="7"/>
<line x1="2" y1="17" x2="7" y2="17"/>
<line x1="17" y1="17" x2="22" y2="17"/>
<line x1="17" y1="7" x2="22" y2="7"/>
</svg>
</div>
)}
</div>
{/* Card Info */}
<div className="content-card-info">
<div className="content-card-text">
<h3 className="content-card-title">
{formatTitle(video.store_name, video.created_at)}
</h3>
<div className="content-card-meta">
<p className="content-card-date">
{formatDate(video.created_at)}
</p>
{/* 좋아요·댓글 API 가 type 을 받으므로 썰박스에도 노출한다.
contentType 이 없으면 id 가 겹치는 다른 영상에 반영된다. */}
<ContentCardSocialActions
videoId={video.video_id}
contentType={video.type}
storeName={video.store_name}
region={video.region}
title={video.title}
description={video.description}
commentCount={video.comment_count ?? 0}
initialLikeCount={video.like_count ?? 0}
initialIsLiked={video.is_liked_by_me}
/>
</div>
</div>
{/* Action Buttons */}
<div className="content-card-actions">
{/* SocialPostingModal 이 content_type 을 함께 보내므로
썰박스 항목도 같은 모달로 업로드한다 (social_upload 병합). */}
<button
className="content-download-btn"
onClick={() => handleUploadClick(video)}
disabled={!video.result_movie_url}
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5">
<path d="M10 13V3M10 3l-4 4M10 3l4 4"/>
<path d="M3 15v2h14v-2"/>
</svg>
<span>{t('ado2Contents.uploadToSocial')}</span>
</button>
<button
className="content-upload-btn"
onClick={() => handleDownload(video.result_movie_url, video.store_name)}
disabled={!video.result_movie_url}
title={t('ado2Contents.download')}
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5">
<path d="M10 3v10M10 13l-4-4M10 13l4-4"/>
<path d="M3 15v2h14v-2"/>
</svg>
</button>
{/* 삭제는 종류별 API 로 분기한다(handleDeleteConfirm).
아이템 전체를 넘겨야 종류를 잃지 않는다. */}
<button
className="content-delete-btn"
onClick={() => handleDeleteClick(video)}
>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5">
<path d="M3 5h14M8 5V3h4v2M6 5v12h8V5"/>
<line x1="8" y1="8" x2="8" y2="14"/>
<line x1="12" y1="8" x2="12" y2="14"/>
</svg>
</button>
</div>
</div>
</div>
))}
</div>
{/* Pagination */}
<div className="ado2-contents-pagination">
<button
className="pagination-btn"
onClick={() => setPage(p => p - 1)}
disabled={!hasPrev}
>
{t('ado2Contents.previous')}
</button>
<span className="pagination-info">{page} / {totalPages}</span>
<button
className="pagination-btn"
onClick={() => setPage(p => p + 1)}
disabled={!hasNext}
>
{t('ado2Contents.next')}
</button>
</div>
</>
)}
{/* 삭제 확인 모달 */}
{deleteModalOpen && (
<div className="delete-modal-overlay" {...deleteModalOverlayHandlers}>
<div className="delete-modal" onClick={(e: React.MouseEvent) => e.stopPropagation()}>
<h2 className="delete-modal-title">{t('ado2Contents.deleteConfirmTitle')}</h2>
<p className="delete-modal-description">{t('ado2Contents.deleteConfirmDesc')}</p>
<div className="delete-modal-actions">
<button
className="delete-modal-btn cancel"
onClick={handleDeleteCancel}
disabled={isDeleting}
>
{t('ado2Contents.cancel')}
</button>
<button
className="delete-modal-btn confirm"
onClick={handleDeleteConfirm}
disabled={isDeleting}
>
{isDeleting ? t('ado2Contents.deleting') : t('ado2Contents.delete')}
</button>
</div>
</div>
</div>
)}
{selectedVideoId !== null && (
<VideoDetailModal
videoId={String(selectedVideoId)}
onClose={() => setSelectedVideoId(null)}
/>
)}
<SsulViewerModal item={selectedSsul} onClose={() => setSelectedSsul(null)} />
{/* 소셜 미디어 업로드 모달 */}
<SocialPostingModal
isOpen={uploadModalOpen}
onClose={handleUploadModalClose}
video={uploadTargetVideo}
onGoToCalendar={onNavigate ? () => onNavigate('콘텐츠 캘린더') : undefined}
/>
</div>
);
};
export default MyContentsPage;
+160 -15
View File
@@ -1,18 +1,58 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { getSocialAccounts, getYouTubeConnectUrl, disconnectSocialAccount, TokenExpiredError, handleSocialReconnect } from '../../utils/api'; import { getSocialAccounts, getYouTubeConnectUrl, disconnectSocialAccount, TokenExpiredError, handleSocialReconnect, getUserCredits, requestCreditCharge } from '../../utils/api';
import { SocialAccount } from '../../types/api'; import { SocialAccount } from '../../types/api';
import { MyInfoTab } from '../../components/navItems';
import MyContentsPage from './MyContentsPage';
import ContentCalendarContent from './ContentCalendarContent';
import { useOverlayClose } from '../../hooks/useOverlayClose';
type TabType = 'basic' | 'payment' | 'business'; type TabType = MyInfoTab;
const MyInfoContent: React.FC = () => { interface MyInfoContentProps {
initialTab?: TabType;
onNavigate?: (id: string) => void;
}
const MyInfoContent: React.FC<MyInfoContentProps> = ({ initialTab, onNavigate }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [activeTab, setActiveTab] = useState<TabType>('business'); const [activeTab, setActiveTab] = useState<TabType>(initialTab || 'contents');
const [businessUrl, setBusinessUrl] = useState(''); const [businessUrl, setBusinessUrl] = useState('');
const [socialAccounts, setSocialAccounts] = useState<SocialAccount[]>([]); const [socialAccounts, setSocialAccounts] = useState<SocialAccount[]>([]);
const [isLoadingAccounts, setIsLoadingAccounts] = useState(false); const [isLoadingAccounts, setIsLoadingAccounts] = useState(false);
const [isConnecting, setIsConnecting] = useState<string | null>(null); const [isConnecting, setIsConnecting] = useState<string | null>(null);
const [credits, setCredits] = useState<number | null>(null);
const [isLoadingCredits, setIsLoadingCredits] = useState(false);
const [showChargePopup, setShowChargePopup] = useState(false);
const [chargeAmount, setChargeAmount] = useState('');
const [chargeNote, setChargeNote] = useState('');
const [isRequesting, setIsRequesting] = useState(false);
const [chargeSuccess, setChargeSuccess] = useState(false);
// initialTab 변경 시 탭 업데이트
useEffect(() => {
if (initialTab) setActiveTab(initialTab);
}, [initialTab]);
// 크레딧 로드
useEffect(() => {
if (activeTab === 'payment') {
loadCredits();
}
}, [activeTab]);
const loadCredits = async () => {
setIsLoadingCredits(true);
try {
const data = await getUserCredits();
setCredits(data.credits);
} catch (error) {
console.error('Failed to load credits:', error);
} finally {
setIsLoadingCredits(false);
}
};
// 소셜 계정 목록 로드 // 소셜 계정 목록 로드
useEffect(() => { useEffect(() => {
@@ -78,13 +118,94 @@ const MyInfoContent: React.FC = () => {
const hasConnectedAccounts = youtubeAccounts.length > 0 || instagramAccounts.length > 0; const hasConnectedAccounts = youtubeAccounts.length > 0 || instagramAccounts.length > 0;
const tabs = [ const tabs = [
{ id: 'basic' as TabType, label: t('myInfo.tabBasic') }, { id: 'contents' as TabType, label: t('myInfo.tabContents') },
{ id: 'calendar' as TabType, label: t('myInfo.tabCalendar') },
{ id: 'payment' as TabType, label: t('myInfo.tabPayment') }, { id: 'payment' as TabType, label: t('myInfo.tabPayment') },
{ id: 'business' as TabType, label: t('myInfo.tabBusiness') }, { id: 'business' as TabType, label: t('myInfo.tabBusiness') },
]; ];
const isWideTab = activeTab === 'contents' || activeTab === 'calendar';
const handleChildNavigate = (id: string) => {
if (id === '내 정보') { setActiveTab('business'); return; }
if (id === '콘텐츠 캘린더') { setActiveTab('calendar'); return; }
if (id === '내 콘텐츠') { setActiveTab('contents'); return; }
onNavigate?.(id);
};
const closeChargePopup = () => { setShowChargePopup(false); setChargeSuccess(false); setChargeAmount(''); setChargeNote(''); };
const chargePopupOverlayHandlers = useOverlayClose(closeChargePopup);
return ( return (
<main className="myinfo-page"> <>
{showChargePopup && (
<div className="myinfo-popup-overlay" {...chargePopupOverlayHandlers}>
<div className="myinfo-popup" onClick={e => e.stopPropagation()}>
{chargeSuccess ? (
<>
<p className="myinfo-popup-message">{t('myInfo.chargeSuccess')}</p>
<button className="myinfo-popup-close" onClick={closeChargePopup}>{t('myInfo.chargeConfirm')}</button>
</>
) : (
<>
<h3 className="myinfo-popup-title">{t('myInfo.chargePopupTitle')}</h3>
<div className="myinfo-popup-field">
<label className="myinfo-popup-label">{t('myInfo.chargeAmountLabel')}</label>
<div className="myinfo-popup-counter">
<button
className="myinfo-popup-counter-btn"
onClick={() => setChargeAmount(v => String(Math.max(1, Number(v || 0) - 1)))}
>−</button>
<input
type="number"
className="myinfo-popup-input myinfo-popup-input--center"
placeholder="0"
value={chargeAmount}
onChange={e => setChargeAmount(e.target.value.replace(/[^0-9]/g, ''))}
min={1}
/>
<button
className="myinfo-popup-counter-btn"
onClick={() => setChargeAmount(v => String(Number(v || 0) + 1))}
>+</button>
</div>
</div>
<div className="myinfo-popup-field">
<label className="myinfo-popup-label">{t('myInfo.chargeNoteLabel')}</label>
<textarea
className="myinfo-popup-textarea"
placeholder={t('myInfo.chargeNotePlaceholder')}
value={chargeNote}
onChange={e => setChargeNote(e.target.value)}
rows={3}
/>
</div>
<div className="myinfo-popup-actions">
<button className="myinfo-popup-cancel" onClick={() => { setShowChargePopup(false); setChargeAmount(''); setChargeNote(''); }}>{t('myInfo.chargeCancel')}</button>
<button
className="myinfo-popup-close"
disabled={!chargeAmount || isRequesting}
onClick={async () => {
setIsRequesting(true);
try {
await requestCreditCharge(Number(chargeAmount), chargeNote);
} catch (e) {
console.error('Charge request failed:', e);
} finally {
setIsRequesting(false);
setChargeSuccess(true);
}
}}
>
{isRequesting ? t('myInfo.chargeSubmitting') : t('myInfo.chargeSubmit')}
</button>
</div>
</>
)}
</div>
</div>
)}
<main className={`myinfo-page ${isWideTab ? 'myinfo-page--wide' : ''}`}>
<h1 className="myinfo-title">{t('myInfo.title')}</h1> <h1 className="myinfo-title">{t('myInfo.title')}</h1>
{/* 탭 네비게이션 */} {/* 탭 네비게이션 */}
@@ -102,21 +223,44 @@ const MyInfoContent: React.FC = () => {
{/* 탭 컨텐츠 */} {/* 탭 컨텐츠 */}
<div className="myinfo-content"> <div className="myinfo-content">
{activeTab === 'basic' && ( {activeTab === 'contents' && (
<div className="myinfo-section"> <MyContentsPage onNavigate={handleChildNavigate} embedded />
<p className="myinfo-placeholder">{t('myInfo.basicPlaceholder')}</p> )}
</div>
{activeTab === 'calendar' && (
<ContentCalendarContent onNavigate={handleChildNavigate} embedded />
)} )}
{activeTab === 'payment' && ( {activeTab === 'payment' && (
<div className="myinfo-section"> <div className="myinfo-section">
<p className="myinfo-placeholder">{t('myInfo.paymentPlaceholder')}</p> <h2 className="myinfo-section-title">{t('myInfo.creditsTitle')}</h2>
<div className="myinfo-credits-card">
{isLoadingCredits ? (
<p className="myinfo-placeholder">{t('myInfo.creditsLoading')}</p>
) : (
<>
<div className="myinfo-credits-row">
<span className="myinfo-credits-label">{t('myInfo.creditsLabel')}</span>
<span className="myinfo-credits-value">{credits !== null ? credits.toLocaleString() : '-'} {t('myInfo.creditsUnit')}</span>
</div>
<div className="myinfo-credits-row">
<p className="myinfo-credits-desc">{t('myInfo.creditsDesc')}</p>
<button
className="myinfo-credits-charge-btn"
onClick={() => setShowChargePopup(true)}
>
{t('myInfo.creditsChargeBtn')}
</button>
</div>
</>
)}
</div>
</div> </div>
)} )}
{activeTab === 'business' && ( {activeTab === 'business' && (
<> <>
{/* 내 비즈니스 섹션 */} {/* 내 비즈니스 섹션
<div className="myinfo-section"> <div className="myinfo-section">
<h2 className="myinfo-section-title">{t('myInfo.myBusiness')}</h2> <h2 className="myinfo-section-title">{t('myInfo.myBusiness')}</h2>
<div className="myinfo-business-card"> <div className="myinfo-business-card">
@@ -137,7 +281,7 @@ const MyInfoContent: React.FC = () => {
</button> </button>
</div> </div>
</div> </div>
</div> </div> */}
{/* 소셜 채널 섹션 */} {/* 소셜 채널 섹션 */}
<div className="myinfo-section"> <div className="myinfo-section">
@@ -154,13 +298,13 @@ const MyInfoContent: React.FC = () => {
<span>{isConnecting === 'youtube' ? t('myInfo.youtubeConnecting') : t('myInfo.youtubeConnect')}</span> <span>{isConnecting === 'youtube' ? t('myInfo.youtubeConnecting') : t('myInfo.youtubeConnect')}</span>
</button> </button>
<button {/* <button
disabled disabled
className="myinfo-social-btn disabled" className="myinfo-social-btn disabled"
> >
<img src="/assets/images/social-instagram.png" alt="Instagram" className="myinfo-social-btn-icon" /> <img src="/assets/images/social-instagram.png" alt="Instagram" className="myinfo-social-btn-icon" />
<span>{t('myInfo.instagramConnect')}</span> <span>{t('myInfo.instagramConnect')}</span>
</button> </button> */}
</div> </div>
{/* 연결된 계정 목록 */} {/* 연결된 계정 목록 */}
@@ -250,6 +394,7 @@ const MyInfoContent: React.FC = () => {
)} )}
</div> </div>
</main> </main>
</>
); );
}; };
+246 -160
View File
@@ -1,5 +1,5 @@
import React, { useState, useRef, useEffect } from 'react'; import React, { useState, useRef, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { generateLyric, waitForLyricComplete, generateSong, waitForSongComplete } from '../../utils/api'; import { generateLyric, waitForLyricComplete, generateSong, waitForSongComplete } from '../../utils/api';
import { LANGUAGE_MAP } from '../../types/api'; import { LANGUAGE_MAP } from '../../types/api';
@@ -16,15 +16,70 @@ interface SoundStudioContentProps {
businessInfo?: BusinessInfo; businessInfo?: BusinessInfo;
imageTaskId: string | null; imageTaskId: string | null;
mId: number; mId: number;
industry?: string;
onStatusChange?: (status: string) => void; onStatusChange?: (status: string) => void;
videoGenerationStatus?: 'idle' | 'generating' | 'complete' | 'error'; videoGenerationStatus?: 'idle' | 'generating' | 'complete' | 'error';
videoGenerationProgress?: number; videoGenerationProgress?: number;
onGoToPayment?: () => void;
} }
type GenerationStatus = 'idle' | 'generating_lyric' | 'generating_song' | 'polling' | 'complete' | 'error'; type GenerationStatus = 'idle' | 'generating_lyric' | 'generating_song' | 'polling' | 'complete' | 'error';
const MAX_RETRY_COUNT = 3; const MAX_RETRY_COUNT = 3;
// 생성 완료된 곡 상태를 새로고침 후에도 복원하기 위한 키
// GenerationFlow의 clearAllProjectStorage가 이 키를 포함해 정리함
const SONG_GENERATION_KEY = 'castad_song_generation';
const GENRE_VALUES = ['kpop', 'pop', 'ballad', 'hip-hop', 'rnb', 'edm', 'jazz', 'rock'];
const genreMap: Record<string, string> = {
'자동 선택': '', // 런타임에 랜덤 결정
'K-POP': 'kpop',
'POP': 'pop',
'발라드': 'ballad',
'Hip-Hop': 'hip-hop',
'R&B': 'rnb',
'EDM': 'edm',
'JAZZ': 'jazz',
'ROCK': 'rock',
};
const getEffectiveGenre = (selectedGenre: string): string => {
if (selectedGenre === '자동 선택') {
return GENRE_VALUES[Math.floor(Math.random() * GENRE_VALUES.length)];
}
return genreMap[selectedGenre] || 'pop';
};
// 실제 영상 생성에 사용된 genre 값(kpop, hip-hop 등)을 화면 표시용 라벨로 변환
const getGenreDisplayLabel = (genreValue: string, t: (key: string) => string): string => {
const displayMap: Record<string, string> = {
kpop: 'K-POP',
pop: 'POP',
ballad: t('soundStudio.genreBallad'),
'hip-hop': 'Hip-Hop',
rnb: 'R&B',
edm: 'EDM',
jazz: 'JAZZ',
rock: 'ROCK',
};
return displayMap[genreValue] || genreValue;
};
const sanitizeError = (message: string, fallback: string): string => {
if (
message.includes('Traceback') ||
message.includes('File "/') ||
message.includes('httpx.') ||
message.includes('httpcore.') ||
message.length > 200
) {
return fallback;
}
return message;
};
const LANGUAGE_FLAGS: Record<string, string> = { const LANGUAGE_FLAGS: Record<string, string> = {
'한국어': '🇰🇷', '한국어': '🇰🇷',
'English': '🇺🇸', 'English': '🇺🇸',
@@ -40,16 +95,18 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
businessInfo, businessInfo,
imageTaskId, imageTaskId,
mId, mId,
industry = '',
onStatusChange, onStatusChange,
videoGenerationStatus = 'idle', videoGenerationStatus = 'idle',
videoGenerationProgress = 0 videoGenerationProgress = 0,
onGoToPayment,
}) => { }) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [selectedType, setSelectedType] = useState('보컬'); const [selectedType, setSelectedType] = useState('보컬');
const [selectedLang, setSelectedLang] = useState('한국어'); const [selectedLang, setSelectedLang] = useState('한국어');
const [selectedGenre, setSelectedGenre] = useState('자동 선택'); const [selectedGenre, setSelectedGenre] = useState('자동 선택');
const [usedGenre, setUsedGenre] = useState('');
const [progress, setProgress] = useState(0); const [progress, setProgress] = useState(0);
const [isDragging, setIsDragging] = useState(false);
const [status, setStatus] = useState<GenerationStatus>('idle'); const [status, setStatus] = useState<GenerationStatus>('idle');
const [lyrics, setLyrics] = useState(''); const [lyrics, setLyrics] = useState('');
const [audioUrl, setAudioUrl] = useState<string | null>(null); const [audioUrl, setAudioUrl] = useState<string | null>(null);
@@ -60,40 +117,41 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
const [statusMessage, setStatusMessage] = useState(''); const [statusMessage, setStatusMessage] = useState('');
const [retryCount, setRetryCount] = useState(0); const [retryCount, setRetryCount] = useState(0);
const [songTaskId, setSongTaskId] = useState<string | null>(null); const [songTaskId, setSongTaskId] = useState<string | null>(null);
const [isLanguageDropdownOpen, setIsLanguageDropdownOpen] = useState(false);
const progressBarRef = useRef<HTMLDivElement>(null);
const audioRef = useRef<HTMLAudioElement>(null); const audioRef = useRef<HTMLAudioElement>(null);
const languageDropdownRef = useRef<HTMLDivElement>(null);
// 완료 데이터를 localStorage에 저장 // 완료 데이터를 localStorage에 저장
const saveSongCompletionData = () => { const saveSongCompletionData = () => {
const completionData = { const completionData = {
businessName: businessInfo?.customer_name || '알 수 없음', businessName: businessInfo?.customer_name || '알 수 없음',
genre: selectedGenre === '자동 선택' ? 'K-POP' : selectedGenre, // '자동 선택'처럼 UI에서 고른 값이 아니라, 실제 영상 생성에 사용된 genre(usedGenre)를 저장
genre: usedGenre ? getGenreDisplayLabel(usedGenre, t) : selectedGenre,
lyrics: lyrics, lyrics: lyrics,
timestamp: Date.now(), timestamp: Date.now(),
}; };
localStorage.setItem('castad_song_completion', JSON.stringify(completionData)); localStorage.setItem('castad_song_completion', JSON.stringify(completionData));
}; };
// Close language dropdown when clicking outside // 새로고침 후 생성 완료된 곡 상태 복원
useEffect(() => { useEffect(() => {
const handleClickOutside = (event: MouseEvent) => { const saved = localStorage.getItem(SONG_GENERATION_KEY);
if (languageDropdownRef.current && !languageDropdownRef.current.contains(event.target as Node)) { if (!saved) return;
setIsLanguageDropdownOpen(false);
}
};
if (isLanguageDropdownOpen) { try {
document.addEventListener('mousedown', handleClickOutside); const parsed = JSON.parse(saved);
if (parsed.status !== 'complete' || !parsed.audioUrl || !parsed.songTaskId) return;
// 저장된 URL로 복원 (public Blob URL이라 만료되지 않음)
// 백엔드에 /song/download 엔드포인트가 없으므로 재조회하지 않는다.
setSongTaskId(parsed.songTaskId);
setAudioUrl(parsed.audioUrl);
setLyrics(parsed.lyrics ?? '');
setStatus('complete');
} catch {
// 파싱 실패 시 무시
} }
}, []); // 마운트 1회만 실행
return () => { // Close language dropdown when clicking outside
document.removeEventListener('mousedown', handleClickOutside);
};
}, [isLanguageDropdownOpen]);
// Auto-navigate to next page when video generation is complete // Auto-navigate to next page when video generation is complete
useEffect(() => { useEffect(() => {
if (videoGenerationStatus === 'complete' && songTaskId) { if (videoGenerationStatus === 'complete' && songTaskId) {
@@ -132,6 +190,18 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
setStatusMessage(''); setStatusMessage('');
setRetryCount(0); setRetryCount(0);
// 새로고침 후에도 복원할 수 있도록 완료된 곡 상태를 저장
try {
localStorage.setItem(SONG_GENERATION_KEY, JSON.stringify({
audioUrl: statusResponse.song_result_url,
songTaskId: taskId,
lyrics: currentLyrics,
status: 'complete',
}));
} catch {
// localStorage 쓰기 실패는 무시
}
} catch (error) { } catch (error) {
console.error('Polling failed:', error); console.error('Polling failed:', error);
@@ -148,7 +218,10 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
} }
} else { } else {
setStatus('error'); setStatus('error');
setErrorMessage(error instanceof Error ? error.message : t('soundStudio.musicGenerationError')); setErrorMessage(sanitizeError(
error instanceof Error ? error.message : '',
t('soundStudio.musicGenerationError')
));
setRetryCount(0); setRetryCount(0);
} }
} }
@@ -159,21 +232,14 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
try { try {
const language = LANGUAGE_MAP[selectedLang] || 'Korean'; const language = LANGUAGE_MAP[selectedLang] || 'Korean';
const genreMap: Record<string, string> = {
'자동 선택': 'pop', const isInstrumental = selectedType === '배경음악';
'K-POP': 'kpop', const effectiveGenre = getEffectiveGenre(selectedGenre);
'발라드': 'ballad', setUsedGenre(effectiveGenre);
'Hip-Hop': 'hip-hop',
'R&B': 'rnb',
'EDM': 'edm',
'JAZZ': 'jazz',
'ROCK': 'rock',
};
const songResponse = await generateSong(imageTaskId, { const songResponse = await generateSong(imageTaskId, {
genre: genreMap[selectedGenre] || 'pop', genre: effectiveGenre,
language, ...(isInstrumental ? { instrumental: true, lyrics: '' } : { language, lyrics: currentLyrics }),
lyrics: currentLyrics,
}); });
if (!songResponse.success) { if (!songResponse.success) {
@@ -185,46 +251,14 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
} catch (error) { } catch (error) {
console.error('Song regeneration failed:', error); console.error('Song regeneration failed:', error);
setStatus('error'); setStatus('error');
setErrorMessage(error instanceof Error ? error.message : t('soundStudio.songRegenerationError')); setErrorMessage(sanitizeError(
error instanceof Error ? error.message : '',
t('soundStudio.songRegenerationError')
));
setRetryCount(0); setRetryCount(0);
} }
}; };
const handleMove = (clientX: number) => {
if (!progressBarRef.current || !audioRef.current) return;
const rect = progressBarRef.current.getBoundingClientRect();
const newProgress = Math.max(0, Math.min(100, ((clientX - rect.left) / rect.width) * 100));
const newTime = (newProgress / 100) * duration;
audioRef.current.currentTime = newTime;
setProgress(newProgress);
setCurrentTime(newTime);
};
const onMouseDown = (e: React.MouseEvent) => {
if (!audioUrl) return;
setIsDragging(true);
handleMove(e.clientX);
};
useEffect(() => {
const onMouseMove = (e: MouseEvent) => {
if (isDragging) handleMove(e.clientX);
};
const onMouseUp = () => {
setIsDragging(false);
};
if (isDragging) {
window.addEventListener('mousemove', onMouseMove);
window.addEventListener('mouseup', onMouseUp);
}
return () => {
window.removeEventListener('mousemove', onMouseMove);
window.removeEventListener('mouseup', onMouseUp);
};
}, [isDragging]);
useEffect(() => { useEffect(() => {
const audio = audioRef.current; const audio = audioRef.current;
if (!audio) return; if (!audio) return;
@@ -284,6 +318,9 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
return; return;
} }
// 새 곡 생성 시작 — 이전에 저장된 완료 곡 제거
localStorage.removeItem(SONG_GENERATION_KEY);
setStatus('generating_lyric'); setStatus('generating_lyric');
setErrorMessage(null); setErrorMessage(null);
setStatusMessage(t('soundStudio.generatingLyrics')); setStatusMessage(t('soundStudio.generatingLyrics'));
@@ -293,6 +330,10 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
try { try {
const language = LANGUAGE_MAP[selectedLang] || 'Korean'; const language = LANGUAGE_MAP[selectedLang] || 'Korean';
const isInstrumental = selectedType === '배경음악';
// 수동 선택한 장르는 가사 생성 시점부터 넘겨서, 그 장르 템포에 맞는 줄 수로 가사를 쓰게 한다.
// '자동 선택'이면 넘기지 않고, 가사 생성 결과로 받은 recommended genre를 그대로 쓴다.
const manualGenre = selectedGenre === '자동 선택' ? undefined : genreMap[selectedGenre];
// 1. 가사 생성 요청 // 1. 가사 생성 요청
console.log('[SoundStudio] Sending m_id:', mId); console.log('[SoundStudio] Sending m_id:', mId);
@@ -303,53 +344,55 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
m_id: mId, m_id: mId,
region: businessInfo.region, region: businessInfo.region,
task_id: imageTaskId, task_id: imageTaskId,
industry,
orientation, orientation,
...(isInstrumental && { instrumental: true }),
...(manualGenre && { genre: manualGenre }),
}); });
if (!lyricResponse.success || !lyricResponse.task_id) { if (!lyricResponse.success || !lyricResponse.task_id) {
throw new Error(lyricResponse.error_message || t('soundStudio.lyricGenerationFailed')); throw new Error(lyricResponse.error_message || t('soundStudio.lyricGenerationFailed'));
} }
// 2. 가사 생성 상태 폴링 → 완료 시 상세 조회 let songLyrics: string | undefined;
setStatusMessage(t('soundStudio.generatingLyrics')); // BGM 모드는 백엔드가 가사/장르 추천 없이 즉시 completed 처리하므로 GPT 추천 장르가 없다.
const lyricDetailResponse = await waitForLyricComplete( // 이 경우에만 기존 랜덤 선택 로직으로 폴백한다.
lyricResponse.task_id, let effectiveGenre = manualGenre || getEffectiveGenre(selectedGenre);
(status: string) => {
if (status === 'processing') { if (!isInstrumental) {
setStatusMessage(t('soundStudio.generatingLyrics')); // 2. 가사 생성 상태 폴링 → 완료 시 상세 조회
setStatusMessage(t('soundStudio.generatingLyrics'));
const lyricDetailResponse = await waitForLyricComplete(
lyricResponse.task_id,
(status: string) => {
if (status === 'processing') {
setStatusMessage(t('soundStudio.generatingLyrics'));
}
} }
);
if (!lyricDetailResponse.lyric_result) {
throw new Error(t('soundStudio.lyricNotReceived'));
} }
);
if (!lyricDetailResponse.lyric_result) { // "I'm sorry" 체크
throw new Error(t('soundStudio.lyricNotReceived')); if (lyricDetailResponse.lyric_result.includes("I'm sorry")) {
throw new Error(t('soundStudio.lyricGenerationError'));
}
setLyrics(lyricDetailResponse.lyric_result);
songLyrics = lyricDetailResponse.lyric_result;
// 가사와 함께 확정된 장르(수동 선택값 또는 GPT 추천값)를 그대로 음악 생성에 사용
effectiveGenre = lyricDetailResponse.genre || effectiveGenre;
} }
// "I'm sorry" 체크
if (lyricDetailResponse.lyric_result.includes("I'm sorry")) {
throw new Error(t('soundStudio.lyricGenerationError'));
}
setLyrics(lyricDetailResponse.lyric_result);
setStatus('generating_song'); setStatus('generating_song');
setStatusMessage(t('soundStudio.generatingSong')); setStatusMessage(t('soundStudio.generatingSong'));
setUsedGenre(effectiveGenre);
const genreMap: Record<string, string> = {
'자동 선택': 'pop',
'K-POP': 'kpop',
'발라드': 'ballad',
'Hip-Hop': 'hip-hop',
'R&B': 'rnb',
'EDM': 'edm',
'JAZZ': 'jazz',
'ROCK': 'rock',
};
const songResponse = await generateSong(imageTaskId, { const songResponse = await generateSong(imageTaskId, {
genre: genreMap[selectedGenre] || 'pop', genre: effectiveGenre,
language, ...(isInstrumental ? { instrumental: true, lyrics: '' } : { language, lyrics: songLyrics }),
lyrics: lyricDetailResponse.lyric_result,
}); });
if (!songResponse.success) { if (!songResponse.success) {
@@ -368,12 +411,15 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
setStatus('polling'); setStatus('polling');
setStatusMessage(t('soundStudio.generatingSong')); setStatusMessage(t('soundStudio.generatingSong'));
await resumePolling(songResponse.task_id, songResponse.song_id, lyricDetailResponse.lyric_result, 0); await resumePolling(songResponse.task_id, songResponse.song_id, songLyrics ?? '', 0);
} catch (error) { } catch (error) {
console.error('Music generation failed:', error); console.error('Music generation failed:', error);
setStatus('error'); setStatus('error');
setErrorMessage(error instanceof Error ? error.message : t('soundStudio.musicGenerationError')); setErrorMessage(sanitizeError(
error instanceof Error ? error.message : '',
t('soundStudio.musicGenerationError')
));
setRetryCount(0); setRetryCount(0);
} }
}; };
@@ -391,6 +437,24 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
const isGenerating = status === 'generating_lyric' || status === 'generating_song' || status === 'polling'; const isGenerating = status === 'generating_lyric' || status === 'generating_song' || status === 'polling';
// 드래그로 인한 잦은 리렌더에서도 가사 파싱(정규식/배열 처리)이 매번 재실행되지 않도록 메모이제이션
const lyricsSections = useMemo(() => {
if (!lyrics) return [];
const lines = lyrics.split('\n').filter(l => l.trim());
const sections: { tag: string | null; lines: string[] }[] = [];
lines.forEach(line => {
const tagMatch = line.trim().match(/^\[(.+)\]$/);
if (tagMatch) {
sections.push({ tag: `[${tagMatch[1]}]`, lines: [] });
} else if (sections.length === 0) {
sections.push({ tag: null, lines: [line] });
} else {
sections[sections.length - 1].lines.push(line);
}
});
return sections.filter(s => s.lines.length > 0);
}, [lyrics]);
// status 변경 시 부모에 알림 // status 변경 시 부모에 알림
useEffect(() => { useEffect(() => {
onStatusChange?.(status); onStatusChange?.(status);
@@ -400,7 +464,14 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
<> <>
<main className="sound-studio-page"> <main className="sound-studio-page">
{audioUrl && ( {audioUrl && (
<audio ref={audioRef} src={audioUrl} preload="metadata" /> <audio
ref={audioRef}
src={audioUrl}
preload="metadata"
onLoadedMetadata={() => {
if (audioRef.current) setDuration(audioRef.current.duration);
}}
/>
)} )}
{/* Header */} {/* Header */}
@@ -428,14 +499,15 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
<label className="input-label">{t('soundStudio.soundTypeLabel')}</label> <label className="input-label">{t('soundStudio.soundTypeLabel')}</label>
<div className="sound-type-grid"> <div className="sound-type-grid">
{[ {[
{ key: '보컬', label: t('soundStudio.soundTypeVocal') }, { key: '보컬', label: t('soundStudio.soundTypeVocal'), disabled: false },
{ key: '배경음악', label: t('soundStudio.soundTypeBGM') }, { key: '배경음악', label: t('soundStudio.soundTypeBGM'), disabled: false },
].map(({ key, label }) => ( ].map(({ key, label, disabled }) => (
<button <button
key={key} key={key}
onClick={() => !isGenerating && setSelectedType(key)} onClick={() => !isGenerating && !disabled && setSelectedType(key)}
disabled={isGenerating} disabled={isGenerating || disabled}
className={`sound-type-btn ${selectedType === key ? 'active' : ''}`} className={`sound-type-btn ${selectedType === key ? 'active' : ''}`}
title={disabled ? t('soundStudio.comingSoon', { defaultValue: '이후 오픈 예정입니다' }) : undefined}
> >
{label} {label}
</button> </button>
@@ -476,7 +548,7 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
))} ))}
</div> </div>
<div className="genre-row"> <div className="genre-row">
{['JAZZ', 'ROCK'].map(genre => ( {['JAZZ', 'ROCK', 'POP'].map(genre => (
<button <button
key={genre} key={genre}
onClick={() => setSelectedGenre(genre)} onClick={() => setSelectedGenre(genre)}
@@ -486,7 +558,6 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
{genre} {genre}
</button> </button>
))} ))}
<div className="genre-btn-placeholder"></div>
</div> </div>
</div> </div>
</div> </div>
@@ -494,39 +565,31 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
{/* Language Selection */} {/* Language Selection */}
<div className="sound-studio-section"> <div className="sound-studio-section">
<label className="input-label">{t('soundStudio.languageLabel')}</label> <label className="input-label">{t('soundStudio.languageLabel')}</label>
<div className="language-selector-wrapper" ref={languageDropdownRef}> <div className="genre-grid language-grid">
<button <div className="genre-row">
onClick={() => setIsLanguageDropdownOpen(!isLanguageDropdownOpen)} {['한국어', 'English', '中文'].map((lang) => (
disabled={isGenerating} <button
className="language-selector" key={lang}
> onClick={() => !isGenerating && setSelectedLang(lang)}
<div className="language-display"> disabled={isGenerating}
<span className="language-flag">{LANGUAGE_FLAGS[selectedLang]}</span> className={`genre-btn ${selectedLang === lang ? 'active' : ''}`}
<span className="language-name">{selectedLang}</span> >
</div> <span>{LANGUAGE_FLAGS[lang]}</span> {lang}
<img </button>
src="/assets/images/icon-dropdown.svg" ))}
alt="" </div>
className={`language-dropdown-icon ${isLanguageDropdownOpen ? 'open' : ''}`} <div className="genre-row">
/> {['日本語', 'ไทย', 'Tiếng Việt'].map((lang) => (
</button> <button
{isLanguageDropdownOpen && ( key={lang}
<div className="language-dropdown-menu"> onClick={() => !isGenerating && setSelectedLang(lang)}
{Object.keys(LANGUAGE_MAP).map((lang) => ( disabled={isGenerating}
<button className={`genre-btn ${selectedLang === lang ? 'active' : ''}`}
key={lang} >
onClick={() => { <span>{LANGUAGE_FLAGS[lang]}</span> {lang}
setSelectedLang(lang); </button>
setIsLanguageDropdownOpen(false); ))}
}} </div>
className={`language-dropdown-item ${selectedLang === lang ? 'active' : ''}`}
>
<span className="language-flag">{LANGUAGE_FLAGS[lang]}</span>
<span className="language-name">{lang}</span>
</button>
))}
</div>
)}
</div> </div>
</div> </div>
@@ -539,6 +602,16 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
</svg> </svg>
{statusMessage} {statusMessage}
</div> </div>
) : status === 'complete' ? (
<>
<button
onClick={handleRegenerate}
className="btn-generate-sound"
>
{t('soundStudio.regenerateButton')}
</button>
<p className="regenerate-hint">{t('soundStudio.regenerateHint')}</p>
</>
) : ( ) : (
<button <button
onClick={handleGenerateMusic} onClick={handleGenerateMusic}
@@ -549,18 +622,30 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
</button> </button>
)} )}
{errorMessage && ( {errorMessage && (() => {
<div className="error-message-new"> const isCreditsError = errorMessage.includes('credit');
{errorMessage} return (
</div> <div className="error-message-new">
)} {isCreditsError ? t('soundStudio.creditsExhausted') : errorMessage}
{isCreditsError && (
<a
href=""
className="charge-credits-link"
onClick={e => { e.preventDefault(); onGoToPayment?.(); }}
>
{t('soundStudio.chargeCredits')}
</a>
)}
</div>
);
})()}
</div> </div>
{/* Right Column - Lyrics */} {/* Right Column - Lyrics */}
<div className="lyrics-column"> <div className="lyrics-column">
<div className="lyrics-header"> <div className="lyrics-header">
<h3 className="column-title">{t('soundStudio.lyricsColumn')}</h3> <h3 className="column-title">{t('soundStudio.lyricsColumn')}</h3>
<p className="lyrics-subtitle">{t('soundStudio.lyricsHint')}</p> {/* <p className="lyrics-subtitle">{t('soundStudio.lyricsHint')}</p> */}
</div> </div>
{/* Audio Player */} {/* Audio Player */}
@@ -582,9 +667,8 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
)} )}
</button> </button>
{/* 진행 표시 전용 — Azure Blob 익명 응답에 Accept-Ranges가 없어 seek가 불안정하므로 드래그 미지원 */}
<div <div
ref={progressBarRef}
onMouseDown={onMouseDown}
className={`audio-progress-container ${!audioUrl ? 'disabled' : ''}`} className={`audio-progress-container ${!audioUrl ? 'disabled' : ''}`}
> >
<div <div
@@ -601,15 +685,17 @@ const SoundStudioContent: React.FC<SoundStudioContentProps> = ({
{/* Lyrics Display */} {/* Lyrics Display */}
<div className="lyrics-display"> <div className="lyrics-display">
{lyrics ? ( {lyrics ? (
<textarea <div className="lyrics-paragraphs">
value={lyrics} {lyricsSections.map((section, i) => (
onChange={(e) => setLyrics(e.target.value)} <div key={i} className="lyrics-section">
className="lyrics-textarea" {section.tag && <span className="lyrics-tag">{section.tag}</span>}
placeholder={t('soundStudio.lyricsPlaceholder')} <p className="lyrics-paragraph">{section.lines.join('\n')}</p>
/> </div>
))}
</div>
) : ( ) : (
<div className="lyrics-placeholder"> <div className="lyrics-placeholder">
{t('soundStudio.lyricsPlaceholder')} {selectedType === '배경음악' ? t('soundStudio.lyricsPlaceholderBGM') : t('soundStudio.lyricsPlaceholder')}
</div> </div>
)} )}
</div> </div>
+41 -282
View File
@@ -1,300 +1,59 @@
import React from 'react';
import React, { useState, useRef, useCallback } from 'react'; import { AutocompleteRequest } from '../../utils/api';
import { useTranslation } from 'react-i18next'; import SearchInputForm, { SearchType } from '../../components/SearchInputForm';
import { searchAccommodation, AccommodationSearchItem, AutocompleteRequest } from '../../utils/api'; import PipelineTabs, { Pipeline } from '../../components/PipelineTabs';
import { CrawlingResponse } from '../../types/api'; import SsulCreateForm from '../Ssulbox/SsulCreateForm';
import { Scen } from '../Ssulbox/ssulData';
type SearchType = 'url' | 'name';
// 환경변수에서 테스트 모드 확인
const isTestPage = import.meta.env.VITE_IS_TESTPAGE === 'true';
interface UrlInputContentProps { interface UrlInputContentProps {
/** 현재 선택된 파이프라인. 소유자는 GenerationFlow (분기·리셋 때문) */
pipeline: Pipeline;
onPipelineChange: (pipeline: Pipeline) => void;
onAnalyze: (value: string, type?: SearchType) => void; onAnalyze: (value: string, type?: SearchType) => void;
onAutocomplete?: (data: AutocompleteRequest) => void; onAutocomplete?: (data: AutocompleteRequest) => void;
onTestData?: (data: CrawlingResponse) => void; onManualInput?: (businessName: string, address: string, category: string, officialSiteUrl?: string) => void;
error: string | null; error: string | null;
/** 썰박스 생성 요청 접수 시. 폴링 소유는 GenerationFlow */
onSsulJobStarted: (taskId: number, scenario: Scen) => void;
/** 크레딧 부족 시 충전 화면으로 */
onGoToPayment: () => void;
} }
const UrlInputContent: React.FC<UrlInputContentProps> = ({ onAnalyze, onAutocomplete, onTestData, error }) => { /**
const { t, i18n } = useTranslation(); * 대시보드 진입 화면.
const [inputValue, setInputValue] = useState(''); *
const [searchType, setSearchType] = useState<SearchType>('name'); * 탭바는 로고와 하위 폼 **사이에 형제로** 얹고 하위 폼만 교체한다.
const [isDropdownOpen, setIsDropdownOpen] = useState(false); */
const [autocompleteResults, setAutocompleteResults] = useState<AccommodationSearchItem[]>([]); const UrlInputContent: React.FC<UrlInputContentProps> = ({
const [isAutocompleteLoading, setIsAutocompleteLoading] = useState(false); pipeline,
const [showAutocomplete, setShowAutocomplete] = useState(false); onPipelineChange,
const [selectedItem, setSelectedItem] = useState<AccommodationSearchItem | null>(null); onAnalyze,
const [isLoadingTest, setIsLoadingTest] = useState(false); onAutocomplete,
onManualInput,
// 테스트 데이터 로드 핸들러 error,
const handleTestData = async () => { onSsulJobStarted,
if (!onTestData) return; onGoToPayment,
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 [highlightedIndex, setHighlightedIndex] = useState<number>(-1);
const debounceRef = useRef<NodeJS.Timeout | null>(null);
const autocompleteRef = useRef<HTMLDivElement>(null);
const searchTypeOptions = [
{ value: 'url' as SearchType, label: 'URL' },
{ value: 'name' as SearchType, label: t('urlInput.searchTypeBusinessName') },
];
const getPlaceholder = () => {
return searchType === 'url'
? 'https://naver.me/abcdef'
: t('urlInput.placeholderBusinessName');
};
const getGuideText = () => {
return searchType === 'url'
? t('urlInput.guideUrl')
: t('urlInput.guideBusinessName');
};
// 업체명 검색 시 자동완성 (디바운스 적용)
const handleAutocompleteSearch = useCallback(async (query: string) => {
if (!query.trim() || searchType !== 'name') {
setAutocompleteResults([]);
setShowAutocomplete(false);
return;
}
setIsAutocompleteLoading(true);
try {
const response = await searchAccommodation(query);
setAutocompleteResults(response.items || []);
setShowAutocomplete(response.items && response.items.length > 0);
} catch (error) {
console.error('자동완성 검색 오류:', error);
setAutocompleteResults([]);
setShowAutocomplete(false);
} finally {
setIsAutocompleteLoading(false);
}
}, [searchType]);
// 자동완성 항목 선택 - 업체 정보 저장
const handleSelectAutocomplete = (item: AccommodationSearchItem) => {
setInputValue(item.title.replace(/<[^>]*>/g, '')); // HTML 태그 제거
setSelectedItem(item); // 선택된 업체 정보 저장
setShowAutocomplete(false);
setAutocompleteResults([]);
setHighlightedIndex(-1);
};
// 키보드 네비게이션 핸들러
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (!showAutocomplete || autocompleteResults.length === 0) return;
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setHighlightedIndex(prev =>
prev < autocompleteResults.length - 1 ? prev + 1 : 0
);
break;
case 'ArrowUp':
e.preventDefault();
setHighlightedIndex(prev =>
prev > 0 ? prev - 1 : autocompleteResults.length - 1
);
break;
case 'Enter':
if (highlightedIndex >= 0 && highlightedIndex < autocompleteResults.length) {
e.preventDefault();
handleSelectAutocomplete(autocompleteResults[highlightedIndex]);
}
break;
case 'Escape':
setShowAutocomplete(false);
setHighlightedIndex(-1);
break;
}
};
// 붙여넣기 시 URL만 추출
const handlePaste = (e: React.ClipboardEvent<HTMLInputElement>) => {
if (searchType !== 'url') return;
const pasted = e.clipboardData.getData('text');
const urlMatch = pasted.match(/https?:\/\/[^\s]+/);
if (urlMatch) {
e.preventDefault();
setInputValue(urlMatch[0]);
}
};
// 폼 제출 처리
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!inputValue.trim()) return;
if (searchType === 'name' && selectedItem && onAutocomplete) {
// 업체명 검색인 경우 autocomplete API 호출
const request: AutocompleteRequest = {
address: selectedItem.address,
roadAddress: selectedItem.roadAddress,
title: selectedItem.title,
};
onAutocomplete(request);
} else {
// URL 검색인 경우 기존 로직
onAnalyze(inputValue.trim(), searchType);
}
};
return ( return (
<div className="url-input-container"> <div className="url-input-container">
<div className="url-input-content"> <div className="url-input-content">
{/* 로고 */}
<div className="url-input-logo"> <div className="url-input-logo">
<img src="/assets/images/ado2-logo.svg" alt="ADO2" /> <img src="/assets/images/ADO2_with Slogan_white.svg" alt="ADO2" />
</div> </div>
{/* URL 입력 폼 */} <PipelineTabs value={pipeline} onChange={onPipelineChange} />
<form onSubmit={handleSubmit} className="url-input-form">
<div className="url-input-wrapper">
{/* 드롭다운 */}
<div className="url-input-dropdown-container">
<button
type="button"
className="url-input-dropdown-trigger"
onClick={() => setIsDropdownOpen(!isDropdownOpen)}
>
<span>{searchTypeOptions.find(opt => opt.value === searchType)?.label}</span>
<svg
width="12"
height="12"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
className={`url-input-dropdown-arrow ${isDropdownOpen ? 'open' : ''}`}
>
<path d="M6 9l6 6 6-6" />
</svg>
</button>
{isDropdownOpen && (
<div className="url-input-dropdown-menu">
{searchTypeOptions.map((option) => (
<button
key={option.value}
type="button"
className={`url-input-dropdown-item ${searchType === option.value ? 'active' : ''}`}
onClick={() => {
setSearchType(option.value);
setIsDropdownOpen(false);
}}
>
{option.label}
</button>
))}
</div>
)}
</div>
{/* 입력 필드 */} {pipeline === 'ado2' ? (
<div className="url-input-field-container" ref={autocompleteRef}> <SearchInputForm
<input onAnalyze={onAnalyze}
type="text" onAutocomplete={onAutocomplete}
value={inputValue} onManualInput={onManualInput}
onChange={(e) => { error={error}
let value = e.target.value; />
) : (
// URL 모드일 때 URL만 추출 (예: "[네이버 지도] https://...") <SsulCreateForm onSubmitted={onSsulJobStarted} onNeedCredit={onGoToPayment} />
if (searchType === 'url') { )}
const urlMatch = value.match(/https?:\/\/\S+/);
if (urlMatch && urlMatch[0] !== value) {
value = urlMatch[0];
}
}
setInputValue(value);
// 업체명 검색일 때 자동완성 검색 (디바운스)
if (searchType === 'name') {
if (debounceRef.current) {
clearTimeout(debounceRef.current);
}
debounceRef.current = setTimeout(() => {
handleAutocompleteSearch(value);
}, 300);
}
}}
onPaste={handlePaste}
onFocus={() => {
if (searchType === 'name' && autocompleteResults.length > 0) {
setShowAutocomplete(true);
}
}}
placeholder={getPlaceholder()}
className="url-input-field"
/>
{/* 자동완성 결과 */}
{showAutocomplete && searchType === 'name' && (
<div className="url-input-autocomplete-dropdown">
{isAutocompleteLoading ? (
<div className="url-input-autocomplete-loading">{t('urlInput.searching')}</div>
) : (
autocompleteResults.map((item, index) => (
<button
key={index}
type="button"
className="url-input-autocomplete-item"
onMouseDown={(e) => {
e.preventDefault();
handleSelectAutocomplete(item);
}}
>
<div className="url-input-autocomplete-title" dangerouslySetInnerHTML={{ __html: item.title }} />
<div className="url-input-autocomplete-address">{item.roadAddress || item.address}</div>
</button>
))
)}
</div>
)}
</div>
</div>
{/* 안내 텍스트 */}
<p className="url-input-guide">
{getGuideText()}
</p>
{/* 에러 메시지 */}
{error && (
<p className="url-input-error">{error}</p>
)}
{/* 검색 버튼 */}
<button type="submit" className="url-input-button">
{t('landing.hero.analyzeButton')}
</button>
</form>
</div> </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> </div>
); );
}; };
-51
View File
@@ -1,51 +0,0 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import Footer from '../../components/Footer';
interface DisplaySectionProps {
onStartClick?: () => void;
}
const DisplaySection: React.FC<DisplaySectionProps> = ({ onStartClick }) => {
const { t } = useTranslation();
// YouTube Shorts 영상 ID들
const videos = [
{ id: 1, videoId: 'OZJ8X4P82OA' },
{ id: 2, videoId: 'hNzMO21O40c' },
{ id: 3, videoId: 'dM8_d6Aud68' },
];
return (
<div className="display-section">
<div className="content-safe-area">
{/* Main visual frames container */}
<div className="display-frames">
{videos.map((video, index) => (
<div
key={video.id}
className={`display-frame ${index === 2 ? 'display-frame-hidden-mobile' : ''}`}
>
<iframe
src={`https://www.youtube.com/embed/${video.videoId}?autoplay=1&mute=1&loop=1&playlist=${video.videoId}&controls=0&showinfo=0&rel=0&modestbranding=1&playsinline=1`}
title={`YouTube Shorts ${video.id}`}
frameBorder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
className="display-video"
/>
</div>
))}
</div>
{/* Action Button */}
<button onClick={onStartClick} className="display-button">
{t('landing.display.startButton')}
</button>
</div>
<Footer />
</div>
);
};
export default DisplaySection;
-538
View File
@@ -1,538 +0,0 @@
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { searchAccommodation, AccommodationSearchItem, AutocompleteRequest } 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';
type SearchType = 'url' | 'name';
// 환경변수에서 테스트 모드 확인
const isTestPage = import.meta.env.VITE_IS_TESTPAGE === 'true';
interface HeroSectionProps {
onAnalyze?: (value: string, type?: SearchType) => void;
onAutocomplete?: (data: AutocompleteRequest) => void;
onTestData?: (data: CrawlingResponse) => void;
onNext?: () => void;
error?: string | null;
scrollProgress?: number; // 0 ~ 1 (스크롤 진행률)
}
const isValidUrl = (string: string): boolean => {
try {
const url = new URL(string);
return url.protocol === 'http:' || url.protocol === 'https:';
} catch {
return false;
}
};
// Orb configuration with movement zones to prevent overlap
interface OrbConfig {
id: string;
size: number;
initialX: number;
initialY: number;
color: string;
// Movement bounds for each orb
minX: number;
maxX: number;
minY: number;
maxY: number;
}
// 6 orbs distributed in a 3x2 grid pattern with overlapping zones for smooth movement
const orbConfigs: OrbConfig[] = [
// Top-left zone
{ id: 'orb-1', size: 500, initialX: -10, initialY: -10, color: 'radial-gradient(circle, #C490FF 20%, #AE72F9 50%, rgba(94, 235, 195, 0.4) 100%)', minX: -30, maxX: 35, minY: -30, maxY: 40 },
// Top-right zone
{ id: 'orb-2', size: 480, initialX: 70, initialY: -5, color: 'radial-gradient(circle, #5EEBC3 25%, rgba(174, 114, 249, 0.6) 70%, rgba(139, 92, 246, 0.3) 100%)', minX: 50, maxX: 110, minY: -30, maxY: 40 },
// Middle-left zone
{ id: 'orb-3', size: 420, initialX: 5, initialY: 35, color: 'radial-gradient(circle, rgba(148, 251, 224, 0.8) 15%, #AE72F9 55%, rgba(94, 235, 195, 0.3) 100%)', minX: -20, maxX: 45, minY: 20, maxY: 65 },
// Middle-right zone
{ id: 'orb-4', size: 400, initialX: 60, initialY: 40, color: 'radial-gradient(circle, rgba(220, 200, 255, 0.95) 10%, rgba(148, 251, 224, 0.85) 45%, rgba(174, 114, 249, 0.5) 100%)', minX: 40, maxX: 100, minY: 25, maxY: 70 },
// Bottom-left zone
{ id: 'orb-5', size: 520, initialX: -8, initialY: 65, color: 'radial-gradient(circle, #B794F6 30%, rgba(148, 251, 224, 0.6) 65%, rgba(174, 114, 249, 0.3) 100%)', minX: -30, maxX: 40, minY: 50, maxY: 110 },
// Bottom-right zone
{ id: 'orb-6', size: 450, initialX: 65, initialY: 70, color: 'radial-gradient(circle, rgba(180, 255, 235, 0.95) 15%, rgba(200, 160, 255, 0.8) 50%, rgba(94, 235, 195, 0.45) 100%)', minX: 45, maxX: 110, minY: 55, maxY: 110 },
];
const HeroSection: React.FC<HeroSectionProps> = ({ onAnalyze, onAutocomplete, onTestData, onNext, error: externalError, scrollProgress = 0 }) => {
const { t, i18n } = useTranslation();
const [inputValue, setInputValue] = useState('');
const [searchType, setSearchType] = useState<SearchType>('name');
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const [localError, setLocalError] = useState('');
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 (error) {
console.error('테스트 데이터 로드 실패:', error);
setLocalError(t('landing.hero.testDataLoadFailed'));
} finally {
setIsLoadingTest(false);
}
};
const [isFocused, setIsFocused] = useState(false);
const [autocompleteResults, setAutocompleteResults] = useState<AccommodationSearchItem[]>([]);
const [isAutocompleteLoading, setIsAutocompleteLoading] = useState(false);
const [showAutocomplete, setShowAutocomplete] = useState(false);
const [selectedItem, setSelectedItem] = useState<AccommodationSearchItem | null>(null);
const [highlightedIndex, setHighlightedIndex] = useState<number>(-1);
const orbRefs = useRef<(HTMLDivElement | null)[]>([]);
const animationRefs = useRef<number[]>([]);
const dropdownRef = useRef<HTMLDivElement>(null);
const autocompleteRef = useRef<HTMLDivElement>(null);
const debounceRef = useRef<NodeJS.Timeout | null>(null);
const tutorial = useTutorial();
// 첫 방문 시 랜딩 튜토리얼 시작
useEffect(() => {
if (!tutorial.hasSeen(TUTORIAL_KEYS.LANDING)) {
const timer = setTimeout(() => {
tutorial.startTutorial(TUTORIAL_KEYS.LANDING);
}, 800);
return () => clearTimeout(timer);
}
}, []);
const searchTypeOptions = [
{ value: 'url' as SearchType, label: 'URL' },
{ value: 'name' as SearchType, label: t('landing.hero.searchTypeBusinessName') },
];
// 드롭다운 외부 클릭 감지
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
setIsDropdownOpen(false);
}
if (autocompleteRef.current && !autocompleteRef.current.contains(event.target as Node)) {
setShowAutocomplete(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
// 업체명 검색 시 자동완성 (디바운스 적용)
const handleAutocompleteSearch = useCallback(async (query: string) => {
if (!query.trim() || searchType !== 'name') {
setAutocompleteResults([]);
setShowAutocomplete(false);
return;
}
setIsAutocompleteLoading(true);
try {
const response = await searchAccommodation(query);
setAutocompleteResults(response.items || []);
setShowAutocomplete(response.items && response.items.length > 0);
} catch (error) {
console.error('자동완성 검색 오류:', error);
setAutocompleteResults([]);
setShowAutocomplete(false);
} finally {
setIsAutocompleteLoading(false);
}
}, [searchType]);
// 자동완성 항목 선택 - 업체 정보 저장
const handleSelectAutocomplete = (item: AccommodationSearchItem) => {
setInputValue(item.title.replace(/<[^>]*>/g, '')); // HTML 태그 제거
setSelectedItem(item); // 선택된 업체 정보 저장
setShowAutocomplete(false);
setAutocompleteResults([]);
setHighlightedIndex(-1);
// LANDING_NAME 튜토리얼 진행 중이면 다음 힌트로 이동
if (tutorial.isActive && tutorial.tutorialKey === TUTORIAL_KEYS.LANDING_NAME) {
tutorial.nextHint();
}
};
// 키보드 네비게이션 핸들러
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
// 자동완성이 표시될 때만 키보드 네비게이션 활성화
if (showAutocomplete && autocompleteResults.length > 0) {
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
setHighlightedIndex(prev =>
prev < autocompleteResults.length - 1 ? prev + 1 : 0
);
return;
case 'ArrowUp':
e.preventDefault();
setHighlightedIndex(prev =>
prev > 0 ? prev - 1 : autocompleteResults.length - 1
);
return;
case 'Enter':
e.preventDefault(); // 항상 Enter 기본 동작 방지
if (highlightedIndex >= 0 && highlightedIndex < autocompleteResults.length) {
handleSelectAutocomplete(autocompleteResults[highlightedIndex]);
}
return;
case 'Escape':
e.preventDefault();
setShowAutocomplete(false);
setHighlightedIndex(-1);
return;
}
}
// 업체명 검색 모드에서 Enter 키 입력 시 기본 동작 방지 (폼 제출 방지)
if (e.key === 'Enter' && searchType === 'name') {
e.preventDefault();
}
};
// Random movement for orbs
useEffect(() => {
const moveOrb = (orb: HTMLDivElement, index: number) => {
const config = orbConfigs[index];
let currentX = config.initialX;
let currentY = config.initialY;
// 초기 타겟은 현재 위치와 동일하게 설정 (순간이동 방지)
let targetX = currentX;
let targetY = currentY;
let scale = 1;
let targetScale = 1;
let isFirstMove = true;
const generateNewTarget = () => {
// Move within the orb's designated zone
const rangeX = config.maxX - config.minX;
const rangeY = config.maxY - config.minY;
if (isFirstMove) {
// 첫 이동은 현재 위치에서 가까운 곳으로 (자연스러운 시작)
const smallRangeX = rangeX * 0.3;
const smallRangeY = rangeY * 0.3;
targetX = currentX + (Math.random() - 0.5) * smallRangeX;
targetY = currentY + (Math.random() - 0.5) * smallRangeY;
// 범위 내로 클램핑
targetX = Math.max(config.minX, Math.min(config.maxX, targetX));
targetY = Math.max(config.minY, Math.min(config.maxY, targetY));
isFirstMove = false;
} else {
targetX = config.minX + Math.random() * rangeX;
targetY = config.minY + Math.random() * rangeY;
}
targetScale = 0.9 + Math.random() * 0.2; // 0.9 to 1.1 (더 작은 범위)
};
const animate = () => {
// Slow speed - 일정한 속도로 부드럽게
const speed = 0.003;
currentX += (targetX - currentX) * speed;
currentY += (targetY - currentY) * speed;
scale += (targetScale - scale) * speed;
// Apply transform
orb.style.left = `${currentX}%`;
orb.style.top = `${currentY}%`;
orb.style.transform = `scale(${scale})`;
// Generate new target when close enough
const distance = Math.sqrt(
Math.pow(targetX - currentX, 2) + Math.pow(targetY - currentY, 2)
);
if (distance < 1) {
generateNewTarget();
}
animationRefs.current[index] = requestAnimationFrame(animate);
};
// 첫 타겟 생성 후 애니메이션 시작
generateNewTarget();
animate();
};
// 모든 공이 동시에 자연스럽게 시작 (딜레이 없이)
orbRefs.current.forEach((orb, index) => {
if (orb) {
moveOrb(orb, index);
}
});
// Cleanup
return () => {
animationRefs.current.forEach(id => cancelAnimationFrame(id));
};
}, []);
const error = externalError || localError;
const getPlaceholder = () => {
return searchType === 'url'
? 'https://naver.me/abcdef'
: t('landing.hero.placeholderBusinessName');
};
const getGuideText = () => {
return searchType === 'url'
? t('landing.hero.guideUrl')
: t('landing.hero.guideBusinessName');
};
const handleStart = () => {
if (!inputValue.trim()) {
setLocalError(searchType === 'url' ? t('landing.hero.errorUrlRequired') : t('landing.hero.errorNameRequired'));
return;
}
if (searchType === 'url' && !isValidUrl(inputValue.trim())) {
setLocalError(t('landing.hero.errorInvalidUrl'));
return;
}
setLocalError('');
if (searchType === 'name' && selectedItem && onAutocomplete) {
// 업체명 검색인 경우 autocomplete API 호출
const request: AutocompleteRequest = {
address: selectedItem.address,
roadAddress: selectedItem.roadAddress,
title: selectedItem.title,
};
onAutocomplete(request);
} else if (onAnalyze) {
// URL 검색인 경우 기존 로직
onAnalyze(inputValue, searchType);
}
};
return (
<div className="hero-section">
{/* Animated background orbs - 스크롤에 따라 빠르게 사라짐 */}
<div
className="hero-bg-orbs"
style={{ opacity: Math.max(0, 1 - scrollProgress * 3) }}
>
{orbConfigs.map((config, index) => (
<div
key={config.id}
ref={el => { orbRefs.current[index] = el; }}
className="hero-orb-random"
style={{
width: `${config.size}px`,
height: `${config.size}px`,
background: config.color,
left: `${config.initialX}%`,
top: `${config.initialY}%`,
}}
/>
))}
</div>
<div className="hero-content">
{/* Logo Image */}
<img
src="/assets/images/ado2-logo.svg"
alt="ADO2"
className="hero-logo"
/>
{/* Input Form */}
<div className="hero-form">
<div className={`hero-input-wrapper ${isFocused ? 'focused' : ''} ${error ? 'error' : ''} ${inputValue && !isFocused ? 'filled' : ''}`}>
{/* 드롭다운 */}
<div className="hero-dropdown-container" ref={dropdownRef}>
<button
type="button"
className="hero-dropdown-trigger"
onClick={() => setIsDropdownOpen(!isDropdownOpen)}
>
<span>{searchTypeOptions.find(opt => opt.value === searchType)?.label}</span>
<svg
width="12"
height="12"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
className={`hero-dropdown-arrow ${isDropdownOpen ? 'open' : ''}`}
>
<path d="M6 9l6 6 6-6" />
</svg>
</button>
{isDropdownOpen && (
<div className="hero-dropdown-menu">
{searchTypeOptions.map((option) => (
<button
key={option.value}
type="button"
className={`hero-dropdown-item ${searchType === option.value ? 'active' : ''}`}
onClick={() => {
setSearchType(option.value);
setIsDropdownOpen(false);
}}
>
{option.label}
</button>
))}
</div>
)}
</div>
<div className="hero-input-container" ref={autocompleteRef}>
<input
type="text"
value={inputValue}
onChange={(e) => {
let value = e.target.value;
// URL 모드일 때 URL만 추출 (예: "[네이버 지도] https://...")
if (searchType === 'url') {
const urlMatch = value.match(/https?:\/\/\S+/);
if (urlMatch && urlMatch[0] !== value) {
value = urlMatch[0];
}
}
setInputValue(value);
setHighlightedIndex(-1); // 입력 시 하이라이트 초기화
if (localError) setLocalError('');
// 업체명 검색일 때 자동완성 검색 (디바운스)
if (searchType === 'name') {
if (debounceRef.current) {
clearTimeout(debounceRef.current);
}
debounceRef.current = setTimeout(() => {
handleAutocompleteSearch(value);
}, 300);
}
}}
onPaste={(e: React.ClipboardEvent<HTMLInputElement>) => {
if (searchType !== 'url') return;
const pasted = e.clipboardData.getData('text');
const urlMatch = pasted.match(/https?:\/\/[^\s]+/);
if (urlMatch) {
e.preventDefault();
setInputValue(urlMatch[0]);
if (localError) setLocalError('');
}
}}
onFocus={() => {
setIsFocused(true);
if (searchType === 'name' && autocompleteResults.length > 0) {
setShowAutocomplete(true);
}
}}
onBlur={() => setIsFocused(false)}
onKeyDown={handleKeyDown}
placeholder={getPlaceholder()}
className={`hero-input ${inputValue ? 'has-value' : ''}`}
/>
{/* 자동완성 결과 */}
{showAutocomplete && searchType === 'name' && (
<div className="hero-autocomplete-dropdown">
{isAutocompleteLoading ? (
<div className="hero-autocomplete-loading">{t('landing.hero.searching')}</div>
) : (
autocompleteResults.map((item, index) => (
<button
key={index}
type="button"
className={`hero-autocomplete-item ${highlightedIndex === index ? 'highlighted' : ''}`}
onMouseDown={(e) => {
e.preventDefault();
handleSelectAutocomplete(item);
}}
onMouseEnter={() => setHighlightedIndex(index)}
>
<div className="hero-autocomplete-title" dangerouslySetInnerHTML={{ __html: item.title }} />
<div className="hero-autocomplete-address">{item.roadAddress || item.address}</div>
</button>
))
)}
</div>
)}
</div>
{inputValue && (
<button
type="button"
className="hero-input-clear"
onClick={() => {
setInputValue('');
setLocalError('');
setAutocompleteResults([]);
setShowAutocomplete(false);
}}
>
<img src="/assets/images/input-clear-icon.svg" alt="Clear" />
</button>
)}
</div>
<span className="hero-input-hint">{getGuideText()}</span>
{error && (
<p className="hero-error">{error}</p>
)}
<button onClick={handleStart} className="hero-button">
{t('landing.hero.analyzeButton')}
</button>
</div>
</div>
{/* Footer Indicator */}
<button onClick={onNext} className="scroll-indicator">
<span className="scroll-indicator-text">{t('landing.hero.scrollMore')}</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>
{/* 테스트 버튼 (VITE_IS_TESTPAGE=true일 때만 표시) */}
{isTestPage && onTestData && (
<button
onClick={handleTestData}
disabled={isLoadingTest}
className="test-data-button"
>
{isLoadingTest ? t('landing.hero.testDataLoading') : t('landing.hero.testData')}
</button>
)}
{tutorial.isActive && (
<TutorialOverlay
hints={tutorial.hints}
currentIndex={tutorial.currentHintIndex}
onNext={tutorial.nextHint}
onPrev={tutorial.prevHint}
onSkip={tutorial.skipTutorial}
groupProgress={tutorial.groupProgress}
/>
)}
</div>
);
};
export default HeroSection;
-70
View File
@@ -1,70 +0,0 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
interface WelcomeSectionProps {
onStartClick?: () => void;
onNext?: () => void;
}
const WelcomeSection: React.FC<WelcomeSectionProps> = () => {
const { t } = useTranslation();
const features = [
{
id: 1,
title: t('landing.welcome.feature1Title'),
description: t('landing.welcome.feature1Desc'),
iconBg: '#9BCACC',
icon: '/assets/images/icon-analysis.svg'
},
{
id: 2,
title: t('landing.welcome.feature2Title'),
description: t('landing.welcome.feature2Desc'),
iconBg: '#DFC7FD',
icon: '/assets/images/icon-content.svg'
},
{
id: 3,
title: t('landing.welcome.feature3Title'),
description: t('landing.welcome.feature3Desc'),
iconBg: '#D4FDF3',
icon: '/assets/images/icon-deploy.svg'
},
];
return (
<div className="welcome-section">
<div className="welcome-content">
{/* Star Icon - Top Center */}
<div className="welcome-star">
<img src="/assets/images/star-icon.svg" alt="star" />
</div>
{/* Header */}
<div className="welcome-header">
<h2 className="welcome-title">{t('landing.welcome.title')}</h2>
<p className="welcome-subtitle">{t('landing.welcome.subtitle')}</p>
</div>
{/* Feature Cards */}
<div className="feature-grid">
{features.map((feature) => (
<div key={feature.id} className="feature-card">
<div className="feature-number-badge">
<span>{feature.id}</span>
</div>
<h3 className="feature-card-title">{feature.title}</h3>
<div className="feature-icon-box" style={{ backgroundColor: feature.iconBg }}>
<img src={feature.icon} alt={feature.title} className="feature-icon-img" />
</div>
<p className="feature-card-description">{feature.description}</p>
</div>
))}
</div>
</div>
</div>
);
};
export default WelcomeSection;
-103
View File
@@ -1,103 +0,0 @@
import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { getKakaoLoginUrl, kakaoCallback } from '../../utils/api';
interface LoginSectionProps {
onBack: () => void;
onLogin: () => void;
}
const LoginSection: React.FC<LoginSectionProps> = ({ onBack, onLogin }) => {
const { t } = useTranslation();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// 카카오 콜백 처리 (URL에서 code 파라미터 확인)
useEffect(() => {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get('code');
if (code) {
handleKakaoCallback(code);
}
}, []);
const handleKakaoCallback = async (code: string) => {
setIsLoading(true);
setError(null);
try {
await kakaoCallback(code);
// URL에서 code 파라미터 제거
const url = new URL(window.location.href);
url.searchParams.delete('code');
window.history.replaceState({}, document.title, url.pathname);
// 로그인 성공
onLogin();
} catch (err) {
console.error('Kakao callback failed:', err);
setError(t('login.kakaoLoginFailed'));
// URL에서 code 파라미터 제거
const url = new URL(window.location.href);
url.searchParams.delete('code');
window.history.replaceState({}, document.title, url.pathname);
} finally {
setIsLoading(false);
}
};
const handleKakaoLogin = async () => {
setIsLoading(true);
setError(null);
try {
const response = await getKakaoLoginUrl();
// 카카오 로그인 페이지로 리다이렉트
window.location.href = response.auth_url;
} catch (err) {
console.error('Failed to get Kakao login URL:', err);
setError(t('login.loginUrlFailed'));
setIsLoading(false);
}
};
return (
<div className="login-container">
{/* Back Button */}
<button onClick={onBack} className="login-back-btn" disabled={isLoading}>
<img src="/assets/images/icon-back.svg" alt="Back" />
<span>{t('login.back')}</span>
</button>
<div className="login-content">
{/* Logo */}
<div className="login-logo">
<img src="/assets/images/ado2-login-logo.svg" alt="ADO2" />
</div>
{/* Error Message */}
{error && (
<div className="login-error">
{error}
</div>
)}
{/* Kakao Login Button */}
<button
onClick={handleKakaoLogin}
className="btn-kakao"
disabled={isLoading}
>
{isLoading ? t('login.loggingIn') : t('login.kakaoStart')}
</button>
</div>
</div>
);
};
export default LoginSection;
+7 -5
View File
@@ -1,11 +1,13 @@
import React from 'react'; import React from 'react';
import { useTranslation } from 'react-i18next';
const SocialConnectError: React.FC = () => { const SocialConnectError: React.FC = () => {
// URL 파라미터 파싱 const { t } = useTranslation();
const searchParams = new URLSearchParams(window.location.search); const searchParams = new URLSearchParams(window.location.search);
const platform = searchParams.get('platform') || 'unknown'; const platform = searchParams.get('platform') || 'unknown';
const errorMessage = searchParams.get('error') || '알 수 없는 오류가 발생했습니다.'; const errorMessage = searchParams.get('error') || t('social.connectError.defaultError');
const platformName = platform === 'youtube' ? 'YouTube' : const platformName = platform === 'youtube' ? 'YouTube' :
platform === 'instagram' ? 'Instagram' : platform === 'instagram' ? 'Instagram' :
@@ -25,19 +27,19 @@ const SocialConnectError: React.FC = () => {
<line x1="9" y1="9" x2="15" y2="15" /> <line x1="9" y1="9" x2="15" y2="15" />
</svg> </svg>
</div> </div>
<h1 className="social-connect-title">{platformName} 연결 실패</h1> <h1 className="social-connect-title">{t('social.connectError.title', { platform: platformName })}</h1>
<p className="social-connect-message"> <p className="social-connect-message">
{errorMessage} {errorMessage}
</p> </p>
<p className="social-connect-detail"> <p className="social-connect-detail">
다시 시도해주세요. 문제가 지속되면 고객 지원에 문의해주세요. {t('social.connectError.detail')}
</p> </p>
<div className="social-connect-actions"> <div className="social-connect-actions">
<button <button
onClick={navigateToHome} onClick={navigateToHome}
className="social-connect-button" className="social-connect-button"
> >
다시 시도 {t('social.connectError.retry')}
</button> </button>
</div> </div>
</div> </div>
+9 -14
View File
@@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
// 연결된 소셜 계정 정보를 저장하는 localStorage 키
const SOCIAL_CONNECTED_KEY = 'castad_social_connected'; const SOCIAL_CONNECTED_KEY = 'castad_social_connected';
interface ConnectedSocialAccount { interface ConnectedSocialAccount {
@@ -13,9 +13,9 @@ interface ConnectedSocialAccount {
} }
const SocialConnectSuccess: React.FC = () => { const SocialConnectSuccess: React.FC = () => {
const { t } = useTranslation();
const [countdown, setCountdown] = useState(3); const [countdown, setCountdown] = useState(3);
// URL 파라미터 파싱
const searchParams = new URLSearchParams(window.location.search); const searchParams = new URLSearchParams(window.location.search);
const platform = searchParams.get('platform') || 'unknown'; const platform = searchParams.get('platform') || 'unknown';
const accountId = searchParams.get('account_id') || ''; const accountId = searchParams.get('account_id') || '';
@@ -26,7 +26,6 @@ const SocialConnectSuccess: React.FC = () => {
platform === 'instagram' ? 'Instagram' : platform === 'instagram' ? 'Instagram' :
platform === 'facebook' ? 'Facebook' : platform; platform === 'facebook' ? 'Facebook' : platform;
// 연결된 계정 정보를 localStorage에 저장
useEffect(() => { useEffect(() => {
if (platform && accountId) { if (platform && accountId) {
const connectedAccount: ConnectedSocialAccount = { const connectedAccount: ConnectedSocialAccount = {
@@ -42,7 +41,6 @@ const SocialConnectSuccess: React.FC = () => {
}, [platform, accountId, channelName, profileImage]); }, [platform, accountId, channelName, profileImage]);
const navigateToHome = () => { const navigateToHome = () => {
// URL을 루트로 변경하고 페이지 새로고침하여 generation_flow로 이동
window.location.href = '/'; window.location.href = '/';
}; };
@@ -64,7 +62,6 @@ const SocialConnectSuccess: React.FC = () => {
return ( return (
<div className="social-connect-page"> <div className="social-connect-page">
<div className="social-connect-card success"> <div className="social-connect-card success">
{/* 프로필 이미지가 있으면 표시 */}
{profileImage ? ( {profileImage ? (
<img <img
src={profileImage} src={profileImage}
@@ -81,15 +78,13 @@ const SocialConnectSuccess: React.FC = () => {
)} )}
<h1 className="social-connect-title"> <h1 className="social-connect-title">
{channelName || platformName} 연결 완료 {t('social.connectSuccess.title', { name: channelName || platformName })}
</h1> </h1>
<p className="social-connect-message"> <p className="social-connect-message">
{channelName ? ( {channelName
<>{platformName} 계정이 성공적으로 연결되었습니다.</> ? t('social.connectSuccess.messageWithChannel', { platform: platformName })
) : ( : t('social.connectSuccess.messageWithoutChannel')}
<>계정이 성공적으로 연결되었습니다.</>
)}
</p> </p>
{channelName && ( {channelName && (
@@ -98,20 +93,20 @@ const SocialConnectSuccess: React.FC = () => {
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"> <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<polyline points="20 6 9 17 4 12" /> <polyline points="20 6 9 17 4 12" />
</svg> </svg>
인증됨 {t('social.connectSuccess.verified')}
</span> </span>
</div> </div>
)} )}
<p className="social-connect-countdown"> <p className="social-connect-countdown">
{countdown}초 후 자동으로 이동합니다... {t('social.connectSuccess.countdown', { count: countdown })}
</p> </p>
<button <button
onClick={navigateToHome} onClick={navigateToHome}
className="social-connect-button" className="social-connect-button"
> >
지금 이동 {t('social.connectSuccess.goNow')}
</button> </button>
</div> </div>
</div> </div>
+8 -6
View File
@@ -1,9 +1,11 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
const API_URL = import.meta.env.VITE_API_URL || 'http://40.82.133.44'; const API_URL = import.meta.env.VITE_API_URL || 'http://40.82.133.44';
const YouTubeOAuthCallback: React.FC = () => { const YouTubeOAuthCallback: React.FC = () => {
const { t } = useTranslation();
const [status, setStatus] = useState<'processing' | 'error'>('processing'); const [status, setStatus] = useState<'processing' | 'error'>('processing');
const [errorMessage, setErrorMessage] = useState<string>(''); const [errorMessage, setErrorMessage] = useState<string>('');
@@ -18,7 +20,7 @@ const YouTubeOAuthCallback: React.FC = () => {
if (error) { if (error) {
console.error('[YouTube OAuth] Error from Google:', error); console.error('[YouTube OAuth] Error from Google:', error);
setStatus('error'); setStatus('error');
setErrorMessage('Google 인증이 취소되었거나 실패했습니다.'); setErrorMessage(t('social.youtubeCallback.errorAuthCancelled'));
setTimeout(() => { setTimeout(() => {
window.location.href = '/social/connect/error?platform=youtube&error=' + encodeURIComponent(error); window.location.href = '/social/connect/error?platform=youtube&error=' + encodeURIComponent(error);
}, 1500); }, 1500);
@@ -28,7 +30,7 @@ const YouTubeOAuthCallback: React.FC = () => {
if (!code) { if (!code) {
console.error('[YouTube OAuth] No code received'); console.error('[YouTube OAuth] No code received');
setStatus('error'); setStatus('error');
setErrorMessage('인증 코드를 받지 못했습니다.'); setErrorMessage(t('social.youtubeCallback.errorNoCode'));
setTimeout(() => { setTimeout(() => {
window.location.href = '/social/connect/error?platform=youtube&error=no_code'; window.location.href = '/social/connect/error?platform=youtube&error=no_code';
}, 1500); }, 1500);
@@ -46,7 +48,7 @@ const YouTubeOAuthCallback: React.FC = () => {
} catch (err) { } catch (err) {
console.error('[YouTube OAuth] Failed to process callback:', err); console.error('[YouTube OAuth] Failed to process callback:', err);
setStatus('error'); setStatus('error');
setErrorMessage('YouTube 연결 처리 중 오류가 발생했습니다.'); setErrorMessage(t('social.youtubeCallback.errorProcessing'));
setTimeout(() => { setTimeout(() => {
window.location.href = '/social/connect/error?platform=youtube&error=processing_failed'; window.location.href = '/social/connect/error?platform=youtube&error=processing_failed';
}, 1500); }, 1500);
@@ -66,8 +68,8 @@ const YouTubeOAuthCallback: React.FC = () => {
<circle cx="25" cy="25" r="20" fill="none" strokeWidth="4" /> <circle cx="25" cy="25" r="20" fill="none" strokeWidth="4" />
</svg> </svg>
</div> </div>
<h1 className="social-connect-title">YouTube 연결 중...</h1> <h1 className="social-connect-title">{t('social.youtubeCallback.connecting')}</h1>
<p className="social-connect-message">잠시만 기다려주세요.</p> <p className="social-connect-message">{t('social.youtubeCallback.pleaseWait')}</p>
</> </>
) : ( ) : (
<> <>
@@ -78,7 +80,7 @@ const YouTubeOAuthCallback: React.FC = () => {
<line x1="9" y1="9" x2="15" y2="15" /> <line x1="9" y1="9" x2="15" y2="15" />
</svg> </svg>
</div> </div>
<h1 className="social-connect-title">연결 실패</h1> <h1 className="social-connect-title">{t('social.youtubeCallback.failed')}</h1>
<p className="social-connect-message">{errorMessage}</p> <p className="social-connect-message">{errorMessage}</p>
</> </>
)} )}
+262
View File
@@ -0,0 +1,262 @@
import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
AccommodationSearchItem,
InsufficientCreditError,
cleanSearchTitle,
createSsulJob,
searchAccommodation,
} from '../../utils/api';
import { SCEN, SCEN_KEYS, Scen, scenDesc, scenName } from './ssulData';
interface SsulCreateFormProps {
/** 생성 요청이 접수되면 호출. 폴링 소유는 GenerationFlow */
onSubmitted: (taskId: number, scenario: Scen) => void;
/** 크레딧 부족(402) 시 충전 화면으로 유도 */
onNeedCredit: () => void;
}
/** 네이버 지도 링크로 보이는가 — 링크면 검색을 건너뛰고 그대로 크롤링한다 */
const isNaverUrl = (s: string): boolean =>
/naver\.me|map\.naver|place\.naver|^https?:\/\//i.test(s.trim());
/** 자동완성 디바운스 — ADO2 SearchInputForm 과 동일 */
const AUTOCOMPLETE_DEBOUNCE = 300;
/**
* 썰박스 생성 폼. 진입 화면의 썰박스 탭에 들어간다.
*
* 원본 썰박스의 CreateSheet(바텀시트) 를 시트 크롬 없이 인라인으로 재배치했다.
* 시나리오 선택과 업장 검색을 한 화면에 둔다(원본은 2단계로 나뉘어 있었으나,
* 여기서는 위저드 스텝퍼가 이미 단계를 보여주므로 중복이다).
*
* **업장 검색은 ADO2 와 같은 방식**이다(2026-07-31 전환):
* 타이핑 중에는 네이버 **검색 API**(`/search/accommodation`, ~0.2초)로 자동완성을
* 띄우고, place URL 해석은 제출 후 서버가 한다(ADO2 `_autocomplete_logic` 과 동일).
* 이전에는 썰박스 전용 지도 크롤링(`/ssul/search/place`)으로 후보를 받았는데
* **17초**가 걸려 UX 가 크게 나빴다.
*/
const SsulCreateForm: React.FC<SsulCreateFormProps> = ({ onSubmitted, onNeedCredit }) => {
const { t } = useTranslation();
const [scenario, setScenario] = useState<Scen | null>(null);
const [input, setInput] = useState('');
const [results, setResults] = useState<AccommodationSearchItem[]>([]);
const [showResults, setShowResults] = useState(false);
const [selected, setSelected] = useState<AccommodationSearchItem | null>(null);
const [searching, setSearching] = useState(false);
const [submitting, setSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const boxRef = useRef<HTMLDivElement>(null);
const isUrl = isNaverUrl(input);
// 업장을 골랐거나 링크를 직접 붙여넣었을 때만 생성 가능
const canSubmit = !!scenario && (!!selected || isUrl) && !submitting;
// 바깥 클릭 시 자동완성 닫기
useEffect(() => {
const onDown = (e: MouseEvent) => {
if (boxRef.current && !boxRef.current.contains(e.target as Node)) {
setShowResults(false);
}
};
document.addEventListener('mousedown', onDown);
return () => document.removeEventListener('mousedown', onDown);
}, []);
// 언마운트 시 대기 중인 디바운스 취소 (setState-after-unmount 방지)
useEffect(() => {
return () => {
if (debounceRef.current) clearTimeout(debounceRef.current);
};
}, []);
const runAutocomplete = async (query: string) => {
if (query.trim().length < 2 || isNaverUrl(query)) {
setResults([]);
setShowResults(false);
return;
}
setSearching(true);
try {
const res = await searchAccommodation(query);
const items = res.items || [];
setResults(items);
setShowResults(items.length > 0);
} catch {
// 검색 실패는 조용히 넘긴다 — 링크 직접 입력 우회 경로가 있다
setResults([]);
setShowResults(false);
} finally {
setSearching(false);
}
};
const handleInputChange = (value: string) => {
setInput(value);
if (selected) setSelected(null);
if (debounceRef.current) clearTimeout(debounceRef.current);
debounceRef.current = setTimeout(() => runAutocomplete(value), AUTOCOMPLETE_DEBOUNCE);
};
const handleSelect = (item: AccommodationSearchItem) => {
// 검색 API 는 제목에 <b> 하이라이트 태그를 섞어 준다 — 그대로 쓰면
// 업장명·SNS 제목에 태그가 노출된다.
const title = cleanSearchTitle(item.title);
setInput(title);
setSelected({ ...item, title });
setShowResults(false);
setResults([]);
};
const handleSubmit = async () => {
if (!scenario || submitting) return;
// 고른 가게가 있으면 업장명을 보내고, 서버가 place URL 을 해석한다
// (ADO2 와 동일한 경로 — NvMapPwScraper.get_place_id_url).
// 링크를 직접 붙여넣었으면 그대로 넘긴다.
const payload = selected ? selected.title : input.trim();
setSubmitting(true);
setError(null);
try {
const res = await createSsulJob({
scenario,
input: payload,
// 고른 가게가 있을 때만 함께 보낸다. 통합 목록의 업장명 표시와
// 업장명·지역 필터가 이 값에 걸린다(링크 직접 입력 시에는 없다).
// 도로명·지번을 모두 보낸다. 백엔드가 도로명에서 시/군 추출에 실패하면
// 지번으로 재시도한다(한쪽만 보내면 지역이 비는 경우가 생긴다).
...(selected && {
store_name: selected.title,
road_address: selected.roadAddress,
address: selected.address,
}),
});
onSubmitted(res.id, scenario);
} catch (e) {
if (e instanceof InsufficientCreditError) {
onNeedCredit();
} else {
setError(t('ssulbox.error.createFailed'));
}
} finally {
setSubmitting(false);
}
};
return (
<div className="ssul-scope ssul-create">
{/* ── 1단계: 시나리오 ─────────────────────────────── */}
<span className="ssul-create__step">{t('ssulbox.create.step1')}</span>
<div className="ssul-create__scenarios">
{SCEN_KEYS.map((key) => {
const pal = SCEN[key];
const active = scenario === key;
return (
<button
key={key}
type="button"
aria-pressed={active}
className={`ssul-scn${active ? ' active' : ''}`}
style={
{
// 표지 그라디언트 2단 + 대표색. CSS 가 옅게 깔아 쓴다
'--scn': pal.hex,
'--scn-a': pal.g[0],
'--scn-b': pal.g[1],
} as React.CSSProperties
}
onClick={() => setScenario(key)}
>
<span className="ssul-scn__emoji" aria-hidden="true">
{pal.emoji}
</span>
<span className="ssul-scn__name">{t(scenName(key))}</span>
<span className="ssul-scn__desc">{t(scenDesc(key))}</span>
</button>
);
})}
</div>
{/* ── 2단계: 업장 ─────────────────────────────────── */}
{/* 2단계는 약하게 — 시선이 1단계(아직 안 고른 경우)로 먼저 가야 한다 */}
<span className="ssul-create__step muted">{t('ssulbox.create.step2')}</span>
{/* 자동완성 드롭다운을 붙이려면 상대 위치 컨테이너가 필요하다 */}
<div className="ssul-create__search" ref={boxRef}>
<input
className="ssul-create__input"
placeholder={t('ssulbox.create.searchPlaceholder')}
value={input}
onChange={(e) => handleInputChange(e.target.value)}
onFocus={() => results.length > 0 && setShowResults(true)}
autoComplete="off"
/>
{showResults && (
<ul className="ssul-places">
{results.map((place, i) => (
<li key={`${place.title}-${i}`}>
<button type="button" onClick={() => handleSelect(place)}>
<b>{cleanSearchTitle(place.title)}</b>
<span>{place.roadAddress || place.address}</span>
</button>
</li>
))}
</ul>
)}
</div>
{/* 상태 안내 — 한 번에 하나만 보인다 */}
{selected ? (
<div className="ssul-picked">
<div className="ssul-picked__body">
<b>{selected.title}</b>
<span>{selected.roadAddress || selected.address}</span>
</div>
</div>
) : isUrl ? (
<div className="ssul-hint ok">{t('ssulbox.create.hintUrlOk')}</div>
) : searching ? (
<div className="ssul-hint">{t('ssulbox.create.placeLoading')}</div>
) : scenario ? (
// 고른 시나리오를 되짚어 준다. 소요 시간은 기본 옵션 실측 전이라
// 분 단위를 못 박지 않는다("수 분 내외").
<div className="ssul-hint dot">
{t('ssulbox.create.hintScenario', { name: t(scenName(scenario)) })}
</div>
) : (
<div className="ssul-hint">{t('ssulbox.create.hintDefault')}</div>
)}
{error && <div className="ssul-hint warn">{error}</div>}
{/* ── 비용 고지 + 제출 ────────────────────────────── */}
{/* 요청 시점에 즉시 차감되므로 누르기 전에 반드시 알린다 */}
<div className="ssul-create__cost">
<span>{t('ssulbox.create.cost')}</span>
<span className="ssul-create__cost-badge">
<span className="ssul-create__coin" aria-hidden="true">
🪙
</span>
{t('ssulbox.create.costValue')}
</span>
</div>
<button
type="button"
className="ssul-create__submit"
disabled={!canSubmit}
onClick={handleSubmit}
>
{submitting ? t('ssulbox.create.submitting') : t('ssulbox.create.submit')}
</button>
</div>
);
};
export default SsulCreateForm;
+488
View File
@@ -0,0 +1,488 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
API_URL,
deleteComment,
getSsulContentById,
getUserMe,
getVideoComments,
isLoggedIn,
postVideoComment,
toggleVideoLike,
} from '../../utils/api';
import type { SsulDetailItem } from '../../utils/api';
import { CommentItem, UserMeResponse } from '../../types/api';
import { buildContentShareUrl, tryNativeShare } from '../../utils/nativeShare';
import LoginPromptModal from '../../components/LoginPromptModal';
import { isSafeHttpUrl } from '../../utils/url';
interface SsulDetailContentProps {
contentId: string;
isModal?: boolean;
onClose?: () => void;
}
/**
* 썰박스 콘텐츠 상세 — castad `VideoDetailContent` 와 같은 3층 구조의 내용부.
* (SsulViewerModal 이 모달로, SsulDetailPage 가 공유 링크 페이지로 감싼다)
*
* UI·동작(좋아요 낙관 갱신·댓글·대댓글·공유·비로그인 게이트)은
* `VideoDetailContent` 와 동일하고, 다른 점은 셋뿐이다:
* 1. 상세 조회가 `GET /ssul/{id}` (video 조회를 쓰면 id 가 겹치는 남의 영상이 열린다)
* 2. 좋아요·댓글 API 에 `contentType='ssul'` 을 얹는다
* 3. 공유 URL 이 `/ssul/share/{id}` 다
*/
const SsulDetailContent: React.FC<SsulDetailContentProps> = ({
contentId,
isModal = false,
onClose,
}) => {
const { t } = useTranslation();
const authed = isLoggedIn();
const [content, setContent] = useState<SsulDetailItem | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [likeCount, setLikeCount] = useState(0);
const [isLiked, setIsLiked] = useState(false);
const [copied, setCopied] = useState(false);
const [isLandscape, setIsLandscape] = useState(false);
const [showSiteOverlay, setShowSiteOverlay] = useState(false);
const [showLoginModal, setShowLoginModal] = useState(false);
const [comments, setComments] = useState<CommentItem[]>([]);
const [commentsTotal, setCommentsTotal] = useState(0);
const [commentsPage, setCommentsPage] = useState(1);
const [commentsHasNext, setCommentsHasNext] = useState(false);
const [commentsLoading, setCommentsLoading] = useState(false);
const [commentInput, setCommentInput] = useState('');
const [commentSubmitting, setCommentSubmitting] = useState(false);
const commentTextareaRef = useRef<HTMLTextAreaElement>(null);
const [currentUser, setCurrentUser] = useState<UserMeResponse | null>(null);
const fetchComments = useCallback(
async (page: number, append = false) => {
setCommentsLoading(true);
try {
const res = await getVideoComments(contentId, page, 20, 'ssul');
const sorted = [...res.items].sort(
(a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime()
);
setComments((prev) => (append ? [...prev, ...sorted] : sorted));
setCommentsTotal(res.total);
setCommentsHasNext(res.has_next);
setCommentsPage(page);
} catch (err) {
console.error('Failed to fetch ssul comments:', err);
} finally {
setCommentsLoading(false);
}
},
[contentId]
);
useEffect(() => {
const fetchContent = async () => {
setLoading(true);
setError(null);
setShowSiteOverlay(false);
try {
const data = await getSsulContentById(contentId);
setContent(data);
setLikeCount(data.like_count);
setIsLiked(data.is_liked_by_me);
} catch (err) {
console.error('Failed to fetch ssul content:', err);
setError(t('ado2Contents.loadFailed'));
} finally {
setLoading(false);
}
};
setIsLandscape(false);
fetchContent();
fetchComments(1);
}, [contentId, fetchComments, t]);
useEffect(() => {
if (!authed) return;
getUserMe().then(setCurrentUser).catch((err) => {
console.error('Failed to fetch current user:', err);
});
}, [authed]);
const formatDate = (dateString: string) => {
const date = new Date(dateString);
return t('videoDetail.dateFormat', {
year: date.getFullYear(),
month: date.getMonth() + 1,
day: date.getDate(),
});
};
const formatCommentDate = (dateString: string) => {
const date = new Date(dateString);
return `${date.getFullYear()}.${String(date.getMonth() + 1).padStart(2, '0')}.${String(
date.getDate()
).padStart(2, '0')}`;
};
// 썰박스 공개 페이지 경로. /video/{id} 를 쓰면 id 가 겹치는 남의 영상이 열린다.
const shareUrl = buildContentShareUrl(API_URL, contentId, 'ssul');
const handleCopyLink = async () => {
try {
await navigator.clipboard.writeText(shareUrl);
} catch {
// clipboard API 미지원 환경에서는 무시
}
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
const handleShareButtonClick = async () => {
const handled = await tryNativeShare({
title: content?.store_name ?? t('videoDetail.kakaoDefaultTitle'),
url: shareUrl,
});
if (handled) {
return;
}
await handleCopyLink();
};
const likeDebounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const handleLike = () => {
if (!authed) {
setShowLoginModal(true);
return;
}
setIsLiked((prev) => !prev);
setLikeCount((prev) => (isLiked ? prev - 1 : prev + 1));
if (likeDebounceRef.current) clearTimeout(likeDebounceRef.current);
likeDebounceRef.current = setTimeout(async () => {
const prevLiked = isLiked;
const prevCount = likeCount;
try {
await toggleVideoLike(contentId, 'ssul');
} catch (err) {
console.error('Failed to toggle ssul like:', err);
setIsLiked(prevLiked);
setLikeCount(prevCount);
}
}, 500);
};
const handleHeaderAction = () => {
if (!isModal && !authed) {
setShowLoginModal(true);
return;
}
onClose?.();
};
const handleCommentFocus = () => {
if (!authed) setShowLoginModal(true);
};
const handleCommentSubmit = async () => {
if (!authed) {
setShowLoginModal(true);
return;
}
if (!commentInput.trim() || commentSubmitting) return;
setCommentSubmitting(true);
try {
await postVideoComment(contentId, commentInput.trim(), undefined, 'ssul');
setCommentInput('');
if (commentTextareaRef.current) {
commentTextareaRef.current.style.height = 'auto';
}
await fetchComments(1);
} catch (err) {
console.error('Failed to post ssul comment:', err);
} finally {
setCommentSubmitting(false);
}
};
const handleDeleteComment = async (commentId: number) => {
try {
await deleteComment(commentId);
await fetchComments(commentsPage);
} catch (err) {
console.error('Failed to delete ssul comment:', err);
}
};
const renderCommentContent = (content_: string | null, isDeleted: boolean) => {
if (isDeleted) {
return (
<span style={{ color: '#6B9EA0', fontStyle: 'italic' }}>
{t('videoDetail.deletedComment')}
</span>
);
}
return content_;
};
return (
<div className={isModal ? 'video-detail-modal-content' : 'video-detail-page-content'}>
{/* 헤더 */}
<div className="video-detail-header">
{isModal ? (
<>
{/* 제목이 없으면 space-between 인 헤더에서 닫기 버튼이 왼쪽으로 붙는다.
문구는 ADO2 상세와 같은 키를 쓴다 — 통합 목록에서 열리는 같은
모달이므로 콘텐츠 종류에 따라 제목이 바뀌면 오히려 어색하다. */}
<h2 className="video-detail-modal-title">{t('sidebar.ado2Contents')}</h2>
<button className="video-detail-close-btn" onClick={handleHeaderAction} aria-label={t('videoDetail.closeAriaLabel')}>
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
</svg>
</button>
</>
) : (
<button className="video-detail-back-btn" onClick={handleHeaderAction}>
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.5">
<path d="M13 4l-6 6 6 6" />
</svg>
{t('sidebar.ado2Contents')}
</button>
)}
</div>
<div className="video-detail-body">
{loading ? (
<div className="ado2-contents-loading">
<div className="loading-spinner"></div>
<p>{t('ado2Contents.loading')}</p>
</div>
) : error ? (
<div className="ado2-contents-error"><p>{error}</p></div>
) : content ? (
<div className={`video-detail-content ${isLandscape ? 'landscape' : ''}`}>
<div className="video-detail-player-wrap">
<video
src={content.video_url}
controls
autoPlay
playsInline
controlsList="nodownload"
onContextMenu={(e) => e.preventDefault()}
className="video-detail-player"
onLoadedMetadata={(e) => {
const v = e.currentTarget;
setIsLandscape(v.videoWidth > v.videoHeight);
}}
onTimeUpdate={(e) => {
if (!content.official_site_url) return;
const v = e.currentTarget;
// 영상 종료 3초 전부터 공식 홈페이지 오버레이 노출
setShowSiteOverlay(
Number.isFinite(v.duration) && v.duration - v.currentTime <= 3
);
}}
/>
{showSiteOverlay && isSafeHttpUrl(content.official_site_url) && (
<a
href={content.official_site_url as string}
target="_blank"
rel="noopener noreferrer"
className="video-site-overlay"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="12" cy="12" r="10"/>
<line x1="2" y1="12" x2="22" y2="12"/>
<path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"/>
</svg>
<span className="video-site-overlay-text">
<strong>{content.store_name}</strong>
{t('videoDetail.siteOverlayLabel')}
</span>
</a>
)}
</div>
<div className="video-detail-info">
<h2 className="video-detail-store">
{content.store_name || t('ssulbox.viewer.untitled')}
</h2>
<p className="video-detail-date">{formatDate(content.created_at)}</p>
{/* 좋아요 + 공유 */}
<div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
<button
className={`video-detail-like-btn ${isLiked ? 'liked' : ''}`}
onClick={handleLike}
>
<svg width="16" height="16" viewBox="0 0 24 24" fill={isLiked ? 'currentColor' : 'none'} stroke="currentColor" strokeWidth="2">
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z" />
</svg>
{likeCount}
</button>
<button
className="video-detail-copy-btn"
onClick={handleShareButtonClick}
title={t('videoDetail.share')}
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
<circle cx="18" cy="5" r="3" /><circle cx="6" cy="12" r="3" /><circle cx="18" cy="19" r="3" />
<line x1="8.59" y1="13.51" x2="15.42" y2="17.49" /><line x1="15.41" y1="6.51" x2="8.59" y2="10.49" />
</svg>
{copied ? t('videoDetail.copied') : t('videoDetail.share')}
</button>
</div>
{/* 댓글 섹션 */}
<div className="video-detail-comments">
<div className="video-detail-comments-header">
<h3 className="video-detail-comments-title">{t('videoDetail.commentsTitle')}</h3>
<span className="video-detail-comments-count">{commentsTotal}</span>
</div>
{authed && currentUser && (
<div className="video-detail-comment-profile">
{currentUser.profile_image_url && (
<img
src={currentUser.profile_image_url}
alt={currentUser.nickname}
className="video-detail-comment-avatar"
/>
)}
<span className="video-detail-comment-nickname">{currentUser.nickname}</span>
</div>
)}
<div className="video-detail-comment-input-wrap">
<textarea
ref={commentTextareaRef}
className="video-detail-comment-input"
placeholder={authed ? t('videoDetail.commentPlaceholder') : t('videoDetail.commentLoginRequired')}
maxLength={500}
rows={1}
value={commentInput}
onChange={(e) => {
setCommentInput(e.target.value);
e.target.style.height = 'auto';
e.target.style.height = `${e.target.scrollHeight}px`;
}}
onFocus={handleCommentFocus}
onKeyDown={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleCommentSubmit();
}
}}
disabled={!authed}
/>
<button
className="video-detail-comment-submit"
onClick={handleCommentSubmit}
disabled={!authed || !commentInput.trim() || commentSubmitting}
>
{commentSubmitting ? t('videoDetail.commentSubmitting') : t('videoDetail.commentSubmit')}
</button>
</div>
{comments.length === 0 && !commentsLoading ? (
<p className="video-detail-comments-empty">{t('videoDetail.noComments')}</p>
) : (
<ul className="video-detail-comment-list">
{comments.map((c) => (
<li key={c.id} className="video-detail-comment-item">
{c.profile_image_url && (
<img
src={c.profile_image_url}
alt={c.nickname || t('videoDetail.anonymous')}
className="video-detail-comment-avatar"
/>
)}
<div className="video-detail-comment-body">
<span className="video-detail-comment-nickname">
{c.nickname || t('videoDetail.anonymous')}
</span>
<p className="video-detail-comment-text">
{renderCommentContent(c.content, c.is_deleted)}
</p>
<div className="video-detail-comment-bottom">
<span className="video-detail-comment-date">{formatCommentDate(c.created_at)}</span>
{c.is_mine && !c.is_deleted && (
<button
className="video-detail-comment-delete"
onClick={() => handleDeleteComment(c.id)}
>
{t('videoDetail.deleteComment')}
</button>
)}
</div>
{c.replies && c.replies.length > 0 && (
<ul className="video-detail-reply-list">
{c.replies.map((r) => (
<li key={r.id} className="video-detail-reply-item">
{r.profile_image_url && (
<img
src={r.profile_image_url}
alt={r.nickname || t('videoDetail.anonymous')}
className="video-detail-comment-avatar small"
/>
)}
<div className="video-detail-comment-body">
<span className="video-detail-comment-nickname">
{r.nickname || t('videoDetail.anonymous')}
</span>
<p className="video-detail-comment-text">
{renderCommentContent(r.content, r.is_deleted)}
</p>
<div className="video-detail-comment-bottom">
<span className="video-detail-comment-date">{formatCommentDate(r.created_at)}</span>
{r.is_mine && !r.is_deleted && (
<button
className="video-detail-comment-delete"
onClick={() => handleDeleteComment(r.id)}
>
{t('videoDetail.deleteComment')}
</button>
)}
</div>
</div>
</li>
))}
</ul>
)}
</div>
</li>
))}
</ul>
)}
{commentsHasNext && (
<button
className="video-detail-comments-more"
onClick={() => fetchComments(commentsPage + 1, true)}
disabled={commentsLoading}
>
{commentsLoading ? t('videoDetail.loadingComments') : t('videoDetail.loadMoreComments')}
</button>
)}
</div>
</div>
</div>
) : null}
</div>
{showLoginModal && (
<LoginPromptModal onClose={() => setShowLoginModal(false)} />
)}
</div>
);
};
export default SsulDetailContent;
+25
View File
@@ -0,0 +1,25 @@
import React from 'react';
import SsulDetailContent from './SsulDetailContent';
interface SsulDetailPageProps {
contentId: string;
}
/**
* 썰박스 공유 링크 페이지 (`/ssul/{id}`) — castad `VideoDetailPage` 와 동일한 패턴.
* 비로그인도 볼 수 있다(백엔드 `GET /ssul/{id}` 가 인증 선택).
*/
const SsulDetailPage: React.FC<SsulDetailPageProps> = ({ contentId }) => {
const handleBack = () => {
localStorage.setItem('castad_active_item', 'ADO2 콘텐츠');
window.location.href = '/';
};
return (
<div className="video-detail-page">
<SsulDetailContent contentId={contentId} isModal={false} onClose={handleBack} />
</div>
);
};
export default SsulDetailPage;
+111
View File
@@ -0,0 +1,111 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
import { SCEN, Scen, scenName } from './ssulData';
/** 생성 잡의 현재 상태. GenerationFlow 가 폴링해 내려준다 */
export interface SsulJob {
taskId: number;
scenario: Scen;
status: 'queued' | 'running' | 'done' | 'error';
/** 0~4. 0=준비, 4=영상 합성 완료 */
step: number;
error: string | null;
}
interface SsulMakingContentProps {
job: SsulJob | null;
/** 실패 후 처음부터 다시 */
onRetry: () => void;
}
/** 백엔드 generator 가 뱉는 4단계. `ssul_content.step` 과 1:1 대응 */
const TOTAL_STEPS = 4;
const STEP_LABEL_KEYS = [
'ssulbox.making.step1',
'ssulbox.making.step2',
'ssulbox.making.step3',
'ssulbox.making.step4',
] as const;
/**
* 썰박스 생성 진행 화면.
*
* 원본은 SSE 로 진행률만 받아 막대 하나를 그렸지만, castad 는 폴링으로
* `step`(0~4)을 받으므로 **지금 무슨 작업 중인지 단계명까지** 보여준다.
* 수 분~십수 분이 걸리는 작업이라 진행바만 있으면 멈춘 것처럼 보인다.
*
* 잡 소유는 GenerationFlow 다. 이 컴포넌트는 표시만 하므로
* 사이드바로 이동해 언마운트돼도 폴링이 끊기지 않는다.
* 그래서 "백그라운드로 전환" 버튼을 두지 않는다 — 사이드바로 그냥 이동하면
* 되고, 버튼이 있으면 마치 전환해야 계속 도는 것처럼 오해를 준다.
*/
const SsulMakingContent: React.FC<SsulMakingContentProps> = ({ job, onRetry }) => {
const { t } = useTranslation();
if (!job) return null;
const palette = SCEN[job.scenario];
const failed = job.status === 'error';
// step 은 "완료한 단계 수"라 진행률은 step/4. queued(0) 면 0%
const percent = Math.round((Math.min(job.step, TOTAL_STEPS) / TOTAL_STEPS) * 100);
// 진행 중인 단계는 완료 수 + 1 (마지막 단계 완료 시엔 더 올리지 않음)
const currentIndex = Math.min(job.step, TOTAL_STEPS - 1);
return (
<div className="ssul-scope ssul-making">
<span className="ssul-making__scenario" style={{ color: palette.hex }}>
<span aria-hidden="true">{palette.emoji}</span> {t(scenName(job.scenario))}
</span>
{failed ? (
<>
<h3 className="ssul-making__title warn">{t('ssulbox.making.failTitle')}</h3>
<p className="ssul-making__desc">{job.error || t('ssulbox.making.failDefault')}</p>
{/* 백엔드가 실패 시 크레딧을 환불한다 — 사용자가 손해 보지 않았음을 알린다 */}
<p className="ssul-making__refund">{t('ssulbox.making.refunded')}</p>
<button type="button" className="ssul-making__btn" onClick={onRetry}>
{t('ssulbox.making.retry')}
</button>
</>
) : (
<>
<h3 className="ssul-making__title">{t('ssulbox.making.title')}</h3>
{/*
단계 사이 구간에서는 진행바가 멈춰 있어 고장처럼 보인다.
스피너는 "살아 있다"는 신호 전용이라 진행률을 표현하지 않는다.
색은 시나리오 대표색을 따른다(민트 고정이면 삼국지·오디세이와 부딪힌다).
*/}
<div
className="ssul-making__spinner"
style={{ ['--scn' as string]: palette.hex }}
aria-hidden="true"
/>
<div
className="ssul-making__bar"
role="progressbar"
aria-valuenow={percent}
aria-valuemin={0}
aria-valuemax={100}
>
<div
className="ssul-making__fill"
style={{ width: `${percent}%`, background: palette.hex }}
/>
</div>
<div className="ssul-making__meta">
<span>{t(STEP_LABEL_KEYS[currentIndex])}</span>
<span className="ssul-making__pct">{percent}%</span>
</div>
<p className="ssul-making__desc">{t('ssulbox.making.takesTime')}</p>
</>
)}
</div>
);
};
export default SsulMakingContent;
+147
View File
@@ -0,0 +1,147 @@
import React, { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { SsulTaskStatus, getSsulTask } from '../../utils/api';
import { VideoListItem } from '../../types/api';
import SocialPostingModal from '../../components/SocialPostingModal';
import CompletionView from '../../components/CompletionView';
import { Scen, scenDesc, scenName } from './ssulData';
interface SsulResultContentProps {
taskId: number;
scenario: Scen;
}
/**
* 썰박스 생성 완료 화면.
*
* **화면은 ADO2 완료 화면과 같은 `CompletionView` 를 쓴다**(2026-08-10 통일).
* 이전에는 `.ssul-scope` 안의 중앙 1단 레이아웃이었는데, 같은 제품 안에서
* 완료 화면이 둘로 갈리는 것이 혼란스러웠고 영상 로딩·에러 처리도 없었다.
* 정보 패널만 썰박스 재료(시나리오·생성일시·시나리오 설명)로 채운다.
*
* `.ssul-scope` 를 벗어나면서 부수 효과가 하나 있다: 예전에는 상위의
* `text-align: center` 가 SNS 업로드 모달 라벨까지 가운데로 끌어당겼는데
* 그 경로가 사라졌다. 다만 오버레이 쪽 방어(`.social-posting-overlay` 의
* `text-align`)는 다른 마운트 지점을 위해 그대로 둔다.
*
* 업로드는 castad `SocialPostingModal` 을 그대로 쓴다 — social_upload 병합으로
* 모달이 `content_type` 을 함께 보내므로 종류 분기가 모달 내부에서 끝난다.
*/
const SsulResultContent: React.FC<SsulResultContentProps> = ({ taskId, scenario }) => {
const { t } = useTranslation();
const [task, setTask] = useState<SsulTaskStatus | null>(null);
const [loadError, setLoadError] = useState(false);
// 영상 전체를 받아오는 동안 시간이 걸린다 — 중복 클릭을 막고 진행을 알린다
const [downloading, setDownloading] = useState(false);
const [showSocialModal, setShowSocialModal] = useState(false);
// 폴링이 끝난 뒤 최종 상태(video_url 포함)를 한 번 더 읽는다.
// 진행 중에는 video_url 이 비어 있으므로 완료 후 조회가 필요하다.
useEffect(() => {
let alive = true;
getSsulTask(taskId)
.then((data) => alive && setTask(data))
.catch(() => alive && setLoadError(true));
return () => {
alive = false;
};
}, [taskId]);
// 파일명은 ADO2 완료 화면과 같은 방식이다 — 업장명 그대로 + .mp4.
// store_name 은 완료(done) 시점에 서버가 반드시 채워 보내지만, 조회 실패로
// task 가 없을 수 있어 ADO2 와 동일한 폴백('콘텐츠')을 둔다.
const fileName = `${task?.store_name || '콘텐츠'}.mp4`;
/**
* 영상 다운로드.
*
* **Blob URL 을 `<a download>` 에 그대로 걸면 다운로드가 아니라 재생 화면으로
* 이동한다** — `download` 속성은 교차 출처 URL 에서 무시되고, 영상은 Azure Blob
* 도메인에 있어 앱과 출처가 다르기 때문이다.
* 그래서 castad `CompletionContent` 와 동일하게 fetch → Blob → 동일 출처
* objectURL 로 바꿔서 내려받는다.
*
* fetch 가 실패하면(CORS 등) 새 탭으로라도 열어준다 — 사용자가 거기서
* 직접 저장할 수 있으므로 아무 일도 안 일어나는 것보다 낫다.
*/
const handleDownload = async () => {
if (!task?.video_url || downloading) return;
setDownloading(true);
try {
const response = await fetch(task.video_url);
const blobUrl = URL.createObjectURL(await response.blob());
const link = document.createElement('a');
link.href = blobUrl;
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(blobUrl);
} catch {
const link = document.createElement('a');
link.href = task.video_url;
link.download = fileName;
link.target = '_blank';
link.rel = 'noopener';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
} finally {
setDownloading(false);
}
};
return (
<CompletionView
// 여기에 도달했다는 것은 생성이 이미 끝났다는 뜻이라 'loading' 은 쓰지 않는다.
// 남는 실패 경우는 최종 상태 조회 실패뿐이며, 재시도 버튼은 두지 않는다
// (생성을 다시 돌리는 것이 아니라 조회만 실패한 것이므로 새로고침이 맞다).
videoState={loadError ? 'error' : task?.video_url ? 'ready' : 'empty'}
videoUrl={task?.video_url}
errorMessage={t('ssulbox.result.loadFailed')}
fileName={fileName}
metaLines={[
`${t('ssulbox.result.scenarioLabel')} : ${t(scenName(scenario))}`,
`${t('ssulbox.result.createdLabel')} : ${
task?.created_at ? new Date(task.created_at).toLocaleString('ko-KR') : '-'
}`,
]}
// ADO2 의 가사 자리. 썰박스는 대본이 영상 안에 그려지므로 내려받을 텍스트가
// 없고, 대신 어떤 이야기인지 알려주는 시나리오 설명을 넣는다.
detailLabel={t('ssulbox.result.scenarioLabel')}
detail={<p className="comp2-lyrics-text">{t(scenDesc(scenario))}</p>}
onDownload={handleDownload}
downloadDisabled={!task?.video_url || downloading}
downloadLabel={
downloading ? t('ssulbox.result.downloading') : t('ssulbox.result.download')
}
onUpload={() => setShowSocialModal(true)}
uploadDisabled={!task?.video_url}
>
{/* castad 모달 재사용 — VideoListItem 형태로 매핑해 넘긴다.
type='ssul' 이 핵심이다: 모달이 content_type 으로 보내므로
id 가 겹치는 ADO2 영상이 업로드되는 사고가 없다. */}
<SocialPostingModal
isOpen={showSocialModal}
onClose={() => setShowSocialModal(false)}
video={
task?.video_url
? ({
type: 'ssul',
video_id: taskId,
store_name: t(scenName(scenario)),
region: '',
task_id: '',
result_movie_url: task.video_url,
created_at: task.created_at,
like_count: 0,
comment_count: 0,
} as VideoListItem)
: null
}
/>
</CompletionView>
);
};
export default SsulResultContent;
+54
View File
@@ -0,0 +1,54 @@
import React, { useEffect } from 'react';
import { VideoListItem } from '../../types/api';
import SsulDetailContent from './SsulDetailContent';
import { useOverlayClose } from '../../hooks/useOverlayClose';
interface SsulViewerModalProps {
/** null 이면 닫힘 */
item: VideoListItem | null;
onClose: () => void;
}
/**
* 썰박스 콘텐츠 모달 — castad `VideoDetailModal` 과 같은 백드롭 래퍼.
* 내용은 `SsulDetailContent` 가 그린다(공유 링크 페이지 `SsulDetailPage` 와 공용).
*
* `VideoDetailModal` 을 그대로 못 쓰는 이유: `videoId` 로 `/video/{id}` 를
* 조회하는데, 썰박스 id 를 넘기면 **id 가 겹치는 다른 ADO2 영상**이 열린다.
*/
const SsulViewerModal: React.FC<SsulViewerModalProps> = ({ item, onClose }) => {
useEffect(() => {
if (!item) return;
// 모달 열릴 때 배경 스크롤 잠금
const prev = document.body.style.overflow;
document.body.style.overflow = 'hidden';
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
};
document.addEventListener('keydown', handleKeyDown);
return () => {
document.body.style.overflow = prev;
document.removeEventListener('keydown', handleKeyDown);
};
}, [item, onClose]);
const overlayCloseHandlers = useOverlayClose(onClose);
if (!item) return null;
return (
<div className="video-detail-overlay" {...overlayCloseHandlers}>
<div className="video-detail-modal-box" onClick={(e) => e.stopPropagation()}>
<SsulDetailContent
contentId={String(item.video_id)}
isModal={true}
onClose={onClose}
/>
</div>
</div>
);
};
export default SsulViewerModal;
+53
View File
@@ -0,0 +1,53 @@
/**
* 썰박스 시나리오 팔레트와 표시 유틸.
*
* 원본(o2o-ssulbox/frontend/src/data.ts)에서 이식하되 **문구(name/desc)는 제외**했다.
* castad 는 ko/en 다국어라 한글이 코드에 박히면 i18n 밖으로 새기 때문이다.
* 표시 문구는 `t('ssulbox.scenario.<key>.name')` / `.desc` 로 가져온다.
*
* 목업(SAMPLE)도 제외했다 — 백엔드 `/ssul/feed` 가 진실 원천이다.
*/
/** 시나리오 코드. 백엔드 `ssul_content.scenario` 와 값이 일치해야 한다 */
export type Scen = 'joseon' | 'samgukji' | 'greek' | 'odyssey';
export interface ScenPalette {
/** 카드 표지 이모지 */
emoji: string;
/** 대표색 (뱃지·강조선) */
hex: string;
/** 표지 그라디언트 시작/끝 */
g: [string, string];
}
export const SCEN: Record<Scen, ScenPalette> = {
joseon: { emoji: '👑', hex: '#3b4cc0', g: ['#4054d6', '#8a3ffb'] },
samgukji: { emoji: '⚔️', hex: '#d63a2f', g: ['#e0402f', '#f0872b'] },
greek: { emoji: '🏛️', hex: '#0a8f6b', g: ['#0a9e78', '#3fb6d6'] },
odyssey: { emoji: '⛵', hex: '#1565c0', g: ['#1565c0', '#42a5f5'] },
};
/** 시나리오 순서. 선택 그리드(2x2)와 필터 칩이 이 순서를 따른다 */
export const SCEN_KEYS = Object.keys(SCEN) as Scen[];
/** 카드 표지 그라디언트 */
export const scGrad = (s: Scen): string =>
`linear-gradient(150deg,${SCEN[s].g[0]} 0%,${SCEN[s].g[1]} 100%)`;
/** i18n 키 헬퍼 — t(scenName('joseon')) 형태로 쓴다 */
export const scenName = (s: Scen): string => `ssulbox.scenario.${s}.name`;
export const scenDesc = (s: Scen): string => `ssulbox.scenario.${s}.desc`;
/**
* 조회수·좋아요 수 축약 표기 (1.2만 / 3.4천).
*
* 한글 단위가 박혀 있어 en 로케일에서는 어색하다. 통합 목록에서 castad 콘텐츠와
* 나란히 놓이므로, 표기 방식은 Phase 8 에서 castad 쪽과 함께 정하는 게 맞다.
* 그때까지는 원본 동작을 유지한다.
*/
export const fmt = (n: number): string =>
n >= 10000
? `${(n / 10000).toFixed(1).replace(/\.0$/, '')}만`
: n >= 1000
? `${(n / 1000).toFixed(1).replace(/\.0$/, '')}천`
: `${n}`;
+111
View File
@@ -0,0 +1,111 @@
/**
* 썰박스 UI 아이콘.
*
* 원본(o2o-ssulbox/frontend/src/icons.tsx)에서 이식하되 **castad 에 대응물이 있는 것은 제외**했다:
* IcHome / IcSearch / IcUser / IcGrid → castad Sidebar 가 대체
* IcBack → castad 각 화면의 뒤로가기 버튼이 대체
*
* 색·굵기는 대부분 CSS(컨텍스트)로 제어된다. 원본이 일부 아이콘에 `stroke="#fff"` 를
* 하드코딩했는데, castad 다크 배경에서도 흰색이 맞아 그대로 두되
* 재사용 가능성이 있는 것은 `currentColor` 로 바꿨다.
*
* 모두 장식용이므로 사용하는 쪽에서 `aria-hidden` 을 붙이거나 접근 가능한 라벨을 준다.
*/
import React from 'react';
/** 재생 (카드 오버레이) */
export const IcPlay: React.FC = () => (
<svg viewBox="0 0 24 24">
<path d="M8 5v14l11-7z" />
</svg>
);
/** 좋아요 (채움) */
export const IcHeart: React.FC = () => (
<svg viewBox="0 0 24 24">
<path d="M12 21s-8-5.3-8-11a4.5 4.5 0 0 1 8-2.8A4.5 4.5 0 0 1 20 10c0 5.7-8 11-8 11z" />
</svg>
);
/** 좋아요 (원본에서 채움과 동일 — 상태는 CSS 로 구분) */
export const IcHeartLine = IcHeart;
/** 댓글 */
export const IcComment: React.FC = () => (
<svg viewBox="0 0 24 24">
<path
d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-5.2A8 8 0 1 1 21 12z"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
/>
</svg>
);
/** 공유 */
export const IcShare: React.FC = () => (
<svg viewBox="0 0 24 24">
<path
d="M22 3 11 14M22 3l-7 19-4-8-8-4z"
fill="none"
stroke="currentColor"
strokeWidth="1.8"
/>
</svg>
);
/** 링크 복사 */
export const IcLink: React.FC = () => (
<svg viewBox="0 0 24 24">
<path
d="M10 13a5 5 0 0 0 7 0l2-2a5 5 0 0 0-7-7l-1 1m0 8a5 5 0 0 1-7 0 5 5 0 0 1 0-7l2-2a5 5 0 0 1 7 0"
fill="none"
stroke="currentColor"
strokeWidth="1.7"
/>
</svg>
);
/** 업로드 */
export const IcUpload: React.FC = () => (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
<path d="M12 15V4M8 8l4-4 4 4M5 15v3a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-3" />
</svg>
);
/** 다운로드 */
export const IcDownload: React.FC = () => (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
<path d="M12 4v11M8 11l4 4 4-4M5 19h14" />
</svg>
);
/** 복사 (캡션) */
export const IcCopy: React.FC = () => (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
<rect x="9" y="9" width="11" height="11" rx="2" />
<path d="M5 15V5a2 2 0 0 1 2-2h8" />
</svg>
);
// ── SNS 플랫폼 ────────────────────────────────────────────────
export const IcYoutube: React.FC = () => (
<svg viewBox="0 0 24 24">
<rect x="2" y="5" width="20" height="14" rx="4" />
<path d="M10 9l5 3-5 3z" fill="#fff" />
</svg>
);
export const IcInstagram: React.FC = () => (
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8">
<rect x="3" y="3" width="18" height="18" rx="5" />
<circle cx="12" cy="12" r="4" />
<circle cx="17.5" cy="6.5" r="1" fill="currentColor" stroke="none" />
</svg>
);
export const IcTiktok: React.FC = () => (
<svg viewBox="0 0 24 24">
<path d="M14 3c.3 2.3 1.8 4 4 4.3V10c-1.5 0-2.9-.5-4-1.3V15a5 5 0 1 1-5-5v2.6a2.4 2.4 0 1 0 2.4 2.4V3z" />
</svg>
);
+941
View File
@@ -0,0 +1,941 @@
/* =====================================================
Layout Components
===================================================== */
/* Landing Page Container - Free Scroll */
.landing-container {
width: 100%;
height: 100dvh;
overflow-y: scroll;
overflow-x: hidden;
background-color: var(--color-bg-darker);
}
.landing-section {
background: var(--Color-teal-800, #002224);
min-height: 100dvh;
width: 100%;
}
/* Page Container */
.page-container {
display: flex;
flex-direction: column;
height: 100%;
padding: var(--spacing-page);
overflow: hidden;
background-color: #002224;
position: relative;
}
@media (min-width: 768px) {
.page-container {
padding: var(--spacing-page-md);
}
}
/* Page Container - Full Height with Background */
.page-container-full {
width: 100%;
min-height: 100dvh;
color: var(--color-text-white);
display: flex;
flex-direction: column;
padding: var(--spacing-page);
background-color: var(--color-bg-dark);
}
@media (min-width: 768px) {
.page-container-full {
padding: var(--spacing-page-md);
}
}
@media (min-width: 1024px) {
.page-container-full {
padding: 2.5rem;
}
}
/* Wizard Page Container - 단계별 페이지 전환용 */
.wizard-page-container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
background-color: var(--color-bg-darker);
overflow-y: auto;
}
/* Main Content Area */
.main-content {
flex: 1;
display: flex;
flex-direction: column;
gap: 1.5rem;
max-width: 72rem;
margin-left: auto;
margin-right: auto;
width: 100%;
min-height: 0;
overflow: hidden;
}
@media (min-width: 1024px) {
.main-content {
flex-direction: row;
}
}
/* Dashboard Layout */
.dashboard-layout {
display: flex;
width: 100%;
min-height: 100dvh;
background-color: var(--color-bg-darker);
color: var(--color-text-white);
}
.dashboard-content {
flex: 1;
min-height: 0;
position: relative;
overflow-y: auto;
padding-left: 0;
}
/* =====================================================
Card Components
===================================================== */
/* Base Card */
.card {
background-color: var(--color-bg-card);
border-radius: var(--radius-3xl);
padding: var(--spacing-page);
border: 1px solid var(--color-border-white-5);
box-shadow: var(--shadow-xl);
}
@media (min-width: 768px) {
.card {
padding: var(--spacing-page-md);
}
}
/* Card Variants */
.card-flex {
display: flex;
flex-direction: column;
}
.card-flex-1 {
flex: 1;
}
.card-flex-2 {
flex: 2;
}
.card-overflow-hidden {
overflow: hidden;
}
/* Card Inner (Darker Background) */
.card-inner {
background-color: rgba(18, 26, 29, 0.5);
border-radius: var(--radius-2xl);
border: 1px solid var(--color-border-white-5);
padding: 1rem;
}
/* =====================================================
Header Components
===================================================== */
/* Page Header */
.page-header {
text-align: center;
margin-bottom: 2rem;
flex-shrink: 0;
}
/* Page Title */
.page-title {
font-size: var(--text-3xl);
font-weight: 700;
margin-bottom: 0.5rem;
letter-spacing: -0.025em;
}
@media (min-width: 768px) {
.page-title {
font-size: var(--text-4xl);
}
}
/* Page Subtitle */
.page-subtitle {
color: var(--color-text-gray-400);
font-size: var(--text-base);
}
@media (min-width: 768px) {
.page-subtitle {
font-size: var(--text-lg);
}
}
/* Section Title (Mint color uppercase) */
.section-title {
color: #94FBE0;
font-size: 16px;
font-weight: 600;
letter-spacing: -0.006em;
margin-bottom: 0;
flex-shrink: 0;
}
/* Section Title Purple */
.section-title-purple {
color: #AE72F9;
font-size: 16px;
font-weight: 600;
letter-spacing: -0.006em;
margin-bottom: 0;
display: block;
}
/* =====================================================
Button Components
===================================================== */
/* Primary Button (Purple) */
.btn-primary {
background-color: var(--color-purple);
color: var(--color-text-white);
font-weight: 700;
padding: 1rem 4rem;
border-radius: var(--radius-full);
transition: all var(--transition-normal);
transform: scale(1);
box-shadow: var(--shadow-purple);
font-size: var(--text-lg);
border: none;
cursor: pointer;
}
.btn-primary:hover {
background-color: var(--color-purple-hover);
}
.btn-primary:active {
transform: scale(0.95);
}
.btn-primary:disabled {
background-color: #4b5563;
color: var(--color-text-gray-400);
cursor: not-allowed;
box-shadow: none;
}
/* Secondary Button (Mint) */
.btn-secondary {
background-color: var(--color-mint);
color: var(--color-bg-dark);
font-weight: 700;
padding: 1rem;
border-radius: var(--radius-xl);
transition: all var(--transition-normal);
transform: scale(1);
font-size: var(--text-base);
border: none;
cursor: pointer;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
}
.btn-secondary:hover {
background-color: var(--color-mint-hover);
}
.btn-secondary:active {
transform: scale(0.98);
}
.btn-secondary:disabled {
background-color: rgba(166, 255, 234, 0.5);
color: rgba(18, 26, 29, 0.5);
cursor: not-allowed;
}
/* Outline Button */
.btn-outline {
background-color: transparent;
border: 1px solid var(--color-border-gray-600);
color: var(--color-text-white);
font-weight: 700;
padding: 1rem 4rem;
border-radius: var(--radius-full);
transition: all var(--transition-normal);
font-size: var(--text-base);
cursor: pointer;
}
.btn-outline:hover {
border-color: var(--color-text-gray-500);
}
/* Back Button */
.btn-back {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.5rem 1.25rem;
border-radius: var(--radius-full);
border: 1px solid var(--color-border-gray-600);
background-color: transparent;
color: var(--color-text-gray-300);
font-size: var(--text-base);
transition: background-color var(--transition-normal);
cursor: pointer;
}
.btn-back:hover {
background-color: rgba(31, 41, 55, 1);
}
/* Regenerate Button (Mint Outline) */
.btn-regenerate {
margin-top: 1rem;
width: 100%;
padding: 0.75rem;
background-color: var(--color-mint-20);
color: var(--color-mint);
border: 1px solid var(--color-mint-30);
font-weight: 700;
border-radius: var(--radius-xl);
transition: background-color var(--transition-normal);
font-size: var(--text-base);
flex-shrink: 0;
cursor: pointer;
}
.btn-regenerate:hover {
background-color: var(--color-mint-30);
}
.btn-regenerate:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Selection Button */
.btn-select {
padding: 0.75rem;
border-radius: var(--radius-xl);
border: 1px solid var(--color-border-gray-700);
background-color: rgba(18, 26, 29, 0.4);
color: var(--color-text-gray-400);
font-size: var(--text-sm);
font-weight: 700;
transition: all var(--transition-normal);
cursor: pointer;
}
.btn-select:hover {
border-color: var(--color-border-gray-600);
}
.btn-select.active {
border-color: var(--color-mint);
background-color: var(--color-bg-dark);
color: var(--color-mint);
}
.btn-select:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* =====================================================
Form Components
===================================================== */
/* Select Input */
.select-input {
width: 100%;
padding: 0.75rem 1rem;
border-radius: var(--radius-xl);
background-color: var(--color-bg-dark);
border: 1px solid var(--color-border-gray-700);
font-size: var(--text-base);
color: var(--color-text-gray-300);
}
.select-input:focus {
outline: none;
border-color: var(--color-mint);
}
.select-input:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Text Input */
.text-input {
width: 100%;
padding: 0.75rem 1rem;
border-radius: var(--radius-xl);
background-color: var(--color-bg-dark);
border: 1px solid var(--color-border-gray-700);
font-size: var(--text-base);
color: var(--color-text-gray-300);
}
.text-input:focus {
outline: none;
border-color: var(--color-mint);
}
/* Textarea - Lyrics */
.textarea-lyrics {
flex: 1;
overflow-y: auto;
font-size: var(--text-sm);
color: var(--color-text-gray-400);
background-color: transparent;
resize: none;
border: none;
padding-right: 0.5rem;
line-height: 1.625;
min-height: 0;
}
.textarea-lyrics:focus {
outline: none;
color: var(--color-text-gray-300);
}
/* =====================================================
Navigation Components
===================================================== */
/* Back Button Container */
.back-button-container {
width: 100%;
max-width: 1040px;
display: flex;
justify-content: flex-start;
margin-bottom: 1.5rem;
flex-shrink: 0;
}
/* Bottom Button Container */
.bottom-button-container {
position: fixed;
bottom: 32px;
left: 0;
right: 0;
display: flex;
justify-content: center;
z-index: 30;
pointer-events: none;
}
.bottom-button-container > * {
pointer-events: all;
}
@media (min-width: 768px) {
.bottom-button-container {
left: 240px;
}
}
/* 모바일: 하단 탭바에 가리지 않도록 띄운다 */
@media (max-width: 767px) {
.bottom-button-container {
bottom: calc(var(--bottom-nav-height) + 16px);
}
}
/* =====================================================
Sidebar Components
===================================================== */
/* Sidebar Container */
.sidebar {
position: sticky;
top: 0;
height: 100vh;
flex-shrink: 0;
display: flex;
flex-direction: column;
background-color: var(--color-bg-dark);
border-right: 1px solid var(--color-border-white-5);
z-index: 50;
}
@media (max-width: 767px) {
.sidebar {
display: none;
}
}
.sidebar.expanded {
width: 15rem;
}
/* Sidebar Header */
.sidebar-header {
padding: 1.25rem;
display: flex;
align-items: center;
justify-content: space-between;
}
/* Sidebar Logo */
.sidebar-logo {
font-family: 'Playfair Display', serif;
font-style: italic;
font-size: var(--text-2xl);
font-weight: 700;
letter-spacing: -0.025em;
color: var(--color-text-white);
cursor: pointer;
transition: color var(--transition-normal);
}
.sidebar-logo:hover {
color: var(--color-mint);
}
/* Sidebar Menu */
.sidebar-menu {
flex: 1;
padding: 0 0.75rem;
margin-top: 1rem;
overflow-y: auto;
}
/* Sidebar Menu Item */
.sidebar-item {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.75rem 1rem;
border-radius: var(--radius-xl);
transition: all var(--transition-normal);
cursor: pointer;
margin-bottom: 0.25rem;
position: relative;
overflow: hidden;
}
.sidebar-item.active {
background-color: var(--color-mint);
color: var(--color-bg-dark);
}
.sidebar-item:not(.active) {
color: var(--color-text-gray-400);
}
.sidebar-item:not(.active):not(.disabled):hover {
background-color: rgba(255, 255, 255, 0.05);
color: var(--color-text-white);
}
.sidebar-item.disabled {
opacity: 0.4;
cursor: not-allowed;
pointer-events: none;
}
.sidebar-item-icon {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
transition: color var(--transition-normal);
}
.sidebar-item.active .sidebar-item-icon {
color: var(--color-bg-dark);
}
.sidebar-item-label {
font-size: 16px;
font-weight: 700;
white-space: nowrap;
}
/* Sidebar Footer */
.sidebar-footer {
padding: 1rem;
margin-top: auto;
display: flex;
flex-direction: column;
gap: 1rem;
}
/* Credit Card */
.credit-card {
background-color: var(--color-bg-card);
border-radius: var(--radius-2xl);
padding: 1rem;
border: 1px solid var(--color-border-white-5);
}
.credit-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
}
.credit-label {
color: var(--color-text-gray-400);
font-size: var(--text-sm);
font-weight: 500;
}
.credit-value {
color: var(--color-text-white);
font-size: var(--text-sm);
font-weight: 700;
}
.credit-bar {
width: 100%;
height: 0.375rem;
background-color: #1f2937;
border-radius: var(--radius-full);
overflow: hidden;
margin-bottom: 0.75rem;
}
.credit-bar-fill {
height: 100%;
background-color: var(--color-mint);
}
.credit-upgrade-btn {
width: 100%;
padding: 0.625rem;
background-color: var(--color-bg-dark);
color: var(--color-text-white);
font-size: var(--text-sm);
font-weight: 700;
border-radius: var(--radius-lg);
border: 1px solid var(--color-border-gray-700);
transition: background-color var(--transition-normal);
cursor: pointer;
}
.credit-upgrade-btn:hover {
background-color: #1f2937;
}
/* Profile Section */
.profile-section {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0 0.5rem;
}
.profile-avatar {
width: 2.5rem;
height: 2.5rem;
border-radius: var(--radius-full);
border: 1px solid var(--color-border-gray-700);
object-fit: cover;
}
.profile-avatar-default {
display: flex;
align-items: center;
justify-content: center;
background-color: var(--color-bg-gray-700);
color: var(--color-text-gray-400);
}
.profile-name {
color: var(--color-text-white);
font-size: var(--text-sm);
font-weight: 700;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.profile-credits {
color: rgba(255, 255, 255, 0.6);
font-size: 12px;
font-weight: 500;
margin-top: 2px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Sidebar Language Switch */
.sidebar-language-switch {
padding: 0 1rem 0.75rem;
display: flex;
justify-content: flex-start;
}
/* Toggle container */
.lang-toggle {
position: relative;
display: flex;
background: rgba(255, 255, 255, 0.08);
border-radius: 999px;
padding: 2px;
width: 100%;
max-width: 120px;
}
.lang-toggle-option {
flex: 1;
position: relative;
z-index: 1;
padding: 4px 0;
font-size: 14px;
font-weight: 600;
letter-spacing: 0.03em;
color: rgba(255, 255, 255, 0.4);
background: none;
border: none;
cursor: pointer;
transition: color 0.3s ease;
text-align: center;
}
.lang-toggle-option.active {
color: #ffffff;
}
.lang-toggle-option:hover:not(.active) {
color: rgba(255, 255, 255, 0.6);
}
/* Sliding indicator */
.lang-toggle-slider {
position: absolute;
top: 2px;
bottom: 2px;
width: calc(50% - 2px);
background: rgba(255, 255, 255, 0.15);
border-radius: 999px;
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
pointer-events: none;
}
.lang-toggle-slider.left {
transform: translateX(2px);
}
.lang-toggle-slider.right {
transform: translateX(calc(100% + 2px));
}
/* Sidebar Footer Actions */
.sidebar-footer-actions {
display: flex;
flex-direction: column;
}
.sidebar-footer-actions .logout-btn {
width: 100%;
}
.sidebar-inquiry-btn {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.75rem 1rem;
color: var(--color-text-gray-400);
text-decoration: none;
transition: color var(--transition-normal);
white-space: nowrap;
font-size: var(--text-sm);
font-weight: 700;
flex-shrink: 0;
}
.sidebar-inquiry-btn:hover {
color: var(--color-text-white);
}
/* Logout Button */
.logout-btn {
width: 100%;
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.75rem 1rem;
color: var(--color-text-gray-400);
background: none;
border: none;
transition: color var(--transition-normal);
cursor: pointer;
}
.logout-btn:hover {
color: var(--color-text-white);
}
.logout-btn-label {
font-size: var(--text-sm);
font-weight: 700;
}
/* Settings Panel (Sidebar 4번째 메뉴 / BottomNav 설정 버튼 공용) */
.settings-panel {
background: var(--color-bg-card);
border: 1px solid var(--color-border-white-10);
border-radius: var(--radius-2xl);
padding: 0.5rem;
display: flex;
flex-direction: column;
gap: 0.125rem;
z-index: 60;
}
.settings-panel-profile {
padding: 0.625rem 0.75rem;
}
.settings-panel-divider {
height: 1px;
background: rgba(255, 255, 255, 0.08);
margin: 0.375rem 0.25rem;
flex-shrink: 0;
}
.sidebar-settings-anchor {
position: relative;
}
.settings-panel--sidebar {
position: absolute;
left: 0;
bottom: calc(100% + 8px);
width: 210px;
max-height: calc(100vh - 96px);
overflow-y: auto;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
}
.settings-panel--bottom {
position: fixed;
/* 설정 버튼이 탭바 오른쪽 끝이므로 오른쪽에 앵커한다 */
right: 8px;
width: 210px;
max-width: calc(100vw - 24px);
bottom: calc(var(--bottom-nav-height) - 5px);
max-height: calc(100vh - 120px);
overflow-y: auto;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
}
.settings-panel-item {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.625rem 0.75rem;
border-radius: var(--radius-lg);
color: var(--color-text-gray-400);
background: none;
border: none;
cursor: pointer;
font-size: var(--text-sm);
font-weight: 700;
text-decoration: none;
text-align: left;
width: 100%;
transition: color var(--transition-normal), background-color var(--transition-normal);
}
.settings-panel-item:hover {
color: var(--color-text-white);
background-color: rgba(255, 255, 255, 0.05);
}
.settings-panel-item.active {
color: var(--color-mint);
}
.settings-panel-item svg {
flex-shrink: 0;
}
.settings-panel-language {
display: flex;
justify-content: flex-start;
padding: 0.375rem 0.75rem;
}
.settings-backdrop {
position: fixed;
inset: 0;
z-index: 55;
}
/* Mobile Bottom Nav */
.bottom-nav {
display: none;
position: fixed;
left: 0;
right: 0;
bottom: 0;
z-index: 50;
height: var(--bottom-nav-height);
padding-bottom: env(safe-area-inset-bottom);
background: var(--color-bg-dark);
border-top: 1px solid var(--color-border-white-5);
}
@media (max-width: 767px) {
.bottom-nav {
display: flex;
}
.has-bottom-nav {
padding-bottom: var(--bottom-nav-height);
}
}
.bottom-nav-item {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 6px;
font-size: 12px;
font-weight: 700;
color: var(--color-text-gray-400);
background: none;
border: none;
cursor: pointer;
}
.bottom-nav-item svg {
width: 24px;
height: 24px;
}
.bottom-nav-item.active {
color: var(--color-mint);
}
+503
View File
@@ -0,0 +1,503 @@
/* =====================================================
Business Settings Components
===================================================== */
/* Settings Container */
.settings-container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 0.75rem;
background-color: var(--color-bg-dark);
color: var(--color-text-white);
overflow: hidden;
}
@media (min-width: 640px) {
.settings-container {
padding: 1rem;
}
}
@media (min-width: 768px) {
.settings-container {
padding: 1.5rem;
}
}
/* Settings Header */
.settings-header {
text-align: center;
margin-bottom: 1rem;
max-width: 42rem;
margin-left: 2.5rem;
}
@media (min-width: 640px) {
.settings-header {
margin-bottom: 1.5rem;
}
}
@media (min-width: 768px) {
.settings-header {
margin-bottom: 2rem;
margin-left: 0;
}
}
.settings-title {
font-size: var(--text-lg);
font-weight: 700;
margin-bottom: 0.25rem;
}
@media (min-width: 640px) {
.settings-title {
font-size: var(--text-xl);
margin-bottom: 0.5rem;
}
}
@media (min-width: 768px) {
.settings-title {
font-size: 24px;
}
}
@media (min-width: 1024px) {
.settings-title {
font-size: var(--text-3xl);
}
}
.settings-description {
color: var(--color-text-gray-400);
font-size: 10px;
font-weight: 300;
line-height: 1.625;
opacity: 0.8;
}
@media (min-width: 640px) {
.settings-description {
font-size: 10px;
}
}
@media (min-width: 768px) {
.settings-description {
font-size: var(--text-xs);
}
}
/* Settings Card */
.settings-card {
width: 100%;
max-width: 36rem;
}
.settings-card-inner {
background-color: var(--color-bg-card);
border-radius: var(--radius-xl);
padding: 0.75rem;
border: 1px solid var(--color-border-white-5);
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
}
@media (min-width: 640px) {
.settings-card-inner {
padding: 1rem;
border-radius: var(--radius-2xl);
}
}
@media (min-width: 768px) {
.settings-card-inner {
padding: 1.5rem;
border-radius: var(--radius-3xl);
}
}
.settings-card-title {
color: var(--color-mint);
font-size: 10px;
font-weight: 700;
margin-bottom: 0.5rem;
letter-spacing: 0.1em;
text-transform: uppercase;
}
@media (min-width: 640px) {
.settings-card-title {
font-size: 10px;
margin-bottom: 0.75rem;
}
}
@media (min-width: 768px) {
.settings-card-title {
font-size: var(--text-xs);
margin-bottom: 1rem;
}
}
/* Social Items */
.social-items {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
@media (min-width: 640px) {
.social-items {
gap: 0.75rem;
}
}
.social-item {
background-color: var(--color-bg-dark);
padding: 0.5rem;
border-radius: var(--radius-lg);
border: 1px solid var(--color-border-white-5);
display: flex;
align-items: center;
justify-content: space-between;
transition: border-color var(--transition-normal);
}
@media (min-width: 640px) {
.social-item {
padding: 0.75rem;
border-radius: var(--radius-xl);
}
}
.social-item:hover {
border-color: var(--color-border-white-10);
}
.social-item-left {
display: flex;
align-items: center;
gap: 0.5rem;
}
@media (min-width: 640px) {
.social-item-left {
gap: 0.75rem;
}
}
.social-item-icon {
width: 1.5rem;
height: 1.5rem;
border-radius: var(--radius-lg);
display: flex;
align-items: center;
justify-content: center;
}
@media (min-width: 640px) {
.social-item-icon {
width: 2rem;
height: 2rem;
}
}
.social-item-icon-inner {
width: 0.75rem;
height: 0.75rem;
}
@media (min-width: 640px) {
.social-item-icon-inner {
width: 1rem;
height: 1rem;
}
}
.social-item-name {
font-size: 10px;
font-weight: 700;
color: var(--color-text-gray-300);
}
@media (min-width: 640px) {
.social-item-name {
font-size: var(--text-xs);
}
}
.social-item-connect {
color: var(--color-mint);
font-size: 10px;
font-weight: 700;
background: none;
border: none;
cursor: pointer;
}
@media (min-width: 640px) {
.social-item-connect {
font-size: 10px;
}
}
.social-item-connect:hover {
text-decoration: underline;
}
/* =====================================================
Footer Component
===================================================== */
/* Landing Footer */
.landing-footer {
width: 100%;
background: var(--Color-teal-800, #002224);
padding: 40px 1.5rem;
}
@media (min-width: 768px) {
.landing-footer {
padding: 48px 5rem;
}
}
@media (min-width: 1024px) {
.landing-footer {
padding: 60px 100px;
}
}
.footer-content {
display: flex;
flex-direction: column;
gap: 2rem;
max-width: 1144px;
margin: 0 auto;
}
@media (min-width: 768px) {
.footer-content {
flex-direction: row;
justify-content: space-between;
align-items: center;
gap: 4rem;
}
}
.footer-left {
min-width: 262px;
display: flex;
flex-direction: column;
gap: 1rem;
}
.footer-logo {
height: 24px;
width: auto;
object-fit: contain;
}
.footer-copyright {
font-size: 14px;
font-weight: 400;
color: #379599;
letter-spacing: -0.006em;
line-height: 1.19;
text-align: center;
}
.footer-links {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
}
.footer-link {
font-size: 14px;
color: #379599;
text-decoration: none;
opacity: 0.8;
}
.footer-link:hover {
opacity: 1;
text-decoration: underline;
}
.footer-link-divider {
font-size: 14px;
color: #379599;
opacity: 0.5;
}
.footer-right {
max-width: 600px;
display: flex;
flex-direction: column;
gap: 4px;
}
.footer-info {
font-size: 12px;
font-weight: 400;
color: #CEE5E6;
letter-spacing: -0.006em;
line-height: 1.19;
}
@media (min-width: 768px) {
.footer-info {
font-size: 14px;
}
}
/* =====================================================
Header Component
===================================================== */
/* Landing Header */
.landing-header {
width: calc(100% - 2rem);
max-width: 1280px;
padding: 12px 12px 12px 24px;
display: flex;
justify-content: space-between;
align-items: center;
position: fixed;
top: 16px;
left: 50%;
transform: translateX(-50%);
z-index: 10100;
background: rgba(0, 34, 36, 0.3);
border: 1px solid rgba(229, 241, 242, 0.2);
border-radius: 999px;
backdrop-filter: blur(40px);
-webkit-backdrop-filter: blur(40px);
}
@media (min-width: 768px) {
.landing-header {
width: calc(100% - 10rem);
}
}
.header-logo {
display: flex;
align-items: center;
height: 16px;
}
.header-logo img {
height: 100%;
width: auto;
object-fit: contain;
}
.header-actions {
display: flex;
align-items: center;
gap: 8px;
}
.header-actions .lang-toggle {
width: auto;
max-width: none;
padding: 2px;
flex-shrink: 0;
}
.header-actions .lang-toggle-option {
padding: 4px 10px;
white-space: nowrap;
}
.header-login-btn {
padding: 10px 24px;
border-radius: 999px;
background-color: #94FBE0;
color: #000000;
font-weight: 600;
font-size: 14px;
border: none;
cursor: pointer;
transition: all var(--transition-normal);
letter-spacing: -0.006em;
line-height: 1.19;
}
.header-login-btn:hover {
background-color: #7fe8cc;
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(148, 251, 224, 0.3);
}
.header-login-btn:active {
transform: scale(0.95);
}
.header-start-btn {
padding: 10px 24px;
border-radius: 999px;
background-color: #AE72F9;
color: #FFFFFF;
font-weight: 600;
font-size: 14px;
border: none;
cursor: pointer;
transition: all var(--transition-normal);
letter-spacing: -0.006em;
line-height: 1.19;
}
.header-start-btn:hover {
background-color: #9B5DE5;
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(174, 114, 249, 0.3);
}
.header-start-btn:active {
transform: scale(0.95);
}
.header-avatar {
width: 2rem;
height: 2rem;
border-radius: var(--radius-full);
overflow: hidden;
border: 1px solid var(--color-border-gray-700);
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
}
@media (min-width: 640px) {
.header-avatar {
width: 2.5rem;
height: 2.5rem;
}
}
.header-avatar img {
width: 100%;
height: 100%;
object-fit: cover;
}
/* =====================================================
Content Safe Area (for Landing Pages)
===================================================== */
.content-safe-area {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+18
View File
@@ -0,0 +1,18 @@
/* CASTAD Design System - 도메인별 CSS 파일 매니페스트 */
@import './tokens.css';
@import './base-components.css';
@import './media-components.css';
@import './generation-flow.css';
@import './landing.css';
@import './dashboard.css';
@import './business-settings.css';
@import './studio-assets.css';
@import './contents-social.css';
@import './modals-overlays.css';
/* 썰박스 UI — 모든 규칙이 .ssul-scope 안에 갇혀 있어 castad 화면에 영향 없음.
ssulbox.css 는 스크립트 생성 파일이므로 직접 수정 금지 (파일 상단 주석 참조).
castad 안에서 새로 만든 화면의 스타일은 ssulbox-castad.css 에 둔다. */
@import './ssulbox.css';
@import './ssulbox-castad.css';
File diff suppressed because it is too large. Load diff
+593
View File
@@ -0,0 +1,593 @@
/* =====================================================
Player Components
===================================================== */
/* Player Bar */
.player-bar {
background-color: rgba(0, 0, 0, 0.4);
border-radius: var(--radius-full);
padding: 0.75rem;
display: flex;
align-items: center;
gap: 0.75rem;
flex-shrink: 0;
}
/* Play Button */
.play-btn {
color: var(--color-mint);
flex-shrink: 0;
transition: transform var(--transition-normal);
background: none;
border: none;
cursor: pointer;
padding: 0;
}
.play-btn:hover {
transform: scale(1.1);
}
.play-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Progress Bar */
.progress-bar-container {
flex: 1;
height: 0.375rem;
background-color: #1f2937;
border-radius: var(--radius-full);
position: relative;
cursor: pointer;
}
.progress-bar-container:disabled,
.progress-bar-container.disabled {
cursor: not-allowed;
opacity: 0.5;
}
.progress-bar-fill {
position: absolute;
left: 0;
top: 0;
height: 100%;
background-color: var(--color-mint);
border-radius: var(--radius-full);
}
.progress-bar-thumb {
position: absolute;
top: 50%;
transform: translateY(-50%) translateX(-50%);
display: flex;
align-items: center;
justify-content: center;
pointer-events: none;
}
.progress-bar-thumb-glow {
position: absolute;
width: 1rem;
height: 1rem;
background-color: var(--color-mint);
border-radius: var(--radius-full);
opacity: 0.2;
animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
.progress-bar-thumb-dot {
width: 0.75rem;
height: 0.75rem;
background-color: var(--color-mint);
border-radius: var(--radius-full);
box-shadow: var(--shadow-mint-glow);
border: 1px solid rgba(18, 26, 29, 0.2);
}
/* Time Display */
.time-display {
font-size: var(--text-sm);
color: var(--color-text-gray-500);
font-family: monospace;
text-align: right;
white-space: nowrap;
}
/* =====================================================
Image Grid Components
===================================================== */
/* Image Grid */
.image-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 0.75rem;
}
.image-grid-4 {
grid-template-columns: repeat(4, 1fr);
gap: 0.5rem;
}
/* Image Item */
.image-item {
aspect-ratio: 1;
background-color: rgba(18, 26, 29, 0.5);
border-radius: var(--radius-xl);
border: 1px solid var(--color-border-white-5);
position: relative;
overflow: hidden;
}
.image-item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.image-item-badge {
position: absolute;
top: 0.5rem;
left: 0.5rem;
padding: 0.25rem 0.5rem;
background-color: var(--color-purple-80);
border-radius: 0.25rem;
font-size: var(--text-xs);
color: var(--color-text-white);
font-weight: 500;
}
.image-item-remove {
position: absolute;
top: 0.5rem;
right: 0.5rem;
width: 1.75rem;
height: 1.75rem;
background-color: rgba(0, 0, 0, 0.6);
border-radius: var(--radius-full);
display: flex;
align-items: center;
justify-content: center;
color: rgba(255, 255, 255, 0.7);
border: none;
cursor: pointer;
transition: all var(--transition-normal);
}
.image-item-remove:hover {
background-color: rgba(239, 68, 68, 0.8);
color: var(--color-text-white);
}
/* =====================================================
Upload Components
===================================================== */
/* Upload Zone */
.upload-zone {
flex: 1;
border: 2px dashed var(--color-border-gray-600);
border-radius: var(--radius-2xl);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 1.5rem;
text-align: center;
cursor: pointer;
transition: border-color var(--transition-normal);
}
.upload-zone:hover {
border-color: rgba(166, 255, 234, 0.5);
}
.upload-zone-icon {
margin-bottom: 1rem;
color: var(--color-text-gray-500);
transition: color var(--transition-normal);
}
.upload-zone:hover .upload-zone-icon {
color: var(--color-mint);
}
.upload-zone-title {
color: var(--color-text-gray-300);
font-size: var(--text-base);
font-weight: 500;
line-height: 1.625;
margin-bottom: 0.5rem;
}
.upload-zone-subtitle {
color: var(--color-text-gray-500);
font-size: var(--text-sm);
}
/* =====================================================
Tag Components
===================================================== */
/* Tag */
.tag {
padding: 0.625rem 1.25rem;
background-color: var(--color-bg-card-inner);
border-radius: var(--radius-full);
font-size: var(--text-base);
color: #e5e7eb;
border: 1px solid var(--color-border-white-10);
}
/* Tag with Dot */
.tag-dot {
display: flex;
align-items: center;
gap: 0.5rem;
font-size: var(--text-sm);
color: var(--color-text-gray-400);
}
.tag-dot::before {
content: '';
width: 0.375rem;
height: 0.375rem;
border-radius: var(--radius-full);
background-color: var(--color-mint);
}
/* =====================================================
Social Card Components
===================================================== */
/* Social Card */
.social-card {
display: flex;
align-items: center;
gap: 1rem;
background-color: var(--color-bg-dark);
padding: 1rem;
border-radius: var(--radius-2xl);
border: 1px solid var(--color-border-white-5);
transition: all var(--transition-normal);
cursor: pointer;
}
.social-card:hover {
border-color: var(--color-border-white-10);
}
.social-card.selected {
border-color: var(--color-mint);
box-shadow: 0 0 15px rgba(166, 255, 234, 0.15);
background-color: var(--color-bg-card);
}
.social-icon {
width: 2.5rem;
height: 2.5rem;
border-radius: var(--radius-xl);
display: flex;
align-items: center;
justify-content: center;
position: relative;
transition: transform var(--transition-slow);
}
.social-icon-inner {
width: 1.5rem;
height: 1.5rem;
color: var(--color-text-white);
}
.social-check {
position: absolute;
top: -0.25rem;
right: -0.25rem;
width: 1.25rem;
height: 1.25rem;
background-color: var(--color-mint);
border-radius: var(--radius-full);
display: flex;
align-items: center;
justify-content: center;
color: var(--color-bg-dark);
border: 2px solid var(--color-bg-dark);
}
.social-name {
font-size: var(--text-base);
font-weight: 700;
transition: color var(--transition-normal);
}
.social-card.selected .social-name {
color: var(--color-text-white);
}
.social-card:not(.selected) .social-name {
color: var(--color-text-gray-300);
}
.social-email {
margin-left: auto;
font-size: var(--text-sm);
color: var(--color-purple);
}
/* =====================================================
Video Preview Components
===================================================== */
/* Video Container */
.video-container {
flex: 1;
background-color: #000;
border-radius: var(--radius-2xl);
position: relative;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
min-height: 200px;
}
.video-pattern {
position: absolute;
inset: 0;
opacity: 0.1;
background-image:
linear-gradient(45deg, var(--color-bg-dark) 25%, transparent 25%),
linear-gradient(-45deg, var(--color-bg-dark) 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, var(--color-bg-dark) 75%),
linear-gradient(-45deg, transparent 75%, var(--color-bg-dark) 75%);
background-size: 40px 40px;
background-position: 0 0, 0 20px, 20px -20px, -20px 0px;
}
.video-controls {
position: absolute;
bottom: 1rem;
left: 1rem;
right: 1rem;
z-index: 10;
}
.video-controls-inner {
display: flex;
align-items: center;
gap: 0.75rem;
}
.video-play-btn {
color: var(--color-text-white);
background: none;
border: none;
cursor: pointer;
transition: color var(--transition-normal);
}
.video-play-btn:hover {
color: var(--color-mint);
}
.video-progress {
flex: 1;
height: 0.375rem;
background-color: rgba(255, 255, 255, 0.2);
border-radius: var(--radius-full);
overflow: hidden;
}
.video-progress-fill {
height: 100%;
background-color: var(--color-mint);
}
/* Video Player */
.video-player {
width: 100%;
height: 100%;
object-fit: contain;
cursor: pointer;
}
/* Video Loading State */
.video-loading {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 2rem;
text-align: center;
}
/* Video Error State */
.video-error {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 2rem;
text-align: center;
}
.video-error svg {
width: 4rem;
height: 4rem;
color: #ef4444;
margin-bottom: 1rem;
}
/* Social Card Disabled State */
.social-card.disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* =====================================================
Tags Container
===================================================== */
.tags-container {
margin-top: 1rem;
background-color: rgba(18, 26, 29, 0.6);
border-radius: var(--radius-xl);
padding: 0.75rem 1rem;
display: flex;
flex-wrap: wrap;
gap: 1rem;
justify-content: center;
border: 1px solid var(--color-border-white-5);
flex-shrink: 0;
}
/* =====================================================
Status Messages
===================================================== */
/* Error Message */
.error-message {
margin-top: 1rem;
padding: 0.75rem;
background-color: rgba(239, 68, 68, 0.1);
border: 1px solid rgba(239, 68, 68, 0.3);
border-radius: var(--radius-xl);
color: #f87171;
font-size: var(--text-sm);
flex-shrink: 0;
}
/* Status Message */
.status-message {
margin-top: 1rem;
padding: 0.75rem;
background-color: var(--color-mint-10);
border: 1px solid var(--color-mint-30);
border-radius: var(--radius-xl);
color: var(--color-mint);
font-size: var(--text-sm);
display: flex;
align-items: center;
gap: 0.5rem;
flex-shrink: 0;
}
/* =====================================================
Utility Classes
===================================================== */
/* Flex utilities */
.flex-center {
display: flex;
align-items: center;
justify-content: center;
}
.flex-between {
display: flex;
align-items: center;
justify-content: space-between;
}
.flex-col {
display: flex;
flex-direction: column;
}
.flex-1 {
flex: 1;
}
.flex-2 {
flex: 2;
}
.shrink-0 {
flex-shrink: 0;
}
.min-h-0 {
min-height: 0;
}
/* Gap utilities */
.gap-2 { gap: 0.5rem; }
.gap-3 { gap: 0.75rem; }
.gap-4 { gap: 1rem; }
.gap-6 { gap: 1.5rem; }
/* Margin utilities */
.mb-1 { margin-bottom: 0.25rem; }
.mb-2 { margin-bottom: 0.5rem; }
.mb-3 { margin-bottom: 0.75rem; }
.mb-4 { margin-bottom: 1rem; }
.mb-6 { margin-bottom: 1.5rem; }
.mt-4 { margin-top: 1rem; }
.mt-6 { margin-top: 1.5rem; }
/* Text utilities */
.text-center { text-align: center; }
.text-right { text-align: right; }
.font-bold { font-weight: 700; }
.font-medium { font-weight: 500; }
/* Overflow utilities */
.overflow-hidden { overflow: hidden; }
.overflow-y-auto { overflow-y: auto; }
/* Width utilities */
.w-full { width: 100%; }
/* Animation */
@keyframes pulse {
0%, 100% { opacity: 0.2; }
50% { opacity: 0.4; }
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.animate-spin {
animation: spin 1s linear infinite;
}
.animate-pulse {
animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
/* Grid utilities */
.grid-cols-3 {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
/* Space utilities */
.space-y-4 > * + * {
margin-top: 1rem;
}
.space-y-5 > * + * {
margin-top: 1.25rem;
}
/* Min width */
.min-w-280 {
min-width: 280px;
}
/* Scrollbar utility */
.scrollbar-hide {
scrollbar-width: none;
-ms-overflow-style: none;
}
.scrollbar-hide::-webkit-scrollbar {
display: none;
}
File diff suppressed because it is too large. Load diff
+504
View File
@@ -0,0 +1,504 @@
/* =====================================================
썰박스 — castad 통합용 신규 컴포넌트 스타일
ssulbox.css 는 원본에서 스크립트로 변환한 파일이라 직접 수정하지 않는다.
castad 안에서 새로 만든 화면(SsulCreateForm 등)의 스타일은 여기에 둔다.
모든 규칙은 원본과 동일하게 `.ssul-scope` 안에 가둔다.
===================================================== */
/* ssulbox.css 의 `.ssul-scope` 는 원본에서 전체 화면 셸(`#app`)이었던 탓에
`overflow: hidden` 을 갖는다. castad 안에서는 셸이 아니라 폼·화면 컨테이너로
쓰므로 그 클리핑이 **요소 바깥으로 그려지는 것들을 잘라 먹는다** —
선택 카드의 링(테두리 바깥 1px)이 좌우에서 잘리고, 버튼 hover 글로우도 잘린다.
생성물 파일은 직접 고치지 않으므로 여기서 되돌린다(0,2,0 이라 이긴다). */
.ssul-scope.ssul-create,
.ssul-scope.ssul-making {
overflow: visible;
}
/* ── 생성 폼 ─────────────────────────────────────── */
.ssul-scope.ssul-create {
width: 100%;
display: flex;
flex-direction: column;
color: var(--color-text-white);
}
.ssul-create__step {
align-self: flex-start;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.04em;
color: var(--color-ssul-accent);
margin-bottom: 10px;
}
/* 2단계 라벨. 강조를 1단계에만 두어 시선 순서를 만든다 */
.ssul-create__step.muted {
font-weight: 600;
color: var(--color-text-gray-400);
}
/* ── 시나리오 2x2 그리드 ─────────────────────────── */
.ssul-create__scenarios {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
width: 100%;
margin-bottom: 22px;
}
.ssul-scn {
position: relative;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 5px;
padding: 14px 12px;
/* 테두리 두께는 모든 상태에서 1px 로 고정한다. 선택 시 굵기를 바꾸면
border-box 안쪽 폭이 줄어 글자가 흔들린다 — 굵기는 box-shadow 링으로 더한다 */
border: 1px solid var(--color-border-white-10);
border-radius: 14px;
background: var(--color-bg-card);
color: inherit;
font-family: inherit;
text-align: left;
cursor: pointer;
overflow: hidden;
transition: border-color var(--transition-normal), transform var(--transition-normal);
}
/* 시나리오 표지 그라디언트를 옅게 깐다.
--scn / --scn-a / --scn-b 는 컴포넌트가 인라인으로 넘긴다. */
.ssul-scn::before {
content: '';
position: absolute;
inset: 0;
background: linear-gradient(150deg, var(--scn-a), var(--scn-b));
/* 비선택은 눌러 둔다 — 채도까지 낮춰야 선택 카드와 확실히 갈린다 */
opacity: 0.22;
filter: saturate(0.75);
pointer-events: none;
transition: opacity var(--transition-normal), filter var(--transition-normal);
}
/* 선택한 카드는 채도·명도를 함께 올린다.
불투명도만 올리면 어두운 배경과 섞여 오히려 탁해지므로 filter 로 직접 올린다. */
.ssul-scn.active::before {
opacity: 0.72;
filter: saturate(1.55) brightness(1.18);
}
.ssul-scn:hover {
border-color: rgba(255, 255, 255, 0.25);
transform: translateY(-1px);
}
/* 선택 표시는 밝은 중립색 테두리로 둔다.
앰버(썰박스 강조색)를 쓰면 시나리오마다 다른 표지색과 부딪힌다 —
특히 삼국지(적)·오디세이(청) 위에서 탁해진다. */
.ssul-scn.active {
border-color: var(--color-mint);
/* 링을 **테두리와 같은 색**으로 둔다. 색이 다르면 안쪽 테두리와 바깥 링이
갈라져 두 줄로 보인다. 같은 색이면 1px 테두리 + 1px 링이 이어져
2px 한 줄로 읽히고, 테두리 두께를 바꾸지 않아 글자도 흔들리지 않는다.
마지막 그림자만 시나리오 대표색 글로우. */
box-shadow:
0 0 0 1px var(--color-mint),
0 0 20px -2px var(--scn);
}
/* 표지가 밝아진 만큼 설명 글자도 올려 대비를 지킨다 */
.ssul-scn.active .ssul-scn__desc {
color: rgba(255, 255, 255, 0.92);
}
.ssul-scn__emoji {
position: relative;
font-size: 22px;
}
.ssul-scn__name {
position: relative;
font-size: 14px;
font-weight: 700;
}
.ssul-scn__desc {
position: relative;
font-size: 12px;
line-height: 1.4;
color: var(--color-text-gray-400);
}
/* ── 업장 검색 (ADO2 식 자동완성) ─────────────────── */
/* position: relative 는 드롭다운(.ssul-places)의 기준점이다 */
.ssul-create__search {
position: relative;
display: flex;
gap: 8px;
width: 100%;
margin-bottom: 10px;
}
.ssul-create__input {
flex: 1;
min-width: 0;
min-height: 46px;
padding: 8px 16px;
border: none;
border-radius: 999px;
background: #fff;
color: #1f2937;
font-family: inherit;
font-size: 14px;
font-weight: 600;
letter-spacing: -0.006em;
}
.ssul-create__input::placeholder {
color: #9ca3af;
font-weight: 500;
}
.ssul-create__search-btn {
flex: none;
padding: 0 18px;
border: 1px solid var(--color-border-white-10);
border-radius: 999px;
background: var(--color-bg-card-inner);
color: var(--color-text-white);
font-family: inherit;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: opacity var(--transition-normal);
}
.ssul-create__search-btn:disabled {
opacity: 0.4;
cursor: default;
}
/* ── 검색 결과 / 선택 / 안내 ─────────────────────── */
/* 입력창 아래로 겹쳐 뜨는 자동완성 드롭다운.
문서 흐름에 넣으면 타이핑할 때마다 아래 요소(비용·버튼)가 밀려 흔들린다. */
.ssul-places {
position: absolute;
top: calc(100% + 6px);
left: 0;
right: 0;
z-index: 20;
max-height: 260px;
overflow-y: auto;
margin: 0;
padding: 0;
list-style: none;
border: 1px solid var(--color-border-white-10);
border-radius: 12px;
background: var(--color-bg-card);
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.45);
}
.ssul-places li + li {
border-top: 1px solid var(--color-border-white-10);
}
.ssul-places button {
display: flex;
flex-direction: column;
gap: 3px;
width: 100%;
padding: 11px 14px;
border: none;
background: var(--color-bg-card);
color: inherit;
font-family: inherit;
text-align: left;
cursor: pointer;
}
.ssul-places button:hover {
background: var(--color-bg-card-inner);
}
.ssul-places b {
font-size: 14px;
font-weight: 700;
}
.ssul-places span {
font-size: 12px;
color: var(--color-text-gray-400);
}
.ssul-picked {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
padding: 11px 14px;
margin-bottom: 14px;
border: 1.5px solid var(--color-ssul-accent);
border-radius: 12px;
background: rgba(255, 184, 107, 0.08);
}
.ssul-picked__body {
display: flex;
flex-direction: column;
gap: 3px;
min-width: 0;
flex: 1;
}
.ssul-picked__body b {
font-size: 14px;
font-weight: 700;
}
.ssul-picked__body span {
font-size: 12px;
color: var(--color-text-gray-400);
}
.ssul-hint {
width: 100%;
padding: 10px 14px;
margin-bottom: 14px;
border-radius: 12px;
background: var(--color-bg-card-inner);
font-size: 12px;
line-height: 1.5;
color: var(--color-text-gray-300);
}
.ssul-hint.ok {
color: var(--color-mint);
}
/* 시나리오 확인 안내 — 앞에 점을 찍어 상태 표시임을 드러낸다 */
.ssul-hint.dot {
display: flex;
align-items: center;
gap: 8px;
color: var(--color-text-gray-300);
}
.ssul-hint.dot::before {
content: '';
flex: none;
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--color-ssul-accent);
}
.ssul-hint.warn {
color: #ffb4a8;
}
/* ── 비용 고지 + 제출 ────────────────────────────── */
.ssul-create__cost {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
padding: 10px 4px;
font-size: 12px;
color: var(--color-text-gray-400);
}
.ssul-create__cost-badge {
display: inline-flex;
align-items: center;
gap: 5px;
font-weight: 700;
color: var(--color-ssul-accent);
}
.ssul-create__coin {
font-size: 14px;
line-height: 1;
}
.ssul-create__submit {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 48px;
border: none;
border-radius: 999px;
background: linear-gradient(90deg, #ff8a5c, var(--color-ssul-accent));
color: #1a1200;
font-family: inherit;
font-size: 16px;
font-weight: 800;
cursor: pointer;
transition: filter var(--transition-normal), box-shadow var(--transition-normal);
}
.ssul-create__submit:hover:not(:disabled) {
filter: brightness(1.08);
box-shadow: 0 4px 28px rgba(255, 180, 90, 0.4);
}
.ssul-create__submit:disabled {
opacity: 0.4;
cursor: default;
}
/* ── 생성 진행 화면 ──────────────────────────────── */
.ssul-scope.ssul-making {
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
max-width: 420px;
/* ssulbox.css 의 베이스 `.ssul-scope { height:100% }` (원본 전체화면 셸 규칙)가
여기까지 상속되어 이 박스 자체가 부모 높이를 꽉 채워버린다. 그러면 아래
margin:auto 가 나눠 가질 여유 공간이 0 이 되어 컨텐츠가 위로 쏠린다.
height:auto 로 되돌려 컨텐츠 크기만큼만 차지하게 해야 margin:auto 가 뜻대로
작동한다(부모 .wizard-page-container 가 height:100% flex column). */
height: auto;
/* `0 auto` 면 수평만 중앙이라 스텝퍼 바로 아래에 붙고 세로 여백이 전부
아래로 몰린다. `auto` 는 상하 여백도 균등 분배해 스텝퍼~바닥 사이
중앙에 놓인다. */
margin: auto;
padding: 48px 20px;
text-align: center;
gap: 10px;
color: var(--color-text-white);
}
.ssul-making__scenario {
font-size: 20px;
font-weight: 700;
}
.ssul-making__title {
margin: 0 0 24px;
font-size: 24px;
font-weight: 700;
letter-spacing: -0.015em;
}
.ssul-making__title.warn {
color: #ffb4a8;
}
/* 진행 스피너 — 원본 LoadingSection 의 회전 요소만 가져왔다.
SVG(loading-spinner.svg)를 쓰지 않은 이유: 색이 민트로 하드코딩돼 있어
시나리오 대표색(삼국지=적, 오디세이=청)과 부딪힌다. CSS 로 그리면 --scn 을 받는다.
`spin` 키프레임은 castad 전역에 이미 있어 재사용한다(새로 만들면 3번째 중복). */
.ssul-making__spinner {
position: relative;
flex: none;
width: 150px;
height: 150px;
margin: 4px 0 26px;
}
/* 트랙(전체 원) */
.ssul-making__spinner::before {
content: '';
position: absolute;
inset: 0;
border-radius: 50%;
border: 7px solid var(--color-border-white-10);
}
/* 회전하는 호 — 3/4 만 칠해 원본 SVG 의 형태를 따른다 */
.ssul-making__spinner::after {
content: '';
position: absolute;
inset: 0;
border-radius: 50%;
border: 7px solid transparent;
border-top-color: var(--scn);
border-right-color: var(--scn);
border-bottom-color: var(--scn);
animation: spin 1.1s linear infinite;
}
.ssul-making__bar {
width: 100%;
height: 6px;
border-radius: 999px;
margin-top: 20px;
background: var(--color-bg-card-inner);
overflow: hidden;
}
.ssul-making__fill {
height: 100%;
border-radius: 999px;
transition: width 400ms ease;
}
.ssul-making__meta {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
margin-top: 10px;
font-size: 16px;
color: var(--color-text-gray-300);
}
.ssul-making__pct {
font-variant-numeric: tabular-nums;
font-weight: 700;
}
.ssul-making__desc {
margin: 22px 0 0;
font-size: 14px;
line-height: 1.6;
color: var(--color-text-gray-400);
}
.ssul-making__refund {
margin: 8px 0 0;
font-size: 14px;
color: var(--color-mint);
}
.ssul-making__btn {
margin-top: 28px;
padding: 12px 24px;
border: 1px solid var(--color-border-white-10);
border-radius: 999px;
background: var(--color-bg-card);
color: var(--color-text-white);
font-family: inherit;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: border-color var(--transition-normal);
}
.ssul-making__btn:hover {
border-color: rgba(255, 255, 255, 0.3);
}
/* 진행바·스피너 애니메이션은 모션 민감 사용자에게 끈다.
스피너는 회전을 멈추면 3/4 호가 그대로 남아 정적 표시로 읽힌다. */
@media (prefers-reduced-motion: reduce) {
.ssul-making__fill {
transition: none;
}
.ssul-making__spinner::after {
animation: none;
}
}
/* 썰박스 뷰어 전용 스타일은 두지 않는다 —
SsulViewerModal 이 castad `video-detail-*` 클래스를 그대로 재사용해
통합 목록에서 어떤 카드를 열든 같은 모양이 나오게 했다. */
/* 결과 화면 스타일은 없다 — SsulResultContent 가 ADO2 완료 화면과 같은
`CompletionView`(comp2-* 클래스)를 쓴다(2026-08-10 통일). */
+571
View File
@@ -0,0 +1,571 @@
/* =====================================================
썰박스 UI — 원본(o2o-ssulbox/frontend/src/index.css)에서 스코프 변환
**이 파일은 스크립트로 생성됐다.** 직접 고치지 말고
scratchpad/scope_ssulbox_css.py 를 고쳐 다시 생성할 것.
변환 내용:
1. @import "tailwindcss" 삭제 (castad 는 index.html 의 Play CDN 사용)
2. #app → .ssul-scope, 100dvh → 100%
3. 모든 최상위 셀렉터에 .ssul-scope 접두
4. 전역 리셋(*, html, body, button, img, ul)을 .ssul-scope 하위로
← 이게 빠지면 castad 전 화면의 버튼·이미지·폰트가 깨진다
5. html,body{height:100%} 삭제
6. :root 변수 → .ssul-scope 로 이동, 값은 castad 다크 팔레트로 매핑
7. .nav* .topbar .brand .login* 삭제 (castad Sidebar/카카오가 대체)
8. --nav-h/--top-h → 0 (셸이 없으므로)
9. .grid → .ssul-grid (Tailwind CDN 의 .grid 와 충돌 회피)
10. font-family 미지정 → castad Noto Sans KR 상속
===================================================== */
/* castad 다크 팔레트로 매핑한 썰박스 변수.
원본은 라이트 테마 기본이었으나 castad 대시보드는 다크 단일이다. */
.ssul-scope {
--bg: var(--color-bg-darker);
--surface: var(--color-bg-card);
--surface-2: var(--color-bg-card-inner);
--fg: var(--color-text-white);
--muted: var(--color-text-gray-400);
--faint: var(--color-text-gray-500);
--border: var(--color-border-white-10);
--elev: 0 2px 16px rgba(0, 0, 0, 0.6);
/* 시나리오 색 (원본 유지) */
--joseon: #3b4cc0;
--samgukji: #d63a2f;
--greek: #0a8f6b;
--greek-2: #e0a91b;
--odyssey: #6d4aff;
--ig: linear-gradient(45deg, #f9a03f 0%, #e6683c 25%, #dc2743 50%, #cc2366 75%, #bc1888 100%);
/* 셸(하단 네비·상단바)이 castad 에는 없으므로 0 */
--nav-h: 0px;
--top-h: 0px;
--r: 14px;
}
/* 원본의 전역 리셋 — 스코프 안으로 가둔다.
요소 리셋은 `:where()` 로 감싸 **특정도를 0 으로** 만든다.
그러지 않으면 `.ssul-scope button`(0,1,1)이 우리 컴포넌트의 BEM
클래스(`.ssul-create__submit` 등 0,1,0)를 임포트 순서와 무관하게 이겨
버튼 배경·테두리가 통째로 사라진다(2026-07-29 실제 발생).
리셋의 목적(클래스 없는 원본 마크업 정규화)은 그대로 유지된다. */
.ssul-scope,
.ssul-scope * {
box-sizing: border-box;
-webkit-tap-highlight-color: transparent;
}
:where(.ssul-scope) :where(button) {
font: inherit;
color: inherit;
background: none;
border: none;
cursor: pointer;
}
:where(.ssul-scope) :where(img) {
display: block;
max-width: 100%;
}
:where(.ssul-scope) :where(ul) {
list-style: none;
}
:where(.ssul-scope) :where(button) {font:inherit;color:inherit;background:none;border:none;cursor:pointer}
:where(.ssul-scope) :where(img) {display:block;max-width:100%}
:where(.ssul-scope) :where(ul) {list-style:none}
.ssul-scope {position:relative;
width:100%;
height:100%;
background:var(--bg);
display:flex;flex-direction:column;
overflow:hidden;}
.ssul-scope .main {flex:1 1 auto;display:flex;flex-direction:column;min-height:0;min-width:0;position:relative}
.ssul-scope .screen {flex:1 1 auto;overflow-y:auto;overflow-x:hidden;
-webkit-overflow-scrolling:touch;
padding-bottom:calc(var(--nav-h) + env(safe-area-inset-bottom) + 8px);}
.ssul-scope .screen::-webkit-scrollbar {width:0}
.ssul-scope .ssul-grid {display:grid;grid-template-columns:1fr 1fr;gap:8px;padding:10px}
.ssul-scope .card {position:relative;aspect-ratio:9/16;border-radius:var(--r);overflow:hidden;
background:#222;isolation:isolate;transition:transform .12s ease;}
.ssul-scope .card:active {transform:scale(.975)}
.ssul-scope .card .cover {position:absolute;inset:0;display:grid;place-items:center}
.ssul-scope .card .cov-vid {position:absolute;inset:0;width:100%;height:100%;object-fit:cover}
.ssul-scope .card .emoji {font-size:58px;filter:drop-shadow(0 3px 8px rgba(0,0,0,.35));opacity:.92}
.ssul-scope .card .shade {position:absolute;inset:0;background:linear-gradient(180deg,rgba(0,0,0,0) 42%,rgba(0,0,0,.72) 100%)}
.ssul-scope .card .meta {position:absolute;left:9px;right:9px;bottom:8px;z-index:2}
.ssul-scope .card .title {color:#fff;font-size:12px;font-weight:700;line-height:1.28;
display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;
text-shadow:0 1px 3px rgba(0,0,0,.5);}
.ssul-scope .card .sub {display:flex;align-items:center;gap:4px;margin-top:5px;color:rgba(255,255,255,.9);font-size:12px;font-variant-numeric:tabular-nums}
.ssul-scope .card .sub svg {width:12px;height:12px;fill:currentColor}
.ssul-scope .badge {position:absolute;top:8px;left:8px;z-index:2;
display:inline-flex;align-items:center;gap:4px;
padding:3px 8px;border-radius:999px;
font-size:10px;font-weight:700;color:#fff;
background:rgba(0,0,0,.32);backdrop-filter:blur(3px);}
.ssul-scope .badge i {width:7px;height:7px;border-radius:50%;display:inline-block}
.ssul-scope .play-fab {position:absolute;top:8px;right:8px;z-index:2;width:24px;height:24px;border-radius:50%;
background:rgba(0,0,0,.35);backdrop-filter:blur(3px);display:grid;place-items:center}
.ssul-scope .play-fab svg {width:12px;height:12px;fill:#fff;margin-left:1px}
.ssul-scope .sec-h {display:flex;align-items:baseline;justify-content:space-between;padding:16px 14px 4px}
.ssul-scope .sec-h h3 {font-size:16px;font-weight:800;letter-spacing:-.01em}
.ssul-scope .sec-h span {font-size:12px;color:var(--muted)}
.ssul-scope .searchbar {position:sticky;top:0;z-index:4;background:var(--bg);padding:10px 12px;border-bottom:1px solid var(--border)}
.ssul-scope .searchbox {display:flex;align-items:center;gap:8px;background:var(--surface-2);border-radius:11px;padding:9px 12px}
.ssul-scope .searchbox svg {width:16px;height:16px;fill:none;stroke:var(--muted);stroke-width:2;flex:0 0 auto}
.ssul-scope .searchbox input {flex:1;background:none;border:none;outline:none;color:var(--fg);font-size:14px}
.ssul-scope .searchbox input::placeholder {color:var(--faint)}
.ssul-scope .chips {display:flex;gap:8px;overflow-x:auto;padding:10px 12px;scrollbar-width:none}
.ssul-scope .chips::-webkit-scrollbar {display:none}
.ssul-scope .chip {flex:0 0 auto;padding:7px 13px;border-radius:999px;background:var(--surface-2);
font-size:14px;font-weight:600;color:var(--muted);border:1px solid transparent;transition:.15s}
.ssul-scope .chip[aria-pressed="true"] {background:var(--fg);color:var(--bg)}
.ssul-scope .empty {padding:60px 24px;text-align:center;color:var(--muted);font-size:14px;line-height:1.6}
.ssul-scope .profile {padding:20px 16px 6px}
.ssul-scope .profile .row {display:flex;align-items:center;gap:18px}
.ssul-scope .avatar {width:74px;height:74px;border-radius:50%;flex:0 0 auto;display:grid;place-items:center;overflow:hidden;
color:#fff;font-size:30px;font-weight:800;background:var(--ig)}
.ssul-scope .avatar img {width:100%;height:100%;object-fit:cover;display:block}
.ssul-scope .avatar.lg {width:92px;height:92px;font-size:38px}
.ssul-scope .stats {flex:1;display:flex;justify-content:space-around;text-align:center}
.ssul-scope .stats b {display:block;font-size:18px;font-weight:800;font-variant-numeric:tabular-nums}
.ssul-scope .stats span {font-size:12px;color:var(--muted)}
.ssul-scope .bio {margin-top:12px}
.ssul-scope .bio .name {font-weight:700;font-size:14px}
.ssul-scope .bio .bio-txt {font-size:14px;color:var(--fg);margin-top:3px;line-height:1.45;white-space:pre-wrap}
.ssul-scope .bio .bio-txt.muted {color:var(--faint)}
.ssul-scope .pe-avatar {display:flex;flex-direction:column;align-items:center;gap:10px;padding:6px 0 14px}
.ssul-scope .pe-av-btns {display:flex;gap:8px}
.ssul-scope .pe-av-btns button {font-size:14px;font-weight:700;color:var(--samgukji);padding:6px 12px;border-radius:9px;background:var(--surface-2)}
.ssul-scope .pe-av-btns button.rm {color:var(--muted)}
.ssul-scope .pe-bio {width:100%;background:var(--surface-2);border:1px solid var(--border);border-radius:12px;padding:11px 13px;
color:var(--fg);outline:none;font-size:14px;resize:none;line-height:1.5}
.ssul-scope .pe-bio:focus {border-color:var(--samgukji)}
.ssul-scope .token-card {display:flex;align-items:center;justify-content:space-between;gap:12px;
margin:14px 0 2px;padding:14px 16px;border-radius:14px;border:1px solid var(--border);
background:linear-gradient(135deg,rgba(220,39,67,.06),rgba(188,24,136,.06))}
.ssul-scope .token-card .tk-left {display:flex;flex-direction:column;gap:1px;min-width:0}
.ssul-scope .token-card .tk-left span {font-size:12px;color:var(--muted);font-weight:600}
.ssul-scope .token-card .tk-left b {font-size:24px;font-weight:800;font-variant-numeric:tabular-nums;line-height:1.15}
.ssul-scope .token-card .tk-left em {font-size:12px;color:var(--muted);font-style:normal;margin-top:2px}
.ssul-scope .token-card .tk-btn {flex:0 0 auto;padding:11px 20px;border-radius:11px;color:#fff;font-weight:800;font-size:14px;
background:var(--ig);box-shadow:0 4px 12px rgba(220,39,67,.28)}
.ssul-scope .pf-actions {display:flex;gap:8px;margin:12px 0 4px}
.ssul-scope .pf-actions button {flex:1;padding:8px;border-radius:9px;background:var(--surface-2);font-size:14px;font-weight:700}
.ssul-scope .pf-tabs {display:flex;border-top:1px solid var(--border);margin-top:12px}
.ssul-scope .pf-tabs button {flex:1;padding:11px;display:grid;place-items:center;color:var(--faint);border-bottom:2px solid transparent}
.ssul-scope .pf-tabs button[aria-selected="true"] {color:var(--fg);border-bottom-color:var(--fg)}
.ssul-scope .pf-tabs svg {width:22px;height:22px;fill:currentColor}
.ssul-scope .scrim {position:absolute;inset:0;z-index:40;background:rgba(0,0,0,.5);opacity:0;pointer-events:none;transition:opacity .22s}
.ssul-scope .scrim.on {opacity:1;pointer-events:auto}
.ssul-scope .sheet {position:absolute;left:0;right:0;bottom:0;z-index:50;
background:var(--surface);border-radius:22px 22px 0 0;
transform:translateY(101%);transition:transform .28s cubic-bezier(.22,1,.36,1);
max-height:92%;display:flex;flex-direction:column;
padding-bottom:env(safe-area-inset-bottom);
box-shadow:0 -8px 40px rgba(0,0,0,.35);
pointer-events:none;}
.ssul-scope .sheet.on {transform:translateY(0);pointer-events:auto}
.ssul-scope .sheet .grab {width:38px;height:4px;border-radius:2px;background:var(--faint);margin:9px auto 4px}
.ssul-scope .sheet-h {display:flex;align-items:center;justify-content:space-between;padding:6px 16px 10px;border-bottom:1px solid var(--border)}
.ssul-scope .sheet-h h3 {font-size:18px;font-weight:800}
.ssul-scope .sheet-h button {color:var(--muted);font-size:22px;line-height:1;padding:4px}
.ssul-scope .sheet-body {overflow-y:auto;padding:16px}
.ssul-scope .step-label {font-size:14px;font-weight:700;color:var(--muted);margin:2px 2px 10px}
.ssul-scope .step-label b {color:var(--fg)}
.ssul-scope .scn-list {display:flex;flex-direction:column;gap:10px}
.ssul-scope .scn {display:flex;align-items:center;gap:14px;padding:14px;border-radius:16px;
border:1.5px solid var(--border);background:var(--surface);text-align:left;transition:.14s;width:100%;}
.ssul-scope .scn:active {transform:scale(.99)}
.ssul-scope .scn[aria-pressed="true"] {border-color:var(--sc);background:color-mix(in srgb,var(--sc) 8%,var(--surface))}
.ssul-scope .scn .ic {width:48px;height:48px;border-radius:13px;display:grid;place-items:center;font-size:26px;flex:0 0 auto;
background:color-mix(in srgb,var(--sc) 15%,var(--surface))}
.ssul-scope .scn .tx {flex:1}
.ssul-scope .scn .tx .t {font-weight:800;font-size:16px}
.ssul-scope .scn .tx .d {font-size:12px;color:var(--muted);margin-top:2px;line-height:1.4}
.ssul-scope .scn .ck {width:22px;height:22px;border-radius:50%;border:2px solid var(--border);flex:0 0 auto;display:grid;place-items:center}
.ssul-scope .scn[aria-pressed="true"] .ck {background:var(--sc);border-color:var(--sc)}
.ssul-scope .scn[aria-pressed="true"] .ck::after {content:"";width:7px;height:11px;border:2.5px solid #fff;border-top:0;border-left:0;transform:rotate(42deg) translateY(-1px)}
.ssul-scope .field {margin-top:20px}
.ssul-scope .field > label {display:block;font-size:14px;font-weight:700;margin-bottom:8px}
.ssul-scope .input {display:flex;align-items:center;gap:8px;background:var(--surface-2);border-radius:12px;padding:12px 14px;border:1.5px solid transparent}
.ssul-scope .input:focus-within {border-color:var(--fg)}
.ssul-scope .input svg {width:17px;height:17px;color:var(--muted);flex:0 0 auto}
.ssul-scope .input input {flex:1;background:none;border:none;outline:none;color:var(--fg);font-size:16px}
.ssul-scope .input input::placeholder {color:var(--faint)}
.ssul-scope .hint {font-size:12px;color:var(--muted);margin-top:7px;line-height:1.5;padding:0 2px}
.ssul-scope .sheet-foot {padding:12px 16px calc(14px + env(safe-area-inset-bottom));border-top:1px solid var(--border);background:var(--surface)}
.ssul-scope .cta {width:100%;padding:15px;border-radius:14px;font-size:16px;font-weight:800;color:#fff;background:var(--ig);
transition:.15s;box-shadow:0 6px 18px rgba(220,39,67,.32)}
.ssul-scope .cta:disabled {background:var(--surface-2);color:var(--faint);box-shadow:none;cursor:not-allowed}
.ssul-scope .making {padding:44px 24px;text-align:center}
@keyframes sp{to{transform:rotate(360deg)}}
.ssul-scope .making h4 {font-size:18px;font-weight:800}
.ssul-scope .making p {font-size:14px;color:var(--muted);margin-top:8px;line-height:1.6}
.ssul-scope .making .prog {margin-top:22px;display:flex;align-items:center;gap:12px}
.ssul-scope .making .prog-bar {flex:1;height:10px;border-radius:99px;background:var(--surface-2);overflow:hidden;position:relative}
.ssul-scope .making .prog-fill {height:100%;border-radius:99px;background:var(--sc,#dc2743);
transition:width .5s cubic-bezier(.22,1,.36,1);position:relative;overflow:hidden}
.ssul-scope .making .prog-fill::after {content:"";position:absolute;inset:0;
background:linear-gradient(90deg,transparent,rgba(255,255,255,.45),transparent);
animation:progsh 1.15s linear infinite}
@keyframes progsh{from{transform:translateX(-100%)}to{transform:translateX(100%)}}
.ssul-scope .making .prog-pct {font-size:14px;font-weight:800;color:var(--fg);min-width:40px;text-align:right;font-variant-numeric:tabular-nums}
.ssul-scope .viewer {position:absolute;inset:0;z-index:60;background:#000;display:none;flex-direction:column}
.ssul-scope .viewer.on {display:flex}
.ssul-scope .viewer .vtop {position:absolute;top:0;left:0;right:0;z-index:3;display:flex;align-items:center;gap:14px;
padding:14px 16px;padding-top:calc(14px + env(safe-area-inset-top));
background:linear-gradient(180deg,rgba(0,0,0,.5),transparent)}
.ssul-scope .viewer .vtop button {color:#fff;display:flex;align-items:center;justify-content:center;
width:38px;height:38px;border-radius:50%;background:rgba(0,0,0,.4);flex:0 0 auto}
.ssul-scope .viewer .vtop button svg {width:22px;height:22px}
.ssul-scope .viewer .vtop h2 {color:#fff;font-size:16px;font-weight:700}
.ssul-scope .vframe {position:absolute;inset:0;display:flex;flex-direction:column;overflow:hidden}
.ssul-scope .vstage {flex:1;position:relative;display:grid;place-items:center;overflow:hidden}
.ssul-scope .vstage .cover {position:absolute;inset:0;display:grid;place-items:center}
.ssul-scope .vstage .cover .emoji {font-size:120px;opacity:.9;filter:drop-shadow(0 6px 20px rgba(0,0,0,.5))}
.ssul-scope .vstage video {width:100%;height:100%;object-fit:contain;background:#000}
.ssul-scope .vbig {position:relative;z-index:2;width:74px;height:74px;border-radius:50%;background:rgba(255,255,255,.14);
backdrop-filter:blur(4px);display:grid;place-items:center;border:1.5px solid rgba(255,255,255,.5)}
.ssul-scope .vbig svg {width:30px;height:30px;fill:#fff;margin-left:4px}
.ssul-scope .vrail {position:absolute;right:10px;bottom:120px;z-index:3;display:flex;flex-direction:column;gap:20px;align-items:center}
.ssul-scope .vrail button {color:#fff;display:flex;flex-direction:column;align-items:center;gap:4px;font-size:12px;font-weight:600;font-variant-numeric:tabular-nums}
.ssul-scope .vrail svg {width:29px;height:29px;fill:#fff}
.ssul-scope .vbottom {position:absolute;left:0;right:64px;bottom:0;z-index:3;padding:16px;pointer-events:none;
padding-bottom:calc(56px + env(safe-area-inset-bottom));
background:linear-gradient(0deg,rgba(0,0,0,.55),transparent)}
.ssul-scope .vbottom .vt {color:#fff;font-weight:800;font-size:18px;line-height:1.3}
.ssul-scope .vbottom .vn {color:rgba(255,255,255,.86);font-size:14px;margin-top:8px;line-height:1.5;
display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.ssul-scope .vbottom .vbadge {margin-bottom:10px}
.ssul-scope .note-pill {display:inline-block;margin-top:12px;font-size:12px;color:rgba(255,255,255,.7);
background:rgba(255,255,255,.12);padding:5px 10px;border-radius:8px}
@media (min-width:860px) {
.ssul-scope {flex-direction:row}
.ssul-scope .screen {padding-bottom:24px}
.ssul-scope .ssul-grid {grid-template-columns:repeat(4,1fr);gap:18px;padding:22px 26px;max-width:1240px;margin:0 auto}
.ssul-scope .sec-h {padding:24px 26px 2px;max-width:1240px;margin:0 auto}
.ssul-scope .sec-h h3 {font-size:22px}
.ssul-scope .searchbar {padding:16px 26px;max-width:1240px;margin:0 auto}
.ssul-scope .chips {padding:6px 26px 14px;max-width:1240px;margin:0 auto}
.ssul-scope .ch-wrap {max-width:1240px;margin:0 auto}
.ssul-scope .sheet {left:50%;right:auto;bottom:auto;top:50%;width:min(460px,92vw);max-height:86vh;
border-radius:22px;transform:translate(-50%,-46%);opacity:0;
transition:transform .22s cubic-bezier(.22,1,.36,1),opacity .22s}
.ssul-scope .sheet.on {transform:translate(-50%,-50%);opacity:1}
.ssul-scope .sheet .grab {display:none}
.ssul-scope .viewer.on {align-items:center;justify-content:center}
.ssul-scope .vframe {position:relative;inset:auto;width:min(430px,26vw);height:min(90vh,780px);
border-radius:18px;box-shadow:0 24px 70px rgba(0,0,0,.6)}
}
.ssul-scope .vrail button.liked svg {fill:#ff3b5c}
.ssul-scope .cmts {position:absolute;left:0;right:0;bottom:0;z-index:5;max-height:64%;display:flex;flex-direction:column;
background:var(--surface);border-radius:18px 18px 0 0;color:var(--fg);box-shadow:0 -8px 30px rgba(0,0,0,.4)}
.ssul-scope .cmts-h {display:flex;justify-content:space-between;align-items:center;padding:12px 16px;border-bottom:1px solid var(--border);font-weight:800;font-size:14px}
.ssul-scope .cmts-h button {color:var(--muted);font-size:20px;line-height:1}
.ssul-scope .cmts-list {flex:1;overflow-y:auto;padding:6px 16px}
.ssul-scope .cmts-empty {color:var(--muted);font-size:14px;text-align:center;padding:30px 0}
.ssul-scope .cmt {padding:9px 0;border-bottom:1px solid var(--border)}
.ssul-scope .cmt .who {font-size:12px;color:var(--muted);font-weight:700}
.ssul-scope .cmt .bd {font-size:14px;margin-top:2px;line-height:1.4}
.ssul-scope .cmt .del {font-size:12px;color:var(--faint);float:right}
.ssul-scope .cmt .rep {margin:8px 0 0 16px;padding-left:10px;border-left:2px solid var(--border)}
.ssul-scope .cmts-in {display:flex;gap:8px;padding:10px 12px;border-top:1px solid var(--border);align-items:center}
.ssul-scope .cmts-in input {flex:1;background:var(--surface-2);border:none;border-radius:20px;padding:10px 14px;color:var(--fg);outline:none;font-size:14px}
.ssul-scope .cmts-in button {color:var(--samgukji);font-weight:800;padding:0 8px;font-size:14px}
.ssul-scope .cmts-in button:disabled {color:var(--faint)}
.ssul-scope .lbl-sub {font-weight:500;color:var(--muted);font-size:12px}
.ssul-scope .input.search {align-items:center}
.ssul-scope .srch-btn {flex:0 0 auto;padding:8px 14px;border-radius:9px;background:var(--fg);color:var(--bg);font-size:14px;font-weight:800}
.ssul-scope .srch-btn:disabled {opacity:.4}
.ssul-scope .places {margin:8px 0 0;list-style:none;border:1px solid var(--border);border-radius:12px;overflow:hidden;background:var(--surface);max-height:230px;overflow-y:auto}
.ssul-scope .places li+li {border-top:1px solid var(--border)}
.ssul-scope .places button {display:flex;flex-direction:column;gap:2px;width:100%;text-align:left;padding:11px 13px;background:none}
.ssul-scope .places button:hover {background:var(--surface-2)}
.ssul-scope .places b {font-size:14px;font-weight:700;color:var(--fg)}
.ssul-scope .places span {font-size:12px;color:var(--muted)}
.ssul-scope .picked {margin:8px 0 0;display:flex;align-items:center;gap:10px;padding:12px 14px;border-radius:12px;
border:1.5px solid color-mix(in srgb,var(--sc,#22c55e) 55%,var(--border));background:color-mix(in srgb,var(--sc,#22c55e) 8%,var(--surface))}
.ssul-scope .picked .pk-body {flex:1;display:flex;flex-direction:column;gap:2px;min-width:0}
.ssul-scope .picked .pk-body b {font-size:16px;font-weight:800;color:var(--fg)}
.ssul-scope .picked .pk-body b::before {content:"✓ ";color:#22c55e}
.ssul-scope .picked .pk-body span {font-size:12px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.ssul-scope .pk-change {flex:0 0 auto;font-size:12px;font-weight:800;color:var(--muted);padding:6px 10px;border-radius:8px;background:var(--surface-2)}
.ssul-scope .place-loading {margin:10px 2px 0;display:flex;align-items:center;gap:9px;font-size:14px;color:var(--muted)}
.ssul-scope .spin.sm {width:16px;height:16px;border-width:2px;margin:0}
.ssul-scope .hint.ok {color:#16a34a}
.ssul-scope .hint.warn {color:#d97706}
.ssul-scope .sns-card {margin:14px 16px 4px;border:1px solid var(--border);border-radius:16px;background:var(--surface);overflow:hidden}
.ssul-scope .sns-h {display:flex;align-items:baseline;gap:8px;padding:13px 16px 9px;border-bottom:1px solid var(--border)}
.ssul-scope .sns-h span {font-size:14px;font-weight:800}
.ssul-scope .sns-h em {font-style:normal;font-size:12px;color:var(--muted)}
.ssul-scope .sns-row {display:flex;align-items:center;gap:11px;padding:11px 16px}
.ssul-scope .sns-row+.sns-row {border-top:1px solid var(--border)}
.ssul-scope .sns-ic {display:grid;place-items:center;width:34px;height:34px;border-radius:9px;background:color-mix(in srgb,var(--sc) 16%,transparent)}
.ssul-scope .sns-ic svg {width:20px;height:20px;fill:var(--sc);stroke:var(--sc)}
.ssul-scope .sns-name {flex:1;font-size:14px;font-weight:600;display:flex;align-items:center;gap:6px}
.ssul-scope .sns-dot {width:7px;height:7px;border-radius:50%;background:#22c55e;display:inline-block}
.ssul-scope .sns-soon {font-style:normal;font-size:10px;font-weight:800;color:var(--muted);background:var(--surface-2);padding:2px 7px;border-radius:10px}
.ssul-scope .sns-btn {padding:7px 15px;border-radius:20px;font-size:14px;font-weight:800;background:var(--fg);color:var(--bg)}
.ssul-scope .sns-btn.on {background:var(--surface-2);color:var(--muted)}
.ssul-scope .sns-btn:disabled {opacity:.5}
.ssul-scope .sns-row.sns-sub {padding-left:61px;border-top:1px solid var(--border)}
.ssul-scope .sns-row.sns-sub .sns-name {font-weight:500;color:var(--muted)}
.ssul-scope .cmts.share .share-list {flex:1;overflow-y:auto;padding:8px 12px}
.ssul-scope .share-row {display:flex;align-items:center;gap:12px;width:100%;padding:13px 8px;background:none}
.ssul-scope .share-row+.share-row {border-top:1px solid var(--border)}
.ssul-scope .share-name {flex:1;text-align:left;font-size:16px;font-weight:700;color:var(--fg)}
.ssul-scope .share-state {font-size:12px;font-weight:800;color:var(--samgukji)}
.ssul-scope .share-row:disabled .share-state {color:var(--faint)}
.ssul-scope .share-row.share-sub {padding-left:54px;border-top:1px solid var(--border)}
.ssul-scope .share-row.share-sub .share-name {font-weight:500}
.ssul-scope .share-hint {padding:10px 16px 14px;font-size:12px;color:var(--muted);line-height:1.5}
.ssul-scope .share-hint b {color:var(--fg)}
.ssul-scope .cmts.cap .cap-body {flex:1;overflow-y:auto;padding:14px 16px;font-size:14px;line-height:1.6;color:var(--fg);white-space:pre-wrap;word-break:break-word}
.ssul-scope .cap-foot {padding:10px 12px;border-top:1px solid var(--border)}
.ssul-scope .cap-copy {display:flex;align-items:center;justify-content:center;gap:7px;width:100%;padding:12px;border-radius:12px;background:var(--samgukji);color:#fff;font-size:14px;font-weight:800}
.ssul-scope .cap-copy svg {width:17px;height:17px;stroke:#fff}
.ssul-scope .toast {position:fixed;left:50%;bottom:86px;z-index:60;transform:translate(-50%,14px);opacity:0;pointer-events:none;
max-width:min(88vw,420px);padding:12px 18px;border-radius:14px;background:rgba(20,18,16,.94);color:#fff;
font-size:14px;font-weight:600;line-height:1.45;text-align:center;box-shadow:0 10px 34px rgba(0,0,0,.4);
transition:opacity .2s,transform .2s}
.ssul-scope .toast.on {opacity:1;transform:translate(-50%,0)}
@media (min-width:860px) {
.ssul-scope .toast {bottom:32px}
}
.ssul-scope .job-badge {position:fixed;right:14px;bottom:86px;z-index:55;padding:11px 16px;border-radius:999px;
background:rgba(20,18,16,.94);color:#fff;font-size:14px;font-weight:700;box-shadow:0 10px 34px rgba(0,0,0,.4);
display:flex;align-items:center;gap:6px;cursor:pointer}
.ssul-scope .job-badge.err {background:#b3261e}
@media (min-width:860px) {
.ssul-scope .job-badge {bottom:32px}
}
.ssul-scope .prods {display:flex;flex-direction:column;gap:10px;margin-top:6px}
.ssul-scope .prod {position:relative;display:grid;grid-template-columns:1fr auto;grid-template-areas:"cr price" "bonus price" "name price";
align-items:center;gap:2px 12px;text-align:left;padding:14px 16px;border-radius:14px;border:1.5px solid var(--border);background:var(--surface)}
.ssul-scope .prod:hover {border-color:var(--samgukji)}
.ssul-scope .prod.best {border-color:var(--samgukji);background:color-mix(in srgb,var(--samgukji) 7%,var(--surface))}
.ssul-scope .prod:disabled {opacity:.55}
.ssul-scope .prod-tag {position:absolute;top:-9px;left:14px;background:var(--samgukji);color:#fff;font-size:10px;font-weight:800;padding:2px 8px;border-radius:10px}
.ssul-scope .prod-cr {grid-area:cr;font-size:16px;color:var(--muted);font-weight:600}
.ssul-scope .prod-cr b {font-size:22px;color:var(--fg);font-weight:800;margin-right:3px}
.ssul-scope .prod-bonus {grid-area:bonus;font-size:12px;color:var(--samgukji);font-weight:700}
.ssul-scope .prod-name {grid-area:name;font-size:12px;color:var(--faint)}
.ssul-scope .prod-price {grid-area:price;font-size:16px;font-weight:800;color:var(--fg);white-space:nowrap}
.ssul-scope .tb-login {background:var(--samgukji);color:#fff;font-size:14px;font-weight:800;padding:8px 15px;border-radius:20px}
.ssul-scope :focus-visible {outline:2px solid var(--samgukji);outline-offset:2px}
File diff suppressed because it is too large. Load diff
+81
View File
@@ -0,0 +1,81 @@
/* =====================================================
CASTAD Design System - CSS Variables & Component Classes
===================================================== */
/* =====================================================
CSS Variables - Design Tokens
===================================================== */
:root {
/* 모바일 하단 탭바 높이 (safe-area 포함).
탭바 자신과, 탭바에 가리면 안 되는 fixed 요소(캘린더 바텀시트 등)가 공유한다 */
--bottom-nav-height: calc(72px + env(safe-area-inset-bottom));
/* Primary Colors */
--color-mint: #a6ffea;
--color-mint-hover: #8affda;
--color-mint-glow: rgba(166, 255, 234, 0.6);
--color-mint-10: rgba(166, 255, 234, 0.1);
--color-mint-20: rgba(166, 255, 234, 0.2);
--color-mint-30: rgba(166, 255, 234, 0.3);
--color-mint-50: rgba(166, 255, 234, 0.5);
--color-purple: #a682ff;
--color-purple-hover: #9570f0;
--color-purple-glow: rgba(166, 130, 255, 0.2);
--color-purple-80: rgba(166, 130, 255, 0.8);
/* 썰박스 파이프라인 강조색 (진입 화면 탭 활성 표시 전용) */
--color-ssul-accent: #ffb86b;
/* Background Colors - Teal-600 based */
--color-bg-dark: #002224;
--color-bg-darker: #001a1c;
--color-bg-card: #003538;
--color-bg-card-inner: #004548;
/* Text Colors */
--color-text-white: #ffffff;
--color-text-gray-300: #d1d5db;
--color-text-gray-400: #9ca3af;
--color-text-gray-500: #6b7280;
/* Border Colors */
--color-border-white-5: rgba(255, 255, 255, 0.05);
--color-border-white-10: rgba(255, 255, 255, 0.1);
--color-border-gray-600: #4b5563;
--color-border-gray-700: #374151;
/* Shadows */
--shadow-xl: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
--shadow-purple: 0 10px 15px -3px rgba(166, 130, 255, 0.2);
--shadow-mint-glow: 0 0 10px rgba(166, 255, 234, 0.6);
/* Spacing */
--spacing-page: 1.5rem;
--spacing-page-md: 2rem;
/* Border Radius */
--radius-sm: 0.5rem;
--radius-md: 0.75rem;
--radius-lg: 1rem;
--radius-xl: 1.25rem;
--radius-2xl: 1rem;
--radius-3xl: 1.5rem;
--radius-full: 9999px;
/* Font Sizes */
--text-xs: 12px;
--text-sm: 14px;
--text-base: 16px;
--text-lg: 18px;
--text-xl: 20px;
--text-2xl: 24px;
--text-3xl: 30px;
--text-4xl: 36px;
/* Transitions */
--transition-fast: 150ms;
--transition-normal: 200ms;
--transition-slow: 300ms;
}
+124 -22
View File
@@ -32,14 +32,21 @@ export interface MarketingAnalysis {
target_keywords: string[]; target_keywords: string[];
} }
export interface ImageListItem {
preview: string; // 미리보기용 CDN 리사이즈 URL
original: string; // 업로드용 원본 URL
}
export interface CrawlingResponse { export interface CrawlingResponse {
image_list: string[]; image_list: ImageListItem[] | null;
image_count: number; image_count: number;
m_id: number; m_id: number;
industry: string;
processed_info: { processed_info: {
customer_name: string; customer_name: string;
region: string; region: string;
detail_region_info: string; detail_region_info: string;
industry: string;
}; };
marketing_analysis: MarketingAnalysis; marketing_analysis: MarketingAnalysis;
} }
@@ -47,14 +54,15 @@ export interface CrawlingResponse {
// URL 이미지 (서버에서 가져온 이미지) // URL 이미지 (서버에서 가져온 이미지)
export interface UrlImage { export interface UrlImage {
type: 'url'; type: 'url';
url: string; url: string; // 업로드용 원본 URL
preview_url: string; // 미리보기용 CDN 리사이즈 URL
} }
// 업로드된 파일 이미지 // 업로드된 파일 이미지
export interface FileImage { export interface FileImage {
type: 'file'; type: 'file';
file: File; file: File; // 업로드용 원본. 썸네일로 대체하지 않는다.
preview: string; // createObjectURL로 생성된 미리보기 URL preview: string | null; // 미리보기용 축소 썸네일 objectURL. 생성 실패 시 null.
} }
export type ImageItem = UrlImage | FileImage; export type ImageItem = UrlImage | FileImage;
@@ -67,7 +75,10 @@ export interface LyricGenerateRequest {
m_id: number; m_id: number;
region: string; region: string;
task_id: string; task_id: string;
industry?: string;
orientation?: 'vertical' | 'horizontal'; orientation?: 'vertical' | 'horizontal';
instrumental?: boolean;
genre?: string; // 사용자가 수동으로 고른 장르. '자동 선택'이면 생략 (GPT가 추천)
} }
// 가사 생성 응답 // 가사 생성 응답
@@ -97,14 +108,16 @@ export interface LyricDetailResponse {
status: string; status: string;
lyric_prompt: string; lyric_prompt: string;
lyric_result: string; lyric_result: string;
genre?: string | null; // 확정된 장르 (수동 선택값 또는 GPT 추천값)
created_at: string; created_at: string;
} }
// 노래 생성 요청 // 노래 생성 요청
export interface SongGenerateRequest { export interface SongGenerateRequest {
genre: string; genre: string;
language: string; language?: string;
lyrics: string; lyrics?: string;
instrumental?: boolean;
} }
// 노래 생성 응답 // 노래 생성 응답
@@ -141,6 +154,13 @@ export interface SongDownloadResponse {
} }
// 영상 생성 응답 // 영상 생성 응답
// 자막 상태 확인 응답
export interface SubtitleStatusResponse {
task_id: string;
status: string; // 'pending' | 'processing' | 'completed' | 'failed' | 'error'
message: string;
}
export interface VideoGenerateResponse { export interface VideoGenerateResponse {
success: boolean; success: boolean;
task_id: string; task_id: string;
@@ -213,22 +233,13 @@ export interface KakaoLoginUrlResponse {
auth_url: string; auth_url: string;
} }
// 카카오 콜백 사용자 정보 // 카카오 콜백 응답 (JWT 토큰) — 백엔드 LoginResponse와 동일 구조
export interface KakaoCallbackUser {
id: number;
nickname: string;
email: string | null;
profile_image_url: string | null;
is_new_user: boolean;
}
// 카카오 콜백 응답 (JWT 토큰)
export interface KakaoCallbackResponse { export interface KakaoCallbackResponse {
access_token: string; access_token: string;
refresh_token: string; refresh_token: string;
token_type: string; token_type: string;
expires_in: number; expires_in: number;
user: KakaoCallbackUser; is_new_user: boolean;
redirect_url: string; redirect_url: string;
} }
@@ -254,14 +265,53 @@ export interface UserMeResponse {
created_at: string; created_at: string;
} }
// 비디오 목록 아이템 export interface UserCreditsResponse {
credits: number;
}
// 비디오 목록 아이템 (갤러리용)
/** 콘텐츠 종류. ADO2 영상과 썰박스가 한 목록에 섞인다 */
export type ContentType = 'video' | 'ssul';
export interface VideoListItem { export interface VideoListItem {
/**
* ⚠️ `video_id` 는 **type 안에서만 유일하다.**
* `video.id` 와 `ssul_content.id` 는 각각 1부터 시작하는 독립 시퀀스라 값이 겹친다.
* 삭제·상세 열기·React key 는 반드시 `(type, video_id)` 쌍으로 다룰 것.
* 특히 `DELETE /archive/videos/{id}` 는 `Video.id` 로 지우므로,
* 썰박스 항목의 id 를 넘기면 **엉뚱한 ADO2 영상이 삭제된다.**
*/
type: ContentType;
video_id: number; video_id: number;
store_name: string; store_name: string;
region: string; region: string;
task_id: string; task_id: string;
result_movie_url: string; result_movie_url: string;
poster_url?: string | null;
thumbnail_url?: string;
title?: string | null;
description?: string | null;
hashtags?: string[] | null;
official_site_url?: string | null;
created_at: string; created_at: string;
like_count: number;
comment_count: number;
is_liked_by_me: boolean;
}
// 비디오 상세 아이템
export interface VideoDetailItem {
video_id: number;
result_movie_url: string;
poster_url?: string | null;
store_name: string;
region: string;
title?: string | null;
description?: string | null;
official_site_url?: string | null;
created_at: string;
like_count: number;
is_liked_by_me: boolean;
} }
// 비디오 목록 응답 // 비디오 목록 응답
@@ -275,6 +325,47 @@ export interface VideosListResponse {
has_prev: boolean; has_prev: boolean;
} }
// 댓글 대댓글
export interface CommentReply {
id: number;
nickname: string;
profile_image_url: string | null;
content: string | null;
is_deleted: boolean;
is_mine: boolean;
created_at: string;
}
// 댓글 아이템
export interface CommentItem {
id: number;
nickname: string;
profile_image_url: string | null;
content: string | null;
is_deleted: boolean;
is_mine: boolean;
created_at: string;
replies: CommentReply[];
}
// 댓글 목록 응답
export interface CommentsResponse {
items: CommentItem[];
total: number;
page: number;
page_size: number;
total_pages: number;
has_next: boolean;
has_prev: boolean;
}
// 좋아요 토글 응답
export interface LikeToggleResponse {
video_id: number;
is_liked: boolean;
like_count: number;
}
// ============================================ // ============================================
// Social OAuth Types // Social OAuth Types
// ============================================ // ============================================
@@ -321,7 +412,9 @@ export interface SocialDisconnectResponse {
// 유튜브 SEO Description 자동완성 요청 // 유튜브 SEO Description 자동완성 요청
export interface YTAutoSeoRequest { export interface YTAutoSeoRequest {
task_id: string; // 아카이브의 비디오 ID /** 썰박스면 'ssul' + task_id 자리에 ssul_content.id 문자열. 생략 시 video */
content_type?: ContentType;
task_id: string; // ADO2 는 task_id, 썰박스는 콘텐츠 id 문자열
} }
// 유튜브 SEO Description 자동완성 응답 // 유튜브 SEO Description 자동완성 응답
@@ -333,7 +426,12 @@ export interface YTAutoSeoResponse {
// 소셜 업로드 요청 // 소셜 업로드 요청
export interface SocialUploadRequest { export interface SocialUploadRequest {
video_id: number; // 아카이브의 비디오 ID /**
* 콘텐츠 종류. video.id 와 ssul_content.id 가 겹치므로 생략(=video)한 채
* 썰박스 id 를 보내면 **엉뚱한 ADO2 영상이 업로드된다.**
*/
content_type?: ContentType;
video_id: number; // 콘텐츠 ID (content_type 안에서만 유일)
social_account_id: number; // 선택된 채널 ID social_account_id: number; // 선택된 채널 ID
title: string; // 최대 100자 title: string; // 최대 100자
description: string; // 최대 5000자 description: string; // 최대 5000자
@@ -345,9 +443,11 @@ export interface SocialUploadRequest {
// 소셜 업로드 응답 // 소셜 업로드 응답
export interface SocialUploadResponse { export interface SocialUploadResponse {
success: boolean; success: boolean;
upload_id: string; upload_id: number;
status: 'pending' | 'uploading' | 'completed' | 'failed'; platform: string;
status: string;
message: string; message: string;
scheduled_at?: string | null; // 예약 업로드 충돌 시 실제 예약 시간 반환
} }
// 소셜 업로드 상태 조회 응답 // 소셜 업로드 상태 조회 응답
@@ -375,6 +475,8 @@ export interface UploadHistoryItem {
status: 'pending' | 'uploading' | 'completed' | 'failed' | 'scheduled' | 'cancelled'; status: 'pending' | 'uploading' | 'completed' | 'failed' | 'scheduled' | 'cancelled';
title: string; title: string;
channel_name: string; channel_name: string;
platform_user_id: string | null;
platform_username: string | null;
scheduled_at: string | null; scheduled_at: string | null;
uploaded_at: string | null; uploaded_at: string | null;
created_at: string; created_at: string;
+636 -42
View File
@@ -1,3 +1,4 @@
import { clearSessionStorage } from './storageKeys';
import { import {
CrawlingResponse, CrawlingResponse,
LyricGenerateRequest, LyricGenerateRequest,
@@ -8,6 +9,7 @@ import {
SongGenerateResponse, SongGenerateResponse,
SongStatusResponse, SongStatusResponse,
SongDownloadResponse, SongDownloadResponse,
SubtitleStatusResponse,
VideoGenerateResponse, VideoGenerateResponse,
VideoStatusResponse, VideoStatusResponse,
VideoDownloadResponse, VideoDownloadResponse,
@@ -28,7 +30,14 @@ import {
TokenExpiredErrorResponse, TokenExpiredErrorResponse,
YTAutoSeoRequest, YTAutoSeoRequest,
YTAutoSeoResponse, YTAutoSeoResponse,
UserCreditsResponse,
VideoDetailItem,
CommentsResponse,
CommentItem,
ContentType,
LikeToggleResponse,
} from '../types/api'; } from '../types/api';
import { uploadImagesSequentially } from './imageUpload.ts';
export const API_URL = import.meta.env.VITE_API_URL || 'http://40.82.133.44'; export const API_URL = import.meta.env.VITE_API_URL || 'http://40.82.133.44';
console.log('[API] API_URL:', API_URL); console.log('[API] API_URL:', API_URL);
@@ -161,6 +170,8 @@ export async function generateSong(taskId: string, request: SongGenerateRequest)
}); });
if (!response.ok) { if (!response.ok) {
const errorBody = await response.json().catch(() => null);
console.error('[generateSong] 422 detail:', JSON.stringify(errorBody));
throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`);
} }
@@ -242,6 +253,52 @@ export async function waitForSongComplete(
return poll(); return poll();
} }
// 자막 상태 확인 API
export async function getSubtitleStatus(taskId: string): Promise<SubtitleStatusResponse> {
const response = await authenticatedFetch(`${API_URL}/lyric/subtitle/status/${taskId}`, {
method: 'GET',
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
// 자막 완료까지 폴링 (5초 간격, 10분 타임아웃)
const SUBTITLE_POLL_INTERVAL = 5000;
const SUBTITLE_POLL_TIMEOUT = 5 * 60 * 1000;
export async function waitForSubtitleComplete(
taskId: string,
onStatusChange?: (status: string) => void
): Promise<SubtitleStatusResponse> {
const startTime = Date.now();
const poll = async (): Promise<SubtitleStatusResponse> => {
if (Date.now() - startTime > SUBTITLE_POLL_TIMEOUT) {
throw new Error('TIMEOUT');
}
const response = await getSubtitleStatus(taskId);
onStatusChange?.(response.status);
if (response.status === 'completed') {
return response;
}
if (response.status === 'failed' || response.status === 'error') {
throw new Error(response.message || '자막 생성에 실패했습니다.');
}
await new Promise(resolve => setTimeout(resolve, SUBTITLE_POLL_INTERVAL));
return poll();
};
return poll();
}
// 영상 생성 API // 영상 생성 API
export async function generateVideo(taskId: string, orientation: 'vertical' | 'horizontal' = 'vertical'): Promise<VideoGenerateResponse> { export async function generateVideo(taskId: string, orientation: 'vertical' | 'horizontal' = 'vertical'): Promise<VideoGenerateResponse> {
const response = await authenticatedFetch(`${API_URL}/video/generate/${taskId}?orientation=${orientation}`, { const response = await authenticatedFetch(`${API_URL}/video/generate/${taskId}?orientation=${orientation}`, {
@@ -255,6 +312,183 @@ export async function generateVideo(taskId: string, orientation: 'vertical' | 'h
return response.json(); return response.json();
} }
// ============================================================
// Meta 전환 추적
// ============================================================
// Meta 픽셀이 심는 1st-party 쿠키 값 읽기 (_fbc/_fbp)
function getCookieValue(name: string): string | null {
const match = document.cookie.match(new RegExp(`(?:^|;\\s*)${name}=([^;]*)`));
return match ? decodeURIComponent(match[1]) : null;
}
// URL의 fbclid로 조립해둔 fbc 폴백 값을 보관하는 localStorage 키
// UTM과 분리해 두어야 가입 완료 후 UTM을 정리해도 이후 이벤트에서 계속 쓸 수 있다.
const FBC_STORAGE_KEY = 'castad_fbc';
// Meta 클릭 ID(fbc) 조회
// 픽셀이 심은 _fbc 쿠키를 우선 사용하고, 없으면 랜딩 시 fbclid로 조립해둔 값을 쓴다.
// 애드블로커·쿠키 정리 등으로 쿠키가 유실돼도 광고 클릭 기여를 잃지 않기 위한 폴백이다.
function getFbc(): string | null {
const cookie = getCookieValue('_fbc');
if (cookie) return cookie;
try {
return localStorage.getItem(FBC_STORAGE_KEY);
} catch {
return null;
}
}
// 첫 영상 생성 완료(FirstVideoCreated) 전환 이벤트 발화 API
// 서버가 first_video_created_at null 여부로 계정당 최초 1회를 판정하고,
// fired=true일 때만 브라우저 픽셀(fbq)을 동일 event_id로 발화해 중복제거를 보장한다.
export async function trackFirstVideoCreated(): Promise<void> {
try {
const response = await authenticatedFetch(`${API_URL}/tracking/meta/first-video-created`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
fbc: getFbc(),
fbp: getCookieValue('_fbp'),
event_source_url: window.location.href,
}),
});
if (!response.ok) return;
const data: { fired: boolean; event_id: string | null } = await response.json();
const fbq = (window as unknown as { fbq?: (...args: unknown[]) => void }).fbq;
if (data.fired && data.event_id && typeof fbq === 'function') {
// 서버 CAPI 이벤트와 동일한 event_id로 발화 → Meta가 중복제거
fbq('trackCustom', 'FirstVideoCreated', {}, { eventID: data.event_id });
}
} catch (error) {
// 전환 추적 실패는 서비스 기능에 영향을 주지 않도록 무시
console.error('[Tracking] FirstVideoCreated failed:', error);
}
}
// UTM 파라미터 localStorage 키 (first-touch 보존)
const UTM_STORAGE_KEY = 'castad_utm';
const UTM_PARAM_NAMES = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'] as const;
// 이벤트 중복제거용 UUID 생성
// crypto.randomUUID는 보안 컨텍스트(https/localhost) 전용이라 미지원 환경 폴백 포함
function generateEventId(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
// fbq 전역 함수 안전 접근
function getFbq(): ((...args: unknown[]) => void) | null {
const fbq = (window as unknown as { fbq?: (...args: unknown[]) => void }).fbq;
return typeof fbq === 'function' ? fbq : null;
}
// 랜딩 진입 URL에서 광고 유입 정보(UTM, fbclid)를 localStorage에 보관한다.
export function storeUtmFromUrl(): void {
try {
const params = new URLSearchParams(window.location.search);
// UTM: 이미 저장된 값이 있으면 덮어쓰지 않아 최초 유입 경로(first-touch)를 보존
if (!localStorage.getItem(UTM_STORAGE_KEY)) {
const utm: Record<string, string> = {};
for (const name of UTM_PARAM_NAMES) {
const value = params.get(name);
if (value) utm[name] = value;
}
if (Object.keys(utm).length > 0) {
localStorage.setItem(UTM_STORAGE_KEY, JSON.stringify(utm));
}
}
// fbclid: 광고 클릭 기여는 최신 클릭이 가져가므로 새 값이 오면 덮어쓴다
// (Meta 픽셀의 _fbc 쿠키도 동일하게 last-touch로 동작)
// 형식: fb.{subdomainIndex}.{creationTime(ms)}.{fbclid}
const fbclid = params.get('fbclid');
if (fbclid) {
localStorage.setItem(FBC_STORAGE_KEY, `fb.1.${Date.now()}.${fbclid}`);
}
} catch (error) {
console.error('[Tracking] storeUtmFromUrl failed:', error);
}
}
// 랜딩 진입(ViewContent) 이벤트 발화 — 비로그인 시점이므로 브라우저 픽셀 단독
export function trackViewContent(): void {
try {
const fbq = getFbq();
if (fbq) {
fbq('track', 'ViewContent', {}, { eventID: generateEventId() });
console.log('[Tracking] ViewContent fired');
} else {
console.warn('[Tracking] ViewContent skipped: fbq not loaded');
}
} catch (error) {
const detail = error instanceof Error ? `${error.name}: ${error.message}\n${error.stack}` : String(error);
console.error('[Tracking] ViewContent failed:', detail);
}
}
// 회원가입 완료(CompleteRegistration) 전환 이벤트 발화 API
// 서버가 registration_tracked_at null 여부로 계정당 최초 1회를 판정하고 UTM을 함께 기록한다.
// fired=true일 때만 브라우저 픽셀(fbq)을 동일 event_id로 발화해 중복제거를 보장한다.
export async function trackCompleteRegistration(): Promise<void> {
try {
let utm: Record<string, string> = {};
try {
utm = JSON.parse(localStorage.getItem(UTM_STORAGE_KEY) ?? '{}');
} catch {
utm = {};
}
const response = await authenticatedFetch(`${API_URL}/tracking/meta/complete-registration`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
fbc: getFbc(),
fbp: getCookieValue('_fbp'),
event_source_url: window.location.href,
utm_source: utm.utm_source ?? null,
utm_medium: utm.utm_medium ?? null,
utm_campaign: utm.utm_campaign ?? null,
utm_content: utm.utm_content ?? null,
utm_term: utm.utm_term ?? null,
}),
});
if (!response.ok) return;
const data: { fired: boolean; event_id: string | null } = await response.json();
if (data.fired && data.event_id) {
const fbq = getFbq();
if (fbq) {
// 서버 CAPI 이벤트와 동일한 event_id로 발화 → Meta가 중복제거
fbq('track', 'CompleteRegistration', {}, { eventID: data.event_id });
}
// 가입 어트리뷰션 저장 완료 → 보관하던 UTM 제거
localStorage.removeItem(UTM_STORAGE_KEY);
}
} catch (error) {
// 전환 추적 실패는 서비스 기능에 영향을 주지 않도록 무시
console.error('[Tracking] CompleteRegistration failed:', error);
}
}
// 영상 상태 확인 API // 영상 상태 확인 API
export async function getVideoStatus(taskId: string): Promise<VideoStatusResponse> { export async function getVideoStatus(taskId: string): Promise<VideoStatusResponse> {
const response = await authenticatedFetch(`${API_URL}/video/status/${taskId}`, { const response = await authenticatedFetch(`${API_URL}/video/status/${taskId}`, {
@@ -323,6 +557,161 @@ export async function deleteVideo(videoId: number): Promise<void> {
} }
} }
// 전체 사용자 영상 목록 조회 API (ADO2 콘텐츠 갤러리용)
export async function getAllVideos(
page: number = 1,
pageSize: number = 20,
sortBy: 'created_at' | 'like_count' | 'comment_count' = 'created_at',
storeName: string = '',
order: 'desc' | 'asc' = 'desc',
region: string = '',
): Promise<VideosListResponse> {
const params = new URLSearchParams({
page: String(page),
page_size: String(pageSize),
sort_by: sortBy,
order,
});
if (storeName.trim()) params.set('store_name', storeName.trim());
if (region.trim()) params.set('region', region.trim());
const response = await authenticatedFetch(`${API_URL}/video/all?${params.toString()}`, {
method: 'GET',
}, { redirectOnAuthFail: false });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
// 단일 영상 상세 조회 API
export async function getVideoById(videoId: string): Promise<VideoDetailItem> {
const response = await authenticatedFetch(`${API_URL}/video/${videoId}`, {
method: 'GET',
}, { redirectOnAuthFail: false });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
// 썰박스 콘텐츠 공개 상세 (비로그인 허용 — 공유 링크 /ssul/{id} 가 사용)
export interface SsulDetailItem {
content_id: number;
scenario: string;
video_url: string;
store_name: string | null;
region: string | null;
/** 업체 공식 링크. 영상 종료 3초 전 오버레이에 쓰며, 미확보 시 null */
official_site_url?: string | null;
created_at: string;
like_count: number;
is_liked_by_me: boolean;
}
export async function getSsulContentById(contentId: string): Promise<SsulDetailItem> {
const response = await authenticatedFetch(`${API_URL}/ssul/${contentId}`, {
method: 'GET',
}, { redirectOnAuthFail: false });
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
// 썰박스 콘텐츠 소프트 삭제.
// ⚠️ deleteVideo(= /archive/videos/{id}, Video.id 기준)와 절대 혼용하지 말 것 —
// id 가 겹치므로 엉뚱한 ADO2 영상이 지워진다. 썰박스는 반드시 이 함수로.
export async function deleteSsulContent(contentId: number): Promise<void> {
const response = await authenticatedFetch(`${API_URL}/ssul/${contentId}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
}
// 댓글 목록 조회
// contentType: video.id 와 ssul_content.id 가 겹치므로 종류를 함께 보낸다 (기본 'video')
export async function getVideoComments(
videoId: string,
page: number = 1,
pageSize: number = 20,
contentType: ContentType = 'video'
): Promise<CommentsResponse> {
const response = await authenticatedFetch(
`${API_URL}/comment/video/${videoId}?page=${page}&page_size=${pageSize}&type=${contentType}`,
{
method: 'GET',
},
{ redirectOnAuthFail: false }
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
// 댓글 작성 (작성자 닉네임/프로필은 서버가 로그인된 카카오 정보로 채움)
export async function postVideoComment(
videoId: string,
content: string,
parentId?: number,
contentType: ContentType = 'video'
): Promise<CommentItem> {
const response = await authenticatedFetch(`${API_URL}/comment/video/${videoId}?type=${contentType}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ content, parent_id: parentId ?? null }),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
// 댓글 삭제
export async function deleteComment(commentId: number): Promise<void> {
const response = await authenticatedFetch(`${API_URL}/comment/${commentId}`, {
method: 'DELETE',
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
}
// 좋아요 토글
export async function toggleVideoLike(
videoId: string,
// video.id 와 ssul_content.id 가 겹치므로 종류를 함께 보내야 한다.
// 기본값 'video' 라 기존 호출부는 수정이 없다.
contentType: ContentType = 'video'
): Promise<LikeToggleResponse> {
const response = await authenticatedFetch(
`${API_URL}/video/${videoId}/like?type=${contentType}`,
{
method: 'POST',
}
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
// 이미지 업로드 API (multipart/form-data) // 이미지 업로드 API (multipart/form-data)
// 타임아웃: 5분 (많은 이미지 업로드 시 시간이 오래 걸릴 수 있음) // 타임아웃: 5분 (많은 이미지 업로드 시 시간이 오래 걸릴 수 있음)
const IMAGE_UPLOAD_TIMEOUT = 5 * 60 * 1000; const IMAGE_UPLOAD_TIMEOUT = 5 * 60 * 1000;
@@ -331,18 +720,10 @@ export async function uploadImages(
imageUrls: ImageUrlItem[], imageUrls: ImageUrlItem[],
files: File[] files: File[]
): Promise<ImageUploadResponse> { ): Promise<ImageUploadResponse> {
const formData = new FormData(); return uploadImagesSequentially(imageUrls, files, postImageUpload);
}
// URL 이미지들을 images_json으로 전달
if (imageUrls.length > 0) {
formData.append('images_json', JSON.stringify(imageUrls));
}
// 파일들을 files로 전달
files.forEach((file) => {
formData.append('files', file);
});
async function postImageUpload(formData: FormData): Promise<ImageUploadResponse> {
const controller = new AbortController(); const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), IMAGE_UPLOAD_TIMEOUT); const timeoutId = setTimeout(() => controller.abort(), IMAGE_UPLOAD_TIMEOUT);
@@ -353,19 +734,21 @@ export async function uploadImages(
signal: controller.signal, signal: controller.signal,
}); });
clearTimeout(timeoutId);
if (!response.ok) { if (!response.ok) {
if (response.status === 413) {
throw new Error('이미지 파일이 너무 커서 업로드할 수 없습니다. 더 작은 이미지를 선택해주세요.');
}
throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`);
} }
return response.json(); return response.json();
} catch (error) { } catch (error) {
clearTimeout(timeoutId);
if (error instanceof Error && error.name === 'AbortError') { if (error instanceof Error && error.name === 'AbortError') {
throw new Error('이미지 업로드 시간이 초과되었습니다. 다시 시도해주세요.'); throw new Error('이미지 업로드 시간이 초과되었습니다. 다시 시도해주세요.');
} }
throw error; throw error;
} finally {
clearTimeout(timeoutId);
} }
} }
@@ -452,11 +835,8 @@ let refreshPromise: Promise<TokenRefreshResponse> | null = null;
function redirectToLogin() { function redirectToLogin() {
// 토큰 삭제 // 토큰 삭제
clearTokens(); clearTokens();
// localStorage 정리 // localStorage 정리 (생성 중이던 상태까지 전부 — 재로그인 시 잔류 방지)
localStorage.removeItem('castad_view_mode'); clearSessionStorage();
localStorage.removeItem('castad_analysis_data');
localStorage.removeItem('castad_wizard_step');
localStorage.removeItem('castad_active_item');
// 홈으로 리다이렉트 // 홈으로 리다이렉트
window.location.href = '/'; window.location.href = '/';
} }
@@ -464,7 +844,8 @@ function redirectToLogin() {
// 401 에러 시 자동으로 토큰 갱신 후 재요청하는 래퍼 함수 // 401 에러 시 자동으로 토큰 갱신 후 재요청하는 래퍼 함수
export async function authenticatedFetch( export async function authenticatedFetch(
url: string, url: string,
options: RequestInit = {} options: RequestInit = {},
{ redirectOnAuthFail = true }: { redirectOnAuthFail?: boolean } = {}
): Promise<Response> { ): Promise<Response> {
// 인증 헤더 + 캐시 방지 헤더 추가 // 인증 헤더 + 캐시 방지 헤더 추가
const headers: HeadersInit = { const headers: HeadersInit = {
@@ -476,14 +857,25 @@ export async function authenticatedFetch(
let response = await fetch(url, { ...options, headers }); let response = await fetch(url, { ...options, headers });
// 401 에러 시 토큰 갱신 시도 // 401 에러 시 에러 코드에 따라 처리
if (response.status === 401) { if (response.status === 401) {
const errorBody = await response.json().catch(() => null);
const errorCode = errorBody?.detail?.code;
// 애초에 토큰이 없던 익명 요청(공개 화면)까지 튕기면 안 되므로 별도 처리
const isMissingToken = errorCode === 'MISSING_TOKEN';
if (errorCode !== 'TOKEN_EXPIRED') {
// INVALID_TOKEN 등 갱신으로 해결 불가한 경우 즉시 로그인 이동
if (redirectOnAuthFail && !isMissingToken) {
redirectToLogin();
}
throw new Error(errorCode ?? 'Unauthorized');
}
try { try {
// 이미 갱신 중이면 기존 Promise 재사용 (중복 요청 방지)
// refreshPromise가 존재하면 재사용, 없으면 새로 생성
if (!refreshPromise) { if (!refreshPromise) {
refreshPromise = refreshAccessToken().finally(() => { refreshPromise = refreshAccessToken().finally(() => {
// 성공/실패 상관없이 Promise 초기화 (다음 갱신을 위해)
refreshPromise = null; refreshPromise = null;
}); });
} }
@@ -500,8 +892,9 @@ export async function authenticatedFetch(
response = await fetch(url, { ...options, headers: newHeaders }); response = await fetch(url, { ...options, headers: newHeaders });
} catch (refreshError) { } catch (refreshError) {
console.error('Token refresh failed:', refreshError); console.error('Token refresh failed:', refreshError);
// 토큰 갱신 실패 시 로그인 페이지로 리다이렉트 if (redirectOnAuthFail) {
redirectToLogin(); redirectToLogin();
}
throw refreshError; throw refreshError;
} }
} }
@@ -599,28 +992,30 @@ export async function refreshAccessToken(): Promise<TokenRefreshResponse> {
// 로컬 스토리지 전체 정리 // 로컬 스토리지 전체 정리
function clearAllLocalData() { function clearAllLocalData() {
clearTokens(); clearTokens();
localStorage.removeItem('castad_view_mode'); clearSessionStorage();
localStorage.removeItem('castad_analysis_data');
localStorage.removeItem('castad_wizard_step');
localStorage.removeItem('castad_active_item');
localStorage.removeItem('castad_song_task_id');
localStorage.removeItem('castad_image_task_id');
localStorage.removeItem('castad_song_generation');
localStorage.removeItem('castad_video_generation');
localStorage.removeItem('castad_video_ratio');
} }
// 로그아웃 // 로그아웃
export async function logout(): Promise<void> { export async function logout(): Promise<void> {
const response = await authenticatedFetch(`${API_URL}/user/auth/logout`, { const refreshToken = getRefreshToken();
method: 'POST',
});
// 응답과 관계없이 로컬 데이터 전체 삭제 try {
clearAllLocalData(); if (refreshToken) {
const response = await authenticatedFetch(`${API_URL}/user/auth/logout`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ refresh_token: refreshToken }),
});
if (!response.ok) { if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); throw new Error(`HTTP error! status: ${response.status}`);
}
}
} finally {
// 응답과 관계없이 로컬 데이터 전체 삭제
clearAllLocalData();
} }
} }
@@ -651,6 +1046,32 @@ export async function getUserMe(): Promise<UserMeResponse> {
return response.json(); return response.json();
} }
// 사용자 크레딧 조회
export async function getUserCredits(): Promise<UserCreditsResponse> {
const response = await authenticatedFetch(`${API_URL}/user/auth/me/credits`, {
method: 'GET',
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
// 크레딧 충전 요청
export async function requestCreditCharge(amount: number, note: string): Promise<void> {
const response = await authenticatedFetch(`${API_URL}/user/credits/charge-requests`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ requested_amount: amount, message: note }),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
}
// 로그인 여부 확인 // 로그인 여부 확인
export function isLoggedIn(): boolean { export function isLoggedIn(): boolean {
return !!getAccessToken(); return !!getAccessToken();
@@ -666,6 +1087,16 @@ export interface AccommodationSearchItem {
title: string; title: string;
} }
// 네이버 검색 API는 title에 <b> 태그와 &amp; 같은 HTML 엔티티를 함께 내려주므로
// 태그 제거 후 엔티티까지 디코딩해야 "&amp;" 같은 원문이 그대로 노출되지 않는다.
// textarea는 DOM에 붙이지 않고 content model상 스크립트를 실행하지 않으므로 엔티티 디코딩 용도로 안전하다.
export const cleanSearchTitle = (title: string): string => {
const withoutTags = title.replace(/<[^>]*>/g, '');
const textarea = document.createElement('textarea');
textarea.innerHTML = withoutTags;
return textarea.value;
};
export interface AccommodationSearchResponse { export interface AccommodationSearchResponse {
count: number; count: number;
items: AccommodationSearchItem[]; items: AccommodationSearchItem[];
@@ -722,6 +1153,42 @@ export async function autocomplete(request: AutocompleteRequest): Promise<Crawli
} }
} }
// 업체명·주소 직접 입력으로 마케팅 분석
export async function marketingAnalysis(storeName: string, address: string, category = '', officialSiteUrl?: string): Promise<CrawlingResponse> {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), CRAWL_TIMEOUT);
try {
const response = await authenticatedFetch(`${API_URL}/marketing`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
store_name: storeName,
address,
category,
official_site_url: officialSiteUrl?.trim() || null,
}),
signal: controller.signal,
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
} catch (error) {
clearTimeout(timeoutId);
if (error instanceof Error && error.name === 'AbortError') {
throw new Error('요청 시간이 초과되었습니다. 다시 시도해주세요.');
}
throw error;
}
}
// ============================================ // ============================================
// Social OAuth TOKEN_EXPIRED 처리 // Social OAuth TOKEN_EXPIRED 처리
// ============================================ // ============================================
@@ -930,3 +1397,130 @@ export async function retryUpload(uploadId: number): Promise<{ success: boolean;
if (!response.ok) throw new Error('재시도 실패'); if (!response.ok) throw new Error('재시도 실패');
return response.json(); return response.json();
} }
// ============================================================================
// 썰박스 (Ssulbox)
// ============================================================================
export interface SsulCreateRequest {
scenario: string;
/**
* 업장명 또는 네이버 지도 링크.
*
* 자동완성으로 고른 경우 **업장명**을 보낸다 — place URL 해석은 서버가
* ADO2 와 동일한 경로(NvMapPwScraper)로 처리한다. 링크를 직접 붙여넣었으면
* 그대로 보낸다.
*/
input: string;
scenes?: number;
seconds?: number;
/** 자동완성으로 고른 경우에만. 목록 표시·필터·place URL 해석에 쓰인다 */
store_name?: string;
/** 지역 추출용(도로명). 백엔드는 이 값을 저장하지 않는다 */
road_address?: string;
/** 지역 추출용(지번). 도로명에서 시/군 추출이 실패할 때의 폴백 */
address?: string;
}
export interface SsulCreateResponse {
id: number;
status: string;
poll_interval_seconds?: number;
}
export async function createSsulJob(
request: SsulCreateRequest
): Promise<SsulCreateResponse> {
const response = await authenticatedFetch(`${API_URL}/ssul/create`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
});
if (response.status === 402) {
throw new InsufficientCreditError();
}
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
}
/** 크레딧 부족(402). 호출부가 충전 화면으로 유도할 수 있게 별도 타입으로 던진다 */
export class InsufficientCreditError extends Error {
constructor(message = '크레딧이 부족합니다.') {
super(message);
this.name = 'InsufficientCreditError';
}
}
export interface SsulTaskStatus {
id: number;
scenario: string;
status: 'queued' | 'running' | 'done' | 'error';
/** 0~4. 0=준비, 4=영상 합성 완료 */
step: number;
error: string | null;
video_url: string | null;
/**
* 대상 업장명. `status === 'done'` 이면 서버가 채워 보낸다.
* 생성 중에는 비어 있을 수 있다 — 행은 요청 즉시 만들어지고 업장명은 그 뒤에 확정된다.
*/
store_name: string;
created_at: string;
}
/** 폴링 간격. castad 의 waitForVideoComplete 와 동일하게 맞춘다 */
const SSUL_POLL_INTERVAL = 3000;
/** 생성이 수 분~십수 분 걸리므로 넉넉히 */
const SSUL_POLL_TIMEOUT = 30 * 60 * 1000;
/** 생성 잡 단건 조회 */
export async function getSsulTask(taskId: number): Promise<SsulTaskStatus> {
const response = await authenticatedFetch(`${API_URL}/ssul/tasks/${taskId}`);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
return response.json();
}
/**
* 진행 중인 내 잡 조회 (새로고침·새 탭 복구용).
* 진행 중인 것이 없으면 null.
*/
export async function getActiveSsulTask(): Promise<SsulTaskStatus | null> {
try {
const response = await authenticatedFetch(`${API_URL}/ssul/tasks/active`);
if (!response.ok) return null;
const data = await response.json();
return data.items?.[0] ?? null;
} catch {
return null;
}
}
/**
* 생성 완료까지 폴링한다. castad 의 waitForVideoComplete 와 같은 재귀 패턴.
*
* SSE 대신 폴링을 쓰는 이유는 계획서 참조 — 요약하면 EventSource 가
* `authenticatedFetch` 의 401 자동 갱신을 못 타고, 스트림이 DB 커넥션을
* 점유하며, 리버스 프록시 버퍼링에 취약하기 때문이다.
*
* @param shouldStop 매 틱마다 확인. true 면 조용히 중단한다(언마운트·로그아웃).
*/
export async function waitForSsulComplete(
taskId: number,
onProgress?: (task: SsulTaskStatus) => void,
shouldStop?: () => boolean,
startedAt: number = Date.now()
): Promise<SsulTaskStatus> {
if (shouldStop?.()) throw new Error('CANCELLED');
if (Date.now() - startedAt > SSUL_POLL_TIMEOUT) throw new Error('TIMEOUT');
const task = await getSsulTask(taskId);
onProgress?.(task);
if (task.status === 'done') return task;
if (task.status === 'error') throw new Error(task.error ?? 'SSUL_FAILED');
await new Promise((resolve) => setTimeout(resolve, SSUL_POLL_INTERVAL));
return waitForSsulComplete(taskId, onProgress, shouldStop, startedAt);
}
+305
View File
@@ -0,0 +1,305 @@
export const MAX_UPLOAD_IMAGE_BYTES = 2 * 1024 * 1024;
export const MAX_UPLOAD_IMAGE_DIMENSION = 2048;
export const MAX_FALLBACK_UPLOAD_IMAGE_BYTES = 15 * 1024 * 1024;
const OUTPUT_MIME_TYPE = 'image/jpeg';
const OUTPUT_EXTENSION = 'jpg';
const BACKEND_IMAGE_EXTENSIONS = new Set(['jpg', 'jpeg', 'png', 'webp', 'heic', 'heif']);
const BACKEND_IMAGE_MIME_TYPES = new Set([
'image/jpeg',
'image/png',
'image/webp',
'image/heic',
'image/heif',
'image/heic-sequence',
'image/heif-sequence',
]);
interface ImageDimensions {
width: number;
height: number;
}
interface DecodedImage extends ImageDimensions {
source: CanvasImageSource;
dispose: () => void;
}
interface CompressionAttempt {
scale: number;
quality: number;
}
const COMPRESSION_ATTEMPTS: CompressionAttempt[] = [
{ scale: 1, quality: 0.86 },
{ scale: 1, quality: 0.74 },
{ scale: 1, quality: 0.62 },
{ scale: 1, quality: 0.5 },
{ scale: 0.85, quality: 0.7 },
{ scale: 0.7, quality: 0.65 },
{ scale: 0.55, quality: 0.6 },
{ scale: 0.4, quality: 0.55 },
];
export function calculateTargetDimensions(
width: number,
height: number,
maxDimension = MAX_UPLOAD_IMAGE_DIMENSION
): ImageDimensions {
if (
!Number.isFinite(width) ||
!Number.isFinite(height) ||
!Number.isFinite(maxDimension) ||
width <= 0 ||
height <= 0 ||
maxDimension <= 0
) {
throw new Error('Image dimensions must be positive finite numbers.');
}
const scale = Math.min(1, maxDimension / Math.max(width, height));
return {
width: Math.max(1, Math.round(width * scale)),
height: Math.max(1, Math.round(height * scale)),
};
}
export function shouldCompressImage(
fileSize: number,
dimensions: ImageDimensions,
maxBytes = MAX_UPLOAD_IMAGE_BYTES,
maxDimension = MAX_UPLOAD_IMAGE_DIMENSION
): boolean {
return (
fileSize > maxBytes ||
dimensions.width > maxDimension ||
dimensions.height > maxDimension
);
}
export function buildCompressedFileName(fileName: string): string {
const extensionIndex = fileName.lastIndexOf('.');
const baseName = extensionIndex > 0 ? fileName.slice(0, extensionIndex) : fileName;
return `${baseName || 'image'}.${OUTPUT_EXTENSION}`;
}
function getFileExtension(fileName: string): string {
const extensionIndex = fileName.lastIndexOf('.');
return extensionIndex >= 0 ? fileName.slice(extensionIndex + 1).toLowerCase() : '';
}
export function isImageInputFile(file: Pick<File, 'name' | 'type'>): boolean {
return file.type.startsWith('image/') || BACKEND_IMAGE_EXTENSIONS.has(getFileExtension(file.name));
}
export function canUploadOriginalImage(file: Pick<File, 'name' | 'type'>): boolean {
const hasAllowedExtension = BACKEND_IMAGE_EXTENSIONS.has(getFileExtension(file.name));
const hasAllowedMimeType = file.type === '' || BACKEND_IMAGE_MIME_TYPES.has(file.type.toLowerCase());
return hasAllowedExtension && hasAllowedMimeType;
}
export function canUploadOriginalAfterCompressionFailure(
fileSize: number,
maxBytes = MAX_FALLBACK_UPLOAD_IMAGE_BYTES
): boolean {
return fileSize <= maxBytes;
}
function useOriginalOrThrow(file: File, cause: unknown): File {
if (!canUploadOriginalImage(file)) {
throw new Error(
`${file.name} 파일을 지원하는 이미지 형식으로 변환할 수 없습니다. ` +
'JPEG, PNG 또는 WebP로 변환한 뒤 다시 시도해주세요.',
{ cause }
);
}
if (!canUploadOriginalAfterCompressionFailure(file.size)) {
throw new Error(
`${file.name} 파일은 15 MB보다 크고 브라우저에서 크기를 줄일 수 없습니다. ` +
'JPEG나 PNG로 변환하거나 더 작은 이미지를 선택해주세요.',
{ cause }
);
}
console.warn(`Image compression was unavailable for ${file.name}; uploading the original.`, cause);
return file;
}
function decodeWithImageElement(file: File): Promise<DecodedImage> {
return new Promise((resolve, reject) => {
const objectUrl = URL.createObjectURL(file);
const image = new Image();
image.onload = () => {
resolve({
source: image,
width: image.naturalWidth,
height: image.naturalHeight,
dispose: () => URL.revokeObjectURL(objectUrl),
});
};
image.onerror = () => {
URL.revokeObjectURL(objectUrl);
reject(new Error(`Unable to decode image: ${file.name}`));
};
image.src = objectUrl;
});
}
async function decodeImage(file: File): Promise<DecodedImage> {
if (typeof createImageBitmap === 'function') {
const bitmap = await createImageBitmap(file);
return {
source: bitmap,
width: bitmap.width,
height: bitmap.height,
dispose: () => bitmap.close(),
};
}
return decodeWithImageElement(file);
}
function canvasToBlob(canvas: HTMLCanvasElement, quality: number): Promise<Blob> {
return new Promise((resolve, reject) => {
canvas.toBlob(
(blob) => {
if (blob) {
resolve(blob);
} else {
reject(new Error('The browser could not compress the image.'));
}
},
OUTPUT_MIME_TYPE,
quality
);
});
}
export async function compressImageForUpload(file: File): Promise<File> {
if (!isImageInputFile(file)) {
throw new Error(`지원하지 않는 이미지 파일입니다: ${file.name}`);
}
let decoded: DecodedImage;
try {
decoded = await decodeImage(file);
} catch (error) {
return useOriginalOrThrow(file, error);
}
try {
if (
canUploadOriginalImage(file) &&
!shouldCompressImage(file.size, {
width: decoded.width,
height: decoded.height,
})
) {
return file;
}
const baseDimensions = calculateTargetDimensions(decoded.width, decoded.height);
let smallestBlob: Blob | null = null;
try {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
if (!context) {
throw new Error('The browser does not support image compression.');
}
for (const attempt of COMPRESSION_ATTEMPTS) {
canvas.width = Math.max(1, Math.round(baseDimensions.width * attempt.scale));
canvas.height = Math.max(1, Math.round(baseDimensions.height * attempt.scale));
// JPEG has no alpha channel. A white background avoids transparent pixels
// becoming black when PNG/WebP images are converted.
context.fillStyle = '#ffffff';
context.fillRect(0, 0, canvas.width, canvas.height);
context.drawImage(decoded.source, 0, 0, canvas.width, canvas.height);
const blob = await canvasToBlob(canvas, attempt.quality);
if (!smallestBlob || blob.size < smallestBlob.size) {
smallestBlob = blob;
}
if (blob.size <= MAX_UPLOAD_IMAGE_BYTES) {
return new File([blob], buildCompressedFileName(file.name), {
type: blob.type || OUTPUT_MIME_TYPE,
lastModified: file.lastModified,
});
}
}
} catch (error) {
return useOriginalOrThrow(file, error);
}
const measuredSize = smallestBlob?.size ?? file.size;
throw new Error(
`${file.name} 파일을 ${Math.round(MAX_UPLOAD_IMAGE_BYTES / (1024 * 1024))} MB 이하로 ` +
`압축할 수 없습니다(압축 결과: ${Math.ceil(measuredSize / (1024 * 1024))} MB).`
);
} finally {
decoded.dispose();
}
}
export const MAX_PREVIEW_DIMENSION = 400;
export const PREVIEW_QUALITY = 0.7;
/**
* 그리드 미리보기 전용 축소 썸네일을 만든다.
*
* 업로드에는 원본 File 을 그대로 쓰고, 여기서 만든 objectURL 은 <img> 에만 쓰인다.
* 핵심은 finally 의 dispose() 로, createImageBitmap 경로에서 원본 비트맵을 즉시
* 해제해 메모리에 원본 크기 비트맵이 남지 않게 한다.
*
* 실패해도 예외를 던지지 않고 null 을 돌려준다. 호출부가 자리표시자를 그린다.
*/
export async function createPreviewThumbnail(file: File): Promise<string | null> {
if (!isImageInputFile(file)) {
return null;
}
let decoded: DecodedImage;
try {
decoded = await decodeImage(file);
} catch (error) {
console.warn(`미리보기 썸네일 디코딩 실패: ${file.name}`, error);
return null;
}
try {
const { width, height } = calculateTargetDimensions(
decoded.width,
decoded.height,
MAX_PREVIEW_DIMENSION
);
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d');
if (!context) {
return null;
}
// JPEG 에는 알파 채널이 없다. 투명 픽셀이 검게 나오지 않도록 흰 배경을 깐다.
context.fillStyle = '#ffffff';
context.fillRect(0, 0, width, height);
context.drawImage(decoded.source, 0, 0, width, height);
const blob = await canvasToBlob(canvas, PREVIEW_QUALITY);
return URL.createObjectURL(blob);
} catch (error) {
console.warn(`미리보기 썸네일 생성 실패: ${file.name}`, error);
return null;
} finally {
decoded.dispose();
}
}
+49
View File
@@ -0,0 +1,49 @@
import type { ImageItem } from '../types/api';
/**
* 같은 파일을 가리키는지 판별하기 위한 키.
*
* 브라우저는 동일한 파일에 대해 name/size/lastModified 를 항상 동일하게 주므로,
* 내용 해시를 계산하지 않고도 비용 없이 중복을 걸러낼 수 있다.
*/
export function getFileIdentity(file: Pick<File, 'name' | 'size' | 'lastModified'>): string {
return `${file.name}|${file.size}|${file.lastModified}`;
}
export interface FileDedupResult {
/** 목록에 새로 넣어야 할 파일 */
newFiles: File[];
/** 중복이라 제외된 파일 수 */
duplicateCount: number;
}
/**
* 이미 목록에 있는 파일, 그리고 이번 배치 안에서 서로 겹치는 파일을 걸러낸다.
*
* url 타입 이미지(크롤링으로 가져온 원격 이미지)는 로컬 파일과 비교할 수단이
* 없으므로 비교 대상에서 제외한다.
*/
export function splitDuplicateFiles(existing: ImageItem[], incoming: File[]): FileDedupResult {
const seen = new Set<string>();
for (const item of existing) {
if (item.type === 'file') {
seen.add(getFileIdentity(item.file));
}
}
const newFiles: File[] = [];
let duplicateCount = 0;
for (const file of incoming) {
const identity = getFileIdentity(file);
if (seen.has(identity)) {
duplicateCount += 1;
continue;
}
seen.add(identity);
newFiles.push(file);
}
return { newFiles, duplicateCount };
}
+83
View File
@@ -0,0 +1,83 @@
import type { ImageUploadResponse, ImageUrlItem } from '../types/api';
import { compressImageForUpload } from './imageCompression.ts';
export const MAX_IMAGES_PER_UPLOAD_TASK = 100;
export type ImageUploadRequest = (formData: FormData) => Promise<ImageUploadResponse>;
export type ImageCompressor = (file: File) => Promise<File>;
interface ImageUploadFormOptions {
imageUrls?: ImageUrlItem[];
file?: File;
taskId?: string;
finalize?: boolean;
}
export function createImageUploadFormData({
imageUrls = [],
file,
taskId,
finalize,
}: ImageUploadFormOptions): FormData {
const formData = new FormData();
if (imageUrls.length > 0) {
formData.append('images_json', JSON.stringify(imageUrls));
}
if (taskId) {
formData.append('task_id', taskId);
}
if (finalize !== undefined) {
formData.append('finalize', String(finalize));
}
if (file) {
formData.append('files', file);
}
return formData;
}
export async function uploadImagesSequentially(
imageUrls: ImageUrlItem[],
files: File[],
sendRequest: ImageUploadRequest,
compressFile: ImageCompressor = compressImageForUpload
): Promise<ImageUploadResponse> {
const totalImageCount = imageUrls.length + files.length;
if (totalImageCount > MAX_IMAGES_PER_UPLOAD_TASK) {
throw new Error(`이미지는 최대 ${MAX_IMAGES_PER_UPLOAD_TASK}장까지 업로드할 수 있습니다.`);
}
if (files.length === 0) {
return sendRequest(createImageUploadFormData({ imageUrls }));
}
let taskId: string | undefined;
let finalResponse: ImageUploadResponse | undefined;
for (let index = 0; index < files.length; index += 1) {
// Compress and upload one source at a time. This prevents both decoded
// image buffers and multipart request bodies from accumulating in memory.
const compressedFile = await compressFile(files[index]);
const isFirstRequest = index === 0;
const isLastRequest = index === files.length - 1;
const formData = createImageUploadFormData({
imageUrls: isFirstRequest ? imageUrls : [],
file: compressedFile,
taskId,
finalize: isLastRequest,
});
finalResponse = await sendRequest(formData);
if (!finalResponse.task_id) {
throw new Error('이미지 업로드 응답에 작업 ID가 없습니다.');
}
if (taskId && finalResponse.task_id !== taskId) {
throw new Error('이미지 업로드 작업 ID가 요청 사이에 변경되었습니다. 다시 시도해주세요.');
}
taskId = finalResponse.task_id;
}
// files.length > 0 guarantees that the loop produced a response.
return finalResponse as ImageUploadResponse;
}
+42
View File
@@ -0,0 +1,42 @@
/**
* 기기의 네이티브 공유 시트를 열고 요청을 처리했는지 반환합니다.
*
* 긴 `text`를 넣으면 카카오 등이 URL을 미리보기가 아니라 본문 텍스트로만 보냅니다.
* 제목·설명은 OG 페이지(`og:title`, `og:description`)에 두고, 여기에는 url(과 짧은 title)만 넘깁니다.
*
* 사용자가 공유 시트를 닫은 경우도 정상적으로 처리된 것으로 간주합니다.
*/
export async function tryNativeShare(data: ShareData): Promise<boolean> {
if (typeof navigator.share !== 'function') {
return false;
}
try {
await navigator.share(data);
return true;
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
return true;
}
return false;
}
}
/** API 서버의 영상 Open Graph 공유 페이지 URL을 만듭니다. */
export function buildVideoShareUrl(apiBaseUrl: string, videoId: number | string): string {
return `${apiBaseUrl.replace(/\/$/, '')}/video/share/${encodeURIComponent(String(videoId))}`;
}
/** 콘텐츠 종류별 공유 URL. video.id 와 ssul_content.id 가 겹치므로 경로를 갈라야 한다. */
export function buildContentShareUrl(
apiBaseUrl: string,
contentId: number | string,
contentType: 'video' | 'ssul' = 'video',
): string {
const base = apiBaseUrl.replace(/\/$/, '');
if (contentType === 'ssul') {
return `${base}/ssul/share/${encodeURIComponent(String(contentId))}`;
}
return buildVideoShareUrl(base, contentId);
}
+76
View File
@@ -0,0 +1,76 @@
/**
* localStorage 키 정의와 정리 함수.
*
* 이 앱에는 라우터도 전역 스토어도 없어서 localStorage 가 사실상의 상태 저장소다.
* 그래서 "언제 무엇을 지우는가"가 흩어지면 조용히 어긋난다 — 이 모듈을 만들기 전에는
* 정리 코드가 5곳에 있었고 지우는 키 목록이 전부 달랐다:
*
* App.tsx initializeOnNewSession video_complete 누락
* GenerationFlow clearAllProjectStorage (프로젝트 키만, 의도된 범위)
* GenerationFlow handleLogout song/video 생성 상태 누락 ← 계정 전환 시 잔류
* api.ts redirectToLogin 위와 동일
* api.ts clearAllLocalData video_complete 누락
*
* 키를 추가할 때는 아래 배열에만 넣으면 5곳에 자동 반영된다.
*/
export const K = {
// 화면 상태
VIEW_MODE: 'castad_view_mode',
ACTIVE_ITEM: 'castad_active_item',
WIZARD_STEP: 'castad_wizard_step',
// 분석 결과
ANALYSIS_DATA: 'castad_analysis_data',
// 생성 진행 상태
SONG_TASK_ID: 'castad_song_task_id',
IMAGE_TASK_ID: 'castad_image_task_id',
SONG_GENERATION: 'castad_song_generation',
VIDEO_GENERATION: 'castad_video_generation',
VIDEO_COMPLETE: 'castad_video_complete',
VIDEO_RATIO: 'castad_video_ratio',
// 썰박스 통합
/** 현재 선택된 파이프라인 ('ado2' | 'ssul') */
PIPELINE: 'castad_pipeline',
/** 진행 중인 썰박스 생성 잡 ID. 권위는 서버(`/ssul/tasks/active`)이고 이건 복구 힌트다 */
SSUL_TASK_ID: 'castad_ssul_task_id',
} as const;
/**
* 하나의 프로젝트(생성 1건)에 딸린 키.
* '새 프로젝트 만들기'로 초기화할 때 지운다. 로그인 상태와 분석 데이터는 남긴다.
*/
export const PROJECT_KEYS: readonly string[] = [
K.WIZARD_STEP,
K.SONG_TASK_ID,
K.IMAGE_TASK_ID,
K.SONG_GENERATION,
K.VIDEO_GENERATION,
K.VIDEO_COMPLETE,
K.VIDEO_RATIO,
K.PIPELINE,
K.SSUL_TASK_ID,
];
/**
* 세션 전체에 걸친 키. 로그아웃·토큰 만료·새 탭 진입 시 전부 지운다.
* PROJECT_KEYS 를 포함한다.
*/
export const SESSION_KEYS: readonly string[] = [
...PROJECT_KEYS,
K.VIEW_MODE,
K.ACTIVE_ITEM,
K.ANALYSIS_DATA,
];
/** 진행 중인 프로젝트 상태만 정리 (로그인·분석 데이터 유지) */
export const clearProjectStorage = (): void => {
PROJECT_KEYS.forEach((key) => localStorage.removeItem(key));
};
/** 세션 상태 전체 정리 (로그아웃·토큰 만료·새 탭) */
export const clearSessionStorage = (): void => {
SESSION_KEYS.forEach((key) => localStorage.removeItem(key));
};
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more