generated from google-gemini/aistudio-repository-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssetLibrary.tsx
More file actions
250 lines (227 loc) · 13.1 KB
/
AssetLibrary.tsx
File metadata and controls
250 lines (227 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
import React, { useState, useMemo, useEffect } from 'react';
import { Brand, BrandAsset, AssetType } from '../types';
import AsyncImage from './AsyncImage';
import FilterIcon from './icons/FilterIcon';
import SwitchVerticalIcon from './icons/SwitchVerticalIcon';
import XMarkIcon from './icons/XMarkIcon';
import ImageIcon from './icons/ImageIcon';
import ExportIcon from './icons/ExportIcon';
import PlayIcon from './icons/PlayIcon';
import { deleteImages, getImage } from '../services/imageDb';
import { generateVideoThumbnail } from '../services/videoUtils';
import AsyncVideo from './AsyncVideo';
import Loader from './Loader';
interface AssetLibraryProps {
brand: Brand;
onUpdateBrand: (updatedBrand: Brand) => void;
onSelectAsset: (assetId: string) => void;
onExportBrand: () => Promise<void>;
isExporting: boolean;
}
const ASSET_TYPE_LABELS: Record<AssetType, string> = {
logo: 'Logo',
palette: 'Palette',
typography: 'Typography',
poster: 'Poster',
banner: 'Banner',
social_ad: 'Social Ad',
instagram_story: 'Instagram Story',
twitter_post: 'Twitter Post',
youtube_thumbnail: 'YouTube Thumbnail',
video_ad: 'Video Ad',
};
const AssetCard: React.FC<{ asset: BrandAsset; onClick: () => void; onDelete: (e: React.MouseEvent) => void; }> = ({ asset, onClick, onDelete }) => {
const [isHovering, setIsHovering] = useState(false);
const [thumbnail, setThumbnail] = useState<string | null>(null);
useEffect(() => {
let isActive = true;
if (asset.type === 'video_ad') {
const getThumb = async () => {
setThumbnail(null); // Reset for new asset
try {
const videoUrl = await getImage(asset.id);
if (videoUrl && isActive) {
const thumbUrl = await generateVideoThumbnail(videoUrl);
if (isActive) setThumbnail(thumbUrl);
}
} catch(e) {
console.error(`Failed to generate thumbnail for ${asset.id}`, e);
}
};
getThumb();
}
return () => { isActive = false; };
}, [asset.id, asset.type]);
const renderContent = () => {
if (asset.type === 'video_ad') {
return isHovering ? (
<AsyncVideo assetId={asset.id} className="w-full h-full object-cover" autoPlay loop muted />
) : (
<>
{thumbnail ? <img src={thumbnail} className="w-full h-full object-cover" alt="Video thumbnail"/> : <div className="w-full h-full flex items-center justify-center"><Loader message="" subMessage=""/></div>}
<div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-100 group-hover:opacity-0 transition-opacity">
<PlayIcon className="w-12 h-12 text-white/80" />
</div>
</>
);
}
if (asset.type === 'palette' && asset.palette) {
return (
<div className="flex flex-col h-full w-full">
{asset.palette.colors.slice(0, 5).map((color) => (
<div key={color.hex} style={{ backgroundColor: color.hex }} className="flex-1" title={`${color.name} (${color.hex})`}></div>
))}
</div>
);
}
if (asset.type === 'typography' && asset.typography) {
return (
<div className="p-4 flex flex-col justify-center items-start h-full bg-slate-100 dark:bg-slate-800 overflow-hidden">
<p
className="text-3xl font-bold text-slate-800 dark:text-slate-100 leading-tight w-full"
style={{ fontFamily: `'${asset.typography.headlineFont.name}', 'Manrope', sans-serif` }}>
Aa
</p>
<p
className="text-sm text-slate-600 dark:text-slate-400 mt-2 leading-snug w-full"
style={{ fontFamily: `'${asset.typography.bodyFont.name}', 'Manrope', sans-serif` }}>
The quick brown fox jumps over the lazy dog.
</p>
</div>
);
}
// For logos, creatives, and other image-based assets
return <AsyncImage assetId={asset.id} alt={asset.prompt} className="w-full h-full object-contain p-2" />;
};
return (
<div onMouseEnter={() => setIsHovering(true)} onMouseLeave={() => setIsHovering(false)} onClick={onClick} className="group relative aspect-square rounded-lg overflow-hidden bg-slate-200 dark:bg-slate-700/50 shadow-md border border-slate-200 dark:border-slate-700/50 cursor-pointer transition-all duration-300 hover:shadow-xl hover:border-indigo-500 dark:hover:border-indigo-400">
{renderContent()}
<div className="absolute bottom-0 left-0 right-0 p-2 bg-gradient-to-t from-black/80 to-transparent">
<h3 className="text-sm font-semibold text-white truncate drop-shadow-md">{ASSET_TYPE_LABELS[asset.type]}</h3>
<p className="text-xs text-slate-300 drop-shadow-md">{new Date(asset.createdAt).toLocaleDateString()}</p>
</div>
<button
onClick={onDelete}
className="absolute top-2 right-2 z-10 p-1.5 bg-black/50 rounded-full text-white opacity-0 group-hover:opacity-100 transition-opacity hover:bg-red-600"
aria-label={`Delete ${ASSET_TYPE_LABELS[asset.type]}`}
title="Delete Asset"
>
<XMarkIcon className="w-4 h-4" />
</button>
</div>
);
};
const AssetLibrary: React.FC<AssetLibraryProps> = ({ brand, onUpdateBrand, onSelectAsset, onExportBrand, isExporting }) => {
const [typeFilters, setTypeFilters] = useState<AssetType[]>([]);
const [tagFilters, setTagFilters] = useState<string[]>([]);
const [sortOrder, setSortOrder] = useState<'newest' | 'oldest'>('newest');
const allAssetTypes = useMemo(() => [...new Set(brand.assets.map(a => a.type))].sort((a,b) => ASSET_TYPE_LABELS[a].localeCompare(ASSET_TYPE_LABELS[b])), [brand.assets]);
const allTags = useMemo(() => [...new Set(brand.assets.flatMap(a => a.tags || []))].sort(), [brand.assets]);
const handleDeleteAsset = async (assetId: string) => {
const assetToDelete = brand.assets.find(a => a.id === assetId);
if (!assetToDelete) return;
if (window.confirm(`Are you sure you want to permanently delete this ${ASSET_TYPE_LABELS[assetToDelete.type]}? This will also delete any associated variants or generated videos and cannot be undone.`)) {
try {
const allAssets = brand.assets;
const idsToDelete = new Set<string>([assetId]);
const findDescendants = (parentId: string) => {
const children = allAssets.filter(a => a.parentId === parentId);
for (const child of children) {
if (!idsToDelete.has(child.id)) {
idsToDelete.add(child.id);
findDescendants(child.id); // Recursively find grandchildren
}
}
};
findDescendants(assetId);
const idsToDeleteArray = Array.from(idsToDelete);
const updatedAssets = allAssets.filter(a => !idsToDelete.has(a.id));
onUpdateBrand({ ...brand, assets: updatedAssets });
// Asynchronously delete from IndexedDB
await deleteImages(idsToDeleteArray);
} catch (err) {
console.error("Failed to delete asset:", err);
// You could add an error state here to display to the user
}
}
};
const filteredAndSortedAssets = useMemo(() => {
let assets = [...brand.assets];
if (typeFilters.length > 0) {
assets = assets.filter(a => typeFilters.includes(a.type));
}
if (tagFilters.length > 0) {
assets = assets.filter(a => tagFilters.every(filterTag => a.tags?.includes(filterTag)));
}
assets.sort((a, b) => {
const dateA = new Date(a.createdAt).getTime();
const dateB = new Date(b.createdAt).getTime();
return sortOrder === 'newest' ? dateB - dateA : dateA - dateB;
});
return assets;
}, [brand.assets, typeFilters, tagFilters, sortOrder]);
const handleTypeFilterToggle = (type: AssetType) => {
setTypeFilters(prev => prev.includes(type) ? prev.filter(t => t !== type) : [...prev, type]);
};
const handleTagFilterToggle = (tag: string) => {
setTagFilters(prev => prev.includes(tag) ? prev.filter(t => t !== tag) : [...prev, tag]);
};
return (
<div className="animate-fade-in">
<div className="bg-white dark:bg-slate-800/50 p-4 rounded-lg shadow-md border border-slate-200 dark:border-slate-700/50 mb-8">
<div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div className="flex-1">
<h3 className="font-semibold text-slate-800 dark:text-slate-200 mb-2 flex items-center gap-2"><FilterIcon className="w-5 h-5" /> Filter Assets</h3>
<div className="flex flex-wrap gap-2">
{allAssetTypes.map(type => (
<button key={type} onClick={() => handleTypeFilterToggle(type)} className={`px-3 py-1 text-xs rounded-full font-semibold transition-colors ${typeFilters.includes(type) ? 'bg-indigo-600 text-white' : 'bg-slate-200 dark:bg-slate-700 hover:bg-slate-300 dark:hover:bg-slate-600 text-slate-700 dark:text-slate-200'}`}>{ASSET_TYPE_LABELS[type]}</button>
))}
{allTags.map(tag => (
<button key={tag} onClick={() => handleTagFilterToggle(tag)} className={`px-3 py-1 text-xs rounded-full font-semibold transition-colors ${tagFilters.includes(tag) ? 'bg-purple-600 text-white' : 'bg-slate-200 dark:bg-slate-700 hover:bg-slate-300 dark:hover:bg-slate-600 text-slate-700 dark:text-slate-200'}`}>#{tag}</button>
))}
</div>
</div>
<div className="flex-shrink-0 flex items-center gap-2">
<button onClick={() => setSortOrder(prev => prev === 'newest' ? 'oldest' : 'newest')} className="flex items-center gap-2 px-3 py-2 text-sm font-semibold bg-slate-200 dark:bg-slate-700 hover:bg-slate-300 dark:hover:bg-slate-600 text-slate-700 dark:text-slate-200 rounded-md transition-colors">
<SwitchVerticalIcon className="w-5 h-5" />
{sortOrder === 'newest' ? 'Newest' : 'Oldest'}
</button>
<button onClick={onExportBrand} disabled={isExporting} className="flex items-center gap-2 px-4 py-2 text-sm font-semibold bg-indigo-600 text-white rounded-lg hover:bg-indigo-500 transition-colors disabled:opacity-50 disabled:cursor-wait shadow">
<ExportIcon className="w-5 h-5" />
{isExporting ? 'Exporting...' : 'Export All'}
</button>
</div>
</div>
{(typeFilters.length > 0 || tagFilters.length > 0) && (
<div className="mt-4 pt-3 border-t border-slate-200 dark:border-slate-700">
<button onClick={() => { setTypeFilters([]); setTagFilters([]); }} className="flex items-center gap-1 text-sm text-indigo-600 dark:text-indigo-400 hover:underline">
<XMarkIcon className="w-4 h-4" /> Clear All Filters
</button>
</div>
)}
</div>
{filteredAndSortedAssets.length > 0 ? (
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4">
{filteredAndSortedAssets.map(asset => (
<AssetCard
key={asset.id}
asset={asset}
onClick={() => onSelectAsset(asset.id)}
onDelete={(e) => {
e.stopPropagation();
handleDeleteAsset(asset.id);
}}
/>
))}
</div>
) : (
<div className="text-center py-20 border-2 border-dashed border-slate-200 dark:border-slate-700 rounded-lg">
<ImageIcon className="w-16 h-16 mx-auto text-slate-400 dark:text-slate-500" />
<h3 className="mt-4 text-lg font-semibold text-slate-700 dark:text-slate-300">No Assets Found</h3>
<p className="mt-1 text-sm text-slate-500 dark:text-slate-400">Try adjusting your filters or generating new assets.</p>
</div>
)}
</div>
);
};
export default AssetLibrary;