Merge branch 'main' into feature-ssulbox
This commit is contained in:
commit
cdddb913a0
@ -211,15 +211,21 @@
|
||||
"selectedImages": "Selected Images",
|
||||
"imageAlt": "Image",
|
||||
"uploadBadge": "Uploaded",
|
||||
"previewUnavailable": "No preview",
|
||||
"imageUpload": "Image Upload",
|
||||
"dragAndDrop": "Drag & drop or\nclick to upload",
|
||||
"videoRatio": "Video Ratio",
|
||||
"minImages": "Min. 5 images",
|
||||
"minImages": "Recommended 30+ images",
|
||||
"youtubeShorts": "YouTube Shorts",
|
||||
"youtubeVideo": "YouTube Video",
|
||||
"back": "Go Back",
|
||||
"loadMore": "Load more",
|
||||
"uploadFailed": "Image upload failed.",
|
||||
"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"
|
||||
},
|
||||
|
||||
@ -259,15 +259,21 @@
|
||||
"selectedImages": "선택된 이미지",
|
||||
"imageAlt": "이미지",
|
||||
"uploadBadge": "업로드",
|
||||
"previewUnavailable": "미리보기 없음",
|
||||
"imageUpload": "이미지 업로드",
|
||||
"dragAndDrop": "이미지를 끌어다 놓거나\n클릭하여 업로드",
|
||||
"videoRatio": "영상 비율",
|
||||
"minImages": "최소 5장",
|
||||
"minImages": "권장 30장 이상",
|
||||
"youtubeShorts": "유튜브 쇼츠",
|
||||
"youtubeVideo": "유튜브 일반",
|
||||
"back": "뒤로가기",
|
||||
"loadMore": "더보기",
|
||||
"uploadFailed": "이미지 업로드에 실패했습니다.",
|
||||
"uploadErrorTitle": "이미지 업로드 초과",
|
||||
"uploadErrorConfirm": "확인",
|
||||
"duplicateSkippedTitle": "중복 이미지 제외",
|
||||
"duplicateSkippedMessage": "이미 추가된 이미지 {{count}}장을 제외했습니다.",
|
||||
"preparingPreviews": "미리보기 준비 중 ({{done}} / {{total}})",
|
||||
"uploading": "업로드 중 (30~60초 소요)",
|
||||
"nextStep": "다음 단계"
|
||||
},
|
||||
|
||||
@ -3,13 +3,19 @@ import React, { useRef, useState, useEffect } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ImageItem, ImageUrlItem } from '../../types/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 {
|
||||
onNext: (imageTaskId: string) => void;
|
||||
onBack?: () => void;
|
||||
imageList: ImageItem[];
|
||||
onRemoveImage: (index: number) => void;
|
||||
onAddImages: (files: File[]) => void;
|
||||
onAddImages: (
|
||||
files: File[],
|
||||
onProgress: (done: number, total: number) => void
|
||||
) => Promise<void>;
|
||||
}
|
||||
|
||||
type VideoRatio = 'vertical' | 'horizontal';
|
||||
@ -27,9 +33,11 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [uploadProgress, setUploadProgress] = useState(0);
|
||||
const [uploadError, setUploadError] = useState<string | null>(null);
|
||||
// 업로드 실패와 중복 제외 안내가 같은 다이얼로그 마크업을 공유한다.
|
||||
const [dialog, setDialog] = useState<{ title: string; message: string } | null>(null);
|
||||
const [videoRatio, setVideoRatio] = useState<VideoRatio>('vertical');
|
||||
const [displayCount, setDisplayCount] = useState(IMAGES_PER_PAGE);
|
||||
const [thumbnailProgress, setThumbnailProgress] = useState<{ done: number; total: number } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const savedRatio = localStorage.getItem('castad_video_ratio') as VideoRatio;
|
||||
@ -38,12 +46,26 @@ 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) => {
|
||||
setVideoRatio(ratio);
|
||||
localStorage.setItem('castad_video_ratio', ratio);
|
||||
};
|
||||
|
||||
const getImageSrc = (item: ImageItem): string => {
|
||||
const getImageSrc = (item: ImageItem): string | null => {
|
||||
return item.type === 'url' ? item.preview_url : item.preview;
|
||||
};
|
||||
|
||||
@ -52,7 +74,7 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
|
||||
setIsUploading(true);
|
||||
setUploadProgress(0);
|
||||
setUploadError(null);
|
||||
setDialog(null);
|
||||
|
||||
const interval = setInterval(() => {
|
||||
setUploadProgress(prev => {
|
||||
@ -85,13 +107,37 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
} catch (error) {
|
||||
clearInterval(interval);
|
||||
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 {
|
||||
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 }),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleDragOver = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
@ -100,10 +146,8 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
const handleDrop = (e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const files = Array.from(e.dataTransfer.files).filter((file: File) =>
|
||||
file.type.startsWith('image/')
|
||||
);
|
||||
if (files.length > 0) onAddImages(files);
|
||||
const files = Array.from(e.dataTransfer.files).filter(isImageInputFile);
|
||||
if (files.length > 0) void runAddImages(files);
|
||||
};
|
||||
|
||||
const handleFileSelect = () => {
|
||||
@ -113,7 +157,7 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const files = e.target.files;
|
||||
if (files && files.length > 0) {
|
||||
onAddImages(Array.from(files));
|
||||
void runAddImages(Array.from(files));
|
||||
e.target.value = '';
|
||||
}
|
||||
};
|
||||
@ -123,6 +167,25 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
|
||||
return (
|
||||
<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">
|
||||
@ -146,6 +209,37 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
</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 - 뒤로가기 버튼 */}
|
||||
<div className="asset-sticky-header">
|
||||
{onBack && (
|
||||
@ -169,6 +263,13 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
<div className="asset-section-header-left">
|
||||
<h3 className="asset-section-title">{t('assetManagement.selectedImages')}</h3>
|
||||
<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>
|
||||
<button onClick={handleFileSelect} className="asset-mobile-upload-btn">
|
||||
<svg width="16" height="16" viewBox="0 0 16 16" fill="none">
|
||||
@ -182,27 +283,46 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
<div className="asset-image-list">
|
||||
{visibleImages.length > 0 && (
|
||||
<div className="asset-image-grid">
|
||||
{visibleImages.map((item, i) => (
|
||||
<div key={i} className="asset-image-item">
|
||||
<img
|
||||
src={getImageSrc(item)}
|
||||
alt={`${t('assetManagement.imageAlt')} ${i + 1}`}
|
||||
referrerPolicy="no-referrer"
|
||||
/>
|
||||
{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>
|
||||
))}
|
||||
{visibleImages.map((item, i) => {
|
||||
const src = getImageSrc(item);
|
||||
const fileName = item.type === 'file' ? item.file.name : '';
|
||||
return (
|
||||
<div key={i} className="asset-image-item">
|
||||
{src ? (
|
||||
<img
|
||||
src={src}
|
||||
alt={`${t('assetManagement.imageAlt')} ${i + 1}`}
|
||||
referrerPolicy="no-referrer"
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
/>
|
||||
) : (
|
||||
<div className="asset-image-placeholder" title={fileName}>
|
||||
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
|
||||
<rect x="3" y="3" width="18" height="18" rx="2"/>
|
||||
<circle cx="8.5" cy="8.5" r="1.5"/>
|
||||
<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>
|
||||
@ -268,9 +388,6 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
|
||||
{/* Fixed Footer - 다음 단계 버튼 */}
|
||||
<div className="asset-sticky-footer">
|
||||
{uploadError && (
|
||||
<p className="text-red-500 text-sm mb-2">{uploadError}</p>
|
||||
)}
|
||||
<button
|
||||
onClick={handleNextWithUpload}
|
||||
disabled={imageList.length === 0 || isUploading}
|
||||
@ -283,7 +400,7 @@ const AssetManagementContent: React.FC<AssetManagementContentProps> = ({
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
accept="image/*,.heic,.heif"
|
||||
multiple
|
||||
onChange={handleFileChange}
|
||||
className="hidden"
|
||||
|
||||
@ -18,8 +18,18 @@ import { crawlUrl, autocomplete, marketingAnalysis, AutocompleteRequest, getUser
|
||||
import WizardStepper from '../../components/WizardStepper';
|
||||
import { NAV, GATED_ITEMS, sanitizeActiveItem, MyInfoTab } from '../../components/navItems';
|
||||
import { useIsMobile } from '../../utils/useIsMobile';
|
||||
import { createPreviewThumbnail } from '../../utils/imageCompression';
|
||||
|
||||
import { saveSearchHistory } from '../../components/SearchHistory/useSearchHistory';
|
||||
|
||||
/** 파일 이미지의 썸네일 objectURL 을 일괄 해제한다. preview 가 null 인 항목은 건너뛴다. */
|
||||
const revokeAllPreviews = (items: ImageItem[]) => {
|
||||
items.forEach(item => {
|
||||
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';
|
||||
@ -241,6 +251,15 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
|
||||
};
|
||||
|
||||
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);
|
||||
|
||||
// analysisData 변경 시 m_id가 바뀐 경우(새로운 분석)에만 imageList 업데이트
|
||||
@ -249,6 +268,8 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
|
||||
console.log('[GenerationFlow] analysisData updated, m_id:', analysisData?.m_id);
|
||||
if (analysisData?.image_list && analysisData.image_list.length > 0) {
|
||||
if (prevAnalysisMIdRef.current !== analysisData.m_id) {
|
||||
// 목록을 통째로 교체하므로 기존 파일 썸네일을 먼저 해제한다.
|
||||
revokeAllPreviews(imageListRef.current);
|
||||
setImageList(analysisData.image_list.map(item => ({ type: 'url' as const, url: item.original, preview_url: item.preview })));
|
||||
}
|
||||
}
|
||||
@ -258,21 +279,35 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
|
||||
const handleRemoveImage = (index: number) => {
|
||||
setImageList(prev => {
|
||||
const item = prev[index];
|
||||
// 파일 이미지인 경우 메모리 해제
|
||||
if (item.type === 'file') {
|
||||
// 파일 이미지인 경우 썸네일 메모리 해제 (생성 실패 시 preview 는 null)
|
||||
if (item.type === 'file' && item.preview) {
|
||||
URL.revokeObjectURL(item.preview);
|
||||
}
|
||||
return prev.filter((_, i) => i !== index);
|
||||
});
|
||||
};
|
||||
|
||||
const handleAddImages = (files: File[]) => {
|
||||
const newImages: ImageItem[] = files.map(file => ({
|
||||
type: 'file',
|
||||
file,
|
||||
preview: URL.createObjectURL(file),
|
||||
}));
|
||||
// 새로 업로드된 이미지를 배열 앞에 추가 (최신 이미지가 상단에 표시)
|
||||
const handleAddImages = async (
|
||||
files: File[],
|
||||
onProgress: (done: number, total: number) => void
|
||||
) => {
|
||||
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]);
|
||||
};
|
||||
|
||||
@ -284,6 +319,7 @@ const GenerationFlow: React.FC<GenerationFlowProps> = ({
|
||||
setSongTaskId(null);
|
||||
setImageTaskId(null);
|
||||
setAnalysisData(null);
|
||||
revokeAllPreviews(imageListRef.current);
|
||||
setImageList([]);
|
||||
setActiveItem(NAV.HOME);
|
||||
};
|
||||
|
||||
@ -832,6 +832,72 @@
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
/* Upload Error Dialog */
|
||||
.asset-upload-error-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1100;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 1rem;
|
||||
background: rgba(0, 17, 18, 0.82);
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
|
||||
.asset-upload-error-dialog {
|
||||
width: min(100%, 420px);
|
||||
padding: 1.5rem;
|
||||
background: #01393B;
|
||||
border: 1px solid #379599;
|
||||
border-radius: 20px;
|
||||
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
|
||||
.asset-upload-error-title {
|
||||
margin: 0;
|
||||
color: #94FBE0;
|
||||
font-size: 1.25rem;
|
||||
font-weight: 700;
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.asset-upload-error-message {
|
||||
margin: 0.75rem 0 1.5rem;
|
||||
color: #E5F1F2;
|
||||
font-size: 0.9375rem;
|
||||
line-height: 1.6;
|
||||
overflow-wrap: anywhere;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.asset-upload-error-confirm {
|
||||
width: 100%;
|
||||
min-height: 44px;
|
||||
padding: 0.75rem 1rem;
|
||||
color: #002224;
|
||||
background: #94FBE0;
|
||||
border: 0;
|
||||
border-radius: 999px;
|
||||
font-size: 0.9375rem;
|
||||
font-weight: 700;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s, transform 0.2s;
|
||||
}
|
||||
|
||||
.asset-upload-error-confirm:hover {
|
||||
background: #B8FFE9;
|
||||
}
|
||||
|
||||
.asset-upload-error-confirm:active {
|
||||
transform: translateY(1px);
|
||||
}
|
||||
|
||||
.asset-upload-error-confirm:focus-visible {
|
||||
outline: 3px solid #CFABFB;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
|
||||
/* Fixed Header - 뒤로가기 */
|
||||
.asset-sticky-header {
|
||||
@ -1031,6 +1097,20 @@
|
||||
letter-spacing: -0.006em;
|
||||
}
|
||||
|
||||
.asset-section-count {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
color: #9BCACC;
|
||||
line-height: 1.19;
|
||||
letter-spacing: -0.006em;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* 업로드 상한(100장)을 넘긴 상태. 추가 자체는 막지 않고 시각적으로만 경고한다. */
|
||||
.asset-section-count-over {
|
||||
color: #fca5a5;
|
||||
}
|
||||
|
||||
/* Asset Section Title */
|
||||
.asset-section-title {
|
||||
font-size: 1.5rem;
|
||||
@ -1133,6 +1213,30 @@
|
||||
object-fit: cover;
|
||||
}
|
||||
|
||||
.asset-image-placeholder {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 6px;
|
||||
padding: 8px;
|
||||
background-color: #001416;
|
||||
color: #379599;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.asset-image-placeholder-name {
|
||||
width: 100%;
|
||||
font-size: 0.6875rem;
|
||||
line-height: 1.2;
|
||||
color: #9BCACC;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.asset-image-badge {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
|
||||
@ -61,8 +61,8 @@ export interface UrlImage {
|
||||
// 업로드된 파일 이미지
|
||||
export interface FileImage {
|
||||
type: 'file';
|
||||
file: File;
|
||||
preview: string; // createObjectURL로 생성된 미리보기 URL
|
||||
file: File; // 업로드용 원본. 썸네일로 대체하지 않는다.
|
||||
preview: string | null; // 미리보기용 축소 썸네일 objectURL. 생성 실패 시 null.
|
||||
}
|
||||
|
||||
export type ImageItem = UrlImage | FileImage;
|
||||
|
||||
@ -37,6 +37,7 @@ import {
|
||||
ContentType,
|
||||
LikeToggleResponse,
|
||||
} from '../types/api';
|
||||
import { uploadImagesSequentially } from './imageUpload.ts';
|
||||
|
||||
export const API_URL = import.meta.env.VITE_API_URL || 'http://40.82.133.44';
|
||||
console.log('[API] API_URL:', API_URL);
|
||||
@ -718,18 +719,10 @@ export async function uploadImages(
|
||||
imageUrls: ImageUrlItem[],
|
||||
files: File[]
|
||||
): Promise<ImageUploadResponse> {
|
||||
const formData = new FormData();
|
||||
|
||||
// URL 이미지들을 images_json으로 전달
|
||||
if (imageUrls.length > 0) {
|
||||
formData.append('images_json', JSON.stringify(imageUrls));
|
||||
}
|
||||
|
||||
// 파일들을 files로 전달
|
||||
files.forEach((file) => {
|
||||
formData.append('files', file);
|
||||
});
|
||||
return uploadImagesSequentially(imageUrls, files, postImageUpload);
|
||||
}
|
||||
|
||||
async function postImageUpload(formData: FormData): Promise<ImageUploadResponse> {
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), IMAGE_UPLOAD_TIMEOUT);
|
||||
|
||||
@ -740,19 +733,21 @@ export async function uploadImages(
|
||||
signal: controller.signal,
|
||||
});
|
||||
|
||||
clearTimeout(timeoutId);
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 413) {
|
||||
throw new Error('이미지 파일이 너무 커서 업로드할 수 없습니다. 더 작은 이미지를 선택해주세요.');
|
||||
}
|
||||
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;
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
305
src/utils/imageCompression.ts
Normal file
305
src/utils/imageCompression.ts
Normal 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
src/utils/imageDedup.ts
Normal file
49
src/utils/imageDedup.ts
Normal 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
src/utils/imageUpload.ts
Normal file
83
src/utils/imageUpload.ts
Normal 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;
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user