Unrestricted Open-source alternative to AI video platforms — Free AI image & video generation studio with 600+ models (Flux, Midjourney, Kling, Sora, Veo). No content filters. Self-hosted, MIT licensed.
JavaScript ai-art-generatorai-image-generationai-video-generationfal-ai-alternativegenerative-aiimage-to-videoinvideo-alternativekling-ailipsynclitellm-alternativemidjourney-alternativemuapiopen-sourceopenrouter-alternativeseedance2sora-alternativetext-to-imagetext-to-videouncensoredwan-video
feat: finalize studio persistence and multiple reference image upload UI
Jaya Prasad Kavuru91ce11df6f03
diff --git a/app/globals.css b/app/globals.cssindex 2b6d0f1a..820ec7eb 100644--- a/app/globals.css+++ b/app/globals.css@@ -2,21 +2,32 @@@tailwind components;@tailwind utilities;+@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap');+* { box-sizing: border-box; margin: 0; padding: 0; }body {background: #050505;color: white;- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;+ -webkit-font-smoothing: antialiased;}:root {--color-primary: #d9ff00;- --bg-app: #050505;+ --bg-app: #030303;--bg-panel: #0a0a0a;--bg-card: #111111;- --border-color: rgba(255,255,255,0.08);- --border-radius-xl: 1rem;+ --border-color: rgba(255,255,255,0.05);+ --border-radius-xl: 0.75rem;+ --glass-bg: rgba(255, 255, 255, 0.03);+ --glass-border: rgba(255, 255, 255, 0.08);+}++.glass-panel {+ background: var(--glass-bg);+ backdrop-filter: blur(12px);+ border: 1px solid var(--glass-border);}.custom-scrollbar::-webkit-scrollbar { width: 4px; }@@ -24,7 +35,7 @@ body {.custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.1); border-radius: 2px; }@keyframes fade-in-up {- from { opacity: 0; transform: translateY(16px); }+ from { opacity: 0; transform: translateY(12px); }to { opacity: 1; transform: translateY(0); }}-.animate-fade-in-up { animation: fade-in-up 0.4s ease forwards; }+.animate-fade-in-up { animation: fade-in-up 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards; }diff --git a/components/ApiKeyModal.js b/components/ApiKeyModal.jsindex f01004be..e0a7fc22 100644--- a/components/ApiKeyModal.js+++ b/components/ApiKeyModal.js@@ -14,50 +14,50 @@ export default function ApiKeyModal({ onSave }) {};return (- <div className="min-h-screen bg-[#050505] flex items-center justify-center px-4">- <div className="w-full max-w-md bg-[#0a0a0a] border border-white/10 rounded-3xl p-8">- <div className="flex flex-col items-center text-center mb-8">- <div className="w-16 h-16 bg-[#d9ff00]/10 rounded-2xl flex items-center justify-center border border-[#d9ff00]/20 mb-6">- <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="#d9ff00" strokeWidth="1.5">- <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L12 17.25l-4.5-4.5L15.5 7.5z"/>+ <div className="min-h-screen bg-[#030303] flex items-center justify-center px-4 font-inter">+ <div className="w-full max-w-sm bg-[#0a0a0a]/40 backdrop-blur-xl border border-white/10 rounded-xl p-10 shadow-2xl">+ <div className="flex flex-col items-center text-center mb-10">+ <div className="w-14 h-14 bg-[#d9ff00]/5 rounded-2xl flex items-center justify-center border border-[#d9ff00]/10 mb-6 group hover:border-[#d9ff00]/30 transition-colors">+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#d9ff00" strokeWidth="1.5" className="group-hover:scale-110 transition-transform">+ <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L12 17.25l-4.5-4.5L15.5 7.5z" strokeLinecap="round" strokeLinejoin="round"/></svg></div>- <h1 className="text-2xl font-black text-white uppercase tracking-wider mb-2">+ <h1 className="text-xl font-bold text-white tracking-tight mb-2">Open Higgsfield AI</h1>- <p className="text-white/40 text-sm">- Enter your <a href="https://muapi.ai" target="_blank" rel="noreferrer" className="text-[#d9ff00] hover:underline">Muapi.ai</a> API key to start generating+ <p className="text-white/40 text-[13px] leading-relaxed px-4">+ Enter your <a href="https://muapi.ai" target="_blank" rel="noreferrer" className="text-[#d9ff00] hover:text-[#e5ff33] transition-colors">Muapi.ai</a> API key to start creating</p></div>- <form onSubmit={handleSubmit} className="space-y-4">- <div>- <label className="block text-xs font-bold text-white/40 uppercase tracking-widest mb-2">- Muapi API Key+ <form onSubmit={handleSubmit} className="space-y-6">+ <div className="space-y-2">+ <label className="block text-xs font-bold text-white/30 ml-1">+ API Access Key</label><inputtype="password"value={key}onChange={(e) => { setKey(e.target.value); setError(''); }}- placeholder="Enter your API key..."- className="w-full bg-black/40 border border-white/5 rounded-xl px-4 py-3 text-white placeholder:text-white/20 focus:outline-none focus:border-[#d9ff00]/40 transition-colors"+ placeholder="Paste your key here..."+ className="w-full bg-white/5 border border-white/[0.03] rounded-md px-5 py-3 text-sm text-white placeholder:text-white/10 focus:outline-none focus:ring-1 focus:ring-[#d9ff00]/30 focus:bg-white/[0.07] transition-all"suppressHydrationWarning/>- {error && <p className="mt-1 text-red-400 text-xs">{error}</p>}+ {error && <p className="mt-2 text-red-500/80 text-[11px] font-medium ml-1">{error}</p>}</div><buttontype="submit"- className="w-full bg-[#d9ff00] text-black font-black py-3 rounded-xl hover:opacity-90 transition-opacity"+ className="w-full bg-[#d9ff00] text-black font-medium py-2.5 rounded-md hover:bg-[#e5ff33] hover:scale-[1.02] active:scale-[0.98] transition-all shadow-lg shadow-[#d9ff00]/5"suppressHydrationWarning>- Launch Studio+ Get Started</button>- <p className="text-center text-xs text-white/30">- Don't have a key?{' '}- <a href="https://muapi.ai" target="_blank" rel="noreferrer" className="text-[#d9ff00] hover:underline">- Get one free at Muapi.ai →+ <p className="text-center text-[12px] text-white/20 pt-2">+ Need a key?{' '}+ <a href="https://muapi.ai" target="_blank" rel="noreferrer" className="text-white/40 hover:text-[#d9ff00] transition-colors font-medium">+ Get one free →</a></p></form>diff --git a/components/StandaloneShell.js b/components/StandaloneShell.jsindex b1424212..d4e029e8 100644--- a/components/StandaloneShell.js+++ b/components/StandaloneShell.js@@ -1,7 +1,7 @@'use client';import { useState, useEffect, useCallback } from 'react';-import { ImageStudio, VideoStudio, LipSyncStudio, CinemaStudio } from 'studio';+import { ImageStudio, VideoStudio, LipSyncStudio, CinemaStudio, getUserBalance } from 'studio';import ApiKeyModal from './ApiKeyModal';const TABS = [@@ -16,25 +16,47 @@ const STORAGE_KEY = 'muapi_key';export default function StandaloneShell() {const [apiKey, setApiKey] = useState(null);const [activeTab, setActiveTab] = useState('image');+ const [balance, setBalance] = useState(null);const [showSettings, setShowSettings] = useState(false);const [hasMounted, setHasMounted] = useState(false);+ const fetchBalance = useCallback(async (key) => {+ try {+ const data = await getUserBalance(key);+ setBalance(data.balance);+ } catch (err) {+ console.error('Balance fetch failed:', err);+ }+ }, []);+useEffect(() => {setHasMounted(true);const stored = localStorage.getItem(STORAGE_KEY);- if (stored) setApiKey(stored);- }, []);+ if (stored) {+ setApiKey(stored);+ fetchBalance(stored);+ }+ }, [fetchBalance]);const handleKeySave = useCallback((key) => {localStorage.setItem(STORAGE_KEY, key);setApiKey(key);- }, []);+ fetchBalance(key);+ }, [fetchBalance]);const handleKeyChange = useCallback(() => {localStorage.removeItem(STORAGE_KEY);setApiKey(null);+ setBalance(null);}, []);+ // Poll for balance every 30 seconds if key is present+ useEffect(() => {+ if (!apiKey) return;+ const interval = setInterval(() => fetchBalance(apiKey), 30000);+ return () => clearInterval(interval);+ }, [apiKey, fetchBalance]);+if (!hasMounted) return (<div className="min-h-screen bg-[#050505] flex items-center justify-center"><div className="animate-spin text-[#d9ff00] text-3xl">◌</div>@@ -46,39 +68,55 @@ export default function StandaloneShell() {}return (- <div className="h-screen bg-[#050505] flex flex-col overflow-hidden">+ <div className="h-screen bg-[#030303] flex flex-col overflow-hidden text-white">{/* Header */}- <header className="flex-shrink-0 flex items-center justify-between px-4 pt-4 pb-0 border-b border-white/5">- <div className="flex items-center gap-3">- <span className="text-white font-black text-lg tracking-wider uppercase">- Open Higgsfield AI- </span>+ <header className="flex-shrink-0 h-14 border-b border-white/[0.03] flex items-center justify-between px-6 bg-black/20 backdrop-blur-md z-40">+ {/* Left: Logo */}+ <div className="flex items-center gap-2">+ <div className="w-8 h-8 bg-white rounded-lg flex items-center justify-center">+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="black" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">+ <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5"/>+ </svg>+ </div>+ <span className="text-sm font-bold tracking-tight hidden sm:block">OpenHiggsfield</span></div>- {/* Tabs */}- <nav className="flex items-center gap-1">+ {/* Center: Navigation */}+ <nav className="absolute left-1/2 -translate-x-1/2 flex items-center gap-6">{TABS.map((tab) => (<buttonkey={tab.id}onClick={() => setActiveTab(tab.id)}- className={`px-4 py-2 text-sm font-medium rounded-t-lg transition-colors ${+ className={`relative py-4 text-[13px] font-medium transition-all whitespace-nowrap px-1 ${activeTab === tab.id- ? 'bg-[#d9ff00] text-black'+ ? 'text-[#d9ff00]': 'text-white/50 hover:text-white'}`}>{tab.label}+ {activeTab === tab.id && (+ <div className="absolute bottom-0 left-0 right-0 h-[2px] bg-[#d9ff00] rounded-full" />+ )}</button>))}</nav>- {/* Settings */}- <button- onClick={() => setShowSettings(true)}- className="text-white/40 hover:text-white text-sm transition-colors"- >- ⚙ Settings- </button>+ {/* Right: Actions */}+ <div className="flex items-center gap-4">+ <div className="flex items-center gap-3 bg-white/5 px-3 py-1.5 rounded-full border border-white/5 transition-colors">+ <div className="w-2 h-2 rounded-full bg-green-500 animate-pulse" />+ <div className="flex flex-col">+ <span className="text-xs font-bold text-white/90">+ ${balance !== null ? `${balance}` : '---'}+ </span>+ </div>+ </div>++ <div+ onClick={() => setShowSettings(true)}+ className="w-8 h-8 rounded-full bg-gradient-to-tr from-[#d9ff00] to-yellow-200 border border-white/20 cursor-pointer hover:scale-105 transition-transform"+ />+ </div></header>{/* Studio Content */}@@ -91,22 +129,34 @@ export default function StandaloneShell() {{/* Settings Modal */}{showSettings && (- <div className="fixed inset-0 bg-black/80 flex items-center justify-center z-50">- <div className="bg-[#111] border border-white/10 rounded-2xl p-8 w-full max-w-md">- <h2 className="text-white font-bold text-xl mb-6">Settings</h2>- <p className="text-white/50 text-sm mb-4">- Current API key: <span className="text-white/80 font-mono">{apiKey.slice(0, 8)}••••••••</span>+ <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-50 animate-fade-in-up">+ <div className="bg-[#0a0a0a] border border-white/10 rounded-xl p-8 w-full max-w-sm shadow-2xl">+ <h2 className="text-white font-bold text-lg mb-2">Settings</h2>+ <p className="text-white/40 text-[13px] mb-8">+ Manage your AI studio preferences and authentication.</p>++ <div className="space-y-4 mb-8">+ <div className="bg-white/5 border border-white/[0.03] rounded-md p-4">+ <label className="block text-xs font-bold text-white/30 mb-2">+ Active API Key+ </label>+ <div className="text-[13px] font-mono text-white/80">+ {apiKey.slice(0, 8)}••••••••••••••••+ </div>+ </div>+ </div>+<div className="flex gap-3"><buttononClick={handleKeyChange}- className="flex-1 py-2 rounded-lg bg-red-500/20 text-red-400 hover:bg-red-500/30 text-sm transition-colors"+ className="flex-1 h-10 rounded-md bg-red-500/10 text-red-400 hover:bg-red-500/20 text-xs font-semibold transition-all">- Change API Key+ Change Key</button><buttononClick={() => setShowSettings(false)}- className="flex-1 py-2 rounded-lg bg-white/5 text-white hover:bg-white/10 text-sm transition-colors"+ className="flex-1 h-10 rounded-md bg-white/5 text-white/80 hover:bg-white/10 text-xs font-semibold transition-all border border-white/5">Close</button>diff --git a/packages/studio/src/components/CinemaStudio.jsx b/packages/studio/src/components/CinemaStudio.jsxindex fea7ebfa..aae308e0 100644--- a/packages/studio/src/components/CinemaStudio.jsx+++ b/packages/studio/src/components/CinemaStudio.jsx@@ -1,782 +1,911 @@"use client";-import { useState, useEffect, useRef, useCallback } from 'react';-import { generateImage } from '../muapi.js';+import { useState, useEffect, useRef, useCallback } from "react";+import { generateImage } from "../muapi.js";// ─── Constants (inlined from promptUtils) ───────────────────────────────────const CAMERA_MAP = {- "Modular 8K Digital": "modular 8K digital cinema camera",- "Full-Frame Cine Digital": "full-frame digital cinema camera",- "Grand Format 70mm Film": "grand format 70mm film camera",- "Studio Digital S35": "Super 35 studio digital camera",- "Classic 16mm Film": "classic 16mm film camera",- "Premium Large Format Digital": "premium large-format digital cinema camera"+ "Modular 8K Digital": "modular 8K digital cinema camera",+ "Full-Frame Cine Digital": "full-frame digital cinema camera",+ "Grand Format 70mm Film": "grand format 70mm film camera",+ "Studio Digital S35": "Super 35 studio digital camera",+ "Classic 16mm Film": "classic 16mm film camera",+ "Premium Large Format Digital": "premium large-format digital cinema camera",};const LENS_MAP = {- "Creative Tilt Lens": "creative tilt lens effect",- "Compact Anamorphic": "compact anamorphic lens",- "Extreme Macro": "extreme macro lens",- "70s Cinema Prime": "1970s cinema prime lens",- "Classic Anamorphic": "classic anamorphic lens",- "Premium Modern Prime": "premium modern prime lens",- "Warm Cinema Prime": "warm-toned cinema prime lens",- "Swirl Bokeh Portrait": "swirl bokeh portrait lens",- "Vintage Prime": "vintage prime lens",- "Halation Diffusion": "halation diffusion filter",- "Clinical Sharp Prime": "ultra-sharp clinical prime lens"+ "Creative Tilt Lens": "creative tilt lens effect",+ "Compact Anamorphic": "compact anamorphic lens",+ "Extreme Macro": "extreme macro lens",+ "70s Cinema Prime": "1970s cinema prime lens",+ "Classic Anamorphic": "classic anamorphic lens",+ "Premium Modern Prime": "premium modern prime lens",+ "Warm Cinema Prime": "warm-toned cinema prime lens",+ "Swirl Bokeh Portrait": "swirl bokeh portrait lens",+ "Vintage Prime": "vintage prime lens",+ "Halation Diffusion": "halation diffusion filter",+ "Clinical Sharp Prime": "ultra-sharp clinical prime lens",};const FOCAL_PERSPECTIVE = {- 8: "ultra-wide perspective",- 14: "wide-angle perspective",- 24: "wide-angle dynamic perspective",- 35: "natural cinematic perspective",- 50: "standard portrait perspective",- 85: "classic portrait perspective"+ 8: "ultra-wide perspective",+ 14: "wide-angle perspective",+ 24: "wide-angle dynamic perspective",+ 35: "natural cinematic perspective",+ 50: "standard portrait perspective",+ 85: "classic portrait perspective",};const APERTURE_EFFECT = {- "f/1.4": "shallow depth of field, creamy bokeh",- "f/4": "balanced depth of field",- "f/11": "deep focus clarity, sharp foreground to background"+ "f/1.4": "shallow depth of field, creamy bokeh",+ "f/4": "balanced depth of field",+ "f/11": "deep focus clarity, sharp foreground to background",};const ASSET_URLS = {- "Modular 8K Digital": "/assets/cinema/modular_8k_digital.webp",- "Full-Frame Cine Digital": "/assets/cinema/full_frame_cine_digital.webp",- "Grand Format 70mm Film": "/assets/cinema/grand_format_70mm_film.webp",- "Studio Digital S35": "/assets/cinema/studio_digital_s35.webp",- "Classic 16mm Film": "/assets/cinema/classic_16mm_film.webp",- "Premium Large Format Digital": "/assets/cinema/premium_large_format_digital.webp",- "Creative Tilt Lens": "/assets/cinema/creative_tilt_lens.webp",- "Compact Anamorphic": "/assets/cinema/compact_anamorphic.webp",- "Extreme Macro": "/assets/cinema/extreme_macro.webp",- "70s Cinema Prime": "/assets/cinema/70s_cinema_prime.webp",- "Classic Anamorphic": "/assets/cinema/classic_anamorphic.webp",- "Premium Modern Prime": "/assets/cinema/premium_modern_prime.webp",- "Warm Cinema Prime": "/assets/cinema/warm_cinema_prime.webp",- "Swirl Bokeh Portrait": "/assets/cinema/swirl_bokeh_portrait.webp",- "Vintage Prime": "/assets/cinema/vintage_prime.webp",- "Halation Diffusion": "/assets/cinema/halation_diffusion.webp",- "Clinical Sharp Prime": "/assets/cinema/clinical_sharp_prime.webp",- "f/1.4": "/assets/cinema/f_1_4.webp",- "f/4": "/assets/cinema/f_4.webp",- "f/11": "/assets/cinema/f_11.webp"+ "Modular 8K Digital": "/assets/cinema/modular_8k_digital.webp",+ "Full-Frame Cine Digital": "/assets/cinema/full_frame_cine_digital.webp",+ "Grand Format 70mm Film": "/assets/cinema/grand_format_70mm_film.webp",+ "Studio Digital S35": "/assets/cinema/studio_digital_s35.webp",+ "Classic 16mm Film": "/assets/cinema/classic_16mm_film.webp",+ "Premium Large Format Digital":+ "/assets/cinema/premium_large_format_digital.webp",+ "Creative Tilt Lens": "/assets/cinema/creative_tilt_lens.webp",+ "Compact Anamorphic": "/assets/cinema/compact_anamorphic.webp",+ "Extreme Macro": "/assets/cinema/extreme_macro.webp",+ "70s Cinema Prime": "/assets/cinema/70s_cinema_prime.webp",+ "Classic Anamorphic": "/assets/cinema/classic_anamorphic.webp",+ "Premium Modern Prime": "/assets/cinema/premium_modern_prime.webp",+ "Warm Cinema Prime": "/assets/cinema/warm_cinema_prime.webp",+ "Swirl Bokeh Portrait": "/assets/cinema/swirl_bokeh_portrait.webp",+ "Vintage Prime": "/assets/cinema/vintage_prime.webp",+ "Halation Diffusion": "/assets/cinema/halation_diffusion.webp",+ "Clinical Sharp Prime": "/assets/cinema/clinical_sharp_prime.webp",+ "f/1.4": "/assets/cinema/f_1_4.webp",+ "f/4": "/assets/cinema/f_4.webp",+ "f/11": "/assets/cinema/f_11.webp",};-const ASPECT_RATIOS = ['16:9', '21:9', '9:16', '1:1', '4:5'];-const RESOLUTIONS = ['1K', '2K', '4K'];+const ASPECT_RATIOS = ["16:9", "21:9", "9:16", "1:1", "4:5"];+const RESOLUTIONS = ["1K", "2K", "4K"];const CAMERAS = Object.keys(CAMERA_MAP);const LENSES = Object.keys(LENS_MAP);-const FOCAL_LENGTHS = Object.keys(FOCAL_PERSPECTIVE).map(k => parseInt(k));+const FOCAL_LENGTHS = Object.keys(FOCAL_PERSPECTIVE).map((k) => parseInt(k));const APERTURES = Object.keys(APERTURE_EFFECT);-function buildNanoBananaPrompt(basePrompt, camera, lens, focalLength, aperture) {- const cameraDesc = CAMERA_MAP[camera] || camera;- const lensDesc = LENS_MAP[lens] || lens;- const perspective = FOCAL_PERSPECTIVE[focalLength] || "";- const depthEffect = APERTURE_EFFECT[aperture] || "";- const qualityTags = ["professional photography", "ultra-detailed", "8K resolution"];- const parts = [- basePrompt,- `shot on a ${cameraDesc}`,- `using a ${lensDesc} at ${focalLength}mm ${perspective ? `(${perspective})` : ''}`,- `aperture ${aperture}`,- depthEffect,- "cinematic lighting",- "natural color science",- "high dynamic range",- qualityTags.join(", ")- ];- return parts.filter(p => p && p.trim() !== "").join(", ");+function buildNanoBananaPrompt(+ basePrompt,+ camera,+ lens,+ focalLength,+ aperture,+) {+ const cameraDesc = CAMERA_MAP[camera] || camera;+ const lensDesc = LENS_MAP[lens] || lens;+ const perspective = FOCAL_PERSPECTIVE[focalLength] || "";+ const depthEffect = APERTURE_EFFECT[aperture] || "";+ const qualityTags = [+ "professional photography",+ "ultra-detailed",+ "8K resolution",+ ];+ const parts = [+ basePrompt,+ `shot on a ${cameraDesc}`,+ `using a ${lensDesc} at ${focalLength}mm ${perspective ? `(${perspective})` : ""}`,+ `aperture ${aperture}`,+ depthEffect,+ "cinematic lighting",+ "natural color science",+ "high dynamic range",+ qualityTags.join(", "),+ ];+ return parts.filter((p) => p && p.trim() !== "").join(", ");}// ─── Dropdown ────────────────────────────────────────────────────────────────function Dropdown({ items, selected, onSelect, triggerRef, onClose }) {- const menuRef = useRef(null);- const [position, setPosition] = useState({ bottom: 0, left: 0 });-- useEffect(() => {- if (triggerRef.current) {- const rect = triggerRef.current.getBoundingClientRect();- setPosition({- bottom: window.innerHeight - rect.top + 8,- left: rect.left- });- }-- const handler = (e) => {- if (- menuRef.current &&- !menuRef.current.contains(e.target) &&- triggerRef.current &&- !triggerRef.current.contains(e.target)- ) {- onClose();- }- };- const timer = setTimeout(() => document.addEventListener('click', handler), 0);- return () => {- clearTimeout(timer);- document.removeEventListener('click', handler);- };- }, [triggerRef, onClose]);-- return (- <div- ref={menuRef}- className="custom-dropdown fixed bg-[#1a1a1a] border border-white/10 rounded-xl py-1 shadow-2xl z-50 flex flex-col min-w-[100px] animate-fade-in"- style={{ bottom: position.bottom, left: position.left }}- >- {items.map(item => (- <button- key={item}- className={`px-3 py-2 text-xs font-bold text-left hover:bg-white/10 transition-colors ${item === selected ? 'text-primary' : 'text-white'}`}- onClick={(e) => {- e.stopPropagation();- onSelect(item);- onClose();- }}- >- {item}- </button>- ))}- </div>+ const menuRef = useRef(null);+ const [position, setPosition] = useState({ bottom: 0, left: 0 });++ useEffect(() => {+ if (triggerRef.current) {+ const rect = triggerRef.current.getBoundingClientRect();+ setPosition({+ bottom: window.innerHeight - rect.top + 8,+ left: rect.left,+ });+ }++ const handler = (e) => {+ if (+ menuRef.current &&+ !menuRef.current.contains(e.target) &&+ triggerRef.current &&+ !triggerRef.current.contains(e.target)+ ) {+ onClose();+ }+ };+ const timer = setTimeout(+ () => document.addEventListener("click", handler),+ 0,);+ return () => {+ clearTimeout(timer);+ document.removeEventListener("click", handler);+ };+ }, [triggerRef, onClose]);++ return (+ <div+ ref={menuRef}+ className="custom-dropdown fixed bg-[#1a1a1a] border border-white/10 rounded-xl py-1 shadow-2xl z-50 flex flex-col min-w-[100px] animate-fade-in"+ style={{ bottom: position.bottom, left: position.left }}+ >+ {items.map((item) => (+ <button+ key={item}+ className={`px-3 py-2 text-xs font-bold text-left hover:bg-white/10 transition-colors ${item === selected ? "text-primary" : "text-white"}`}+ onClick={(e) => {+ e.stopPropagation();+ onSelect(item);+ onClose();+ }}+ >+ {item}+ </button>+ ))}+ </div>+ );}// ─── Scroll Column (Camera Controls) ─────────────────────────────────────────function ScrollColumn({ title, items, columnKey, value, onChange }) {- const listRef = useRef(null);- const isDragging = useRef(false);- const startY = useRef(0);- const scrollTopStart = useRef(0);- const isSnapEnabled = useRef(true);-- // Scroll to initial value on mount- useEffect(() => {- const list = listRef.current;- if (!list) return;- const timer = setTimeout(() => {- const target = Array.from(list.children).find(- c => c.dataset.value == String(value)- );- if (target) target.scrollIntoView({ block: 'center' });- }, 100);- return () => clearTimeout(timer);- }, []); // eslint-disable-line react-hooks/exhaustive-deps-- const handleScroll = useCallback(() => {- const list = listRef.current;- if (!list) return;- const centerY = list.scrollTop + list.clientHeight / 2;- let closest = null;- let minDist = Infinity;-- const children = Array.from(list.children).filter(c => c.dataset.value);- children.forEach(child => {- const childCenter = child.offsetTop + child.offsetHeight / 2;- const dist = Math.abs(centerY - childCenter);- if (dist < minDist) {- minDist = dist;- closest = child;- }- });-- children.forEach(child => {- const imgBox = child.querySelector('[data-imgbox]');- const label = child.querySelector('[data-label]');- const focalSpan = imgBox?.querySelector('[data-focal-text]');- const isClosest = child === closest;-- if (isClosest) {- child.classList.remove('opacity-30', 'scale-75', 'blur-[1px]');- child.classList.add('opacity-100', 'scale-100', 'blur-0', 'z-30');- if (imgBox) {- imgBox.classList.add('border-primary/50', 'shadow-glow-sm', 'scale-110');- imgBox.classList.remove('border-white/10', 'bg-white/5');- }- if (focalSpan) focalSpan.classList.add('text-primary');- if (label) label.classList.add('text-primary', 'text-shadow-sm');- } else {- child.classList.add('opacity-30', 'scale-75', 'blur-[1px]');- child.classList.remove('opacity-100', 'scale-100', 'blur-0', 'z-30');- if (imgBox) {- imgBox.classList.remove('border-primary/50', 'shadow-glow-sm', 'scale-110');- imgBox.classList.add('border-white/10', 'bg-white/5');- }- if (focalSpan) focalSpan.classList.remove('text-primary');- if (label) label.classList.remove('text-primary', 'text-shadow-sm');- }- });-- if (closest) {- const newVal = columnKey === 'focal'- ? parseInt(closest.dataset.value)- : closest.dataset.value;- if (String(newVal) !== String(value)) {- onChange(newVal);- }- }- }, [columnKey, value, onChange]);-- // Attach scroll handler with initial check- useEffect(() => {- const list = listRef.current;- if (!list) return;- list.addEventListener('scroll', handleScroll);- const timer = setTimeout(handleScroll, 150);- return () => {- list.removeEventListener('scroll', handleScroll);- clearTimeout(timer);- };- }, [handleScroll]);-- // Mouse drag handlers- const onMouseDown = (e) => {- isDragging.current = true;- isSnapEnabled.current = false;- listRef.current.classList.add('cursor-grabbing');- listRef.current.classList.remove('snap-y');- startY.current = e.pageY - listRef.current.offsetTop;- scrollTopStart.current = listRef.current.scrollTop;- e.preventDefault();- };-- const onMouseLeave = () => {- isDragging.current = false;- listRef.current.classList.remove('cursor-grabbing');- listRef.current.classList.add('snap-y');- };-- const onMouseUp = () => {- isDragging.current = false;- listRef.current.classList.remove('cursor-grabbing');- listRef.current.classList.add('snap-y');- };+ const listRef = useRef(null);+ const isDragging = useRef(false);+ const startY = useRef(0);+ const scrollTopStart = useRef(0);+ const isSnapEnabled = useRef(true);++ // Scroll to initial value on mount+ useEffect(() => {+ const list = listRef.current;+ if (!list) return;+ const timer = setTimeout(() => {+ const target = Array.from(list.children).find(+ (c) => c.dataset.value == String(value),+ );+ if (target) target.scrollIntoView({ block: "center" });+ }, 100);+ return () => clearTimeout(timer);+ }, []); // eslint-disable-line react-hooks/exhaustive-deps++ const handleScroll = useCallback(() => {+ const list = listRef.current;+ if (!list) return;+ const centerY = list.scrollTop + list.clientHeight / 2;+ let closest = null;+ let minDist = Infinity;++ const children = Array.from(list.children).filter((c) => c.dataset.value);+ children.forEach((child) => {+ const childCenter = child.offsetTop + child.offsetHeight / 2;+ const dist = Math.abs(centerY - childCenter);+ if (dist < minDist) {+ minDist = dist;+ closest = child;+ }+ });- const onMouseMove = (e) => {- if (!isDragging.current) return;- e.preventDefault();- const y = e.pageY - listRef.current.offsetTop;- const walk = (y - startY.current) * 1.5;- listRef.current.scrollTop = scrollTopStart.current - walk;- };+ children.forEach((child) => {+ const imgBox = child.querySelector("[data-imgbox]");+ const label = child.querySelector("[data-label]");+ const focalSpan = imgBox?.querySelector("[data-focal-text]");+ const isClosest = child === closest;++ if (isClosest) {+ child.classList.remove("opacity-30", "scale-75", "blur-[1px]");+ child.classList.add("opacity-100", "scale-100", "blur-0", "z-30");+ if (imgBox) {+ imgBox.classList.add(+ "border-primary/50",+ "shadow-glow-sm",+ "scale-110",+ );+ imgBox.classList.remove("border-white/10", "bg-white/5");+ }+ if (focalSpan) focalSpan.classList.add("text-primary");+ if (label) label.classList.add("text-primary", "text-shadow-sm");+ } else {+ child.classList.add("opacity-30", "scale-75", "blur-[1px]");+ child.classList.remove("opacity-100", "scale-100", "blur-0", "z-30");+ if (imgBox) {+ imgBox.classList.remove(+ "border-primary/50",+ "shadow-glow-sm",+ "scale-110",+ );+ imgBox.classList.add("border-white/10", "bg-white/5");+ }+ if (focalSpan) focalSpan.classList.remove("text-primary");+ if (label) label.classList.remove("text-primary", "text-shadow-sm");+ }+ });- const onItemClick = (item) => {- const list = listRef.current;- if (!list) return;- const target = Array.from(list.children).find(- c => c.dataset.value == String(item)- );- if (target) target.scrollIntoView({ behavior: 'smooth', block: 'center' });+ if (closest) {+ const newVal =+ columnKey === "focal"+ ? parseInt(closest.dataset.value)+ : closest.dataset.value;+ if (String(newVal) !== String(value)) {+ onChange(newVal);+ }+ }+ }, [columnKey, value, onChange]);++ // Attach scroll handler with initial check+ useEffect(() => {+ const list = listRef.current;+ if (!list) return;+ list.addEventListener("scroll", handleScroll);+ const timer = setTimeout(handleScroll, 150);+ return () => {+ list.removeEventListener("scroll", handleScroll);+ clearTimeout(timer);};+ }, [handleScroll]);++ // Mouse drag handlers+ const onMouseDown = (e) => {+ isDragging.current = true;+ isSnapEnabled.current = false;+ listRef.current.classList.add("cursor-grabbing");+ listRef.current.classList.remove("snap-y");+ startY.current = e.pageY - listRef.current.offsetTop;+ scrollTopStart.current = listRef.current.scrollTop;+ e.preventDefault();+ };++ const onMouseLeave = () => {+ isDragging.current = false;+ listRef.current.classList.remove("cursor-grabbing");+ listRef.current.classList.add("snap-y");+ };++ const onMouseUp = () => {+ isDragging.current = false;+ listRef.current.classList.remove("cursor-grabbing");+ listRef.current.classList.add("snap-y");+ };++ const onMouseMove = (e) => {+ if (!isDragging.current) return;+ e.preventDefault();+ const y = e.pageY - listRef.current.offsetTop;+ const walk = (y - startY.current) * 1.5;+ listRef.current.scrollTop = scrollTopStart.current - walk;+ };++ const onItemClick = (item) => {+ const list = listRef.current;+ if (!list) return;+ const target = Array.from(list.children).find(+ (c) => c.dataset.value == String(item),+ );+ if (target) target.scrollIntoView({ behavior: "smooth", block: "center" });+ };++ return (+ <div className="flex flex-col items-center relative w-[140px] md:w-[160px] shrink-0 snap-center group">+ <div className="mb-3 text-[9px] font-black text-white/40 uppercase tracking-[0.2em] text-center">+ {title}+ </div>+ <div className="relative overflow-hidden w-full h-[40vh] md:h-[320px] bg-[#050505]/60 rounded-2xl border border-white/[0.05] shadow-2xl backdrop-blur-2xl transition-transform duration-500 hover:scale-[1.01] hover:border-white/[0.1]">+ {/* Top mask */}+ <div className="absolute top-0 left-0 right-0 h-32 bg-gradient-to-b from-[#0a0a0a] via-[#0a0a0a]/40 to-transparent z-20 pointer-events-none" />+ {/* Bottom mask */}+ <div className="absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-[#0a0a0a] via-[#0a0a0a]/40 to-transparent z-20 pointer-events-none" />+ {/* Center selection indicator */}+ <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[85%] h-[80px] bg-primary/[0.03] border border-primary/[0.1] rounded-2xl pointer-events-none z-0" />- return (- <div className="flex flex-col items-center relative w-[140px] md:w-[160px] shrink-0 snap-center group">- <div className="mb-3 text-[9px] font-black text-white/40 uppercase tracking-[0.2em] text-center">- {title}- </div>- <div className="relative overflow-hidden w-full h-[40vh] md:h-[320px] bg-[#1a1a1a]/80 rounded-[2rem] border border-white/5 shadow-2xl backdrop-blur-xl transition-transform duration-300 hover:scale-[1.02] hover:border-white/10">- {/* Top mask */}- <div className="absolute top-0 left-0 right-0 h-24 bg-gradient-to-b from-[#1a1a1a] via-[#1a1a1a]/80 to-transparent z-20 pointer-events-none rounded-t-[2rem]" />- {/* Bottom mask */}- <div className="absolute bottom-0 left-0 right-0 h-24 bg-gradient-to-t from-[#1a1a1a] via-[#1a1a1a]/80 to-transparent z-20 pointer-events-none rounded-b-[2rem]" />- {/* Center glow */}- <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-4/5 h-[80px] bg-primary/5 blur-xl rounded-full pointer-events-none z-0" />-+ <div+ ref={listRef}+ className="h-full overflow-y-auto no-scrollbar snap-y snap-mandatory relative z-10"+ onMouseDown={onMouseDown}+ onMouseLeave={onMouseLeave}+ onMouseUp={onMouseUp}+ onMouseMove={onMouseMove}+ >+ {/* Top spacer */}+ <div style={{ height: "calc(50% - 50px)" }} />++ {items.map((item) => {+ const imageUrl = ASSET_URLS[item];+ return (+ <div+ key={item}+ data-value={item}+ className="h-[100px] flex flex-col items-center justify-center gap-3 snap-center cursor-pointer transition-all duration-500 ease-out text-white p-2 select-none opacity-30 scale-75 blur-[1px]"+ onClick={() => onItemClick(item)}+ ><div- ref={listRef}- className="h-full overflow-y-auto no-scrollbar snap-y snap-mandatory relative z-10"- onMouseDown={onMouseDown}- onMouseLeave={onMouseLeave}- onMouseUp={onMouseUp}- onMouseMove={onMouseMove}+ data-imgbox="true"+ className="w-14 h-14 rounded-xl border border-white/10 bg-white/5 flex items-center justify-center transition-all duration-500 shadow-inner overflow-hidden relative">- {/* Top spacer */}- <div style={{ height: 'calc(50% - 50px)' }} />-- {items.map(item => {- const imageUrl = ASSET_URLS[item];- return (- <div- key={item}- data-value={item}- className="h-[100px] flex flex-col items-center justify-center gap-3 snap-center cursor-pointer transition-all duration-500 ease-out text-white p-2 select-none opacity-30 scale-75 blur-[1px]"- onClick={() => onItemClick(item)}- >- <div- data-imgbox="true"- className="w-14 h-14 rounded-xl border border-white/10 bg-white/5 flex items-center justify-center transition-all duration-500 shadow-inner overflow-hidden relative"- >- {imageUrl ? (- <img- src={imageUrl}- alt={String(item)}- className="w-full h-full object-cover opacity-80"- />- ) : columnKey === 'focal' ? (- <span data-focal-text="true" className="text-lg font-bold text-white/50">- {item}- </span>- ) : (- <div className="w-3 h-3 bg-white/20 rounded-full" />- )}- </div>- <span- data-label="true"- className="text-[9px] md:text-[10px] font-bold uppercase text-center leading-tight max-w-full truncate px-1 tracking-wider"- >- {item}- </span>- </div>- );- })}-- {/* Bottom spacer */}- <div style={{ height: 'calc(50% - 50px)' }} />+ {imageUrl ? (+ <img+ src={imageUrl}+ alt={String(item)}+ className="w-full h-full object-cover opacity-80"+ />+ ) : columnKey === "focal" ? (+ <span+ data-focal-text="true"+ className="text-lg font-bold text-white/50"+ >+ {item}+ </span>+ ) : (+ <div className="w-3 h-3 bg-white/20 rounded-full" />+ )}</div>- </div>+ <span+ data-label="true"+ className="text-[9px] md:text-[10px] font-bold uppercase text-center leading-tight max-w-full truncate px-1 tracking-wider"+ >+ {item}+ </span>+ </div>+ );+ })}++ {/* Bottom spacer */}+ <div style={{ height: "calc(50% - 50px)" }} /></div>- );+ </div>+ </div>+ );}-// ─── Camera Controls Overlay ─────────────────────────────────────────────────--function CameraControlsOverlay({ isOpen, onClose, settings, onSettingsChange }) {- const backdropRef = useRef(null);-- const handleBackdropClick = (e) => {- if (e.target === backdropRef.current) onClose();- };-- const updateSetting = (key) => (val) => {- onSettingsChange(prev => ({ ...prev, [key]: val }));- };-- return (- <div- ref={backdropRef}- className={`fixed inset-0 bg-black/80 backdrop-blur-md z-40 flex items-center justify-center transition-opacity duration-300 ${isOpen ? 'opacity-100 pointer-events-auto' : 'opacity-0 pointer-events-none'}`}- onClick={handleBackdropClick}- >- <div- className={`w-full max-w-4xl bg-[#141414] border border-white/10 rounded-3xl p-4 md:p-8 shadow-2xl transform transition-transform duration-300 flex flex-col max-h-[90vh] ${isOpen ? 'scale-100' : 'scale-95'}`}+function CameraControlsOverlay({+ isOpen,+ onClose,+ settings,+ onSettingsChange,+}) {+ const backdropRef = useRef(null);++ const handleBackdropClick = (e) => {+ if (e.target === backdropRef.current) onClose();+ };++ const updateSetting = (key) => (val) => {+ onSettingsChange((prev) => ({ ...prev, [key]: val }));+ };++ return (+ <div+ ref={backdropRef}+ className={`fixed inset-0 bg-[#0a0a0a]/80 backdrop-blur-2xl z-[100] flex items-center justify-center transition-all duration-500 ${isOpen ? "opacity-100" : "opacity-0 pointer-events-none"}`}+ onClick={handleBackdropClick}+ >+ <div+ className={`w-full max-w-5xl bg-[#0a0a0a]/60 border border-white/10 rounded-2xl p-6 md:p-10 shadow-3xl transform transition-all duration-500 flex flex-col max-h-[90vh] ${isOpen ? "scale-100 translate-y-0" : "scale-95 translate-y-10"}`}+ >+ {/* Header */}+ <div className="flex items-center justify-between mb-10">+ <div className="flex flex-col gap-1">+ <h2 className="text-xl font-bold text-white tracking-tight">+ Camera Configuration+ </h2>+ <p className="text-[11px] font-medium text-white/20 uppercase tracking-[0.2em]">+ Select hardware & optics+ </p>+ </div>+ <button+ onClick={onClose}+ className="w-10 h-10 rounded-full bg-white/[0.03] border border-white/[0.05] flex items-center justify-center text-white/40 hover:text-white hover:bg-white/[0.06] transition-all"+ >+ <svg+ width="20"+ height="20"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2.5">- {/* Header */}- <div className="flex items-center justify-between mb-8">- <div className="flex gap-4">- <button className="px-4 py-2 bg-white text-black text-xs font-bold rounded-full">All</button>- </div>- <button- onClick={onClose}- className="text-white/50 hover:text-white transition-colors"- >- <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <path d="M18 6L6 18M6 6l12 12" />- </svg>- </button>- </div>+ <path d="M18 6L6 18M6 6l12 12" />+ </svg>+ </button>+ </div>- {/* Scroll columns */}- <div className="w-full flex justify-start md:justify-center gap-3 md:gap-6 py-4 md:py-8 overflow-x-auto no-scrollbar snap-x px-4 md:px-0">- <ScrollColumn- title="Camera"- items={CAMERAS}- columnKey="camera"- value={settings.camera}- onChange={updateSetting('camera')}- />- <ScrollColumn- title="Lens"- items={LENSES}- columnKey="lens"- value={settings.lens}- onChange={updateSetting('lens')}- />- <ScrollColumn- title="Focal Length"- items={FOCAL_LENGTHS}- columnKey="focal"- value={settings.focal}- onChange={updateSetting('focal')}- />- <ScrollColumn- title="Aperture"- items={APERTURES}- columnKey="aperture"- value={settings.aperture}- onChange={updateSetting('aperture')}- />- </div>- </div>+ {/* Scroll columns */}+ <div className="w-full flex justify-start md:justify-center gap-3 md:gap-6 py-4 md:py-8 overflow-x-auto no-scrollbar snap-x px-4 md:px-0">+ <ScrollColumn+ title="Camera"+ items={CAMERAS}+ columnKey="camera"+ value={settings.camera}+ onChange={updateSetting("camera")}+ />+ <ScrollColumn+ title="Lens"+ items={LENSES}+ columnKey="lens"+ value={settings.lens}+ onChange={updateSetting("lens")}+ />+ <ScrollColumn+ title="Focal Length"+ items={FOCAL_LENGTHS}+ columnKey="focal"+ value={settings.focal}+ onChange={updateSetting("focal")}+ />+ <ScrollColumn+ title="Aperture"+ items={APERTURES}+ columnKey="aperture"+ value={settings.aperture}+ onChange={updateSetting("aperture")}+ /></div>- );+ </div>+ </div>+ );}// ─── Main Component ───────────────────────────────────────────────────────────-export default function CinemaStudio({ apiKey, onGenerationComplete, historyItems }) {- // ── Settings state ──- const [settings, setSettings] = useState({- prompt: '',- aspect_ratio: '16:9',- camera: CAMERAS[0],- lens: LENSES[0],- focal: 35,- aperture: 'f/1.4'- });- const [resolution, setResolution] = useState('2K');-- // ── UI state ──- const [isOverlayOpen, setIsOverlayOpen] = useState(false);- const [isGenerating, setIsGenerating] = useState(false);- const [canvasUrl, setCanvasUrl] = useState(null); // null = prompt view- const [activeHistoryIndex, setActiveHistoryIndex] = useState(null);-- // ── Internal history state (used when historyItems prop is not provided) ──- const [internalHistory, setInternalHistory] = useState([]);-- // ── Dropdown state ──- const [openDropdown, setOpenDropdown] = useState(null); // 'ar' | 'res' | null- const arBtnRef = useRef(null);- const resBtnRef = useRef(null);-- // ── Textarea auto-grow ──- const textareaRef = useRef(null);- const resultImgRef = useRef(null);-- // Derive effective history (prop wins over internal)- const history = historyItems != null ? historyItems : internalHistory;-- const formatSummaryValue = () =>- `${settings.lens}, ${settings.focal}mm, ${settings.aperture}`;-- // ── Textarea auto-height ──- const handleTextareaInput = (e) => {- const el = e.target;- el.style.height = 'auto';- el.style.height = el.scrollHeight + 'px';- setSettings(prev => ({ ...prev, prompt: el.value }));- };+export default function CinemaStudio({+ apiKey,+ onGenerationComplete,+ historyItems,+}) {+ const PERSIST_KEY = "hg_cinema_studio_persistent";++ // ── Settings state ──+ const [settings, setSettings] = useState({+ prompt: "",+ aspect_ratio: "16:9",+ camera: CAMERAS[0],+ lens: LENSES[0],+ focal: 35,+ aperture: "f/1.4",+ });+ const [resolution, setResolution] = useState("2K");++ // ── UI state ──+ const [isOverlayOpen, setIsOverlayOpen] = useState(false);+ const [isGenerating, setIsGenerating] = useState(false);+ const [canvasUrl, setCanvasUrl] = useState(null); // null = prompt view+ const [fullscreenUrl, setFullscreenUrl] = useState(null);+ const [activeHistoryIndex, setactiveHistoryIndex] = useState(null);++ // ── Internal history state (used when historyItems prop is not provided) ──+ const [internalHistory, setInternalHistory] = useState([]);++ // ── Dropdown state ──+ const [openDropdown, setOpenDropdown] = useState(null); // 'ar' | 'res' | null+ const arBtnRef = useRef(null);+ const resBtnRef = useRef(null);++ // ── Textarea auto-grow ──+ const textareaRef = useRef(null);+ const resultImgRef = useRef(null);++ // ── Persistence: Load ────────────────────────────────────────────────────+ useEffect(() => {+ try {+ const stored = localStorage.getItem(PERSIST_KEY);+ if (stored) {+ const data = JSON.parse(stored);+ if (data.settings) setSettings(data.settings);+ if (data.resolution) setResolution(data.resolution);+ if (data.internalHistory) setInternalHistory(data.internalHistory);+ }+ } catch (err) {+ console.warn("Failed to load CinemaStudio persistence:", err);+ }+ }, []);++ // ── Persistence: Save ────────────────────────────────────────────────────+ useEffect(() => {+ const timer = setTimeout(() => {+ try {+ const state = {+ settings,+ resolution,+ internalHistory,+ };+ localStorage.setItem(PERSIST_KEY, JSON.stringify(state));+ } catch (err) {+ console.warn("Failed to save CinemaStudio persistence:", err);+ }+ }, 500); // 500ms debounce+ return () => clearTimeout(timer);+ }, [settings, resolution, internalHistory]);++ // Derive effective history (prop wins over internal)+ const history = historyItems != null ? historyItems : internalHistory;++ useEffect(() => {+ setCanvasUrl(history[0]?.url || null);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [historyItems]);++ const formatSummaryValue = () =>+ `${settings.lens}, ${settings.focal}mm, ${settings.aperture}`;++ // ── Textarea auto-height ──+ const handleTextareaInput = (e) => {+ const el = e.target;+ el.style.height = "auto";+ el.style.height = el.scrollHeight + "px";+ setSettings((prev) => ({ ...prev, prompt: el.value }));+ };++ // ── Generate ──+ const handleGenerate = useCallback(async () => {+ const basePrompt = settings.prompt.trim();+ if (!basePrompt || isGenerating) return;++ setIsGenerating(true);++ const finalPrompt = buildNanoBananaPrompt(+ basePrompt,+ settings.camera,+ settings.lens,+ settings.focal,+ settings.aperture,+ );- // ── Generate ──- const handleGenerate = useCallback(async () => {- const basePrompt = settings.prompt.trim();- if (!basePrompt || isGenerating) return;-- setIsGenerating(true);-- const finalPrompt = buildNanoBananaPrompt(- basePrompt,- settings.camera,- settings.lens,- settings.focal,- settings.aperture- );-- try {- const res = await generateImage(apiKey, {- model: 'nano-banana-pro',- prompt: finalPrompt,- aspect_ratio: settings.aspect_ratio,- resolution: resolution.toLowerCase(),- negative_prompt: 'blurry, low quality, distortion, bad composition'- });-- if (res && res.url) {- const entry = {- url: res.url,- timestamp: Date.now(),- settings: {- prompt: basePrompt,- camera: settings.camera,- lens: settings.lens,- focal: settings.focal,- aperture: settings.aperture,- aspect_ratio: settings.aspect_ratio,- resolution- }- };-- // Only update internal history if not using prop-driven history- if (historyItems == null) {- setInternalHistory(prev => [entry, ...prev].slice(0, 50));- }-- setActiveHistoryIndex(0);- setCanvasUrl(res.url);-- if (onGenerationComplete) {- onGenerationComplete({- url: res.url,- model: 'nano-banana-pro',- prompt: basePrompt,- type: 'cinema'- });- }- } else {- throw new Error('No data returned');- }- } catch (e) {- console.error(e);- alert('Generation Failed: ' + e.message);- } finally {- setIsGenerating(false);- }- }, [settings, resolution, apiKey, isGenerating, onGenerationComplete, historyItems]);-- // ── Regenerate ──- const handleRegenerate = useCallback(() => {- setCanvasUrl(null);- // Small delay then generate- setTimeout(() => handleGenerate(), 300);- }, [handleGenerate]);-- // ── Download ──- const handleDownload = useCallback(async () => {- if (!canvasUrl) return;- try {- const response = await fetch(canvasUrl);- const blob = await response.blob();- const blobUrl = URL.createObjectURL(blob);- const a = document.createElement('a');- a.href = blobUrl;- a.download = `cinema-shot-${Date.now()}.jpg`;- document.body.appendChild(a);- a.click();- document.body.removeChild(a);- URL.revokeObjectURL(blobUrl);- } catch {- window.open(canvasUrl, '_blank');- }- }, [canvasUrl]);-- // ── Load history item ──- const loadHistoryItem = (entry, idx) => {- if (entry.settings) {- setSettings(prev => ({- ...prev,- camera: entry.settings.camera ?? prev.camera,- lens: entry.settings.lens ?? prev.lens,- focal: entry.settings.focal ?? prev.focal,- aperture: entry.settings.aperture ?? prev.aperture,- aspect_ratio: entry.settings.aspect_ratio ?? prev.aspect_ratio,- prompt: entry.settings.prompt ?? prev.prompt- }));- if (entry.settings.resolution) setResolution(entry.settings.resolution);-- // Sync textarea height- if (textareaRef.current) {- textareaRef.current.value = entry.settings.prompt || '';- textareaRef.current.style.height = 'auto';- textareaRef.current.style.height = textareaRef.current.scrollHeight + 'px';- }- }- setActiveHistoryIndex(idx);- setCanvasUrl(entry.url);- };+ try {+ const res = await generateImage(apiKey, {+ model: "nano-banana-pro",+ prompt: finalPrompt,+ aspect_ratio: settings.aspect_ratio,+ resolution: resolution.toLowerCase(),+ negative_prompt: "blurry, low quality, distortion, bad composition",+ });++ if (res && res.url) {+ const entry = {+ url: res.url,+ timestamp: Date.now(),+ settings: {+ prompt: basePrompt,+ camera: settings.camera,+ lens: settings.lens,+ focal: settings.focal,+ aperture: settings.aperture,+ aspect_ratio: settings.aspect_ratio,+ resolution,+ },+ };- const resetToPrompt = () => {- setCanvasUrl(null);- setSettings(prev => ({ ...prev, prompt: '' }));- if (textareaRef.current) {- textareaRef.current.value = '';- textareaRef.current.style.height = 'auto';- setTimeout(() => textareaRef.current?.focus(), 50);+ // Only update internal history if not using prop-driven history+ if (historyItems == null) {+ setInternalHistory((prev) => [entry, ...prev].slice(0, 50));}- };-- const showCanvas = canvasUrl !== null;- return (- <div className="w-full h-full flex flex-col items-center justify-center bg-black relative overflow-hidden">+ setCanvasUrl(res.url);- {/* ── 1. Hero Section (Empty State) ── */}- <div- className={`flex flex-col items-center justify-center text-center px-4 animate-fade-in-up transition-all duration-700 ${showCanvas ? 'opacity-0 pointer-events-none scale-95' : 'opacity-100 scale-100'}`}- >- <div className="mb-4 text-xs font-bold text-white/40 tracking-[0.2em] uppercase">- Cinema Studio 2.0+ if (onGenerationComplete) {+ onGenerationComplete({+ url: res.url,+ model: "nano-banana-pro",+ prompt: basePrompt,+ type: "cinema",+ });+ }+ } else {+ throw new Error("No data returned");+ }+ } catch (e) {+ console.error(e);+ alert("Generation Failed: " + e.message);+ } finally {+ setIsGenerating(false);+ }+ }, [+ settings,+ resolution,+ apiKey,+ isGenerating,+ onGenerationComplete,+ historyItems,+ ]);++ // ── Regenerate ──+ const handleRegenerate = useCallback(() => {+ setCanvasUrl(null);+ // Small delay then generate+ setTimeout(() => handleGenerate(), 300);+ }, [handleGenerate]);++ // ── Download ──+ const handleDownload = useCallback(async () => {+ if (!canvasUrl) return;+ try {+ const response = await fetch(canvasUrl);+ const blob = await response.blob();+ const blobUrl = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = blobUrl;+ a.download = `cinema-shot-${Date.now()}.jpg`;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(blobUrl);+ } catch {+ window.open(canvasUrl, "_blank");+ }+ }, [canvasUrl]);++ // ── Load history item ──+ const loadHistoryItem = (entry, idx) => {+ if (entry.settings) {+ setSettings((prev) => ({+ ...prev,+ camera: entry.settings.camera ?? prev.camera,+ lens: entry.settings.lens ?? prev.lens,+ focal: entry.settings.focal ?? prev.focal,+ aperture: entry.settings.aperture ?? prev.aperture,+ aspect_ratio: entry.settings.aspect_ratio ?? prev.aspect_ratio,+ prompt: entry.settings.prompt ?? prev.prompt,+ }));+ if (entry.settings.resolution) setResolution(entry.settings.resolution);++ // Sync textarea height+ if (textareaRef.current) {+ textareaRef.current.value = entry.settings.prompt || "";+ textareaRef.current.style.height = "auto";+ textareaRef.current.style.height =+ textareaRef.current.scrollHeight + "px";+ }+ }+ setCanvasUrl(entry.url);+ };++ const resetToPrompt = () => {+ setCanvasUrl(null);+ setSettings((prev) => ({ ...prev, prompt: "" }));+ if (textareaRef.current) {+ textareaRef.current.value = "";+ textareaRef.current.style.height = "auto";+ setTimeout(() => textareaRef.current?.focus(), 50);+ }+ };++ // ── Render ───────────────────────────────────────────────────────────────+ return (+ <div className="w-full h-full flex flex-col items-center justify-center bg-black relative overflow-hidden">++ {/* ── CENTRAL GALLERY AREA ── */}+ <div className="flex-1 w-full max-w-7xl mx-auto overflow-y-auto custom-scrollbar pb-40 lg:pb-32 px-2">+ {history.length > 0 ? (+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 w-full pt-4 animate-fade-in-up">+ {history.map((entry, idx) => (+ <div+ key={entry.timestamp ?? idx}+ className="relative group rounded-2xl overflow-hidden border border-white/10 bg-[#0a0a0a] shadow-xl hover:border-[#d9ff00]/50 transition-all duration-300 flex flex-col cursor-pointer"+ onClick={() => loadHistoryItem(entry, idx)}+ >+ <img+ src={entry.url}+ alt={`History item ${idx + 1}`}+ className="w-full aspect-[4/3] object-cover bg-black/40"+ />++ {/* Overlay actions */}+ <div className="absolute top-2 right-2 flex flex-col gap-2 opacity-0 group-hover:opacity-100 transition-opacity">+ <button+ type="button"+ title="Fullscreen"+ onClick={(e) => {+ e.stopPropagation();+ setFullscreenUrl(entry.url);+ }}+ className="p-2 bg-black/60 backdrop-blur-md rounded-full text-white hover:bg-[#d9ff00] hover:text-black transition-all border border-white/10"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <polyline points="15 3 21 3 21 9" />+ <polyline points="9 21 3 21 3 15" />+ <line x1="21" y1="3" x2="14" y2="10" />+ <line x1="3" y1="21" x2="10" y2="14" />+ </svg>+ </button>+ <button+ type="button"+ title="Download"+ onClick={async (e) => {+ e.stopPropagation();+ try {+ const response = await fetch(entry.url);+ const blob = await response.blob();+ const blobUrl = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = blobUrl;+ a.download = `cinema-shot-${entry.id || idx}.jpg`;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(blobUrl);+ } catch {+ window.open(entry.url, "_blank");+ }+ }}+ className="p-2 bg-black/60 backdrop-blur-md rounded-full text-white hover:bg-[#d9ff00] hover:text-black transition-all border border-white/10"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" />+ </svg>+ </button></div>- <h1 className="text-4xl md:text-6xl font-black text-transparent bg-clip-text bg-gradient-to-b from-white to-white/50 tracking-tight leading-tight mb-2">- What would you shoot<br />with infinite budget?- </h1>- </div>- {/* ── 2. Canvas Area (Result View) ── */}- <div- className={`absolute inset-0 flex flex-col items-center justify-center p-4 min-[800px]:p-16 z-30 transition-all duration-1000 bg-black/90 backdrop-blur-3xl ${showCanvas ? 'opacity-100 translate-y-0 scale-100 pointer-events-auto' : 'opacity-0 translate-y-10 scale-95 pointer-events-none'}`}- >- <div className="relative group max-w-full max-h-[70vh] flex items-center justify-center">- {canvasUrl && (- <img- ref={resultImgRef}- src={canvasUrl}- alt="Generated cinema shot"- className="max-h-[60vh] max-w-[90vw] rounded-2xl shadow-2xl border border-white/10 object-contain"- />- )}+ {/* Details */}+ <div className="p-3 bg-black/80 backdrop-blur-sm border-t border-white/5 flex-1 flex flex-col justify-between gap-2">+ <p className="text-white/70 text-xs line-clamp-3 leading-relaxed">+ {entry.settings?.prompt || "No prompt"}+ </p>+ <div className="flex items-center justify-between mt-1 flex-wrap gap-1">+ <span className="text-[10px] font-bold text-[#d9ff00] px-2 py-0.5 bg-[#d9ff00]/10 rounded border border-[#d9ff00]/20">+ {entry.settings?.camera || "Standard"}+ </span>+ <div className="flex gap-2">+ <span className="text-[10px] text-white/40">{entry.settings?.lens || "35mm"}</span>+ {entry.settings?.aspect_ratio && (+ <span className="text-[10px] text-white/40">{entry.settings.aspect_ratio}</span>+ )}+ </div>+ </div></div>-- {/* Canvas Controls */}- <div- className={`mt-8 flex gap-3 justify-center transition-opacity duration-500 delay-500 ${showCanvas ? 'opacity-100' : 'opacity-0'}`}- >- <button- onClick={() => handleRegenerate()}- className="bg-white/10 hover:bg-white/20 px-6 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wide transition-all border border-white/5 backdrop-blur-lg text-white hover:border-white/20"- >- ↻ Regenerate- </button>- <button- onClick={handleDownload}- className="bg-[#d9ff00] text-black px-6 py-2.5 rounded-xl text-xs font-black uppercase tracking-wide hover:bg-white transition-colors shadow-glow-sm hover:scale-105 active:scale-95"- >- ↓ Download- </button>- <button- onClick={resetToPrompt}- className="bg-white/10 hover:bg-white/20 px-6 py-2.5 rounded-xl text-xs font-bold uppercase tracking-wide transition-all border border-white/5 backdrop-blur-lg text-white hover:border-white/20"- >- + New Shot- </button>+ </div>+ ))}+ </div>+ ) : (+ <div className="flex flex-col items-center justify-center h-full text-center px-4 animate-fade-in-up transition-all duration-700 min-h-[50vh]">+ <div className="mb-12 relative group">+ <div className="absolute inset-0 bg-primary/10 blur-[120px] rounded-full opacity-30 group-hover:opacity-60 transition-opacity duration-1000" />+ <div className="relative w-24 h-24 md:w-32 md:h-32 bg-white/[0.02] rounded-[2rem] flex items-center justify-center border border-white/[0.05] overflow-hidden backdrop-blur-sm">+ <div className="w-16 h-16 bg-primary/5 rounded-2xl flex items-center justify-center border border-primary/10 relative z-10 transition-transform duration-500 group-hover:scale-110">+ <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="text-primary opacity-80">+ <path d="M23 7l-7 5 7 5V7z" />+ <rect x="1" y="5" width="15" height="14" rx="2" ry="2" />+ </svg></div>+ <div className="absolute top-4 right-4 text-[10px] text-primary/40 animate-pulse">REC</div>+ </div></div>-- {/* ── 3. Floating Prompt Bar ── */}- <div- className={`absolute bottom-8 left-4 right-4 md:left-0 md:right-0 md:mx-auto md:max-w-4xl z-30 transition-all duration-700 ${showCanvas ? 'opacity-0 pointer-events-none translate-y-20' : 'opacity-100 translate-y-0'}`}- >- <div className="bg-[#1a1a1a] border border-white/10 rounded-[2rem] p-4 flex justify-between shadow-3xl items-end relative">-- {/* Left Column */}- <div className="flex-1 flex flex-col gap-3 min-h-[80px] justify-between py-1 px-1">- {/* Input Row */}- <div className="flex items-start gap-3 w-full">- <textarea- ref={textareaRef}- placeholder="Describe your scene - use @ to add characters & props"- className="flex-1 bg-transparent border-none text-white text-lg font-medium placeholder:text-white/20 focus:outline-none resize-none h-[28px] leading-relaxed overflow-hidden"- rows={1}- onInput={handleTextareaInput}- />- </div>-- {/* Settings Toolbar */}- <div className="flex items-center gap-3">- {/* Aspect Ratio Button */}- <div className="relative">- <button- ref={arBtnRef}- className="flex items-center gap-1.5 px-3 py-1.5 text-[10px] font-bold text-white/50 hover:text-white transition-colors bg-white/5 hover:bg-white/10 rounded-lg border border-white/5"- onClick={() => setOpenDropdown(d => d === 'ar' ? null : 'ar')}- >- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <rect x="2" y="7" width="20" height="10" rx="2" ry="2" />- </svg>- {settings.aspect_ratio}- </button>- {openDropdown === 'ar' && (- <Dropdown- items={ASPECT_RATIOS}- selected={settings.aspect_ratio}- onSelect={(val) => setSettings(prev => ({ ...prev, aspect_ratio: val }))}- triggerRef={arBtnRef}- onClose={() => setOpenDropdown(null)}- />- )}- </div>-- {/* Resolution Button */}- <div className="relative">- <button- ref={resBtnRef}- className="flex items-center gap-1.5 px-3 py-1.5 text-[10px] font-bold text-white/50 hover:text-white transition-colors bg-white/5 hover:bg-white/10 rounded-lg border border-white/5"- onClick={() => setOpenDropdown(d => d === 'res' ? null : 'res')}- >- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">- <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />- </svg>- {resolution}- </button>- {openDropdown === 'res' && (- <Dropdown- items={RESOLUTIONS}- selected={resolution}- onSelect={setResolution}- triggerRef={resBtnRef}- onClose={() => setOpenDropdown(null)}- />- )}- </div>- </div>- </div>-- {/* Right Group */}- <div className="flex items-center gap-2 h-full self-end mb-1">- {/* Summary Card (triggers overlay) */}- <button- className="flex flex-col items-start justify-center px-4 py-2 bg-[#2a2a2a] rounded-xl border border-white/5 hover:border-white/20 transition-colors text-left flex-1 min-w-[100px] md:min-w-[140px] max-w-[240px] h-[56px] relative group overflow-hidden"- onClick={() => setIsOverlayOpen(true)}- >- <div className="absolute top-2 right-2 w-2 h-2 bg-primary rounded-full shadow-glow-sm" />- <span className="text-[10px] font-bold text-white uppercase truncate w-full tracking-wide">- {settings.camera}- </span>- <span className="text-[10px] font-medium text-white/60 truncate w-full">- {formatSummaryValue()}- </span>- </button>-- {/* Generate Button */}- <button- className="h-[56px] px-8 bg-[#d9ff00] text-black rounded-xl font-black text-xs uppercase hover:bg-white transition-colors shadow-lg disabled:opacity-50 disabled:cursor-not-allowed"- disabled={isGenerating || !settings.prompt.trim()}- onClick={handleGenerate}- >- {isGenerating ? 'SHOOTING...' : 'GENERATE ✨'}- </button>- </div>- </div>+ <h1 className="text-3xl sm:text-5xl md:text-6xl font-extrabold text-white tracking-tight mb-4 text-center px-4">+ <span className="text-white/40 font-medium">START CREATING WITH</span><br />+ <span className="text-white uppercase tracking-wider">Cinema Studio</span>+ </h1>+ <p className="text-white/40 text-sm md:text-base font-medium tracking-wide text-center max-w-lg leading-relaxed">+ What would you shoot with infinite budget?+ </p>+ </div>+ )}+ </div>++ {/* ── BOTTOM PROMPT BAR ── */}+ <div className="absolute bottom-4 left-4 right-4 md:left-0 md:right-0 md:mx-auto md:max-w-[95%] lg:max-w-4xl z-30 transition-all duration-700 animate-fade-in-up">+ <div className="bg-[#0a0a0a]/80 backdrop-blur-3xl border border-white/10 rounded-md p-4 flex justify-between shadow-2xl items-end relative gap-2">+ {/* Left Column */}+ <div className="flex-1 flex flex-col gap-3 min-h-[80px] justify-between py-1">+ {/* Input Row */}+ <div className="flex items-start gap-4 w-full">+ <textarea+ ref={textareaRef}+ placeholder="Describe your cinema scene..."+ className="w-full bg-transparent border-none text-white text-sm placeholder:text-white/10 focus:outline-none resize-none pt-1 leading-relaxed min-h-[40px] max-h-[150px] md:max-h-[250px] overflow-y-auto custom-scrollbar disabled:opacity-40"+ rows={1}+ onInput={handleTextareaInput}+ /></div>-- {/* ── 4. History Sidebar ── */}- <div className="fixed right-0 top-0 h-full w-20 md:w-24 bg-black/60 backdrop-blur-xl border-l border-white/5 z-50 flex flex-col items-center py-4 gap-3 overflow-y-auto transition-all duration-500">- <div className="text-[9px] font-bold text-white/40 uppercase tracking-widest mb-2">- History+ <div className="flex justify-between gap-2">+ <div className="flex flex-wrap items-center gap-3">+ {/* Aspect Ratio Button */}+ <div className="relative">+ <button+ ref={arBtnRef}+ className="flex items-center gap-1.5 px-3 py-1 bg-white/[0.03] hover:bg-white/10 text-xs font-bold text-white/40 hover:text-white transition-colors rounded-md border border-white/[0.03]"+ onClick={() =>+ setOpenDropdown((d) => (d === "ar" ? null : "ar"))+ }+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="opacity-40">+ <rect x="2" y="7" width="20" height="10" rx="2" ry="2" />+ </svg>+ {settings.aspect_ratio}+ </button>+ {openDropdown === "ar" && (+ <Dropdown+ items={ASPECT_RATIOS}+ selected={settings.aspect_ratio}+ onSelect={(val) =>+ setSettings((prev) => ({ ...prev, aspect_ratio: val }))+ }+ triggerRef={arBtnRef}+ onClose={() => setOpenDropdown(null)}+ />+ )}</div>- <div className="flex flex-col gap-2 w-full px-2">- {history.map((entry, idx) => (- <div- key={entry.timestamp ?? idx}- className={`relative group/thumb cursor-pointer rounded-lg overflow-hidden border-2 transition-all duration-300 aspect-square ${idx === activeHistoryIndex ? 'border-[#d9ff00] shadow-glow-sm' : 'border-white/10 hover:border-white/30'}`}- onClick={() => loadHistoryItem(entry, idx)}- >- <img- src={entry.url}- alt={`History item ${idx + 1}`}- className="w-full h-full object-cover opacity-80 group-hover/thumb:opacity-100 transition-opacity"- />- <div className="absolute inset-0 bg-black/50 opacity-0 group-hover/thumb:opacity-100 transition-opacity flex items-center justify-center">- <span className="text-[8px] font-bold text-white uppercase">Load</span>- </div>- </div>- ))}++ {/* Resolution Button */}+ <div className="relative">+ <button+ ref={resBtnRef}+ className="flex items-center gap-1.5 px-3 py-1 bg-white/[0.03] hover:bg-white/10 text-xs font-bold text-white/40 hover:text-white transition-colors rounded-md border border-white/[0.03]"+ onClick={() =>+ setOpenDropdown((d) => (d === "res" ? null : "res"))+ }+ >+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="opacity-40">+ <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z" />+ </svg>+ {resolution}+ </button>+ {openDropdown === "res" && (+ <Dropdown+ items={RESOLUTIONS}+ selected={resolution}+ onSelect={setResolution}+ triggerRef={resBtnRef}+ onClose={() => setOpenDropdown(null)}+ />+ )}</div>- </div>+ </div>+ <div className="flex items-center gap-3 h-full self-end mb-1">+ {/* Summary Card (triggers overlay) */}+ <button+ className="flex flex-col items-start justify-center px-4 py-1.5 bg-white/[0.03] rounded-md border border-white/[0.03] hover:border-white/20 transition-all text-left flex-1 min-w-[100px] md:min-w-[160px] max-w-[240px] h-[50px] relative group overflow-hidden"+ onClick={() => setIsOverlayOpen(true)}+ >+ <div className="absolute top-3 right-3 w-1.5 h-1.5 bg-[#d9ff00] rounded-full shadow-lg shadow-[#d9ff00]/20" />+ <span className="text-[9px] font-bold text-white/30 uppercase truncate w-full tracking-wider group-hover:text-white transition-colors">+ {settings.camera}+ </span>+ <span className="text-xs font-semibold text-white/70 truncate w-full group-hover:text-[#d9ff00] transition-colors">+ {formatSummaryValue()}+ </span>+ </button>- {/* ── 5. Camera Controls Overlay ── */}- <CameraControlsOverlay- isOpen={isOverlayOpen}- onClose={() => setIsOverlayOpen(false)}- settings={settings}- onSettingsChange={setSettings}- />+ {/* Generate Button */}+ <button+ className="h-[50px] px-8 bg-[#d9ff00] text-black rounded-md font-medium text-sm hover:bg-[#e5ff33] hover:scale-[1.02] active:scale-[0.98] transition-all flex items-center justify-center gap-2 shadow-lg shadow-[#d9ff00]/10 disabled:opacity-50 disabled:cursor-not-allowed"+ disabled={isGenerating || !settings.prompt.trim()}+ onClick={handleGenerate}+ >+ {isGenerating ? (+ <>+ <span className="animate-spin inline-block text-black">◌</span> SHOOTING...+ </>+ ) : (+ <>+ <span>SHOOT</span>+ </>+ )}+ </button>+ </div>+ </div>+ </div></div>- );+ </div>++ {/* ── Camera Controls Overlay ── */}+ <CameraControlsOverlay+ isOpen={isOverlayOpen}+ onClose={() => setIsOverlayOpen(false)}+ settings={settings}+ onSettingsChange={setSettings}+ />+ </div>+ );}diff --git a/packages/studio/src/components/ImageStudio.jsx b/packages/studio/src/components/ImageStudio.jsxindex ce59eacb..8f454faa 100644--- a/packages/studio/src/components/ImageStudio.jsx+++ b/packages/studio/src/components/ImageStudio.jsx@@ -16,7 +16,6 @@ import {// ─── helpers ────────────────────────────────────────────────────────────────-async function downloadImage(url, filename) {try {const response = await fetch(url);@@ -36,7 +35,7 @@ async function downloadImage(url, filename) {// ─── UploadButton (inline picker) ───────────────────────────────────────────-function UploadButton({ apiKey, maxImages, onSelect, onClear }) {+function UploadButton({ apiKey, maxImages, onSelect, onClear, initialUrls = [] }) {const [panelOpen, setPanelOpen] = useState(false);const [uploading, setUploading] = useState(false);const [selectedEntries, setSelectedEntries] = useState([]); // [{url, thumbnail}]@@ -63,6 +62,28 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {return () => window.removeEventListener("click", handler);}, [panelOpen]);+ // Sync initialUrls from parent (e.g. restored from localStorage)+ useEffect(() => {+ if (initialUrls && initialUrls.length > 0) {+ // Avoid infinite loops by only updating if URLs actually changed+ const currentUrls = selectedEntries.map(e => e.url);+ const isSame = initialUrls.length === currentUrls.length && initialUrls.every(u => currentUrls.includes(u));+ if (isSame) return;++ const newEntries = initialUrls.map(url => ({ url }));+ setSelectedEntries(newEntries);++ // Also ensure they are in the history panel+ setUploadHistory(prev => {+ const existingUrls = prev.map(h => h.url);+ const missing = initialUrls+ .filter(u => !existingUrls.includes(u))+ .map(u => ({ id: `restored-${u}`, name: "Restored Image", url: u, progress: 100 }));+ return [...missing, ...prev];+ });+ }+ }, [initialUrls]); // eslint-disable-line react-hooks/exhaustive-deps+// When maxImages changes, trim excess selectionsuseEffect(() => {if (selectedEntries.length > maxImages) {@@ -81,7 +102,7 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {const urls = entries.map((e) => e.url);onSelect({ url: urls[0], urls, thumbnail: entries[0].url });},- [onSelect]+ [onSelect],);const handleFileChange = async (e) => {@@ -90,16 +111,20 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {e.target.value = "";const MAX_IMAGE_SIZE = 10 * 1024 * 1024; // 10MB- const tooLarge = files.filter(f => f.size > MAX_IMAGE_SIZE);+ const tooLarge = files.filter((f) => f.size > MAX_IMAGE_SIZE);if (tooLarge.length > 0) {- alert(`The following images are too large (max 10MB): ${tooLarge.map(f => f.name).join(', ')}`);+ alert(+ `The following images are too large (max 10MB): ${tooLarge.map((f) => f.name).join(", ")}`,+ );return;}setUploading(true);try {const toUpload =- maxImages === 1 ? files.slice(0, 1) : files.slice(0, maxImages - selectedEntries.length || 1);+ maxImages === 1+ ? files.slice(0, 1)+ : files.slice(0, maxImages - selectedEntries.length || 1);await Promise.all(toUpload.map(async (file) => {@@ -113,7 +138,7 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {const uploadedUrl = await uploadFile(apiKey, file, (pct) => {setLastUploadProgress(pct);setUploadHistory((prev) =>- prev.map((h) => (h.id === id ? { ...h, progress: pct } : h))+ prev.map((h) => (h.id === id ? { ...h, progress: pct } : h)),);});@@ -124,7 +149,7 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {return { ...h, url: uploadedUrl, progress: 100 };}return h;- })+ }),);// Auto-select if there's room@@ -142,7 +167,7 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {setUploadHistory((prev) => prev.filter((h) => h.id !== id));throw err;}- })+ }),);} catch (err) {alert(`Image upload failed: ${err.message}`);@@ -155,7 +180,8 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {const handleCellClick = (entry) => {const selIdx = selectedEntries.findIndex((e) => e.url === entry.url);const isSelected = selIdx !== -1;- const atMax = maxImages > 1 && !isSelected && selectedEntries.length >= maxImages;+ const atMax =+ maxImages > 1 && !isSelected && selectedEntries.length >= maxImages;if (atMax) return;if (maxImages === 1) {@@ -169,7 +195,10 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {next = selectedEntries.filter((_, i) => i !== selIdx);if (next.length === 0) onClear?.();} else {- next = [...selectedEntries, { url: entry.url, localUrl: entry.localUrl }];+ next = [+ ...selectedEntries,+ { url: entry.url, localUrl: entry.localUrl },+ ];}setSelectedEntries(next);}@@ -179,7 +208,7 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {e.stopPropagation();if (entry.localUrl) URL.revokeObjectURL(entry.localUrl);setUploadHistory((prev) => prev.filter((h) => h.id !== entry.id));-+const next = selectedEntries.filter((s) => s.url !== entry.url);if (next.length !== selectedEntries.length) {setSelectedEntries(next);@@ -215,25 +244,38 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {badge = (<div className="absolute inset-0 flex flex-col items-center justify-center bg-black/60 z-10"><div className="w-4 h-4 rounded-full border border-primary/30 border-t-primary animate-spin mb-0.5" />- <span className="text-[8px] font-black text-primary">{lastUploadProgress}%</span>+ <span className="text-[8px] font-black text-primary">+ {lastUploadProgress}%+ </span></div>);} else if (count > 1) {badge = (<div className="absolute bottom-0.5 right-0.5 min-w-[16px] h-4 bg-primary rounded-full flex items-center justify-center px-0.5">- <span className="text-[9px] font-black text-black leading-none">{count}</span>+ <span className="text-[9px] font-black text-black leading-none">+ {count}+ </span></div>);} else if (canAddMore) {badge = (<div className="absolute bottom-0.5 right-0.5 min-w-[16px] h-4 bg-white/80 rounded-full flex items-center justify-center px-0.5 border border-primary/60">- <span className="text-[9px] font-black text-black leading-none">+</span>+ <span className="text-[9px] font-black text-black leading-none">+ ++ </span></div>);} else {badge = (<div className="absolute bottom-0.5 right-0.5 min-w-[16px] h-4 bg-primary rounded-full flex items-center justify-center px-0.5">- <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="black" strokeWidth="4">+ <svg+ width="8"+ height="8"+ viewBox="0 0 24 24"+ fill="none"+ stroke="black"+ strokeWidth="4"+ ><polyline points="20 6 9 17 4 12" /></svg></div>@@ -242,18 +284,53 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {triggerContent = (<>{uploading && hasSelection && (- <div className="absolute inset-0 flex flex-col items-center justify-center bg-black/60 z-10">+ <div className="absolute inset-0 flex flex-col items-center justify-center bg-black/60 z-30"><div className="w-4 h-4 rounded-full border border-primary/30 border-t-primary animate-spin mb-0.5" />- <span className="text-[8px] font-black text-primary">{lastUploadProgress}%</span>+ <span className="text-[8px] font-black text-primary">+ {lastUploadProgress}%+ </span></div>)}- {mainEntry?.url ? (- <img src={mainEntry.url} alt="" className={`w-full h-full object-cover transition-all duration-300 ${uploading && hasSelection ? 'blur-[2px] scale-110 opacity-60' : 'blur-0 scale-100 opacity-100'}`} />+ {count > 1 ? (+ <div className="relative w-full h-full p-1.5 flex items-center justify-center">+ {/* Bottom Image */}+ {selectedEntries[1]?.url && (+ <div className="absolute top-1 left-1 w-6 h-6 rounded-md border border-black/40 overflow-hidden shadow-lg rotate-[-8deg] translate-x-[-1px] translate-y-[-1px]">+ <img+ src={selectedEntries[1].url}+ alt=""+ className="w-full h-full object-cover"+ />+ </div>+ )}+ {/* Top Image */}+ {selectedEntries[0]?.url && (+ <div className="absolute bottom-1 right-1 w-7 h-7 rounded-sm border-[1.5px] border-black/60 overflow-hidden shadow-2xl z-10 rotate-[4deg] translate-x-[1px] translate-y-[1px]">+ <img+ src={selectedEntries[0].url}+ alt=""+ className={`w-full h-full object-cover transition-all duration-300 ${+ uploading && hasSelection ? "blur-[2px] opacity-60" : "opacity-100"+ }`}+ />+ </div>+ )}+ </div>+ ) : mainEntry?.url ? (+ <img+ src={mainEntry.url}+ alt=""+ className={`w-full h-full object-cover transition-all duration-300 ${+ uploading && hasSelection ? "blur-[2px] scale-110 opacity-60" : "blur-0 scale-100 opacity-100"+ }`}+ />) : (- <div className="w-full h-full flex flex-col items-center justify-center bg-white/5 animate-pulse">- <div className="w-4 h-4 rounded-full border border-primary/20 border-t-primary animate-spin mb-0.5" />- <span className="text-[8px] font-black text-primary">{lastUploadProgress}%</span>- </div>+ <div className="w-full h-full flex flex-col items-center justify-center bg-white/5 animate-pulse">+ <div className="w-4 h-4 rounded-full border border-primary/20 border-t-primary animate-spin mb-0.5" />+ <span className="text-[8px] font-black text-primary">+ {lastUploadProgress}%+ </span>+ </div>)}{!uploading && badge}</>@@ -267,11 +344,18 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {fill="none"stroke="currentColor"strokeWidth="2"- className="text-muted group-hover:text-primary transition-colors"+ className="text-white/40 group-hover:text-primary transition-colors">- <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4" />- <polyline points="17 8 12 3 7 8" />- <line x1="12" y1="3" x2="12" y2="15" />+ <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>);}@@ -280,11 +364,11 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {? count > 1? `${count} of ${maxImages} images selected — click to manage`: isMulti- ? `1 image selected — click to add more (up to ${maxImages})`- : "Reference image"+ ? `1 image selected — click to add more (up to ${maxImages})`+ : "Reference image": isMulti- ? `Add up to ${maxImages} images`- : "Reference image";+ ? `Add up to ${maxImages} images`+ : "Reference image";return (<div className="relative">@@ -307,7 +391,7 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {e.stopPropagation();setPanelOpen((o) => !o);}}- className={`w-10 h-10 shrink-0 rounded-xl border transition-all flex items-center justify-center relative overflow-hidden mt-1.5 bg-white/5 hover:bg-white/10 group ${+ className={`w-10 h-10 shrink-0 rounded-full border transition-all flex items-center justify-center relative overflow-hidden mt-1.5 bg-white/5 hover:bg-white/10 group ${hasSelection? "border-primary/60 hover:border-primary/40": "border-white/10 hover:border-primary/40"@@ -321,12 +405,12 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {<divref={panelRef}onClick={(e) => e.stopPropagation()}- className="absolute z-50 bottom-[calc(100%+8px)] left-0 bg-[#111] rounded-3xl p-3 shadow-4xl border border-white/10 w-72"+ className="absolute z-50 bottom-[calc(100%+8px)] left-0 bg-[#111] rounded-xl p-3 shadow-4xl border border-white/10 w-96">{/* Header */}<div className="flex items-center justify-between px-1 pb-3 mb-2 border-b border-white/5"><div className="flex flex-col gap-0.5">- <span className="text-[10px] font-bold text-secondary uppercase tracking-widest">+ <span className="text-xs font-bold text-secondary">Reference Images</span>{isMulti && (@@ -352,7 +436,7 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {setPanelOpen(false);fileInputRef.current?.click();}}- className="flex items-center gap-1.5 px-3 py-1.5 bg-primary/10 hover:bg-primary/20 text-primary rounded-xl text-xs font-bold transition-all border border-primary/20"+ className="flex items-center gap-1.5 px-3 py-1.5 bg-primary/10 hover:bg-primary/20 text-primary rounded-full text-xs font-bold transition-all border border-primary/20"><svgwidth="11"@@ -392,9 +476,12 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {) : (<div className="grid grid-cols-3 gap-2 max-h-56 overflow-y-auto custom-scrollbar pr-0.5">{uploadHistory.map((entry) => {- const selIdx = selectedEntries.findIndex((e) => e.url === entry.url);+ const selIdx = selectedEntries.findIndex(+ (e) => e.url === entry.url,+ );const isSelected = selIdx !== -1;- const atMax = isMulti && !isSelected && selectedEntries.length >= maxImages;+ const atMax =+ isMulti && !isSelected && selectedEntries.length >= maxImages;return (<div@@ -402,7 +489,9 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {title={entry.name}onClick={() => entry.url && handleCellClick(entry)}className={`relative rounded-xl overflow-hidden border-2 cursor-pointer group/cell aspect-square transition-all ${- isSelected ? "border-primary shadow-glow" : "border-white/10 hover:border-white/30"+ isSelected+ ? "border-primary shadow-glow"+ : "border-white/10 hover:border-white/30"} ${atMax ? "opacity-40 cursor-not-allowed" : ""} ${!entry.url ? "cursor-wait" : ""}`}>{entry.url ? (@@ -413,8 +502,10 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {/>) : (<div className="w-full h-full bg-white/5 flex flex-col items-center justify-center">- <div className="w-8 h-8 rounded-full border-2 border-primary/30 border-t-primary animate-spin mb-1" />- <span className="text-[10px] font-black text-primary">{entry.progress}%</span>+ <div className="w-8 h-8 rounded-full border-2 border-primary/30 border-t-primary animate-spin mb-1" />+ <span className="text-[10px] font-black text-primary">+ {entry.progress}%+ </span></div>)}@@ -427,7 +518,14 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {onClick={(e) => handleRemoveFromHistory(e, entry)}className="w-5 h-5 bg-red-500/80 hover:bg-red-500 rounded-md flex items-center justify-center transition-colors">- <svg width="8" height="8" viewBox="0 0 24 24" fill="none" stroke="white" strokeWidth="3">+ <svg+ width="8"+ height="8"+ viewBox="0 0 24 24"+ fill="none"+ stroke="white"+ strokeWidth="3"+ ><line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" /></svg>@@ -439,9 +537,18 @@ function UploadButton({ apiKey, maxImages, onSelect, onClear }) {{isSelected && (<div className="absolute top-1 left-1 min-w-[20px] h-5 bg-primary rounded-full flex items-center justify-center px-1">{isMulti ? (- <span className="text-[10px] font-black text-black">{selIdx + 1}</span>+ <span className="text-[10px] font-black text-black">+ {selIdx + 1}+ </span>) : (- <svg width="9" height="9" viewBox="0 0 24 24" fill="none" stroke="black" strokeWidth="4">+ <svg+ width="9"+ height="9"+ viewBox="0 0 24 24"+ fill="none"+ stroke="black"+ strokeWidth="4"+ ><polyline points="20 6 9 17 4 12" /></svg>)}@@ -482,12 +589,12 @@ function ModelDropdown({ models, selectedModel, onSelect, onClose }) {const filtered = models.filter((m) =>m.name.toLowerCase().includes(search.toLowerCase()) ||- m.id.toLowerCase().includes(search.toLowerCase())+ m.id.toLowerCase().includes(search.toLowerCase()),);return (- <div className="flex flex-col h-full max-h-[70vh]">- <div className="px-2 pb-3 mb-2 border-b border-white/5 shrink-0">+ <div className="flex flex-col gap-2 h-full max-h-[60vh]">+ <div className="border-b border-white/5 shrink-0"><div className="flex items-center gap-3 bg-white/5 rounded-xl px-4 py-2.5 border border-white/5 focus-within:border-primary/50 transition-colors"><svgwidth="14"@@ -511,7 +618,7 @@ function ModelDropdown({ models, selectedModel, onSelect, onClose }) {/></div></div>- <div className="text-[10px] font-bold text-secondary uppercase tracking-widest px-3 py-2 shrink-0">+ <div className="text-xs font-medium text-secondary py-2 shrink-0">Available models</div><div className="flex flex-col gap-1.5 overflow-y-auto custom-scrollbar pr-1 pb-2">@@ -523,7 +630,7 @@ function ModelDropdown({ models, selectedModel, onSelect, onClose }) {onSelect(m);onClose();}}- className={`flex items-center justify-between p-3.5 hover:bg-white/5 rounded-2xl cursor-pointer transition-all border border-transparent hover:border-white/5 ${+ className={`flex items-center justify-between p-3.5 hover:bg-white/5 rounded-lg cursor-pointer transition-all border border-transparent hover:border-white/5 ${selectedModel === m.id ? "bg-white/5 border-white/5" : ""}`}>@@ -533,18 +640,27 @@ function ModelDropdown({ models, selectedModel, onSelect, onClose }) {m.family === "kontext"? "bg-blue-500/10 text-blue-400": m.family === "effects"- ? "bg-purple-500/10 text-purple-400"- : "bg-primary/10 text-primary"- } border border-white/5 rounded-xl flex items-center justify-center font-black text-sm shadow-inner uppercase`}+ ? "bg-purple-500/10 text-purple-400"+ : "bg-primary/10 text-primary"+ } border border-white/5 rounded-full flex items-center justify-center font-bold text-xs shadow-inner uppercase`}>{m.name.charAt(0)}</div><div className="flex flex-col gap-0.5">- <span className="text-xs font-bold text-white tracking-tight">{m.name}</span>+ <span className="text-xs font-bold text-white tracking-tight">+ {m.name}+ </span></div></div>{selectedModel === m.id && (- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#d9ff00" strokeWidth="4">+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ stroke="#d9ff00"+ strokeWidth="4"+ ><polyline points="20 6 9 17 4 12" /></svg>)}@@ -560,7 +676,7 @@ function ModelDropdown({ models, selectedModel, onSelect, onClose }) {function SimpleDropdown({ title, options, selected, onSelect, onClose }) {return (<>- <div className="text-[10px] font-bold text-muted uppercase tracking-widest px-3 py-2 border-b border-white/5 mb-2">+ <div className="text-xs font-medium text-muted pb-2 border-b border-white/5 mb-2">{title}</div><div className="flex flex-col gap-1">@@ -572,13 +688,20 @@ function SimpleDropdown({ title, options, selected, onSelect, onClose }) {onSelect(opt);onClose();}}- className="flex items-center justify-between p-3.5 hover:bg-white/5 rounded-2xl cursor-pointer transition-all group"+ className="flex items-center justify-between p-2 hover:bg-white/5 rounded-md cursor-pointer transition-all group"><span className="text-xs font-bold text-white opacity-80 group-hover:opacity-100">{opt}</span>{selected === opt && (- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#d9ff00" strokeWidth="4">+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ stroke="#d9ff00"+ strokeWidth="4"+ ><polyline points="20 6 9 17 4 12" /></svg>)}@@ -591,13 +714,19 @@ function SimpleDropdown({ title, options, selected, onSelect, onClose }) {// ─── Main Component ───────────────────────────────────────────────────────────-export default function ImageStudio({ apiKey, onGenerationComplete, historyItems }) {+export default function ImageStudio({+ apiKey,+ onGenerationComplete,+ historyItems,+}) {+ const PERSIST_KEY = "hg_image_studio_persistent";+// ── Model / mode state ──────────────────────────────────────────────────const [imageMode, setImageMode] = useState(false); // false=t2i, true=i2iconst [selectedModelId, setSelectedModelId] = useState(t2iModels[0].id);const [selectedModelName, setSelectedModelName] = useState(t2iModels[0].name);const [selectedAr, setSelectedAr] = useState(- t2iModels[0].inputs?.aspect_ratio?.default || "1:1"+ t2iModels[0].inputs?.aspect_ratio?.default || "1:1",);const [selectedQuality, setSelectedQuality] = useState(() => {const resolutions = getResolutionsForModel(t2iModels[0].id);@@ -613,6 +742,7 @@ export default function ImageStudio({ apiKey, onGenerationComplete, historyItemsconst [dropdownOpen, setDropdownOpen] = useState(null); // 'model' | 'ar' | 'quality' | nullconst [generating, setGenerating] = useState(false);const [generateError, setGenerateError] = useState(null);+ const [fullscreenUrl, setFullscreenUrl] = useState(null);// ── Canvas / history state ──────────────────────────────────────────────const [currentImageUrl, setCurrentImageUrl] = useState(null);@@ -639,14 +769,59 @@ export default function ImageStudio({ apiKey, onGenerationComplete, historyItemsreturn () => window.removeEventListener("click", handler);}, [dropdownOpen]);- // ── Textarea auto-resize ─────────────────────────────────────────────────- const handleTextareaInput = () => {- const el = textareaRef.current;- if (!el) return;- el.style.height = "auto";- const maxHeight = window.innerWidth < 768 ? 150 : 250;- el.style.height = Math.min(el.scrollHeight, maxHeight) + "px";- };+ // ── Persistence: Load ────────────────────────────────────────────────────+ useEffect(() => {+ try {+ const stored = localStorage.getItem(PERSIST_KEY);+ if (stored) {+ const data = JSON.parse(stored);+ if (data.imageMode !== undefined) setImageMode(data.imageMode);+ if (data.selectedModelId) setSelectedModelId(data.selectedModelId);+ if (data.selectedModelName) setSelectedModelName(data.selectedModelName);+ if (data.selectedAr) setSelectedAr(data.selectedAr);+ if (data.selectedQuality) setSelectedQuality(data.selectedQuality);+ if (data.maxImages) setMaxImages(data.maxImages);+ if (data.prompt) setPrompt(data.prompt);+ if (data.uploadedImageUrls) setUploadedImageUrls(data.uploadedImageUrls);+ if (data.localHistory) setLocalHistory(data.localHistory);+ }+ } catch (err) {+ console.warn("Failed to load ImageStudio persistence:", err);+ }+ }, []);++ // ── Persistence: Save ────────────────────────────────────────────────────+ useEffect(() => {+ const timer = setTimeout(() => {+ try {+ const state = {+ imageMode,+ selectedModelId,+ selectedModelName,+ selectedAr,+ selectedQuality,+ maxImages,+ prompt,+ uploadedImageUrls,+ localHistory,+ };+ localStorage.setItem(PERSIST_KEY, JSON.stringify(state));+ } catch (err) {+ console.warn("Failed to save ImageStudio persistence:", err);+ }+ }, 500); // 500ms debounce+ return () => clearTimeout(timer);+ }, [+ imageMode,+ selectedModelId,+ selectedModelName,+ selectedAr,+ selectedQuality,+ maxImages,+ prompt,+ uploadedImageUrls,+ localHistory,+ ]);// ── Derived: current model lists & helpers ───────────────────────────────const currentModels = imageMode ? i2iModels : t2iModels;@@ -661,6 +836,15 @@ export default function ImageStudio({ apiKey, onGenerationComplete, historyItems: getQualityFieldForModel(selectedModelId);const showQualityBtn = currentResolutions.length > 0;+ // ── Textarea auto-resize ─────────────────────────────────────────────────+ const handleTextareaInput = () => {+ const el = textareaRef.current;+ if (!el) return;+ el.style.height = "auto";+ const maxHeight = window.innerWidth < 768 ? 150 : 250;+ el.style.height = Math.min(el.scrollHeight, maxHeight) + "px";+ };+// ── Upload picker callbacks ──────────────────────────────────────────────const handleUploadSelect = useCallback(({ url, urls }) => {@@ -679,7 +863,7 @@ export default function ImageStudio({ apiKey, onGenerationComplete, historyItemssetMaxImages(getMaxImagesForI2IModel(firstI2I.id));}},- [imageMode]+ [imageMode],);const handleUploadClear = useCallback(() => {@@ -719,11 +903,10 @@ export default function ImageStudio({ apiKey, onGenerationComplete, historyItemssetActiveHistoryIdx(0);setCurrentImageUrl(entry.url);},- [historyItems]+ [historyItems],);- // ── View state: 'prompt' | 'canvas' ─────────────────────────────────────- const showCanvas = currentImageUrl !== null;+ // ── View state ─────────────────────────────────────const resetToPrompt = () => {setCurrentImageUrl(null);@@ -817,122 +1000,83 @@ export default function ImageStudio({ apiKey, onGenerationComplete, historyItemsuploadedImageUrls.length > 1? `${uploadedImageUrls.length} images selected — describe the transformation (optional)`: imageMode- ? "Describe how to transform this image (optional)"- : "Describe the image you want to create";+ ? "Describe how to transform this image (optional)"+ : "Describe the image you want to create";// ── Render ───────────────────────────────────────────────────────────────return (- <div className="w-full h-full flex flex-col items-center justify-center bg-app-bg relative p-4 md:p-6 overflow-y-auto custom-scrollbar overflow-x-hidden">-- {/* ── CANVAS VIEW ─────────────────────────────────────────────────── */}- {showCanvas && (- <div className="absolute inset-0 flex flex-col items-center justify-center p-4 min-[800px]:p-16 z-10">- {/* History sidebar */}- {history.length > 0 && (- <div className="fixed right-0 top-0 h-full w-20 md:w-24 bg-black/60 backdrop-blur-xl border-l border-white/5 z-50 flex flex-col items-center py-4 gap-3 overflow-y-auto">- <div className="text-[9px] font-bold text-muted uppercase tracking-widest mb-2">- History- </div>- <div className="flex flex-col gap-2 w-full px-2">- {history.map((entry, idx) => (- <div- key={entry.id || idx}- onClick={() => {- setCurrentImageUrl(entry.url);- setActiveHistoryIdx(idx);+ <div className="w-full h-full flex flex-col items-center justify-center bg-app-bg relative p-4 md:p-6 overflow-hidden">++ {/* ── CENTRAL GALLERY AREA ── */}+ <div className="flex-1 w-full max-w-7xl mx-auto overflow-y-auto custom-scrollbar pb-40 lg:pb-32 px-2">+ {history.length > 0 ? (+ <div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6 w-full pt-4 animate-fade-in-up">+ {history.map((entry, idx) => (+ <div+ key={entry.id || idx}+ className="relative group rounded-2xl overflow-hidden border border-white/10 bg-[#0a0a0a] shadow-xl hover:border-primary/50 transition-all duration-300 flex flex-col"+ >+ <img+ src={entry.url}+ alt={entry.prompt?.substring(0, 30) || "Generated image"}+ className="w-full aspect-square object-cover bg-black/40 cursor-pointer hover:opacity-80 transition-opacity"+ onClick={() => setFullscreenUrl(entry.url)}+ />++ {/* Overlay actions */}+ <div className="absolute top-2 right-2 flex flex-col gap-2 opacity-0 group-hover:opacity-100 transition-opacity">+ <button+ type="button"+ title="Fullscreen"+ onClick={(e) => {+ e.stopPropagation();+ setFullscreenUrl(entry.url);}}- className={`relative group/thumb cursor-pointer rounded-xl overflow-hidden border-2 transition-all duration-300 ${- idx === activeHistoryIdx- ? "border-primary shadow-glow"- : "border-white/10 hover:border-white/30"- }`}+ className="p-2 bg-black/60 backdrop-blur-md rounded-full text-white hover:bg-primary hover:text-black transition-all border border-white/10">- <img- src={entry.url}- alt={entry.prompt?.substring(0, 30) || "Generated"}- className="w-full aspect-square object-cover"- />- <div className="absolute inset-0 bg-black/60 opacity-0 group-hover/thumb:opacity-100 transition-opacity flex items-center justify-center gap-1">- <button- type="button"- title="Download"- onClick={(e) => {- e.stopPropagation();- downloadImage(entry.url, `muapi-${entry.id || idx}.jpg`);- }}- className="p-1.5 bg-primary rounded-lg text-black hover:scale-110 transition-transform"- >- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">- <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" />- </svg>- </button>- </div>+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <polyline points="15 3 21 3 21 9" />+ <polyline points="9 21 3 21 3 15" />+ <line x1="21" y1="3" x2="14" y2="10" />+ <line x1="3" y1="21" x2="10" y2="14" />+ </svg>+ </button>+ <button+ type="button"+ title="Download"+ onClick={(e) => {+ e.stopPropagation();+ downloadImage(entry.url, `muapi-${entry.id || idx}.jpg`);+ }}+ className="p-2 bg-black/60 backdrop-blur-md rounded-full text-white hover:bg-primary hover:text-black transition-all border border-white/10"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" />+ </svg>+ </button>+ </div>++ {/* Prompt & Details */}+ <div className="p-3 bg-black/80 backdrop-blur-sm border-t border-white/5 flex-1 flex flex-col justify-between gap-2">+ <p className="text-white/70 text-xs line-clamp-3 leading-relaxed" title={entry.prompt}>+ {entry.prompt || "No prompt provided"}+ </p>+ <div className="flex items-center justify-between mt-1">+ <span className="text-[10px] font-bold text-primary px-2 py-0.5 bg-primary/10 rounded border border-primary/20">+ {entry.model?.replace("-", " ")}+ </span>+ <span className="text-[10px] text-white/40">{entry.aspect_ratio}</span></div>- ))}+ </div></div>- </div>- )}-- {/* Main image */}- <div className="relative group">- <img- src={currentImageUrl}- alt={history[activeHistoryIdx]?.prompt || "Generated image"}- className="max-h-[60vh] max-w-[80vw] rounded-3xl shadow-3xl border border-white/10 interactive-glow object-contain"- />- </div>-- {/* Canvas controls */}- <div className="mt-6 flex gap-3 justify-center">- <button- type="button"- onClick={handleGenerate}- disabled={generating}- className="bg-white/10 hover:bg-white/20 px-6 py-2.5 rounded-2xl text-xs font-bold transition-all border border-white/5 backdrop-blur-lg text-white disabled:opacity-50"- >- ↻ Regenerate- </button>- <button- type="button"- onClick={() => {- const entry = history[activeHistoryIdx];- downloadImage(currentImageUrl, `muapi-${entry?.id || "image"}.jpg`);- }}- className="bg-primary text-black px-6 py-2.5 rounded-2xl text-xs font-bold transition-all shadow-glow active:scale-95"- >- ↓ Download- </button>- <button- type="button"- onClick={resetToPrompt}- className="bg-white/10 hover:bg-white/20 px-6 py-2.5 rounded-2xl text-xs font-bold transition-all border border-white/5 backdrop-blur-lg text-white"- >- + New- </button>+ ))}</div>- </div>- )}-- {/* ── PROMPT VIEW ─────────────────────────────────────────────────── */}- {!showCanvas && (- <>- {/* Hero */}- <div className="flex flex-col items-center mb-10 md:mb-20 animate-fade-in-up transition-all duration-700">- <div className="mb-10 relative group">- <div className="absolute inset-0 bg-primary/20 blur-[100px] rounded-full opacity-40 group-hover:opacity-70 transition-opacity duration-1000" />- <div className="relative w-24 h-24 md:w-32 md:h-32 bg-teal-900/40 rounded-3xl flex items-center justify-center border border-white/5 overflow-hidden">- <svg- width="80"- height="80"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="1"- className="text-primary opacity-20 absolute -right-4 -bottom-4"- >- <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />- </svg>- <div className="w-16 h-16 bg-primary/10 rounded-2xl flex items-center justify-center border border-primary/20 shadow-glow relative z-10">+ ) : (+ <div className="flex flex-col items-center justify-center h-full animate-fade-in-up transition-all duration-700 min-h-[50vh]">+ <div className="mb-12 relative group">+ <div className="absolute inset-0 bg-primary/10 blur-[120px] rounded-full opacity-30 group-hover:opacity-60 transition-opacity duration-1000" />+ <div className="relative w-24 h-24 md:w-32 md:h-32 bg-white/[0.02] rounded-[2rem] flex items-center justify-center border border-white/[0.05] overflow-hidden backdrop-blur-sm">+ <div className="w-16 h-16 bg-primary/5 rounded-2xl flex items-center justify-center border border-primary/10 relative z-10 transition-transform duration-500 group-hover:scale-110"><svgwidth="32"height="32"@@ -940,229 +1084,228 @@ export default function ImageStudio({ apiKey, onGenerationComplete, historyItemsfill="none"stroke="currentColor"strokeWidth="1.5"- className="text-primary"+ className="text-primary opacity-80"><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></div>- <div className="absolute top-4 right-4 text-primary animate-pulse">✨</div>+ <div className="absolute top-4 right-4 text-[10px] text-primary/40 animate-pulse">+ ✨+ </div></div></div>- <h1 className="text-2xl sm:text-4xl md:text-7xl font-black text-white tracking-widest uppercase mb-4 selection:bg-primary selection:text-black text-center px-4">- Image Studio+ <h1 className="text-3xl sm:text-5xl md:text-6xl font-extrabold text-white tracking-tight mb-4 text-center px-4">+ <span className="text-white/40 font-medium">START CREATING WITH</span>+ <br />+ <span className="text-white">IMAGE STUDIO</span></h1>- <p className="text-secondary text-sm font-medium tracking-wide opacity-60">- Transform images with AI — upscale, stylize, animate and more+ <p className="text-white/40 text-sm md:text-base font-medium tracking-wide text-center max-w-lg leading-relaxed">+ Describe a scene, character, mood, or style — and watch it come to life</p></div>+ )}+ </div>- {/* Prompt bar */}- <div className="w-full max-w-4xl relative z-40 animate-fade-in-up" style={{ animationDelay: "0.2s" }}>- <div className="w-full bg-[#111]/90 backdrop-blur-xl border border-white/10 rounded-[1.5rem] md:rounded-[2.5rem] p-3 md:p-5 flex flex-col gap-3 md:gap-5 shadow-3xl">-- {/* Top row: upload picker + textarea */}- <div className="flex items-start gap-5 px-2">- <UploadButton- apiKey={apiKey}- maxImages={maxImages}- onSelect={handleUploadSelect}- onClear={handleUploadClear}- />- <textarea- ref={textareaRef}- value={prompt}- onChange={(e) => setPrompt(e.target.value)}- onInput={handleTextareaInput}- placeholder={placeholderText}- rows={1}- className="flex-1 bg-transparent border-none text-white text-base md:text-xl placeholder:text-muted focus:outline-none resize-none pt-2.5 leading-relaxed min-h-[40px] max-h-[150px] md:max-h-[250px] overflow-y-auto custom-scrollbar"- />- </div>+ {/* ── BOTTOM PROMPT BAR ── */}+ <div+ className="absolute bottom-4 w-full max-w-[95%] lg:max-w-4xl z-40 animate-fade-in-up"+ style={{ animationDelay: "0.2s" }}+ >+ <div className="w-full bg-[#0a0a0a]/80 backdrop-blur-3xl rounded-md border border-white/10 p-4 flex flex-col gap-2 shadow-2xl">+ {/* Top row: upload picker + textarea */}+ <div className="flex items-center gap-2">+ <UploadButton+ apiKey={apiKey}+ maxImages={maxImages}+ onSelect={handleUploadSelect}+ onClear={handleUploadClear}+ initialUrls={uploadedImageUrls}+ />+ <div className="flex-1 flex flex-col gap-2">+ <textarea+ ref={textareaRef}+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ onInput={handleTextareaInput}+ placeholder={placeholderText}+ rows={1}+ className="w-full bg-transparent border-none text-white text-sm placeholder:text-white/20 focus:outline-none resize-none pt-1 leading-relaxed min-h-[40px] max-h-[150px] md:max-h-[250px] overflow-y-auto custom-scrollbar"+ />+ </div>+ </div>- {/* Bottom row: controls + generate */}- <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 px-2 pt-4 border-t border-white/5 relative">-- {/* Left controls */}- <div className="flex items-center gap-1.5 md:gap-2.5 relative flex-wrap pb-1 md:pb-0">-- {/* Model button */}- <div className="relative">- <button- type="button"- onClick={(e) => {- e.stopPropagation();- setDropdownOpen((o) => (o === "model" ? null : "model"));- }}- className="flex items-center gap-1.5 md:gap-2.5 px-3 md:px-4 py-2 md:py-2.5 bg-white/5 hover:bg-white/10 rounded-xl md:rounded-2xl transition-all border border-white/5 group whitespace-nowrap"- >- <div className="w-5 h-5 bg-primary rounded-md flex items-center justify-center shadow-lg shadow-primary/20">- <span className="text-[10px] font-black text-black">G</span>- </div>- <span className="text-xs font-bold text-white group-hover:text-primary transition-colors">- {selectedModelName}- </span>- <svg- width="10"- height="10"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="4"- className="opacity-20 group-hover:opacity-100 transition-opacity"- >- <path d="M6 9l6 6 6-6" />- </svg>- </button>-- {dropdownOpen === "model" && (- <div- ref={dropdownRef}- onClick={(e) => e.stopPropagation()}- className="absolute bottom-[calc(100%+8px)] left-0 z-50 bg-[#111] rounded-3xl p-3 shadow-4xl border border-white/10 w-[calc(100vw-3rem)] max-w-xs"- >- <ModelDropdown- models={currentModels}- selectedModel={selectedModelId}- onSelect={handleModelSelect}- onClose={() => setDropdownOpen(null)}- />- </div>- )}+ {/* Bottom row: controls + generate */}+ <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 pt-2 border-t border-white/[0.03] relative">+ {/* Left controls */}+ <div className="flex items-center gap-2 relative flex-wrap pb-1 md:pb-0">+ {/* Model button */}+ <div className="relative">+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ setDropdownOpen((o) => (o === "model" ? null : "model"));+ }}+ className="flex items-center gap-2 px-3 py-2 bg-white/[0.03] hover:bg-white/[0.06] rounded-md transition-all border border-white/[0.03] group whitespace-nowrap"+ >+ <div className="w-4 h-4 bg-[#d9ff00] rounded flex items-center justify-center">+ <span className="text-[9px] font-bold text-black uppercase">G</span></div>+ <span className="text-xs font-semibold text-white/70 group-hover:text-[#d9ff00] transition-colors">+ {selectedModelName}+ </span>+ <svg+ width="10"+ height="10"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="4"+ className="opacity-50 group-hover:opacity-100 transition-opacity flex-shrink-0"+ >+ <path d="M6 9l6 6 6-6" />+ </svg>+ </button>- {/* Aspect ratio button */}- <div className="relative">- <button- type="button"- onClick={(e) => {- e.stopPropagation();- setDropdownOpen((o) => (o === "ar" ? null : "ar"));- }}- className="flex items-center gap-1.5 md:gap-2.5 px-3 md:px-4 py-2 md:py-2.5 bg-white/5 hover:bg-white/10 rounded-xl md:rounded-2xl transition-all border border-white/5 group whitespace-nowrap"- >- <svg- width="16"- height="16"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2.5"- className="opacity-60 text-secondary"- >- <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />- </svg>- <span className="text-xs font-bold text-white group-hover:text-primary transition-colors">- {selectedAr}- </span>- <svg- width="10"- height="10"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="4"- className="opacity-20 group-hover:opacity-100 transition-opacity"- >- <path d="M6 9l6 6 6-6" />- </svg>- </button>-- {dropdownOpen === "ar" && (- <div- onClick={(e) => e.stopPropagation()}- className="absolute bottom-[calc(100%+8px)] left-0 z-50 bg-[#111] rounded-3xl p-3 shadow-4xl border border-white/10 max-w-[240px]"- >- <SimpleDropdown- title="Aspect Ratio"- options={currentAspectRatios}- selected={selectedAr}- onSelect={(val) => setSelectedAr(val)}- onClose={() => setDropdownOpen(null)}- />- </div>- )}+ {dropdownOpen === "model" && (+ <div+ ref={dropdownRef}+ onClick={(e) => e.stopPropagation()}+ className="absolute bottom-[calc(100%+12px)] left-0 z-50 bg-[#0a0a0a] rounded-lg p-3 shadow-2xl border border-white/[0.05] w-[calc(100vw-3rem)] max-w-xs"+ >+ <ModelDropdown+ models={currentModels}+ selectedModel={selectedModelId}+ onSelect={handleModelSelect}+ onClose={() => setDropdownOpen(null)}+ /></div>+ )}+ </div>- {/* Quality/resolution button */}- {showQualityBtn && (- <div className="relative">- <button- type="button"- onClick={(e) => {- e.stopPropagation();- setDropdownOpen((o) => (o === "quality" ? null : "quality"));- }}- className="flex items-center gap-1.5 md:gap-2.5 px-3 md:px-4 py-2 md:py-2.5 bg-white/5 hover:bg-white/10 rounded-xl md:rounded-2xl transition-all border border-white/5 group whitespace-nowrap"- >- <svg- width="16"- height="16"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="2.5"- className="opacity-60 text-secondary"- >- <path d="M6 2L3 6v15a2 2 0 002 2h14a2 2 0 002-2V6l-3-4H6z" />- </svg>- <span className="text-xs font-bold text-white group-hover:text-primary transition-colors">- {selectedQuality || currentResolutions[0]}- </span>- <svg- width="10"- height="10"- viewBox="0 0 24 24"- fill="none"- stroke="currentColor"- strokeWidth="4"- className="opacity-20 group-hover:opacity-100 transition-opacity"- >- <path d="M6 9l6 6 6-6" />- </svg>- </button>-- {dropdownOpen === "quality" && (- <div- onClick={(e) => e.stopPropagation()}- className="absolute bottom-[calc(100%+8px)] left-0 z-50 bg-[#111] rounded-3xl p-3 shadow-4xl border border-white/10 max-w-[200px]"- >- <SimpleDropdown- title="Resolution"- options={currentResolutions}- selected={selectedQuality}- onSelect={(val) => setSelectedQuality(val)}- onClose={() => setDropdownOpen(null)}- />- </div>- )}- </div>- )}- </div>-- {/* Generate button */}+ {/* Aspect ratio button */}+ <div className="relative"><buttontype="button"- onClick={handleGenerate}- disabled={generating}- className="bg-primary text-black px-6 md:px-8 py-3 md:py-3.5 rounded-xl md:rounded-[1.5rem] font-black text-sm md:text-base hover:shadow-glow hover:scale-105 active:scale-95 transition-all flex items-center justify-center gap-2.5 w-full sm:w-auto shadow-lg disabled:opacity-70 disabled:cursor-not-allowed disabled:scale-100"+ onClick={(e) => {+ e.stopPropagation();+ setDropdownOpen((o) => (o === "ar" ? null : "ar"));+ }}+ className="flex items-center gap-2 px-3 py-2 bg-white/[0.03] hover:bg-white/[0.06] rounded-md transition-all border border-white/[0.03] group whitespace-nowrap">- {generating ? (- <>- <span className="animate-spin inline-block text-black">◌</span>- Generating...- </>- ) : generateError ? (- `Error: ${generateError}`- ) : (- "Generate ✨"- )}+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="opacity-40 text-white">+ <rect x="3" y="3" width="18" height="18" rx="2" ry="2" />+ </svg>+ <span className="text-[11px] font-semibold text-white/70 group-hover:text-[#d9ff00] transition-colors">+ {selectedAr}+ </span></button>++ {dropdownOpen === "ar" && (+ <div+ onClick={(e) => e.stopPropagation()}+ className="absolute bottom-[calc(100%+12px)] left-0 z-50 bg-[#0a0a0a] rounded-md p-3 shadow-2xl border border-white/10 min-w-[160px]"+ >+ <SimpleDropdown+ title="Aspect Ratio"+ options={currentAspectRatios}+ selected={selectedAr}+ onSelect={(val) => setSelectedAr(val)}+ onClose={() => setDropdownOpen(null)}+ />+ </div>+ )}</div>++ {/* Quality/resolution button */}+ {showQualityBtn && (+ <div className="relative">+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ setDropdownOpen((o) => (o === "quality" ? null : "quality"));+ }}+ className="flex items-center gap-2 px-3 py-2 bg-white/[0.03] hover:bg-white/[0.06] rounded-xl transition-all border border-white/[0.03] group whitespace-nowrap"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="opacity-40 text-white">+ <path d="M6 2L3 6v15a2 2 0 002 2h14a2 2 0 002-2V6l-3-4H6z" />+ </svg>+ <span className="text-[11px] font-semibold text-white/70 group-hover:text-[#d9ff00] transition-colors">+ {selectedQuality || currentResolutions[0]}+ </span>+ </button>++ {dropdownOpen === "quality" && (+ <div+ onClick={(e) => e.stopPropagation()}+ className="absolute bottom-[calc(100%+12px)] left-0 z-50 bg-[#0a0a0a] rounded-[1.5rem] p-3 shadow-2xl border border-white/[0.05] min-w-[160px]"+ >+ <SimpleDropdown+ title="Resolution"+ options={currentResolutions}+ selected={selectedQuality}+ onSelect={(val) => setSelectedQuality(val)}+ onClose={() => setDropdownOpen(null)}+ />+ </div>+ )}+ </div>+ )}</div>++ {/* Generate button */}+ <button+ type="button"+ onClick={handleGenerate}+ disabled={generating}+ className="bg-[#d9ff00] text-black px-4 py-2 rounded-md font-medium text-sm hover:bg-[#e5ff33] hover:scale-[1.02] active:scale-[0.98] transition-all flex items-center justify-center gap-2 w-full sm:w-auto shadow-lg shadow-[#d9ff00]/10 disabled:opacity-50 disabled:cursor-not-allowed z-10"+ >+ {generating ? (+ <>+ <span className="animate-spin inline-block text-black">◌</span>+ Generating...+ </>+ ) : generateError ? (+ `Error: ${generateError}`+ ) : (+ <>+ <span>Generate</span>+ </>+ )}+ </button></div>- </>+ </div>+ </div>++ {/* ── FULLSCREEN IMAGE MODAL ── */}+ {fullscreenUrl && (+ <div+ className="fixed inset-0 z-[100] flex items-center justify-center bg-black/95 backdrop-blur-sm animate-fade-in"+ onClick={() => setFullscreenUrl(null)}+ >+ <button+ type="button"+ className="absolute top-6 right-6 p-3 bg-white/10 hover:bg-white/20 rounded-full text-white transition-colors border border-white/10"+ onClick={(e) => {+ e.stopPropagation();+ setFullscreenUrl(null);+ }}+ >+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">+ <line x1="18" y1="6" x2="6" y2="18" />+ <line x1="6" y1="6" x2="18" y2="18" />+ </svg>+ </button>+ <img+ src={fullscreenUrl}+ alt="Fullscreen Preview"+ className="max-w-[95vw] max-h-[95vh] rounded-2xl shadow-2xl object-contain animate-scale-up"+ onClick={(e) => e.stopPropagation()}+ />+ </div>)}</div>);diff --git a/packages/studio/src/components/LipSyncStudio.jsx b/packages/studio/src/components/LipSyncStudio.jsxindex 63552994..32fe0cc8 100644--- a/packages/studio/src/components/LipSyncStudio.jsx+++ b/packages/studio/src/components/LipSyncStudio.jsx@@ -1,787 +1,1036 @@"use client";-import { useState, useEffect, useRef, useCallback } from 'react';-import { processLipSync, uploadFile } from '../muapi.js';+import { useState, useEffect, useRef, useCallback } from "react";+import { processLipSync, uploadFile } from "../muapi.js";import {- lipsyncModels,- imageLipSyncModels,- videoLipSyncModels,- getLipSyncModelById,- getResolutionsForLipSyncModel,-} from '../models.js';+ lipsyncModels,+ imageLipSyncModels,+ videoLipSyncModels,+ getLipSyncModelById,+ getResolutionsForLipSyncModel,+} from "../models.js";// ---------------------------------------------------------------------------// Upload button states// ---------------------------------------------------------------------------const UPLOAD_STATE = {- IDLE: 'idle',- UPLOADING: 'uploading',- READY: 'ready',+ IDLE: "idle",+ UPLOADING: "uploading",+ READY: "ready",};-function MediaPickerButton({ accept, label, icon, onUpload, onClear, uploadState, progress, fileName, previewUrl, isVideo, apiKey }) {- const inputRef = useRef(null);-- const handleClick = (e) => {- e.stopPropagation();- if (uploadState === UPLOAD_STATE.READY) {- onClear();- return;- }- inputRef.current?.click();- };-- const handleChange = async (e) => {- const file = e.target.files?.[0];- if (!file) return;- e.target.value = '';- await onUpload(file);- };-- const borderClass =+function MediaPickerButton({+ accept,+ label,+ icon,+ onUpload,+ onClear,+ uploadState,+ progress,+ fileName,+ previewUrl,+ isVideo,+ apiKey,+}) {+ const inputRef = useRef(null);++ const handleClick = (e) => {+ e.stopPropagation();+ if (uploadState === UPLOAD_STATE.READY) {+ onClear();+ return;+ }+ inputRef.current?.click();+ };++ const handleChange = async (e) => {+ const file = e.target.files?.[0];+ if (!file) return;+ e.target.value = "";+ await onUpload(file);+ };++ const borderClass =+ uploadState === UPLOAD_STATE.READY+ ? "border-primary/60 bg-primary/5"+ : "border-white/[0.03] bg-white/[0.03] hover:bg-white/[0.06] hover:border-primary/40";++ return (+ <button+ type="button"+ title={uploadState === UPLOAD_STATE.READY- ? 'border-primary/60 bg-primary/10'- : 'border-white/10 bg-white/5 hover:bg-white/10 hover:border-primary/40';-- return (- <button- type="button"- title={- uploadState === UPLOAD_STATE.READY- ? `${fileName} — click to clear`- : `Upload ${label.toLowerCase()} file`- }- onClick={handleClick}- className={`flex-shrink-0 w-14 h-14 rounded-xl border transition-all flex items-center justify-center relative overflow-hidden group ${borderClass}`}- >- <input- ref={inputRef}- type="file"- accept={accept}- className="hidden"- onChange={handleChange}- />-- {/* Idle state */}- {uploadState === UPLOAD_STATE.IDLE && (- <div className="flex flex-col items-center justify-center gap-1 w-full h-full">- {icon}- <span className="text-[9px] text-muted group-hover:text-primary font-bold transition-colors">- {label.toUpperCase()}- </span>- </div>- )}-- {/* Uploading indicator */}- {uploadState === UPLOAD_STATE.UPLOADING && (- <div className="flex flex-col items-center justify-center w-full h-full absolute inset-0 bg-black/60 z-10 animate-pulse">- <div className="w-4 h-4 rounded-full border border-primary/30 border-t-primary animate-spin mb-0.5" />- <span className="text-[8px] font-black text-primary">{progress}%</span>- </div>- )}-- {/* Ready state */}- {uploadState === UPLOAD_STATE.READY && (- <div className="flex flex-col items-center justify-center gap-1 w-full h-full absolute inset-0 bg-primary/10">- {previewUrl ? (- isVideo ? (- <video src={previewUrl} className="w-full h-full object-cover" muted />- ) : (- <img src={previewUrl} alt="" className="w-full h-full object-cover" />- )- ) : (- <>- {icon}- <span className="text-[9px] text-primary font-bold">READY</span>- </>- )}- </div>- )}- </button>- );+ ? `${fileName} — click to clear`+ : `Upload ${label.toLowerCase()} file`+ }+ onClick={handleClick}+ className={`flex-shrink-0 w-10 h-10 rounded-full border transition-all flex items-center justify-center relative overflow-hidden group ${borderClass}`}+ >+ <input+ ref={inputRef}+ type="file"+ accept={accept}+ className="hidden"+ onChange={handleChange}+ />++ {/* Idle state */}+ {uploadState === UPLOAD_STATE.IDLE && (+ <div className="flex flex-col items-center justify-center gap-1 w-full h-full">+ {icon}+ </div>+ )}++ {/* Uploading indicator */}+ {uploadState === UPLOAD_STATE.UPLOADING && (+ <div className="flex flex-col items-center justify-center w-full h-full absolute inset-0 bg-black/60 z-10 animate-pulse">+ <div className="w-4 h-4 rounded-full border border-primary/30 border-t-primary animate-spin mb-0.5" />+ <span className="text-xs font-black text-primary">+ {progress}%+ </span>+ </div>+ )}++ {/* Ready state */}+ {uploadState === UPLOAD_STATE.READY && (+ <div className="flex flex-col items-center justify-center gap-1 w-full h-full absolute inset-0 bg-primary/10 rounded-full">+ {previewUrl ? (+ isVideo ? (+ <video+ src={previewUrl}+ className="w-full h-full object-cover"+ muted+ />+ ) : (+ <img+ src={previewUrl}+ alt=""+ className="w-full h-full object-cover"+ />+ )+ ) : (+ <>+ {icon}+ </>+ )}+ </div>+ )}+ </button>+ );}// ---------------------------------------------------------------------------// Inline dropdown// ---------------------------------------------------------------------------function Dropdown({ isOpen, items, selectedId, onSelect, onClose, anchorRef }) {- const dropRef = useRef(null);- const [style, setStyle] = useState({});-- useEffect(() => {- if (!isOpen || !anchorRef?.current || !dropRef.current) return;-- const rect = anchorRef.current.getBoundingClientRect();- const ddHeight = dropRef.current.offsetHeight;- const spaceBelow = window.innerHeight - rect.bottom - 8;- const spaceAbove = rect.top - 8;-- let top, bottom, maxHeight;- if (spaceBelow >= ddHeight || spaceBelow >= spaceAbove) {- top = rect.bottom + 8;- bottom = 'auto';- maxHeight = Math.max(150, spaceBelow - 8);- } else {- top = 'auto';- bottom = window.innerHeight - rect.top + 8;- maxHeight = Math.max(150, spaceAbove - 8);- }- const left = Math.min(rect.left, window.innerWidth - 220);- setStyle({ top, bottom, left, maxHeight });- }, [isOpen, anchorRef]);-- useEffect(() => {- if (!isOpen) return;- const handler = (e) => {- if (!dropRef.current?.contains(e.target) && !anchorRef?.current?.contains(e.target)) {- onClose();- }- };- window.addEventListener('click', handler);- return () => window.removeEventListener('click', handler);- }, [isOpen, onClose, anchorRef]);-- if (!isOpen) return null;-- return (- <div- ref={dropRef}- style={{ position: 'fixed', zIndex: 100, minWidth: 200, overflowY: 'auto', ...style }}- className="bg-[#111] border border-white/10 rounded-2xl shadow-3xl p-2 custom-scrollbar"+ const dropRef = useRef(null);+ const [style, setStyle] = useState({});++ useEffect(() => {+ if (!isOpen || !anchorRef?.current || !dropRef.current) return;++ const rect = anchorRef.current.getBoundingClientRect();+ const ddHeight = dropRef.current.offsetHeight;+ const spaceBelow = window.innerHeight - rect.bottom - 8;+ const spaceAbove = rect.top - 8;++ let top, bottom, maxHeight;+ if (spaceBelow >= ddHeight || spaceBelow >= spaceAbove) {+ top = rect.bottom + 8;+ bottom = "auto";+ maxHeight = Math.max(150, spaceBelow - 8);+ } else {+ top = "auto";+ bottom = window.innerHeight - rect.top + 8;+ maxHeight = Math.max(150, spaceAbove - 8);+ }+ const left = Math.min(rect.left, window.innerWidth - 220);+ setStyle({ top, bottom, left, maxHeight });+ }, [isOpen, anchorRef]);++ useEffect(() => {+ if (!isOpen) return;+ const handler = (e) => {+ if (+ !dropRef.current?.contains(e.target) &&+ !anchorRef?.current?.contains(e.target)+ ) {+ onClose();+ }+ };+ window.addEventListener("click", handler);+ return () => window.removeEventListener("click", handler);+ }, [isOpen, onClose, anchorRef]);++ if (!isOpen) return null;++ return (+ <div+ ref={dropRef}+ style={{+ position: "fixed",+ zIndex: 100,+ overflowY: "auto",+ ...style,+ }}+ className="bg-[#111] border border-white/10 rounded-lg shadow-3xl p-2 custom-scrollbar w-[calc(100vw-3rem)] max-w-xs"+ >+ {items.map((item) => (+ <button+ key={item.id}+ type="button"+ onClick={() => {+ onSelect(item);+ onClose();+ }}+ className={`w-full text-left px-4 py-2 rounded text-sm transition-all hover:bg-white/10 ${+ item.id === selectedId+ ? "text-primary font-bold bg-primary/5"+ : "text-white font-medium"+ }`}>- {items.map((item) => (- <button- key={item.id}- type="button"- onClick={() => { onSelect(item); onClose(); }}- className={`w-full text-left px-4 py-2.5 rounded-xl text-sm transition-all hover:bg-white/10 ${- item.id === selectedId ? 'text-primary font-bold bg-primary/5' : 'text-white font-medium'- }`}- >- <div>{item.name}</div>- {item.description && (- <div className="text-xs text-muted mt-0.5">- {item.description.slice(0, 60)}...- </div>- )}- </button>- ))}- </div>- );+ <div>{item.name}</div>+ {item.description && (+ <div className="text-xs text-muted mt-0.5">+ {item.description.slice(0, 60)}...+ </div>+ )}+ </button>+ ))}+ </div>+ );}// ---------------------------------------------------------------------------// History sidebar thumbnail// ---------------------------------------------------------------------------function HistoryThumb({ entry, isActive, onSelect, onDownload }) {- return (- <div- onClick={onSelect}- className={`relative group/thumb cursor-pointer rounded-xl overflow-hidden border-2 transition-all duration-300 ${- isActive ? 'border-primary shadow-glow' : 'border-white/10 hover:border-white/30'- }`}+ return (+ <div+ onClick={onSelect}+ className={`relative group/thumb cursor-pointer rounded-lg overflow-hidden border-2 transition-all duration-300 ${+ isActive+ ? "border-primary shadow-glow"+ : "border-white/10 hover:border-white/30"+ }`}+ >+ <video+ src={entry.url}+ preload="metadata"+ muted+ className="w-full aspect-square object-cover"+ />+ <div className="absolute inset-0 bg-black/60 opacity-0 group-hover/thumb:opacity-100 transition-opacity flex items-center justify-center">+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ onDownload(entry);+ }}+ className="p-1.5 bg-primary rounded-lg text-black hover:scale-110 transition-transform"+ title="Download">- <video src={entry.url} preload="metadata" muted className="w-full aspect-square object-cover" />- <div className="absolute inset-0 bg-black/60 opacity-0 group-hover/thumb:opacity-100 transition-opacity flex items-center justify-center">- <button- type="button"- onClick={(e) => { e.stopPropagation(); onDownload(entry); }}- className="p-1.5 bg-primary rounded-lg text-black hover:scale-110 transition-transform"- title="Download"- >- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">- <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" />- </svg>- </button>- </div>- </div>- );+ <svg+ width="12"+ height="12"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="3"+ >+ <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" />+ </svg>+ </button>+ </div>+ </div>+ );}// ---------------------------------------------------------------------------// SVG icons// ----------------------------------------------------------------------------const MicIcon = ({ className = 'text-muted group-hover:text-primary transition-colors' }) => (- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className={className}>- <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z" />- <path d="M19 10v2a7 7 0 0 1-14 0v-2" />- <line x1="12" y1="19" x2="12" y2="23" />- </svg>+const MicIcon = ({+ className = "text-muted group-hover:text-primary transition-colors",+}) => (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ className={className}+ >+ <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z" />+ <path d="M19 10v2a7 7 0 0 1-14 0v-2" />+ <line x1="12" y1="19" x2="12" y2="23" />+ </svg>);-const VideoIcon = ({ className = 'text-muted group-hover:text-primary transition-colors' }) => (- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className={className}>- <polygon points="23 7 16 12 23 17 23 7" />- <rect x="1" y="5" width="15" height="14" rx="2" ry="2" />- </svg>+const VideoIcon = ({+ className = "text-muted group-hover:text-primary transition-colors",+}) => (+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ className={className}+ >+ <polygon points="23 7 16 12 23 17 23 7" />+ <rect x="1" y="5" width="15" height="14" rx="2" ry="2" />+ </svg>);// ---------------------------------------------------------------------------// Main component// ----------------------------------------------------------------------------export default function LipSyncStudio({ apiKey, onGenerationComplete, historyItems }) {- // ── Mode & model state ──────────────────────────────────────────────────- const [inputMode, setInputMode] = useState('image'); // 'image' | 'video'-- const currentModels = inputMode === 'image' ? imageLipSyncModels : videoLipSyncModels;- const firstModel = currentModels[0];-- const [selectedModelId, setSelectedModelId] = useState(firstModel?.id ?? '');- const [selectedResolution, setSelectedResolution] = useState(- firstModel?.inputs?.resolution?.default ?? '480p'- );-- // ── Upload state ────────────────────────────────────────────────────────- const [imageState, setImageState] = useState(UPLOAD_STATE.IDLE);- const [imageName, setImageName] = useState('');- const [imageUrl, setImageUrl] = useState(null);-- const [videoState, setVideoState] = useState(UPLOAD_STATE.IDLE);- const [videoName, setVideoName] = useState('');- const [videoUrl, setVideoUrl] = useState(null);-- const [audioState, setAudioState] = useState(UPLOAD_STATE.IDLE);- const [audioName, setAudioName] = useState('');- const [audioUrl, setAudioUrl] = useState(null);-- // ── Individual progress states ──- const [imageProgress, setImageProgress] = useState(0);- const [videoProgress, setVideoProgress] = useState(0);- const [audioProgress, setAudioProgress] = useState(0);-- // ── Prompt ──────────────────────────────────────────────────────────────- const [prompt, setPrompt] = useState('');-- // ── Generation / UI state ───────────────────────────────────────────────- const [isGenerating, setIsGenerating] = useState(false);- const [generateError, setGenerateError] = useState(null);- const [view, setView] = useState('input'); // 'input' | 'result'- const [activeResultUrl, setActiveResultUrl] = useState(null);-- // ── History ─────────────────────────────────────────────────────────────- // If historyItems prop is provided, use it; otherwise use internal state.- const [internalHistory, setInternalHistory] = useState([]);- const history = historyItems ?? internalHistory;- const [activeHistoryIdx, setActiveHistoryIdx] = useState(0);-- // ── Dropdown state ──────────────────────────────────────────────────────- const [openDropdown, setOpenDropdown] = useState(null); // 'model' | 'resolution' | null- const modelBtnRef = useRef(null);- const resolutionBtnRef = useRef(null);-- // ── Video ref for result ────────────────────────────────────────────────- const resultVideoRef = useRef(null);-- // ── Derived model info ──────────────────────────────────────────────────- const selectedModel = lipsyncModels.find((m) => m.id === selectedModelId);- const resolutionOptions = getResolutionsForLipSyncModel(selectedModelId);- const showResolution = resolutionOptions.length > 0;- const showPrompt = !!selectedModel?.hasPrompt;-- // ── Sync model when mode changes ────────────────────────────────────────- useEffect(() => {- const models = inputMode === 'image' ? imageLipSyncModels : videoLipSyncModels;- const first = models[0];- if (!first) return;- setSelectedModelId(first.id);- setSelectedResolution(first.inputs?.resolution?.default ?? '480p');- }, [inputMode]);-- // ── Upload handlers ─────────────────────────────────────────────────────- const handleImageUpload = useCallback(async (file) => {- if (file.size > 10 * 1024 * 1024) {- alert("Image exceeds 10MB limit.");- return;+export default function LipSyncStudio({+ apiKey,+ onGenerationComplete,+ historyItems,+}) {+ const PERSIST_KEY = "hg_lipsync_studio_persistent";++ // ── Mode & model state ──────────────────────────────────────────────────+ const [inputMode, setInputMode] = useState("image"); // 'image' | 'video'++ const currentModels =+ inputMode === "image" ? imageLipSyncModels : videoLipSyncModels;+ const firstModel = currentModels[0];++ const [selectedModelId, setSelectedModelId] = useState(firstModel?.id ?? "");+ const [selectedResolution, setSelectedResolution] = useState(+ firstModel?.inputs?.resolution?.default ?? "480p",+ );++ // ── Upload state ────────────────────────────────────────────────────────+ const [imageState, setImageState] = useState(UPLOAD_STATE.IDLE);+ const [imageName, setImageName] = useState("");+ const [imageUrl, setImageUrl] = useState(null);++ const [videoState, setVideoState] = useState(UPLOAD_STATE.IDLE);+ const [videoName, setVideoName] = useState("");+ const [videoUrl, setVideoUrl] = useState(null);++ const [audioState, setAudioState] = useState(UPLOAD_STATE.IDLE);+ const [audioName, setAudioName] = useState("");+ const [audioUrl, setAudioUrl] = useState(null);++ // ── Individual progress states ──+ const [imageProgress, setImageProgress] = useState(0);+ const [videoProgress, setVideoProgress] = useState(0);+ const [audioProgress, setAudioProgress] = useState(0);++ // ── Prompt ──────────────────────────────────────────────────────────────+ const [prompt, setPrompt] = useState("");++ // ── Generation / UI state ───────────────────────────────────────────────+ const [isGenerating, setIsGenerating] = useState(false);+ const [generateError, setGenerateError] = useState(null);+ const [fullscreenUrl, setFullscreenUrl] = useState(null);+ const [view, setView] = useState("input"); // 'input' | 'result'+ const [activeResultUrl, setActiveResultUrl] = useState(null);++ // ── History ─────────────────────────────────────────────────────────────+ // If historyItems prop is provided, use it; otherwise use internal state.+ const [internalHistory, setInternalHistory] = useState([]);+ const history = historyItems ?? internalHistory;+ const [activeHistoryIdx, setActiveHistoryIdx] = useState(0);++ // ── Dropdown state ──────────────────────────────────────────────────────+ const [openDropdown, setOpenDropdown] = useState(null); // 'model' | 'resolution' | null+ const modelBtnRef = useRef(null);+ const resolutionBtnRef = useRef(null);++ // ── Video ref for result ────────────────────────────────────────────────+ const resultVideoRef = useRef(null);+ const hasRestored = useRef(false);++ // ── Persistence: Load ────────────────────────────────────────────────────+ useEffect(() => {+ try {+ const stored = localStorage.getItem(PERSIST_KEY);+ if (stored) {+ const data = JSON.parse(stored);+ if (data.inputMode) setInputMode(data.inputMode);+ if (data.selectedModelId) setSelectedModelId(data.selectedModelId);+ if (data.selectedResolution) setSelectedResolution(data.selectedResolution);+ if (data.imageUrl) {+ setImageUrl(data.imageUrl);+ setImageState(UPLOAD_STATE.READY);}- setImageState(UPLOAD_STATE.UPLOADING);- setImageProgress(0);- try {- const url = await uploadFile(apiKey, file, (pct) => {- setImageProgress(pct);- });- setImageUrl(url);- setImageName(file.name);- setImageState(UPLOAD_STATE.READY);- } catch (err) {- setImageState(UPLOAD_STATE.IDLE);- alert(`Image upload failed: ${err.message}`);- } finally {- setImageProgress(0);+ if (data.videoUrl) {+ setVideoUrl(data.videoUrl);+ setVideoState(UPLOAD_STATE.READY);}- }, [apiKey]);-- const handleVideoPick = useCallback(async (file) => {- if (file.size > 50 * 1024 * 1024) {- alert("Video exceeds 50MB limit.");- return;+ if (data.audioUrl) {+ setAudioUrl(data.audioUrl);+ setAudioState(UPLOAD_STATE.READY);}- setVideoState(UPLOAD_STATE.UPLOADING);+ if (data.imageName) setImageName(data.imageName);+ if (data.videoName) setVideoName(data.videoName);+ if (data.audioName) setAudioName(data.audioName);+ if (data.prompt) setPrompt(data.prompt);+ if (data.internalHistory) setInternalHistory(data.internalHistory);+ }+ } catch (err) {+ console.warn("Failed to load LipSyncStudio persistence:", err);+ } finally {+ hasRestored.current = true;+ }+ }, []);++ // ── Persistence: Save ────────────────────────────────────────────────────+ useEffect(() => {+ const timer = setTimeout(() => {+ try {+ const state = {+ inputMode,+ selectedModelId,+ selectedResolution,+ imageUrl,+ imageName,+ videoUrl,+ videoName,+ audioUrl,+ audioName,+ prompt,+ internalHistory,+ };+ localStorage.setItem(PERSIST_KEY, JSON.stringify(state));+ } catch (err) {+ console.warn("Failed to save LipSyncStudio persistence:", err);+ }+ }, 500); // 500ms debounce+ return () => clearTimeout(timer);+ }, [+ inputMode,+ selectedModelId,+ selectedResolution,+ imageUrl,+ imageName,+ videoUrl,+ videoName,+ audioUrl,+ audioName,+ prompt,+ internalHistory,+ ]);++ // ── Derived model info ──────────────────────────────────────────────────+ const selectedModel = lipsyncModels.find((m) => m.id === selectedModelId);+ const resolutionOptions = getResolutionsForLipSyncModel(selectedModelId);+ const showResolution = resolutionOptions.length > 0;+ const showPrompt = !!selectedModel?.hasPrompt;++ // ── Sync model when mode changes ────────────────────────────────────────+ useEffect(() => {+ if (hasRestored.current) return;+ const models =+ inputMode === "image" ? imageLipSyncModels : videoLipSyncModels;+ const first = models[0];+ if (!first) return;+ setSelectedModelId(first.id);+ setSelectedResolution(first.inputs?.resolution?.default ?? "480p");+ }, [inputMode]);++ // ── Upload handlers ─────────────────────────────────────────────────────+ const handleImageUpload = useCallback(+ async (file) => {+ if (file.size > 10 * 1024 * 1024) {+ alert("Image exceeds 10MB limit.");+ return;+ }+ setImageState(UPLOAD_STATE.UPLOADING);+ setImageProgress(0);+ try {+ const url = await uploadFile(apiKey, file, (pct) => {+ setImageProgress(pct);+ });+ setImageUrl(url);+ setImageName(file.name);+ setImageState(UPLOAD_STATE.READY);+ } catch (err) {+ setImageState(UPLOAD_STATE.IDLE);+ alert(`Image upload failed: ${err.message}`);+ } finally {+ setImageProgress(0);+ }+ },+ [apiKey],+ );++ const handleVideoPick = useCallback(+ async (file) => {+ if (file.size > 50 * 1024 * 1024) {+ alert("Video exceeds 50MB limit.");+ return;+ }+ setVideoState(UPLOAD_STATE.UPLOADING);+ setVideoProgress(0);+ try {+ const url = await uploadFile(apiKey, file, (pct) => {+ setVideoProgress(pct);+ });+ setVideoUrl(url);+ setVideoName(file.name);+ setVideoState(UPLOAD_STATE.READY);+ } catch (err) {+ setVideoState(UPLOAD_STATE.IDLE);+ alert(`Video upload failed: ${err.message}`);+ } finally {setVideoProgress(0);- try {- const url = await uploadFile(apiKey, file, (pct) => {- setVideoProgress(pct);- });- setVideoUrl(url);- setVideoName(file.name);- setVideoState(UPLOAD_STATE.READY);- } catch (err) {- setVideoState(UPLOAD_STATE.IDLE);- alert(`Video upload failed: ${err.message}`);- } finally {- setVideoProgress(0);- }- }, [apiKey]);-- const handleAudioPick = useCallback(async (file) => {- if (file.size > 10 * 1024 * 1024) {- alert("Audio file exceeds 10MB limit.");- return;- }- setAudioState(UPLOAD_STATE.UPLOADING);+ }+ },+ [apiKey],+ );++ const handleAudioPick = useCallback(+ async (file) => {+ if (file.size > 10 * 1024 * 1024) {+ alert("Audio file exceeds 10MB limit.");+ return;+ }+ setAudioState(UPLOAD_STATE.UPLOADING);+ setAudioProgress(0);+ try {+ const url = await uploadFile(apiKey, file, (pct) => {+ setAudioProgress(pct);+ });+ setAudioUrl(url);+ setAudioName(file.name);+ setAudioState(UPLOAD_STATE.READY);+ } catch (err) {+ setAudioState(UPLOAD_STATE.IDLE);+ alert(`Audio upload failed: ${err.message}`);+ } finally {setAudioProgress(0);- try {- const url = await uploadFile(apiKey, file, (pct) => {- setAudioProgress(pct);- });- setAudioUrl(url);- setAudioName(file.name);- setAudioState(UPLOAD_STATE.READY);- } catch (err) {- setAudioState(UPLOAD_STATE.IDLE);- alert(`Audio upload failed: ${err.message}`);- } finally {- setAudioProgress(0);- }- }, [apiKey]);-- // ── Mode toggle ─────────────────────────────────────────────────────────- const switchToImage = () => {- if (inputMode === 'image') return;- setInputMode('image');- setVideoUrl(null);- setVideoState(UPLOAD_STATE.IDLE);- setVideoName('');- };-- const switchToVideo = () => {- if (inputMode === 'video') return;- setInputMode('video');- setImageUrl(null);- setImageState(UPLOAD_STATE.IDLE);- setImageName('');- };-- // ── Model selection ─────────────────────────────────────────────────────- const handleModelSelect = (model) => {- setSelectedModelId(model.id);- const resolutions = getResolutionsForLipSyncModel(model.id);- if (resolutions.length > 0) {- setSelectedResolution(model.inputs?.resolution?.default ?? resolutions[0]);- }- };-- // ── History helpers ─────────────────────────────────────────────────────- const addToInternalHistory = useCallback((entry) => {- setInternalHistory((prev) => [entry, ...prev].slice(0, 30));- }, []);-- const downloadFile = async (url, filename) => {- try {- const response = await fetch(url);- const blob = await response.blob();- const blobUrl = URL.createObjectURL(blob);- const a = document.createElement('a');- a.href = blobUrl;- a.download = filename;- document.body.appendChild(a);- a.click();- document.body.removeChild(a);- URL.revokeObjectURL(blobUrl);- } catch {- window.open(url, '_blank');- }- };+ }+ },+ [apiKey],+ );++ // ── Mode toggle ─────────────────────────────────────────────────────────+ const switchToImage = () => {+ if (inputMode === "image") return;+ setInputMode("image");+ setVideoUrl(null);+ setVideoState(UPLOAD_STATE.IDLE);+ setVideoName("");+ };++ const switchToVideo = () => {+ if (inputMode === "video") return;+ setInputMode("video");+ setImageUrl(null);+ setImageState(UPLOAD_STATE.IDLE);+ setImageName("");+ };++ // ── Model selection ─────────────────────────────────────────────────────+ const handleModelSelect = (model) => {+ setSelectedModelId(model.id);+ const resolutions = getResolutionsForLipSyncModel(model.id);+ if (resolutions.length > 0) {+ setSelectedResolution(+ model.inputs?.resolution?.default ?? resolutions[0],+ );+ }+ };++ // ── History helpers ─────────────────────────────────────────────────────+ const addToInternalHistory = useCallback((entry) => {+ setInternalHistory((prev) => [entry, ...prev].slice(0, 30));+ }, []);++ const downloadFile = async (url, filename) => {+ try {+ const response = await fetch(url);+ const blob = await response.blob();+ const blobUrl = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = blobUrl;+ a.download = filename;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(blobUrl);+ } catch {+ window.open(url, "_blank");+ }+ };++ // ── Generation ──────────────────────────────────────────────────────────+ const handleGenerate = async () => {+ if (!audioUrl) {+ alert("Please upload an audio file first.");+ return;+ }+ if (inputMode === "image" && !imageUrl) {+ alert("Please upload a portrait image first.");+ return;+ }+ if (inputMode === "video" && !videoUrl) {+ alert("Please upload a source video first.");+ return;+ }++ setIsGenerating(true);+ setGenerateError(null);++ try {+ const lipsyncParams = {+ model: selectedModelId,+ audio_url: audioUrl,+ };+ if (inputMode === "image") lipsyncParams.image_url = imageUrl;+ else lipsyncParams.video_url = videoUrl;+ if (prompt && selectedModel?.hasPrompt) lipsyncParams.prompt = prompt;+ if (showResolution) lipsyncParams.resolution = selectedResolution;+ if (selectedModel?.hasSeed) lipsyncParams.seed = -1;++ const res = await processLipSync(apiKey, lipsyncParams);++ if (!res?.url) throw new Error("No video URL returned by API");++ const genId = res.id || Date.now().toString();+ const entry = {+ id: genId,+ url: res.url,+ prompt,+ model: selectedModelId,+ timestamp: new Date().toISOString(),+ };++ if (!historyItems) addToInternalHistory(entry);++ setActiveResultUrl(res.url);+ setActiveHistoryIdx(0);+ setView("result");++ if (onGenerationComplete) {+ onGenerationComplete({+ url: res.url,+ model: selectedModelId,+ prompt,+ type: "lipsync",+ });+ }+ } catch (e) {+ console.error("[LipSyncStudio]", e);+ setGenerateError(e.message?.slice(0, 80) ?? "Unknown error");+ setTimeout(() => setGenerateError(null), 4000);+ } finally {+ setIsGenerating(false);+ }+ };++ // ── Reset to input view ─────────────────────────────────────────────────+ const handleNew = () => {+ setView("input");+ setActiveResultUrl(null);+ setPrompt("");+ setImageUrl(null);+ setImageState(UPLOAD_STATE.IDLE);+ setImageName("");+ setVideoUrl(null);+ setVideoState(UPLOAD_STATE.IDLE);+ setVideoName("");+ setAudioUrl(null);+ setAudioState(UPLOAD_STATE.IDLE);+ setAudioName("");+ };++ // ── Media status labels ─────────────────────────────────────────────────+ const mediaStatusText =+ inputMode === "image"+ ? imageState === UPLOAD_STATE.READY+ ? `✓ ${imageName}`+ : "No image"+ : videoState === UPLOAD_STATE.READY+ ? `✓ ${videoName}`+ : "No video";+ const mediaStatusClass =+ (inputMode === "image" ? imageState : videoState) === UPLOAD_STATE.READY+ ? "text-primary"+ : "text-muted";++ const audioStatusText =+ audioState === UPLOAD_STATE.READY ? `✓ ${audioName}` : "No audio";+ const audioStatusClass =+ audioState === UPLOAD_STATE.READY ? "text-primary" : "text-muted";++ const hasHistory = history.length > 0;++ // ── Dropdown item lists ─────────────────────────────────────────────────+ const modelDropdownItems = currentModels;+ const resolutionDropdownItems = resolutionOptions.map((r) => ({+ id: r,+ name: r,+ }));++ // ── Render ──────────────────────────────────────────────────────────────+ return (+ <div className="w-full h-full flex flex-col items-center justify-center bg-app-bg relative overflow-hidden">++ {/* ── CENTRAL GALLERY AREA ── */}+ <div className="flex-1 w-full max-w-7xl mx-auto overflow-y-auto custom-scrollbar pb-40 lg:pb-32 px-2">+ {history.length > 0 ? (+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 w-full pt-4 animate-fade-in-up">+ {history.map((entry, idx) => (+ <div+ key={entry.id || idx}+ className="relative group rounded-2xl overflow-hidden border border-white/10 bg-[#0a0a0a] shadow-xl hover:border-primary/50 transition-all duration-300 flex flex-col"+ >+ <video+ src={entry.url}+ className="w-full aspect-video object-cover bg-black/40 cursor-pointer hover:opacity-80 transition-opacity"+ onClick={() => setFullscreenUrl(entry.url)}+ controls={false}+ loop+ muted+ playsInline+ onMouseOver={(e) => e.target.play()}+ onMouseOut={(e) => {+ e.target.pause();+ e.target.currentTime = 0;+ }}+ />++ {/* Overlay actions */}+ <div className="absolute top-2 right-2 flex flex-col gap-2 opacity-0 group-hover:opacity-100 transition-opacity">+ <button+ type="button"+ title="Fullscreen"+ onClick={(e) => {+ e.stopPropagation();+ setFullscreenUrl(entry.url);+ }}+ className="p-2 bg-black/60 backdrop-blur-md rounded-full text-white hover:bg-primary hover:text-black transition-all border border-white/10"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <polyline points="15 3 21 3 21 9" />+ <polyline points="9 21 3 21 3 15" />+ <line x1="21" y1="3" x2="14" y2="10" />+ <line x1="3" y1="21" x2="10" y2="14" />+ </svg>+ </button>+ <button+ type="button"+ title="Download"+ onClick={(e) => {+ e.stopPropagation();+ downloadFile(entry.url, `lipsync-${entry.id || idx}.mp4`);+ }}+ className="p-2 bg-black/60 backdrop-blur-md rounded-full text-white hover:bg-primary hover:text-black transition-all border border-white/10"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" />+ </svg>+ </button>+ </div>- // ── Generation ──────────────────────────────────────────────────────────- const handleGenerate = async () => {- if (!audioUrl) { alert('Please upload an audio file first.'); return; }- if (inputMode === 'image' && !imageUrl) { alert('Please upload a portrait image first.'); return; }- if (inputMode === 'video' && !videoUrl) { alert('Please upload a source video first.'); return; }-- setIsGenerating(true);- setGenerateError(null);-- try {- const lipsyncParams = {- model: selectedModelId,- audio_url: audioUrl,- };- if (inputMode === 'image') lipsyncParams.image_url = imageUrl;- else lipsyncParams.video_url = videoUrl;- if (prompt && selectedModel?.hasPrompt) lipsyncParams.prompt = prompt;- if (showResolution) lipsyncParams.resolution = selectedResolution;- if (selectedModel?.hasSeed) lipsyncParams.seed = -1;-- const res = await processLipSync(apiKey, lipsyncParams);-- if (!res?.url) throw new Error('No video URL returned by API');-- const genId = res.id || Date.now().toString();- const entry = {- id: genId,- url: res.url,- prompt,- model: selectedModelId,- timestamp: new Date().toISOString(),- };-- if (!historyItems) addToInternalHistory(entry);-- setActiveResultUrl(res.url);- setActiveHistoryIdx(0);- setView('result');-- if (onGenerationComplete) {- onGenerationComplete({ url: res.url, model: selectedModelId, prompt, type: 'lipsync' });- }- } catch (e) {- console.error('[LipSyncStudio]', e);- setGenerateError(e.message?.slice(0, 80) ?? 'Unknown error');- setTimeout(() => setGenerateError(null), 4000);- } finally {- setIsGenerating(false);- }- };+ {/* Details */}+ <div className="p-3 bg-black/80 backdrop-blur-sm border-t border-white/5 flex-1 flex flex-col justify-between gap-2">+ <div className="flex items-center justify-between flex-wrap gap-1">+ <span className="text-[10px] font-bold text-primary px-2 py-0.5 bg-primary/10 rounded border border-primary/20 whitespace-nowrap">+ {entry.model?.name || entry.model || "Lip Sync"}+ </span>+ {entry.resolution && (+ <span className="text-[10px] text-white/40">{entry.resolution}</span>+ )}+ </div>+ </div>+ </div>+ ))}+ </div>+ ) : (+ <div className="flex flex-col items-center justify-center h-full animate-fade-in-up transition-all duration-700 min-h-[50vh]">+ <div className="mb-12 relative group">+ <div className="absolute inset-0 bg-primary/10 blur-[120px] rounded-full opacity-30 group-hover:opacity-60 transition-opacity duration-1000" />+ <div className="relative w-24 h-24 md:w-32 md:h-32 bg-white/[0.02] rounded-[2rem] flex items-center justify-center border border-white/[0.05] overflow-hidden backdrop-blur-sm">+ <div className="w-16 h-16 bg-primary/5 rounded-2xl flex items-center justify-center border border-primary/10 relative z-10 transition-transform duration-500 group-hover:scale-110">+ <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="text-primary opacity-80">+ <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z" />+ <path d="M19 10v2a7 7 0 0 1-14 0v-2" />+ <line x1="12" y1="19" x2="12" y2="23" />+ <line x1="8" y1="23" x2="16" y2="23" />+ </svg>+ </div>+ <div className="absolute top-4 right-4 text-[10px] text-primary/40 animate-pulse">🎙</div>+ </div>+ </div>+ <h1 className="text-3xl sm:text-5xl md:text-6xl font-extrabold text-white tracking-tight mb-4 text-center px-4">+ <span className="text-white/40 font-medium">START CREATING WITH</span><br />+ <span className="text-white">LIP SYNC</span>+ </h1>+ <p className="text-white/40 text-sm md:text-base font-medium tracking-wide text-center max-w-lg leading-relaxed">+ Animate portraits or sync lips to audio with AI+ </p>+ </div>+ )}+ </div>++ {/* ── BOTTOM PROMPT BAR ── */}+ <div className="absolute bottom-4 w-full max-w-[95%] lg:max-w-4xl z-40 animate-fade-in-up" style={{ animationDelay: "0.2s" }}>+ <div className="w-full bg-[#0a0a0a]/80 backdrop-blur-3xl rounded-md border border-white/10 p-4 flex flex-col gap-2 shadow-2xl">+ {/* Mode toggle row */}+ <div className="flex items-center gap-2 px-3">+ <button+ type="button"+ onClick={switchToImage}+ className={`px-3 py-1 rounded-md text-xs font-bold transition-all border ${+ inputMode === "image"+ ? "border-primary/60 bg-primary/5 text-primary"+ : "border-white/[0.03] bg-white/[0.03] text-white/40 hover:border-white/20 hover:text-white"+ }`}+ >+ 🖼 Portrait Image+ </button>+ <button+ type="button"+ onClick={switchToVideo}+ className={`px-3 py-1 rounded-md text-[10px] font-bold transition-all border ${+ inputMode === "video"+ ? "border-primary/60 bg-primary/5 text-primary"+ : "border-white/[0.03] bg-white/[0.03] text-white/40 hover:border-white/20 hover:text-white"+ }`}+ >+ 🎬 Video+ </button>+ </div>++ {/* Uploads row */}+ <div className="flex items-center gap-2 px-1">+ <div className="flex items-center gap-2">+ {/* Image picker — only in image mode */}+ {inputMode === "image" && (+ <MediaPickerButton+ accept="image/*"+ label="Image"+ icon={+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ className="text-white/40 group-hover:text-primary transition-colors"+ >+ <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>+ }+ onUpload={handleImageUpload}+ onClear={() => {+ setImageUrl(null);+ setImageState(UPLOAD_STATE.IDLE);+ setImageName("");+ }}+ uploadState={imageState}+ progress={imageProgress}+ fileName={imageName}+ previewUrl={imageUrl}+ isVideo={false}+ apiKey={apiKey}+ />+ )}++ {/* Video picker — only in video mode */}+ {inputMode === "video" && (+ <MediaPickerButton+ accept="video/*"+ label="Video"+ icon={+ <VideoIcon className="text-white/40 group-hover:text-primary transition-colors" />+ }+ onUpload={handleVideoPick}+ onClear={() => {+ setVideoUrl(null);+ setVideoState(UPLOAD_STATE.IDLE);+ setVideoName("");+ }}+ uploadState={videoState}+ progress={videoProgress}+ fileName={videoName}+ previewUrl={videoUrl}+ isVideo={true}+ apiKey={apiKey}+ />+ )}++ {/* Audio picker — always visible */}+ <MediaPickerButton+ accept="audio/*"+ label="Audio"+ icon={+ <MicIcon className="text-white/40 group-hover:text-primary transition-colors" />+ }+ onUpload={handleAudioPick}+ onClear={() => {+ setAudioUrl(null);+ setAudioState(UPLOAD_STATE.IDLE);+ setAudioName("");+ }}+ uploadState={audioState}+ progress={audioProgress}+ fileName={audioName}+ previewUrl={null}+ isVideo={false}+ apiKey={apiKey}+ />+ </div>- // ── Reset to input view ─────────────────────────────────────────────────- const handleNew = () => {- setView('input');- setActiveResultUrl(null);- setPrompt('');- setImageUrl(null); setImageState(UPLOAD_STATE.IDLE); setImageName('');- setVideoUrl(null); setVideoState(UPLOAD_STATE.IDLE); setVideoName('');- setAudioUrl(null); setAudioState(UPLOAD_STATE.IDLE); setAudioName('');- };+ {/* Prompt textarea */}+ {showPrompt && (+ <div className="flex-1 flex flex-col">+ <textarea+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ placeholder="Describe speech style..."+ className="w-full bg-transparent border-none text-white text-sm placeholder:text-white/10 focus:outline-none resize-none pt-1 leading-relaxed min-h-[40px] max-h-[150px] md:max-h-[250px] overflow-y-auto custom-scrollbar disabled:opacity-40"+ rows={1}+ />+ </div>+ )}+ </div>- // ── Media status labels ─────────────────────────────────────────────────- const mediaStatusText = inputMode === 'image'- ? (imageState === UPLOAD_STATE.READY ? `✓ ${imageName}` : 'No image')- : (videoState === UPLOAD_STATE.READY ? `✓ ${videoName}` : 'No video');- const mediaStatusClass = (inputMode === 'image' ? imageState : videoState) === UPLOAD_STATE.READY- ? 'text-primary' : 'text-muted';-- const audioStatusText = audioState === UPLOAD_STATE.READY ? `✓ ${audioName}` : 'No audio';- const audioStatusClass = audioState === UPLOAD_STATE.READY ? 'text-primary' : 'text-muted';-- const hasHistory = history.length > 0;-- // ── Dropdown item lists ─────────────────────────────────────────────────- const modelDropdownItems = currentModels;- const resolutionDropdownItems = resolutionOptions.map((r) => ({ id: r, name: r }));-- // ── Render ──────────────────────────────────────────────────────────────- return (- <div className="w-full h-full flex flex-col items-center justify-center bg-app-bg relative p-4 md:p-6 overflow-y-auto custom-scrollbar overflow-x-hidden">-- {/* ── History sidebar ── */}- {hasHistory && (- <div className="fixed right-0 top-0 h-full w-20 md:w-24 bg-black/60 backdrop-blur-xl border-l border-white/5 z-50 flex flex-col items-center py-4 gap-3 overflow-y-auto transition-all duration-500">- <div className="text-[9px] font-bold text-muted uppercase tracking-widest mb-2">History</div>- <div className="flex flex-col gap-2 w-full px-2">- {history.map((entry, idx) => (- <HistoryThumb- key={entry.id ?? idx}- entry={entry}- isActive={idx === activeHistoryIdx}- onSelect={() => {- setActiveResultUrl(entry.url);- setActiveHistoryIdx(idx);- setView('result');- }}- onDownload={(e) => downloadFile(e.url, `lipsync-${e.id ?? idx}.mp4`)}- />- ))}- </div>+ {/* Bottom controls row */}+ <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 pt-2 border-t border-white/[0.03] relative">+ <div className="flex items-center gap-2 px-1">+ {/* Model selector */}+ <div className="relative">+ <button+ ref={modelBtnRef}+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ setOpenDropdown(+ openDropdown === "model" ? null : "model",+ );+ }}+ className="flex items-center gap-2 px-2 py-1.5 bg-white/[0.03] hover:bg-white/[0.06] rounded-md transition-all border border-white/[0.03] group whitespace-nowrap"+ >+ <div className="w-3.5 h-3.5 bg-[#d9ff00] rounded-sm flex items-center justify-center">+ <span className="text-[9px] font-black text-black">+ S+ </span>+ </div>+ <span className="text-xs font-semibold text-white/70 group-hover:text-[#d9ff00] transition-colors">+ {selectedModel?.name ?? "Select model"}+ </span>+ <svg+ width="10"+ height="10"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="4"+ className="opacity-50 group-hover:opacity-100 transition-opacity flex-shrink-0"+ >+ <path d="M6 9l6 6 6-6" />+ </svg>+ </button>+ <Dropdown+ isOpen={openDropdown === "model"}+ items={modelDropdownItems}+ selectedId={selectedModelId}+ onSelect={handleModelSelect}+ onClose={() => setOpenDropdown(null)}+ anchorRef={modelBtnRef}+ />+ </div>++ {/* Resolution selector */}+ {showResolution && (+ <div className="relative">+ <button+ ref={resolutionBtnRef}+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ setOpenDropdown(+ openDropdown === "resolution" ? null : "resolution",+ );+ }}+ className="flex items-center gap-2 px-2 py-1.5 bg-white/[0.03] hover:bg-white/[0.06] rounded-md transition-all border border-white/[0.03] group whitespace-nowrap"+ >+ <span className="text-xs font-semibold text-white/70 group-hover:text-[#d9ff00] transition-colors">+ {selectedResolution}+ </span>+ </button>+ <Dropdown+ isOpen={openDropdown === "resolution"}+ items={resolutionDropdownItems}+ selectedId={selectedResolution}+ onSelect={(item) => setSelectedResolution(item.id)}+ onClose={() => setOpenDropdown(null)}+ anchorRef={resolutionBtnRef}+ /></div>- )}+ )}+ </div>- {/* ── Input view ── */}- {view === 'input' && (+ {/* Generate button */}+ <button+ type="button"+ onClick={handleGenerate}+ disabled={isGenerating}+ className="bg-[#d9ff00] text-black px-4 py-2 rounded-md font-medium text-sm hover:bg-[#e5ff33] hover:scale-[1.02] active:scale-[0.98] transition-all flex items-center justify-center gap-2 w-full sm:w-auto shadow-lg shadow-[#d9ff00]/10 disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {isGenerating ? (<>- {/* Hero */}- <div className="flex flex-col items-center mb-10 md:mb-20 animate-fade-in-up transition-all duration-700">- <div className="mb-10 relative group">- <div className="absolute inset-0 bg-primary/20 blur-[100px] rounded-full opacity-40 group-hover:opacity-70 transition-opacity duration-1000" />- <div className="relative w-24 h-24 md:w-32 md:h-32 bg-teal-900/40 rounded-3xl flex items-center justify-center border border-white/5 overflow-hidden">- <svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" className="text-primary opacity-20 absolute -right-4 -bottom-4">- <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z" />- <path d="M19 10v2a7 7 0 0 1-14 0v-2" />- <line x1="12" y1="19" x2="12" y2="23" />- <line x1="8" y1="23" x2="16" y2="23" />- </svg>- <div className="w-16 h-16 bg-primary/10 rounded-2xl flex items-center justify-center border border-primary/20 shadow-glow relative z-10">- <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="text-primary">- <path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z" />- <path d="M19 10v2a7 7 0 0 1-14 0v-2" />- <line x1="12" y1="19" x2="12" y2="23" />- <line x1="8" y1="23" x2="16" y2="23" />- </svg>- </div>- <div className="absolute top-4 right-4 text-primary animate-pulse">🎙</div>- </div>- </div>- <h1 className="text-2xl sm:text-4xl md:text-7xl font-black text-white tracking-widest uppercase mb-4 selection:bg-primary selection:text-black text-center px-4">- Lip Sync- </h1>- <p className="text-secondary text-sm font-medium tracking-wide opacity-60">- Animate portraits or sync lips to audio with AI- </p>- </div>-- {/* Input bar */}- <div className="w-full max-w-4xl relative z-40 animate-fade-in-up" style={{ animationDelay: '0.2s' }}>- <div className="w-full bg-[#111]/90 backdrop-blur-xl border border-white/10 rounded-[1.5rem] md:rounded-[2.5rem] p-3 md:p-5 flex flex-col gap-3 md:gap-5 shadow-3xl">-- {/* Mode toggle row */}- <div className="flex items-center gap-2 px-2">- <span className="text-xs text-muted font-bold uppercase tracking-widest mr-2">Input:</span>- <button- type="button"- onClick={switchToImage}- className={`px-4 py-1.5 rounded-xl text-xs font-bold transition-all border ${- inputMode === 'image'- ? 'border-primary bg-primary/10 text-primary'- : 'border-white/10 text-muted hover:border-white/30 hover:text-white'- }`}- >- 🖼 Portrait Image- </button>- <button- type="button"- onClick={switchToVideo}- className={`px-4 py-1.5 rounded-xl text-xs font-bold transition-all border ${- inputMode === 'video'- ? 'border-primary bg-primary/10 text-primary'- : 'border-white/10 text-muted hover:border-white/30 hover:text-white'- }`}- >- 🎬 Video- </button>- </div>-- {/* Uploads row */}- <div className="flex items-start gap-3 px-2">- {/* Image picker — only in image mode */}- {inputMode === 'image' && (- <MediaPickerButton- accept="image/*"- label="Image"- icon={- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-muted group-hover:text-primary transition-colors">- <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>- }- onUpload={handleImageUpload}- onClear={() => {- setImageUrl(null);- setImageState(UPLOAD_STATE.IDLE);- setImageName('');- }}- uploadState={imageState}- progress={imageProgress}- fileName={imageName}- previewUrl={imageUrl}- isVideo={false}- apiKey={apiKey}- />- )}-- {/* Video picker — only in video mode */}- {inputMode === 'video' && (- <MediaPickerButton- accept="video/*"- label="Video"- icon={<VideoIcon />}- onUpload={handleVideoPick}- onClear={() => {- setVideoUrl(null);- setVideoState(UPLOAD_STATE.IDLE);- setVideoName('');- }}- uploadState={videoState}- progress={videoProgress}- fileName={videoName}- previewUrl={videoUrl}- isVideo={true}- apiKey={apiKey}- />- )}-- {/* Audio picker — always visible */}- <MediaPickerButton- accept="audio/*"- label="Audio"- icon={<MicIcon />}- onUpload={handleAudioPick}- onClear={() => { setAudioUrl(null); setAudioState(UPLOAD_STATE.IDLE); setAudioName(''); }}- uploadState={audioState}- progress={audioProgress}- fileName={audioName}- previewUrl={null}- isVideo={false}- apiKey={apiKey}- />-- {/* Prompt textarea */}- {showPrompt && (- <textarea- value={prompt}- onChange={(e) => setPrompt(e.target.value)}- placeholder="Optional: describe the talking style or motion..."- className="flex-1 bg-transparent text-white placeholder-muted/50 text-sm resize-none outline-none min-h-[56px] leading-relaxed pt-1"- rows={2}- />- )}- </div>-- {/* Status labels */}- <div className="flex items-center gap-3 px-2 text-xs text-muted">- <span className={mediaStatusClass}>{mediaStatusText}</span>- <span>·</span>- <span className={audioStatusClass}>{audioStatusText}</span>- </div>-- {/* Bottom controls row */}- <div className="flex items-center gap-2 md:gap-3 flex-wrap px-2">- {/* Model selector */}- <div className="relative">- <button- ref={modelBtnRef}- type="button"- onClick={(e) => {- e.stopPropagation();- setOpenDropdown(openDropdown === 'model' ? null : 'model');- }}- className="flex items-center gap-2 px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 hover:border-primary/40 transition-all text-xs font-bold text-white group"- >- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-primary">- <polygon points="23 7 16 12 23 17 23 7" />- <rect x="1" y="5" width="15" height="14" rx="2" ry="2" />- </svg>- <span>{selectedModel?.name ?? 'Select model'}</span>- <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="text-muted group-hover:text-white transition-colors">- <polyline points="6 9 12 15 18 9" />- </svg>- </button>- <Dropdown- isOpen={openDropdown === 'model'}- items={modelDropdownItems}- selectedId={selectedModelId}- onSelect={handleModelSelect}- onClose={() => setOpenDropdown(null)}- anchorRef={modelBtnRef}- />- </div>-- {/* Resolution selector */}- {showResolution && (- <div className="relative">- <button- ref={resolutionBtnRef}- type="button"- onClick={(e) => {- e.stopPropagation();- setOpenDropdown(openDropdown === 'resolution' ? null : 'resolution');- }}- className="flex items-center gap-2 px-3 py-2 rounded-xl bg-white/5 hover:bg-white/10 border border-white/10 hover:border-primary/40 transition-all text-xs font-bold text-white group"- >- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-primary">- <rect x="2" y="3" width="20" height="14" rx="2" ry="2" />- <line x1="8" y1="21" x2="16" y2="21" />- <line x1="12" y1="17" x2="12" y2="21" />- </svg>- <span>{selectedResolution}</span>- <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="text-muted group-hover:text-white transition-colors">- <polyline points="6 9 12 15 18 9" />- </svg>- </button>- <Dropdown- isOpen={openDropdown === 'resolution'}- items={resolutionDropdownItems}- selectedId={selectedResolution}- onSelect={(item) => setSelectedResolution(item.id)}- onClose={() => setOpenDropdown(null)}- anchorRef={resolutionBtnRef}- />- </div>- )}-- {/* Generate button */}- <button- type="button"- onClick={handleGenerate}- disabled={isGenerating}- className="ml-auto px-6 py-2.5 bg-primary text-black font-black text-sm rounded-2xl hover:scale-105 active:scale-95 transition-all shadow-glow disabled:opacity-50 disabled:cursor-not-allowed disabled:hover:scale-100"- >- {isGenerating ? (- <><span className="animate-spin inline-block mr-2 text-black">◌</span>Generating...</>- ) : generateError ? (- `Error: ${generateError}`- ) : (- 'Generate ✨'- )}- </button>- </div>- </div>- </div>+ <span className="animate-spin inline-block text-black">+ ◌+ </span>{" "}+ Generating...</>- )}+ ) : generateError ? (+ `Error: ${generateError}`+ ) : (+ <>+ <span>Sync Lip</span>+ </>+ )}+ </button>+ </div>+ </div>+ </div>- {/* ── Result canvas view ── */}- {view === 'result' && activeResultUrl && (- <div className="absolute inset-0 flex flex-col items-center justify-center p-4 min-[800px]:p-16 z-10 transition-all duration-1000">- <div className="relative group">- <video- ref={resultVideoRef}- src={activeResultUrl}- className="max-h-[60vh] max-w-[80vw] rounded-3xl shadow-3xl border border-white/10 interactive-glow object-contain"- controls- loop- autoPlay- playsInline- />- </div>- <div className="mt-6 flex gap-3 justify-center">- <button- type="button"- onClick={handleGenerate}- disabled={isGenerating}- className="bg-white/10 hover:bg-white/20 px-6 py-2.5 rounded-2xl text-xs font-bold transition-all border border-white/5 backdrop-blur-lg text-white disabled:opacity-50"- >- ↻ Regenerate- </button>- <button- type="button"- onClick={() => {- const entry = history.find((e) => e.url === activeResultUrl);- downloadFile(activeResultUrl, `lipsync-${entry?.id ?? 'clip'}.mp4`);- }}- className="bg-primary text-black px-6 py-2.5 rounded-2xl text-xs font-bold transition-all shadow-glow active:scale-95"- >- ↓ Download- </button>- <button- type="button"- onClick={handleNew}- className="bg-white/10 hover:bg-white/20 px-6 py-2.5 rounded-2xl text-xs font-bold transition-all border border-white/5 backdrop-blur-lg text-white"- >- + New- </button>- </div>- </div>- )}+ {/* ── FULLSCREEN MEDIA MODAL ── */}+ {fullscreenUrl && (+ <div+ className="fixed inset-0 z-[100] flex items-center justify-center bg-black/95 backdrop-blur-sm animate-fade-in"+ onClick={() => setFullscreenUrl(null)}+ >+ <button+ type="button"+ className="absolute top-6 right-6 p-3 bg-white/10 hover:bg-white/20 rounded-full text-white transition-colors border border-white/10"+ onClick={(e) => {+ e.stopPropagation();+ setFullscreenUrl(null);+ }}+ >+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">+ <line x1="18" y1="6" x2="6" y2="18" />+ <line x1="6" y1="6" x2="18" y2="18" />+ </svg>+ </button>+ <video+ src={fullscreenUrl}+ controls+ autoPlay+ loop+ className="max-w-[95vw] max-h-[95vh] rounded-2xl shadow-2xl object-contain animate-scale-up"+ onClick={(e) => e.stopPropagation()}+ /></div>- );+ )}+ </div>+ );}diff --git a/packages/studio/src/components/VideoStudio.jsx b/packages/studio/src/components/VideoStudio.jsxindex 24d6d30e..6cd99a7c 100644--- a/packages/studio/src/components/VideoStudio.jsx+++ b/packages/studio/src/components/VideoStudio.jsx@@ -1,1018 +1,1446 @@"use client";-import { useState, useEffect, useRef, useCallback } from 'react';-import { generateVideo, generateI2V, uploadFile } from '../muapi.js';+import { useState, useEffect, useRef, useCallback } from "react";+import { generateVideo, generateI2V, uploadFile } from "../muapi.js";import {- t2vModels,- i2vModels,- v2vModels,- getAspectRatiosForVideoModel,- getDurationsForModel,- getResolutionsForVideoModel,- getAspectRatiosForI2VModel,- getDurationsForI2VModel,- getResolutionsForI2VModel,- getModesForModel,-} from '../models.js';+ t2vModels,+ i2vModels,+ v2vModels,+ getAspectRatiosForVideoModel,+ getDurationsForModel,+ getResolutionsForVideoModel,+ getAspectRatiosForI2VModel,+ getDurationsForI2VModel,+ getResolutionsForI2VModel,+ getModesForModel,+} from "../models.js";// ── tiny helpers ──────────────────────────────────────────────────────────────function getQualitiesForModel(modelList, modelId) {- const model = modelList.find(m => m.id === modelId);- return model?.inputs?.quality?.enum || [];+ const model = modelList.find((m) => m.id === modelId);+ return model?.inputs?.quality?.enum || [];}async function downloadFile(url, filename) {- try {- const response = await fetch(url);- const blob = await response.blob();- const blobUrl = URL.createObjectURL(blob);- const a = document.createElement('a');- a.href = blobUrl;- a.download = filename;- document.body.appendChild(a);- a.click();- document.body.removeChild(a);- URL.revokeObjectURL(blobUrl);- } catch {- window.open(url, '_blank');- }+ try {+ const response = await fetch(url);+ const blob = await response.blob();+ const blobUrl = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = blobUrl;+ a.download = filename;+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ URL.revokeObjectURL(blobUrl);+ } catch {+ window.open(url, "_blank");+ }}// ── SVG icons (kept inline to avoid extra deps) ───────────────────────────────const CheckSvg = () => (- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#d9ff00" strokeWidth="4">- <polyline points="20 6 9 17 4 12" />- </svg>+ <svg+ width="16"+ height="16"+ viewBox="0 0 24 24"+ fill="none"+ stroke="#d9ff00"+ strokeWidth="4"+ >+ <polyline points="20 6 9 17 4 12" />+ </svg>);const VideoIconSvg = ({ className }) => (- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className={className}>- <polygon points="23 7 16 12 23 17 23 7" />- <rect x="1" y="5" width="15" height="14" rx="2" ry="2" />- </svg>+ <svg+ width="18"+ height="18"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ className={className}+ >+ <polygon points="23 7 16 12 23 17 23 7" />+ <rect x="1" y="5" width="15" height="14" rx="2" ry="2" />+ </svg>);const VideoReadySvg = () => (- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-primary">- <polygon points="23 7 16 12 23 17 23 7" />- <rect x="1" y="5" width="15" height="14" rx="2" ry="2" />- <polyline points="7 10 10 13 15 8" stroke="#d9ff00" strokeWidth="2.5" />- </svg>+ <svg+ width="18"+ height="18"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ className="text-primary"+ >+ <polygon points="23 7 16 12 23 17 23 7" />+ <rect x="1" y="5" width="15" height="14" rx="2" ry="2" />+ <polyline points="7 10 10 13 15 8" stroke="#d9ff00" strokeWidth="2.5" />+ </svg>);// ── Dropdown components ───────────────────────────────────────────────────────function DropdownItem({ label, selected, onClick }) {- return (- <div- className="flex items-center justify-between p-3.5 hover:bg-white/5 rounded-2xl cursor-pointer transition-all group"- onClick={onClick}- >- <span className="text-xs font-bold text-white opacity-80 group-hover:opacity-100 capitalize">{label}</span>- {selected && <CheckSvg />}- </div>- );+ return (+ <div+ className="flex items-center justify-between p-3.5 hover:bg-white/5 rounded-2xl cursor-pointer transition-all group"+ onClick={onClick}+ >+ <span className="text-xs font-bold text-white opacity-80 group-hover:opacity-100 capitalize">+ {label}+ </span>+ {selected && <CheckSvg />}+ </div>+ );}function ModelDropdown({ imageMode, selectedModel, onSelect, onClose }) {- const [search, setSearch] = useState('');-- const generationModels = imageMode ? i2vModels : t2vModels;-- const lf = search.toLowerCase();- const filteredMain = generationModels.filter(- m => m.name.toLowerCase().includes(lf) || m.id.toLowerCase().includes(lf)- );- const filteredV2V = v2vModels.filter(- m => m.name.toLowerCase().includes(lf) || m.id.toLowerCase().includes(lf)- );-- const getIconColor = (m, isV2V) => {- if (isV2V) return 'bg-orange-500/10 text-orange-400';- if (m.id.includes('kling')) return 'bg-blue-500/10 text-blue-400';- if (m.id.includes('veo')) return 'bg-purple-500/10 text-purple-400';- if (m.id.includes('sora')) return 'bg-rose-500/10 text-rose-400';- return 'bg-primary/10 text-primary';- };-- const renderItem = (m, isV2V = false) => (+ const [search, setSearch] = useState("");++ const generationModels = imageMode ? i2vModels : t2vModels;++ const lf = search.toLowerCase();+ const filteredMain = generationModels.filter(+ (m) => m.name.toLowerCase().includes(lf) || m.id.toLowerCase().includes(lf),+ );+ const filteredV2V = v2vModels.filter(+ (m) => m.name.toLowerCase().includes(lf) || m.id.toLowerCase().includes(lf),+ );++ const getIconColor = (m, isV2V) => {+ if (isV2V) return "bg-orange-500/10 text-orange-400";+ if (m.id.includes("kling")) return "bg-blue-500/10 text-blue-400";+ if (m.id.includes("veo")) return "bg-purple-500/10 text-purple-400";+ if (m.id.includes("sora")) return "bg-rose-500/10 text-rose-400";+ return "bg-primary/10 text-primary";+ };++ const renderItem = (m, isV2V = false) => (+ <div+ key={m.id}+ className={`flex items-center justify-between p-3.5 hover:bg-white/5 rounded-2xl cursor-pointer transition-all border border-transparent hover:border-white/5 ${selectedModel === m.id ? "bg-white/5 border-white/5" : ""}`}+ onClick={(e) => {+ e.stopPropagation();+ onSelect(m, isV2V);+ onClose();+ }}+ >+ <div className="flex items-center gap-3.5"><div- key={m.id}- className={`flex items-center justify-between p-3.5 hover:bg-white/5 rounded-2xl cursor-pointer transition-all border border-transparent hover:border-white/5 ${selectedModel === m.id ? 'bg-white/5 border-white/5' : ''}`}- onClick={(e) => { e.stopPropagation(); onSelect(m, isV2V); onClose(); }}+ className={`w-10 h-10 ${getIconColor(m, isV2V)} border border-white/5 rounded-xl flex items-center justify-center font-black text-sm shadow-inner uppercase`}>- <div className="flex items-center gap-3.5">- <div className={`w-10 h-10 ${getIconColor(m, isV2V)} border border-white/5 rounded-xl flex items-center justify-center font-black text-sm shadow-inner uppercase`}>- {m.name.charAt(0)}- </div>- <div className="flex flex-col gap-0.5">- <span className="text-xs font-bold text-white tracking-tight">{m.name}</span>- {isV2V && <span className="text-[9px] text-orange-400/70">Upload a video to use</span>}- </div>- </div>- {selectedModel === m.id && <CheckSvg />}+ {m.name.charAt(0)}</div>- );-- return (- <div className="flex flex-col h-full max-h-[70vh]">- <div className="px-2 pb-3 mb-2 border-b border-white/5 shrink-0">- <div className="flex items-center gap-3 bg-white/5 rounded-xl px-4 py-2.5 border border-white/5 focus-within:border-primary/50 transition-colors">- <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" className="text-muted">- <circle cx="11" cy="11" r="8" />- <path d="M21 21l-4.35-4.35" />- </svg>- <input- type="text"- placeholder="Search models..."- value={search}- onChange={e => setSearch(e.target.value)}- onClick={e => e.stopPropagation()}- className="bg-transparent border-none text-xs text-white focus:ring-0 w-full p-0 outline-none"- />- </div>- </div>- <div className="text-[10px] font-bold text-secondary uppercase tracking-widest px-3 py-2 shrink-0">- Video models- </div>- <div className="flex flex-col gap-1.5 overflow-y-auto custom-scrollbar pr-1 pb-2">- {filteredMain.map(m => renderItem(m, false))}- {filteredV2V.length > 0 && (- <>- <div className="text-[10px] font-bold text-orange-400/70 uppercase tracking-widest px-3 py-2 mt-1 border-t border-white/5">- Video Tools- </div>- {filteredV2V.map(m => renderItem(m, true))}- </>- )}- </div>+ <div className="flex flex-col gap-0.5">+ <span className="text-xs font-bold text-white tracking-tight">+ {m.name}+ </span>+ {isV2V && (+ <span className="text-[9px] text-orange-400/70">+ Upload a video to use+ </span>+ )}</div>- );+ </div>+ {selectedModel === m.id && <CheckSvg />}+ </div>+ );++ return (+ <div className="flex flex-col h-full max-h-[70vh]">+ <div className="px-2 pb-3 mb-2 border-b border-white/5 shrink-0">+ <div className="flex items-center gap-3 bg-white/5 rounded-xl px-4 py-2.5 border border-white/5 focus-within:border-primary/50 transition-colors">+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="3"+ className="text-muted"+ >+ <circle cx="11" cy="11" r="8" />+ <path d="M21 21l-4.35-4.35" />+ </svg>+ <input+ type="text"+ placeholder="Search models..."+ value={search}+ onChange={(e) => setSearch(e.target.value)}+ onClick={(e) => e.stopPropagation()}+ className="bg-transparent border-none text-xs text-white focus:ring-0 w-full p-0 outline-none"+ />+ </div>+ </div>+ <div className="text-xs font-bold text-secondary px-3 py-2 shrink-0">+ Video models+ </div>+ <div className="flex flex-col gap-1.5 overflow-y-auto custom-scrollbar pr-1 pb-2">+ {filteredMain.map((m) => renderItem(m, false))}+ {filteredV2V.length > 0 && (+ <>+ <div className="text-xs font-bold text-orange-400/70 px-3 py-2 mt-1 border-t border-white/5">+ Video Tools+ </div>+ {filteredV2V.map((m) => renderItem(m, true))}+ </>+ )}+ </div>+ </div>+ );}// ── Control button ────────────────────────────────────────────────────────────function ControlBtn({ icon, label, onClick, style }) {- return (- <button- type="button"- onClick={onClick}- style={style}- className="flex items-center gap-1.5 md:gap-2.5 px-3 md:px-4 py-2 md:py-2.5 bg-white/5 hover:bg-white/10 rounded-xl md:rounded-2xl transition-all border border-white/5 group whitespace-nowrap"- >- {icon}- <span className="text-xs font-bold text-white group-hover:text-primary transition-colors">{label}</span>- <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="4" className="opacity-20 group-hover:opacity-100 transition-opacity">- <path d="M6 9l6 6 6-6" />- </svg>- </button>- );+ return (+ <button+ type="button"+ onClick={onClick}+ style={style}+ className="flex items-center gap-1.5 md:gap-2.5 px-3 md:px-4 py-2 md:py-2.5 bg-white/5 hover:bg-white/10 rounded-xl md:rounded-2xl transition-all border border-white/5 group whitespace-nowrap"+ >+ {icon}+ <span className="text-xs font-bold text-white group-hover:text-primary transition-colors">+ {label}+ </span>+ <svg+ width="10"+ height="10"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="4"+ className="opacity-20 group-hover:opacity-100 transition-opacity"+ >+ <path d="M6 9l6 6 6-6" />+ </svg>+ </button>+ );}// ── Dropdown panel ─────────────────────────────────────────────────────────────// Rendered inside a `relative` wrapper div; floats above the anchor button.-// ── Main component ────────────────────────────────────────────────────────────-export default function VideoStudio({ apiKey, onGenerationComplete, historyItems }) {- // ── mode state ──- const [imageMode, setImageMode] = useState(false); // i2v- const [v2vMode, setV2vMode] = useState(false);-- // ── model / params ──- const defaultModel = t2vModels[0];- const [selectedModel, setSelectedModel] = useState(defaultModel.id);- const [selectedModelName, setSelectedModelName] = useState(defaultModel.name);- const [selectedAr, setSelectedAr] = useState(defaultModel.inputs?.aspect_ratio?.default || '16:9');- const [selectedDuration, setSelectedDuration] = useState(defaultModel.inputs?.duration?.default || 5);- const [selectedResolution, setSelectedResolution] = useState(defaultModel.inputs?.resolution?.default || '');- const [selectedQuality, setSelectedQuality] = useState(defaultModel.inputs?.quality?.default || '');- const [selectedMode, setSelectedMode] = useState('');-- // ── upload progress ──- const [imageProgress, setImageProgress] = useState(0);- const [videoProgress, setVideoProgress] = useState(0);-- // ── control visibility ──- const [showAr, setShowAr] = useState(true);- const [showDuration, setShowDuration] = useState(true);- const [showResolution, setShowResolution] = useState(false);- const [showQuality, setShowQuality] = useState(false);- const [showMode, setShowMode] = useState(false);-- // ── uploads ──- const [uploadedImageUrl, setUploadedImageUrl] = useState(null);- const [imageUploading, setImageUploading] = useState(false);- const [uploadedVideoUrl, setUploadedVideoUrl] = useState(null);- const [videoUploading, setVideoUploading] = useState(false);- const [uploadedVideoName, setUploadedVideoName] = useState(null);-- // ── generation / canvas ──- const [generating, setGenerating] = useState(false);- const [generateError, setGenerateError] = useState(null);- const [canvasUrl, setCanvasUrl] = useState(null);- const [canvasModel, setCanvasModel] = useState(null);- const [showCanvas, setShowCanvas] = useState(false);- const [lastGenerationId, setLastGenerationId] = useState(null);- const [lastGenerationModel, setLastGenerationModel] = useState(null);-- // ── history ──- const [localHistory, setLocalHistory] = useState([]);- const [activeHistoryIdx, setActiveHistoryIdx] = useState(0);-- // ── dropdown ──- const [openDropdown, setOpenDropdown] = useState(null); // 'model'|'ar'|'duration'|'resolution'|'quality'|'mode'|null-- // ── prompt ──- const [prompt, setPrompt] = useState('');- const [promptDisabled, setPromptDisabled] = useState(false);-- // ── refs ──- const containerRef = useRef(null);- const textareaRef = useRef(null);- const dropdownRef = useRef(null);- const imageFileInputRef = useRef(null);- const videoFileInputRef = useRef(null);- const resultVideoRef = useRef(null);-- // ── derived data ──- const history = historyItems ?? localHistory;-- const getCurrentModels = useCallback(() => {- if (v2vMode) return v2vModels;- return imageMode ? i2vModels : t2vModels;- }, [imageMode, v2vMode]);-- const getCurrentAspectRatios = useCallback((id) =>- imageMode ? getAspectRatiosForI2VModel(id) : getAspectRatiosForVideoModel(id),- [imageMode]);-- const getCurrentDurations = useCallback((id) =>- imageMode ? getDurationsForI2VModel(id) : getDurationsForModel(id),- [imageMode]);-- const getCurrentResolutions = useCallback((id) =>- imageMode ? getResolutionsForI2VModel(id) : getResolutionsForVideoModel(id),- [imageMode]);-- const getCurrentModel = useCallback(() =>- getCurrentModels().find(m => m.id === selectedModel),- [getCurrentModels, selectedModel]);-- // ── update controls when model/mode changes ──────────────────────────────- const applyControlsForModel = useCallback((modelId, isImageMode, isV2vMode) => {- if (isV2vMode) {- setShowAr(false); setShowDuration(false); setShowResolution(false);- setShowQuality(false); setShowMode(false);- return;- }-- const modelList = isImageMode ? i2vModels : t2vModels;- const model = modelList.find(m => m.id === modelId);-- const ars = isImageMode ? getAspectRatiosForI2VModel(modelId) : getAspectRatiosForVideoModel(modelId);- if (ars.length > 0) { setSelectedAr(ars[0]); setShowAr(true); } else { setShowAr(false); }-- const durations = isImageMode ? getDurationsForI2VModel(modelId) : getDurationsForModel(modelId);- if (durations.length > 0) { setSelectedDuration(durations[0]); setShowDuration(true); } else { setShowDuration(false); }-- const resolutions = isImageMode ? getResolutionsForI2VModel(modelId) : getResolutionsForVideoModel(modelId);- if (resolutions.length > 0) { setSelectedResolution(resolutions[0]); setShowResolution(true); } else { setShowResolution(false); }-- const qualities = getQualitiesForModel(modelList, modelId);- if (qualities.length > 0) {- setSelectedQuality(model?.inputs?.quality?.default || qualities[0]);- setShowQuality(true);- } else { setSelectedQuality(''); setShowQuality(false); }-- const modes = getModesForModel(modelId);- if (modes.length > 0) {- setSelectedMode(model?.inputs?.mode?.default || modes[0]);- setShowMode(true);- } else { setSelectedMode(''); setShowMode(false); }- }, []);-- // Initialise controls for default model on mount- useEffect(() => {- applyControlsForModel(defaultModel.id, false, false);- // eslint-disable-next-line react-hooks/exhaustive-deps- }, []);-- // ── close dropdown on outside click ─────────────────────────────────────- useEffect(() => {- if (!openDropdown) return;- const handler = (e) => {- if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {- setOpenDropdown(null);- }+export default function VideoStudio({+ apiKey,+ onGenerationComplete,+ historyItems,+}) {+ const PERSIST_KEY = "hg_video_studio_persistent";++ // ── mode state ──+ const [imageMode, setImageMode] = useState(false); // i2v+ const [v2vMode, setV2vMode] = useState(false);++ // ── model / params ──+ const defaultModel = t2vModels[0];+ const [selectedModel, setSelectedModel] = useState(defaultModel.id);+ const [selectedModelName, setSelectedModelName] = useState(defaultModel.name);+ const [selectedAr, setSelectedAr] = useState(+ defaultModel.inputs?.aspect_ratio?.default || "16:9",+ );+ const [selectedDuration, setSelectedDuration] = useState(+ defaultModel.inputs?.duration?.default || 5,+ );+ const [selectedResolution, setSelectedResolution] = useState(+ defaultModel.inputs?.resolution?.default || "",+ );+ const [selectedQuality, setSelectedQuality] = useState(+ defaultModel.inputs?.quality?.default || "",+ );+ const [selectedMode, setSelectedMode] = useState("");++ // ── upload progress ──+ const [imageProgress, setImageProgress] = useState(0);+ const [videoProgress, setVideoProgress] = useState(0);++ // ── control visibility ──+ const [showAr, setShowAr] = useState(true);+ const [showDuration, setShowDuration] = useState(true);+ const [showResolution, setShowResolution] = useState(false);+ const [showQuality, setShowQuality] = useState(false);+ const [showMode, setShowMode] = useState(false);++ // ── uploads ──+ const [uploadedImageUrl, setUploadedImageUrl] = useState(null);+ const [imageUploading, setImageUploading] = useState(false);+ const [uploadedVideoUrl, setUploadedVideoUrl] = useState(null);+ const [videoUploading, setVideoUploading] = useState(false);+ const [uploadedVideoName, setUploadedVideoName] = useState(null);++ // ── generation / canvas ──+ const [generating, setGenerating] = useState(false);+ const [generateError, setGenerateError] = useState(null);+ const [fullscreenUrl, setFullscreenUrl] = useState(null);+ const [canvasUrl, setCanvasUrl] = useState(null);+ const [canvasModel, setCanvasModel] = useState(null);+ const [showCanvas, setShowCanvas] = useState(false);+ const [lastGenerationId, setLastGenerationId] = useState(null);+ const [lastGenerationModel, setLastGenerationModel] = useState(null);++ // ── history ──+ const [localHistory, setLocalHistory] = useState([]);+ const [activeHistoryIdx, setActiveHistoryIdx] = useState(0);++ // ── dropdown ──+ const [openDropdown, setOpenDropdown] = useState(null); // 'model'|'ar'|'duration'|'resolution'|'quality'|'mode'|null++ // ── prompt ──+ const [prompt, setPrompt] = useState("");+ const [promptDisabled, setPromptDisabled] = useState(false);++ // ── refs ──+ const containerRef = useRef(null);+ const textareaRef = useRef(null);+ const dropdownRef = useRef(null);+ const imageFileInputRef = useRef(null);+ const videoFileInputRef = useRef(null);+ const resultVideoRef = useRef(null);+ const hasRestored = useRef(false);++ // ── derived data ──+ const history = historyItems ?? localHistory;++ const getCurrentModels = useCallback(() => {+ if (v2vMode) return v2vModels;+ return imageMode ? i2vModels : t2vModels;+ }, [imageMode, v2vMode]);++ const getCurrentAspectRatios = useCallback(+ (id) =>+ imageMode+ ? getAspectRatiosForI2VModel(id)+ : getAspectRatiosForVideoModel(id),+ [imageMode],+ );++ const getCurrentDurations = useCallback(+ (id) =>+ imageMode ? getDurationsForI2VModel(id) : getDurationsForModel(id),+ [imageMode],+ );++ const getCurrentResolutions = useCallback(+ (id) =>+ imageMode+ ? getResolutionsForI2VModel(id)+ : getResolutionsForVideoModel(id),+ [imageMode],+ );++ const getCurrentModel = useCallback(+ () => getCurrentModels().find((m) => m.id === selectedModel),+ [getCurrentModels, selectedModel],+ );++ // ── update controls when model/mode changes ──────────────────────────────+ const applyControlsForModel = useCallback(+ (modelId, isImageMode, isV2vMode) => {+ if (isV2vMode) {+ setShowAr(false);+ setShowDuration(false);+ setShowResolution(false);+ setShowQuality(false);+ setShowMode(false);+ return;+ }++ const modelList = isImageMode ? i2vModels : t2vModels;+ const model = modelList.find((m) => m.id === modelId);++ const ars = isImageMode+ ? getAspectRatiosForI2VModel(modelId)+ : getAspectRatiosForVideoModel(modelId);+ if (ars.length > 0) {+ setSelectedAr(ars[0]);+ setShowAr(true);+ } else {+ setShowAr(false);+ }++ const durations = isImageMode+ ? getDurationsForI2VModel(modelId)+ : getDurationsForModel(modelId);+ if (durations.length > 0) {+ setSelectedDuration(durations[0]);+ setShowDuration(true);+ } else {+ setShowDuration(false);+ }++ const resolutions = isImageMode+ ? getResolutionsForI2VModel(modelId)+ : getResolutionsForVideoModel(modelId);+ if (resolutions.length > 0) {+ setSelectedResolution(resolutions[0]);+ setShowResolution(true);+ } else {+ setShowResolution(false);+ }++ const qualities = getQualitiesForModel(modelList, modelId);+ if (qualities.length > 0) {+ setSelectedQuality(model?.inputs?.quality?.default || qualities[0]);+ setShowQuality(true);+ } else {+ setSelectedQuality("");+ setShowQuality(false);+ }++ const modes = getModesForModel(modelId);+ if (modes.length > 0) {+ setSelectedMode(model?.inputs?.mode?.default || modes[0]);+ setShowMode(true);+ } else {+ setSelectedMode("");+ setShowMode(false);+ }+ },+ [],+ );++ // ── Persistence: Load ────────────────────────────────────────────────────+ useEffect(() => {+ try {+ const stored = localStorage.getItem(PERSIST_KEY);+ if (stored) {+ const data = JSON.parse(stored);+ if (data.imageMode !== undefined) setImageMode(data.imageMode);+ if (data.v2vMode !== undefined) setV2vMode(data.v2vMode);+ if (data.selectedModel) setSelectedModel(data.selectedModel);+ if (data.selectedModelName) setSelectedModelName(data.selectedModelName);+ if (data.selectedAr) setSelectedAr(data.selectedAr);+ if (data.selectedDuration) setSelectedDuration(data.selectedDuration);+ if (data.selectedResolution) setSelectedResolution(data.selectedResolution);+ if (data.selectedQuality) setSelectedQuality(data.selectedQuality);+ if (data.selectedMode) setSelectedMode(data.selectedMode);+ if (data.uploadedImageUrl) setUploadedImageUrl(data.uploadedImageUrl);+ if (data.uploadedVideoUrl) setUploadedVideoUrl(data.uploadedVideoUrl);+ if (data.uploadedVideoName) setUploadedVideoName(data.uploadedVideoName);+ if (data.prompt) setPrompt(data.prompt);+ if (data.localHistory) setLocalHistory(data.localHistory);++ // Update control visibility based on restored model/mode+ applyControlsForModel(+ data.selectedModel || defaultModel.id,+ !!data.imageMode,+ !!data.v2vMode+ );+ }+ } catch (err) {+ console.warn("Failed to load VideoStudio persistence:", err);+ } finally {+ hasRestored.current = true;+ }+ }, [applyControlsForModel, defaultModel.id]);++ // ── Persistence: Save ────────────────────────────────────────────────────+ useEffect(() => {+ const timer = setTimeout(() => {+ try {+ const state = {+ imageMode,+ v2vMode,+ selectedModel,+ selectedModelName,+ selectedAr,+ selectedDuration,+ selectedResolution,+ selectedQuality,+ selectedMode,+ uploadedImageUrl,+ uploadedVideoUrl,+ uploadedVideoName,+ prompt,+ localHistory,};- window.addEventListener('click', handler);- return () => window.removeEventListener('click', handler);- }, [openDropdown]);-- // ── textarea auto-resize ──────────────────────────────────────────────────- const handlePromptInput = (e) => {- setPrompt(e.target.value);- const el = e.target;- el.style.height = 'auto';- const maxH = window.innerWidth < 768 ? 150 : 250;- el.style.height = Math.min(el.scrollHeight, maxH) + 'px';- };-- // ── image upload ─────────────────────────────────────────────────────────- const handleImageFileChange = async (e) => {- const file = e.target.files[0];- if (!file) return;- if (file.size > 10 * 1024 * 1024) {- alert("Image exceeds 10MB limit.");- return;- }- setImageUploading(true);- setImageProgress(0);-- try {- const url = await uploadFile(apiKey, file, (pct) => {- setImageProgress(pct);- });- setUploadedImageUrl(url);-- // Clear v2v if active- setUploadedVideoUrl(null);- setUploadedVideoName(null);- setV2vMode(false);-- if (!imageMode) {- const firstI2V = i2vModels[0];- setImageMode(true);- setSelectedModel(firstI2V.id);- setSelectedModelName(firstI2V.name);- applyControlsForModel(firstI2V.id, true, false);- }- setPromptDisabled(false);- } catch (err) {- console.error('[VideoStudio] Image upload failed:', err);- alert(`Image upload failed: ${err.message}`);- } finally {- setImageUploading(false);- setImageProgress(0);- if (imageFileInputRef.current) imageFileInputRef.current.value = '';- }+ localStorage.setItem(PERSIST_KEY, JSON.stringify(state));+ } catch (err) {+ console.warn("Failed to save VideoStudio persistence:", err);+ }+ }, 500); // 500ms debounce+ return () => clearTimeout(timer);+ }, [+ imageMode,+ v2vMode,+ selectedModel,+ selectedModelName,+ selectedAr,+ selectedDuration,+ selectedResolution,+ selectedQuality,+ selectedMode,+ uploadedImageUrl,+ uploadedVideoUrl,+ uploadedVideoName,+ prompt,+ localHistory,+ ]);++ // Initialise controls for default model on mount+ useEffect(() => {+ if (hasRestored.current) return;+ applyControlsForModel(defaultModel.id, false, false);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ // ── close dropdown on outside click ─────────────────────────────────────+ useEffect(() => {+ if (!openDropdown) return;+ const handler = (e) => {+ if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {+ setOpenDropdown(null);+ }};+ window.addEventListener("click", handler);+ return () => window.removeEventListener("click", handler);+ }, [openDropdown]);++ // ── textarea auto-resize ──────────────────────────────────────────────────+ const handlePromptInput = (e) => {+ setPrompt(e.target.value);+ const el = e.target;+ el.style.height = "auto";+ const maxH = window.innerWidth < 768 ? 150 : 250;+ el.style.height = Math.min(el.scrollHeight, maxH) + "px";+ };++ // ── image upload ─────────────────────────────────────────────────────────+ const handleImageFileChange = async (e) => {+ const file = e.target.files[0];+ if (!file) return;+ if (file.size > 10 * 1024 * 1024) {+ alert("Image exceeds 10MB limit.");+ return;+ }+ setImageUploading(true);+ setImageProgress(0);- const clearImageUpload = () => {+ try {+ const url = await uploadFile(apiKey, file, (pct) => {+ setImageProgress(pct);+ });+ setUploadedImageUrl(url);++ // Clear v2v if active+ setUploadedVideoUrl(null);+ setUploadedVideoName(null);+ setV2vMode(false);++ if (!imageMode) {+ const firstI2V = i2vModels[0];+ setImageMode(true);+ setSelectedModel(firstI2V.id);+ setSelectedModelName(firstI2V.name);+ applyControlsForModel(firstI2V.id, true, false);+ }+ setPromptDisabled(false);+ } catch (err) {+ console.error("[VideoStudio] Image upload failed:", err);+ alert(`Image upload failed: ${err.message}`);+ } finally {+ setImageUploading(false);+ setImageProgress(0);+ if (imageFileInputRef.current) imageFileInputRef.current.value = "";+ }+ };++ const clearImageUpload = () => {+ setUploadedImageUrl(null);+ setImageMode(false);+ const first = t2vModels[0];+ setSelectedModel(first.id);+ setSelectedModelName(first.name);+ applyControlsForModel(first.id, false, false);+ setPromptDisabled(false);+ };++ // ── video upload ─────────────────────────────────────────────────────────+ const handleVideoFileChange = async (e) => {+ const file = e.target.files[0];+ if (!file) return;+ if (file.size > 50 * 1024 * 1024) {+ alert("Video exceeds 50MB limit.");+ return;+ }+ setVideoUploading(true);+ setVideoProgress(0);+ try {+ const url = await uploadFile(apiKey, file, (pct) => {+ setVideoProgress(pct);+ });+ setUploadedVideoUrl(url);+ setUploadedVideoName(file.name);++ // Clear image mode if active+ if (imageMode) {setUploadedImageUrl(null);setImageMode(false);- const first = t2vModels[0];- setSelectedModel(first.id);- setSelectedModelName(first.name);- applyControlsForModel(first.id, false, false);- setPromptDisabled(false);- };-- // ── video upload ─────────────────────────────────────────────────────────- const handleVideoFileChange = async (e) => {- const file = e.target.files[0];- if (!file) return;- if (file.size > 50 * 1024 * 1024) {- alert("Video exceeds 50MB limit.");- return;- }- setVideoUploading(true);- setVideoProgress(0);- try {- const url = await uploadFile(apiKey, file, (pct) => {- setVideoProgress(pct);- });- setUploadedVideoUrl(url);- setUploadedVideoName(file.name);-- // Clear image mode if active- if (imageMode) {- setUploadedImageUrl(null);- setImageMode(false);- }- setV2vMode(true);- const firstV2V = v2vModels[0];- setSelectedModel(firstV2V.id);- setSelectedModelName(firstV2V.name);- applyControlsForModel(firstV2V.id, false, true);- setPrompt('');- setPromptDisabled(true);- } catch (err) {- console.error('[VideoStudio] Video upload failed:', err);- alert(`Video upload failed: ${err.message}`);- } finally {- setVideoUploading(false);- setVideoProgress(0);- if (videoFileInputRef.current) videoFileInputRef.current.value = '';+ }+ setV2vMode(true);+ const firstV2V = v2vModels[0];+ setSelectedModel(firstV2V.id);+ setSelectedModelName(firstV2V.name);+ applyControlsForModel(firstV2V.id, false, true);+ setPrompt("");+ setPromptDisabled(true);+ } catch (err) {+ console.error("[VideoStudio] Video upload failed:", err);+ alert(`Video upload failed: ${err.message}`);+ } finally {+ setVideoUploading(false);+ setVideoProgress(0);+ if (videoFileInputRef.current) videoFileInputRef.current.value = "";+ }+ };++ const clearVideoUpload = () => {+ setUploadedVideoUrl(null);+ setUploadedVideoName(null);+ setV2vMode(false);+ const first = t2vModels[0];+ setSelectedModel(first.id);+ setSelectedModelName(first.name);+ applyControlsForModel(first.id, false, false);+ setPromptDisabled(false);+ };++ // ── model selection from dropdown ─────────────────────────────────────────+ const handleModelSelect = useCallback(+ (m, isV2V) => {+ if (isV2V) {+ setV2vMode(true);+ setImageMode(false);+ setUploadedImageUrl(null);+ setUploadedImagePreview(null);+ setSelectedModel(m.id);+ setSelectedModelName(m.name);+ applyControlsForModel(m.id, false, true);+ setPrompt("");+ setPromptDisabled(true);+ } else {+ if (v2vMode) {+ setV2vMode(false);+ setUploadedVideoUrl(null);+ setUploadedVideoName(null);+ setPromptDisabled(false);}- };+ setSelectedModel(m.id);+ setSelectedModelName(m.name);+ applyControlsForModel(m.id, imageMode, false);+ }+ },+ [v2vMode, imageMode, applyControlsForModel],+ );++ // ── add to local history ──────────────────────────────────────────────────+ const addToLocalHistory = useCallback((entry) => {+ setLocalHistory((prev) => [entry, ...prev].slice(0, 30));+ setActiveHistoryIdx(0);+ }, []);++ // ── show result in canvas ─────────────────────────────────────────────────+ const showVideoInCanvas = useCallback((url, model) => {+ setCanvasUrl(url);+ setCanvasModel(model);+ setShowCanvas(true);+ }, []);++ // ── generate ──────────────────────────────────────────────────────────────+ const handleGenerate = useCallback(async () => {+ const currentModel = getCurrentModel();+ const isExtendMode = currentModel?.requiresRequestId;+ const trimmedPrompt = prompt.trim();++ if (v2vMode) {+ if (!uploadedVideoUrl) {+ alert("Please upload a video first.");+ return;+ }+ } else if (isExtendMode) {+ if (!lastGenerationId) {+ alert(+ "No Seedance 2.0 generation found to extend. Generate a video first.",+ );+ return;+ }+ } else if (imageMode) {+ if (!uploadedImageUrl) {+ alert("Please upload a start frame image first.");+ return;+ }+ } else {+ if (!trimmedPrompt) {+ alert("Please enter a prompt to generate a video.");+ return;+ }+ }- const clearVideoUpload = () => {- setUploadedVideoUrl(null);- setUploadedVideoName(null);- setV2vMode(false);- const first = t2vModels[0];- setSelectedModel(first.id);- setSelectedModelName(first.name);- applyControlsForModel(first.id, false, false);- setPromptDisabled(false);- };+ setGenerating(true);+ setGenerateError(null);++ let hadError = false;- // ── model selection from dropdown ─────────────────────────────────────────- const handleModelSelect = useCallback((m, isV2V) => {- if (isV2V) {- setV2vMode(true);- setImageMode(false);- setUploadedImageUrl(null);- setUploadedImagePreview(null);- setSelectedModel(m.id);- setSelectedModelName(m.name);- applyControlsForModel(m.id, false, true);- setPrompt('');- setPromptDisabled(true);+ try {+ let res;++ if (v2vMode) {+ // V2V: use generateVideo with video_url (the v2v models use the video endpoint)+ res = await generateVideo(apiKey, {+ model: selectedModel,+ video_url: uploadedVideoUrl,+ });+ if (!res?.url) throw new Error("No video URL returned by API");++ const genId = res.id || Date.now().toString();+ setLastGenerationId(null);+ setLastGenerationModel(null);+ const entry = {+ id: genId,+ url: res.url,+ prompt: "",+ model: selectedModel,+ timestamp: new Date().toISOString(),+ };+ addToLocalHistory(entry);+ showVideoInCanvas(res.url, selectedModel);+ if (onGenerationComplete)+ onGenerationComplete({+ url: res.url,+ model: selectedModel,+ prompt: "",+ type: "video",+ });+ } else if (imageMode) {+ const i2vParams = { model: selectedModel, image_url: uploadedImageUrl };+ if (trimmedPrompt) i2vParams.prompt = trimmedPrompt;+ i2vParams.aspect_ratio = selectedAr;+ const durations = getDurationsForI2VModel(selectedModel);+ if (durations.length > 0) i2vParams.duration = selectedDuration;+ const resolutions = getResolutionsForI2VModel(selectedModel);+ if (resolutions.length > 0) i2vParams.resolution = selectedResolution;+ if (selectedQuality) i2vParams.quality = selectedQuality;+ if (selectedMode) i2vParams.mode = selectedMode;++ res = await generateI2V(apiKey, i2vParams);+ if (!res?.url) throw new Error("No video URL returned by API");++ const genId = res.id || Date.now().toString();+ if (selectedModel === "seedance-v2.0-i2v") {+ setLastGenerationId(genId);+ setLastGenerationModel(selectedModel);} else {- if (v2vMode) {- setV2vMode(false);- setUploadedVideoUrl(null);- setUploadedVideoName(null);- setPromptDisabled(false);- }- setSelectedModel(m.id);- setSelectedModelName(m.name);- applyControlsForModel(m.id, imageMode, false);+ setLastGenerationId(null);+ setLastGenerationModel(null);}- }, [v2vMode, imageMode, applyControlsForModel]);-- // ── add to local history ──────────────────────────────────────────────────- const addToLocalHistory = useCallback((entry) => {- setLocalHistory(prev => [entry, ...prev].slice(0, 30));- setActiveHistoryIdx(0);- }, []);-- // ── show result in canvas ─────────────────────────────────────────────────- const showVideoInCanvas = useCallback((url, model) => {- setCanvasUrl(url);- setCanvasModel(model);- setShowCanvas(true);- }, []);-- // ── generate ──────────────────────────────────────────────────────────────- const handleGenerate = useCallback(async () => {- const currentModel = getCurrentModel();- const isExtendMode = currentModel?.requiresRequestId;- const trimmedPrompt = prompt.trim();-- if (v2vMode) {- if (!uploadedVideoUrl) { alert('Please upload a video first.'); return; }- } else if (isExtendMode) {- if (!lastGenerationId) { alert('No Seedance 2.0 generation found to extend. Generate a video first.'); return; }- } else if (imageMode) {- if (!uploadedImageUrl) { alert('Please upload a start frame image first.'); return; }+ const entry = {+ id: genId,+ url: res.url,+ prompt: trimmedPrompt,+ model: selectedModel,+ aspect_ratio: selectedAr,+ duration: selectedDuration,+ timestamp: new Date().toISOString(),+ };+ addToLocalHistory(entry);+ showVideoInCanvas(res.url, selectedModel);+ if (onGenerationComplete)+ onGenerationComplete({+ url: res.url,+ model: selectedModel,+ prompt: trimmedPrompt,+ type: "video",+ });+ } else {+ // T2V (including extend mode)+ const params = { model: selectedModel };+ if (trimmedPrompt) params.prompt = trimmedPrompt;++ if (isExtendMode) {+ params.request_id = lastGenerationId;} else {- if (!trimmedPrompt) { alert('Please enter a prompt to generate a video.'); return; }+ params.aspect_ratio = selectedAr;}- setGenerating(true);- setGenerateError(null);-- let hadError = false;-- try {- let res;-- if (v2vMode) {- // V2V: use generateVideo with video_url (the v2v models use the video endpoint)- res = await generateVideo(apiKey, {- model: selectedModel,- video_url: uploadedVideoUrl,- });- if (!res?.url) throw new Error('No video URL returned by API');-- const genId = res.id || Date.now().toString();- setLastGenerationId(null);- setLastGenerationModel(null);- const entry = { id: genId, url: res.url, prompt: '', model: selectedModel, timestamp: new Date().toISOString() };- addToLocalHistory(entry);- showVideoInCanvas(res.url, selectedModel);- if (onGenerationComplete) onGenerationComplete({ url: res.url, model: selectedModel, prompt: '', type: 'video' });-- } else if (imageMode) {- const i2vParams = { model: selectedModel, image_url: uploadedImageUrl };- if (trimmedPrompt) i2vParams.prompt = trimmedPrompt;- i2vParams.aspect_ratio = selectedAr;- const durations = getDurationsForI2VModel(selectedModel);- if (durations.length > 0) i2vParams.duration = selectedDuration;- const resolutions = getResolutionsForI2VModel(selectedModel);- if (resolutions.length > 0) i2vParams.resolution = selectedResolution;- if (selectedQuality) i2vParams.quality = selectedQuality;- if (selectedMode) i2vParams.mode = selectedMode;-- res = await generateI2V(apiKey, i2vParams);- if (!res?.url) throw new Error('No video URL returned by API');-- const genId = res.id || Date.now().toString();- if (selectedModel === 'seedance-v2.0-i2v') {- setLastGenerationId(genId);- setLastGenerationModel(selectedModel);- } else {- setLastGenerationId(null);- setLastGenerationModel(null);+ const durations = getDurationsForModel(selectedModel);+ if (durations.length > 0) params.duration = selectedDuration;+ const resolutions = getResolutionsForVideoModel(selectedModel);+ if (resolutions.length > 0) params.resolution = selectedResolution;+ if (selectedQuality) params.quality = selectedQuality;+ if (selectedMode) params.mode = selectedMode;++ res = await generateVideo(apiKey, params);+ if (!res?.url) throw new Error("No video URL returned by API");++ const genId = res.id || Date.now().toString();+ if (+ selectedModel === "seedance-v2.0-t2v" ||+ selectedModel === "seedance-v2.0-i2v"+ ) {+ setLastGenerationId(genId);+ setLastGenerationModel(selectedModel);+ } else {+ setLastGenerationId(null);+ setLastGenerationModel(null);+ }+ const entry = {+ id: genId,+ url: res.url,+ prompt: trimmedPrompt,+ model: selectedModel,+ aspect_ratio: selectedAr,+ duration: selectedDuration,+ timestamp: new Date().toISOString(),+ };+ addToLocalHistory(entry);+ showVideoInCanvas(res.url, selectedModel);+ if (onGenerationComplete)+ onGenerationComplete({+ url: res.url,+ model: selectedModel,+ prompt: trimmedPrompt,+ type: "video",+ });+ }+ } catch (e) {+ hadError = true;+ console.error("[VideoStudio]", e);+ setGenerateError(e.message?.slice(0, 80) || "Generation failed");+ setTimeout(() => setGenerateError(null), 4000);+ } finally {+ setGenerating(false);+ }+ }, [+ apiKey,+ prompt,+ v2vMode,+ imageMode,+ selectedModel,+ selectedAr,+ selectedDuration,+ selectedResolution,+ selectedQuality,+ selectedMode,+ uploadedImageUrl,+ uploadedVideoUrl,+ lastGenerationId,+ getCurrentModel,+ addToLocalHistory,+ showVideoInCanvas,+ onGenerationComplete,+ ]);++ // ── reset to prompt bar ───────────────────────────────────────────────────+ const resetToPromptBar = useCallback(() => {+ setShowCanvas(false);+ }, []);++ const handleNewPrompt = useCallback(() => {+ resetToPromptBar();+ setPrompt("");+ setUploadedImageUrl(null);+ setUploadedImagePreview(null);+ setImageMode(false);+ setUploadedVideoUrl(null);+ setUploadedVideoName(null);+ setV2vMode(false);+ const first = t2vModels[0];+ setSelectedModel(first.id);+ setSelectedModelName(first.name);+ applyControlsForModel(first.id, false, false);+ setPromptDisabled(false);+ setTimeout(() => textareaRef.current?.focus(), 50);+ }, [resetToPromptBar, applyControlsForModel]);++ const handleExtend = useCallback(() => {+ if (!lastGenerationId) return;+ resetToPromptBar();+ setPrompt("");+ setUploadedImageUrl(null);+ setUploadedImagePreview(null);+ setImageMode(false);+ setSelectedModel("seedance-v2.0-extend");+ setSelectedModelName("Seedance 2.0 Extend");+ applyControlsForModel("seedance-v2.0-extend", false, false);+ setPromptDisabled(false);+ setTimeout(() => textareaRef.current?.focus(), 50);+ }, [lastGenerationId, resetToPromptBar, applyControlsForModel]);++ // ── derived UI values ────────────────────────────────────────────────────+ const isSeedance2Canvas =+ canvasModel === "seedance-v2.0-t2v" || canvasModel === "seedance-v2.0-i2v";+ const currentModelObj = getCurrentModel();+ const isExtendMode = currentModelObj?.requiresRequestId;++ const promptPlaceholder = v2vMode+ ? "Video ready — click Generate to remove watermark"+ : imageMode+ ? "Describe the motion or effect (optional)"+ : isExtendMode+ ? "Optional: describe how to continue the video..."+ : "Describe the video you want to create";++ const toggleDropdown = (type) => (e) => {+ e.stopPropagation();+ setOpenDropdown((prev) => (prev === type ? null : type));+ };++ // ── render ────────────────────────────────────────────────────────────────+ return (+ <div+ ref={containerRef}+ className="w-full h-full flex flex-col items-center justify-center bg-app-bg relative overflow-hidden"+ >+ {/* ── CENTRAL GALLERY AREA ── */}+ <div className="flex-1 w-full max-w-7xl mx-auto overflow-y-auto custom-scrollbar pb-40 lg:pb-32 px-2">+ {history.length > 0 ? (+ <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 w-full pt-4 animate-fade-in-up">+ {history.map((entry, idx) => {+ const isSeedance2 = entry.model === "seedance-v2.0-t2v" || entry.model === "seedance-v2.0-i2v";+ return (+ <div+ key={entry.id || idx}+ className="relative group rounded-2xl overflow-hidden border border-white/10 bg-[#0a0a0a] shadow-xl hover:border-primary/50 transition-all duration-300 flex flex-col"+ >+ <video+ src={entry.url}+ className="w-full aspect-video object-cover bg-black/40 cursor-pointer hover:opacity-80 transition-opacity"+ onClick={() => setFullscreenUrl(entry.url)}+ controls={false}+ loop+ muted+ playsInline+ onMouseOver={(e) => e.target.play()}+ onMouseOut={(e) => {+ e.target.pause();+ e.target.currentTime = 0;+ }}+ />++ {/* Overlay actions */}+ <div className="absolute top-2 right-2 flex flex-col gap-2 opacity-0 group-hover:opacity-100 transition-opacity">+ <button+ type="button"+ title="Fullscreen"+ onClick={(e) => {+ e.stopPropagation();+ setFullscreenUrl(entry.url);+ }}+ className="p-2 bg-black/60 backdrop-blur-md rounded-full text-white hover:bg-primary hover:text-black transition-all border border-white/10"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <polyline points="15 3 21 3 21 9" />+ <polyline points="9 21 3 21 3 15" />+ <line x1="21" y1="3" x2="14" y2="10" />+ <line x1="3" y1="21" x2="10" y2="14" />+ </svg>+ </button>+ <button+ type="button"+ title="Download"+ onClick={(e) => {+ e.stopPropagation();+ downloadFile(entry.url, `video-${entry.id || idx}.mp4`);+ }}+ className="p-2 bg-black/60 backdrop-blur-md rounded-full text-white hover:bg-primary hover:text-black transition-all border border-white/10"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">+ <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" />+ </svg>+ </button>+ {isSeedance2 && (+ <button+ type="button"+ title="Extend this video using Seedance 2.0 Extend"+ onClick={(e) => {+ e.stopPropagation();+ setLastGenerationId(entry.id);+ handleExtend();+ }}+ className="p-2 bg-black/60 backdrop-blur-md rounded-full text-white hover:bg-primary hover:text-black transition-all border border-white/10"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <path d="M5 12h14M12 5l7 7-7 7" />+ </svg>+ </button>+ )}+ </div>++ {/* Prompt & Details */}+ <div className="p-3 bg-black/80 backdrop-blur-sm border-t border-white/5 flex-1 flex flex-col justify-between gap-2">+ <p className="text-white/70 text-xs line-clamp-3 leading-relaxed" title={entry.prompt}>+ {entry.prompt || "No prompt provided"}+ </p>+ <div className="flex items-center justify-between mt-1 flex-wrap gap-1">+ <span className="text-[10px] font-bold text-primary px-2 py-0.5 bg-primary/10 rounded border border-primary/20 whitespace-nowrap">+ {entry.model?.replace("-", " ")}+ </span>+ <div className="flex gap-2">+ {entry.resolution && (+ <span className="text-[10px] text-white/40">{entry.resolution}</span>+ )}+ {entry.duration && (+ <span className="text-[10px] text-white/40">{entry.duration}s</span>+ )}+ </div>+ </div>+ </div>+ </div>+ );+ })}+ </div>+ ) : (+ <div className="flex flex-col items-center justify-center h-full animate-fade-in-up transition-all duration-700 min-h-[50vh]">+ <div className="mb-12 relative group">+ <div className="absolute inset-0 bg-primary/10 blur-[120px] rounded-full opacity-30 group-hover:opacity-60 transition-opacity duration-1000" />+ <div className="relative w-24 h-24 md:w-32 md:h-32 bg-white/[0.02] rounded-[2rem] flex items-center justify-center border border-white/[0.05] overflow-hidden backdrop-blur-sm">+ <div className="w-16 h-16 bg-primary/5 rounded-2xl flex items-center justify-center border border-primary/10 relative z-10 transition-transform duration-500 group-hover:scale-110">+ <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="text-primary opacity-80">+ <polygon points="23 7 16 12 23 17 23 7" />+ <rect x="1" y="5" width="15" height="14" rx="2" ry="2" />+ </svg>+ </div>+ <div className="absolute top-4 right-4 text-[10px] text-primary/40 animate-pulse">✨</div>+ </div>+ </div>+ <h1 className="text-3xl sm:text-5xl md:text-6xl font-extrabold text-white tracking-tight mb-4 text-center px-4">+ <span className="text-white/40 font-medium">START CREATING WITH</span><br />+ <span className="text-white">VIDEO STUDIO</span>+ </h1>+ <p className="text-white/40 text-sm md:text-base font-medium tracking-wide text-center max-w-lg leading-relaxed">+ Animate images into stunning AI videos with motion effects+ </p>+ </div>+ )}+ </div>++ {/* ── BOTTOM PROMPT BAR ── */}+ <div className="absolute bottom-4 w-full max-w-[95%] lg:max-w-4xl z-40 animate-fade-in-up" style={{ animationDelay: "0.2s" }}>+ <div className="w-full bg-[#0a0a0a]/80 backdrop-blur-3xl rounded-md border border-white/10 p-4 flex flex-col gap-2 shadow-2xl">+ <div className="flex items-center gap-2 px-1">+ {/* Image upload button */}+ <div className="relative">+ <input+ ref={imageFileInputRef}+ type="file"+ accept="image/*"+ className="hidden"+ onChange={handleImageFileChange}+ />+ <button+ type="button"+ title={+ uploadedImageUrl+ ? "Clear image"+ : "Upload image for Image-to-Video"}- const entry = { id: genId, url: res.url, prompt: trimmedPrompt, model: selectedModel, aspect_ratio: selectedAr, duration: selectedDuration, timestamp: new Date().toISOString() };- addToLocalHistory(entry);- showVideoInCanvas(res.url, selectedModel);- if (onGenerationComplete) onGenerationComplete({ url: res.url, model: selectedModel, prompt: trimmedPrompt, type: 'video' });-- } else {- // T2V (including extend mode)- const params = { model: selectedModel };- if (trimmedPrompt) params.prompt = trimmedPrompt;-- if (isExtendMode) {- params.request_id = lastGenerationId;- } else {- params.aspect_ratio = selectedAr;+ onClick={() =>+ uploadedImageUrl+ ? clearImageUpload()+ : imageFileInputRef.current?.click()}+ className={`w-10 h-10 shrink-0 rounded-full border transition-all flex items-center justify-center relative overflow-hidden ${uploadedImageUrl ? "border-primary/60 bg-primary/5" : "bg-white/5 border-white/[0.03] hover:bg-white/10 hover:border-primary/40"} group`}+ >+ {imageUploading ? (+ <div className="absolute inset-0 flex flex-col items-center justify-center bg-black/60 z-10">+ <div className="w-4 h-4 rounded-full border border-primary/30 border-t-primary animate-spin mb-0.5" />+ <span className="text-[8px] font-black text-primary">+ {imageProgress}%+ </span>+ </div>+ ) : null}++ {uploadedImageUrl ? (+ <img+ src={uploadedImageUrl}+ alt=""+ className={`w-full h-full object-cover rounded-full ${imageUploading ? "opacity-40 blur-[2px]" : "opacity-100"}`}+ />+ ) : (+ !imageUploading && (+ <svg+ width="18"+ height="18"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ className="text-white/40 group-hover:text-primary transition-colors"+ >+ <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>+ )+ )}+ </button>+ </div>- const durations = getDurationsForModel(selectedModel);- if (durations.length > 0) params.duration = selectedDuration;- const resolutions = getResolutionsForVideoModel(selectedModel);- if (resolutions.length > 0) params.resolution = selectedResolution;- if (selectedQuality) params.quality = selectedQuality;- if (selectedMode) params.mode = selectedMode;-- res = await generateVideo(apiKey, params);- if (!res?.url) throw new Error('No video URL returned by API');-- const genId = res.id || Date.now().toString();- if (selectedModel === 'seedance-v2.0-t2v' || selectedModel === 'seedance-v2.0-i2v') {- setLastGenerationId(genId);- setLastGenerationModel(selectedModel);- } else {- setLastGenerationId(null);- setLastGenerationModel(null);+ {/* Video upload button */}+ <div className="relative">+ <input+ ref={videoFileInputRef}+ type="file"+ accept="video/*"+ className="hidden"+ onChange={handleVideoFileChange}+ />+ <button+ type="button"+ title={+ uploadedVideoUrl+ ? `${uploadedVideoName} — click to clear`+ : "Upload video to remove watermark"}- const entry = { id: genId, url: res.url, prompt: trimmedPrompt, model: selectedModel, aspect_ratio: selectedAr, duration: selectedDuration, timestamp: new Date().toISOString() };- addToLocalHistory(entry);- showVideoInCanvas(res.url, selectedModel);- if (onGenerationComplete) onGenerationComplete({ url: res.url, model: selectedModel, prompt: trimmedPrompt, type: 'video' });- }- } catch (e) {- hadError = true;- console.error('[VideoStudio]', e);- setGenerateError(e.message?.slice(0, 80) || 'Generation failed');- setTimeout(() => setGenerateError(null), 4000);- } finally {- setGenerating(false);- }- }, [- apiKey, prompt, v2vMode, imageMode, selectedModel, selectedAr, selectedDuration,- selectedResolution, selectedQuality, selectedMode, uploadedImageUrl, uploadedVideoUrl,- lastGenerationId, getCurrentModel, addToLocalHistory, showVideoInCanvas, onGenerationComplete,- ]);-- // ── reset to prompt bar ───────────────────────────────────────────────────- const resetToPromptBar = useCallback(() => {- setShowCanvas(false);- }, []);-- const handleNewPrompt = useCallback(() => {- resetToPromptBar();- setPrompt('');- setUploadedImageUrl(null);- setUploadedImagePreview(null);- setImageMode(false);- setUploadedVideoUrl(null);- setUploadedVideoName(null);- setV2vMode(false);- const first = t2vModels[0];- setSelectedModel(first.id);- setSelectedModelName(first.name);- applyControlsForModel(first.id, false, false);- setPromptDisabled(false);- setTimeout(() => textareaRef.current?.focus(), 50);- }, [resetToPromptBar, applyControlsForModel]);-- const handleExtend = useCallback(() => {- if (!lastGenerationId) return;- resetToPromptBar();- setPrompt('');- setUploadedImageUrl(null);- setUploadedImagePreview(null);- setImageMode(false);- setSelectedModel('seedance-v2.0-extend');- setSelectedModelName('Seedance 2.0 Extend');- applyControlsForModel('seedance-v2.0-extend', false, false);- setPromptDisabled(false);- setTimeout(() => textareaRef.current?.focus(), 50);- }, [lastGenerationId, resetToPromptBar, applyControlsForModel]);-- // ── derived UI values ────────────────────────────────────────────────────- const isSeedance2Canvas = canvasModel === 'seedance-v2.0-t2v' || canvasModel === 'seedance-v2.0-i2v';- const currentModelObj = getCurrentModel();- const isExtendMode = currentModelObj?.requiresRequestId;-- const promptPlaceholder = v2vMode- ? 'Video ready — click Generate to remove watermark'- : imageMode- ? 'Describe the motion or effect (optional)'- : isExtendMode- ? 'Optional: describe how to continue the video...'- : 'Describe the video you want to create';-- const toggleDropdown = (type) => (e) => {- e.stopPropagation();- setOpenDropdown(prev => prev === type ? null : type);- };+ onClick={() =>+ uploadedVideoUrl+ ? clearVideoUpload()+ : videoFileInputRef.current?.click()+ }+ className={`w-10 h-10 shrink-0 rounded-full border transition-all flex items-center justify-center relative overflow-hidden ${uploadedVideoUrl ? "border-primary/60 bg-white/5" : "bg-white/[0.03] border-white/[0.03] hover:bg-white/10 hover:border-primary/40"} group`}+ >+ {videoUploading ? (+ <div className="absolute inset-0 flex flex-col items-center justify-center bg-black/60 z-10">+ <div className="w-4 h-4 rounded-full border border-primary/30 border-t-primary animate-spin mb-0.5" />+ <span className="text-[8px] font-black text-primary">+ {videoProgress}%+ </span>+ </div>+ ) : uploadedVideoUrl ? (+ <video+ src={uploadedVideoUrl}+ className={`w-full h-full object-cover rounded-full ${videoUploading ? "opacity-40 blur-[2px]" : "opacity-100"}`}+ muted+ />+ ) : (+ <VideoIconSvg className="text-white/40 group-hover:text-primary transition-colors" />+ )}+ </button>+ </div>- // ── render ────────────────────────────────────────────────────────────────- return (- <div- ref={containerRef}- className="w-full h-full flex flex-col items-center justify-center bg-app-bg relative p-4 md:p-6 overflow-y-auto custom-scrollbar overflow-x-hidden"- >- {/* ── History Sidebar ── */}- {history.length > 0 && (- <div className="fixed right-0 top-0 h-full w-20 md:w-24 bg-black/60 backdrop-blur-xl border-l border-white/5 z-50 flex flex-col items-center py-4 gap-3 overflow-y-auto transition-all duration-500">- <div className="text-[9px] font-bold text-muted uppercase tracking-widest mb-2">History</div>- <div className="flex flex-col gap-2 w-full px-2">- {history.map((entry, idx) => (- <div- key={entry.id || idx}- className={`relative group/thumb cursor-pointer rounded-xl overflow-hidden border-2 transition-all duration-300 ${activeHistoryIdx === idx ? 'border-primary shadow-glow' : 'border-white/10 hover:border-white/30'}`}- onClick={(e) => {- if (e.target.closest('.hist-download')) {- downloadFile(entry.url, `video-${entry.id || idx}.mp4`);- return;- }- setActiveHistoryIdx(idx);- if (entry.model === 'seedance-v2.0-t2v' || entry.model === 'seedance-v2.0-i2v') {- setLastGenerationId(entry.id);- setLastGenerationModel(entry.model);- } else {- setLastGenerationId(null);- setLastGenerationModel(null);- }- showVideoInCanvas(entry.url, entry.model);- }}- >- <video src={entry.url} preload="metadata" muted className="w-full aspect-square object-cover" />- <div className="absolute inset-0 bg-black/60 opacity-0 group-hover/thumb:opacity-100 transition-opacity flex items-center justify-center gap-1">- <button className="hist-download p-1.5 bg-primary rounded-lg text-black hover:scale-110 transition-transform" title="Download">- <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3">- <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4M7 10l5 5 5-5M12 15V3" />- </svg>- </button>- </div>- </div>+ {/* Prompt textarea */}+ <div className="flex-1 flex flex-col gap-1">+ <textarea+ ref={textareaRef}+ value={prompt}+ onChange={handlePromptInput}+ placeholder={promptPlaceholder}+ disabled={promptDisabled}+ rows={1}+ className="w-full bg-transparent border-none text-white text-sm placeholder:text-white/10 focus:outline-none resize-none pt-1 leading-relaxed min-h-[40px] max-h-[150px] md:max-h-[250px] overflow-y-auto custom-scrollbar disabled:opacity-40"+ />+ </div>+ </div>++ {/* Extend banner */}+ {isExtendMode && (+ <div className="flex items-center gap-2 px-3 py-1.5 mx-3 bg-primary/5 border border-primary/10 rounded-lg text-[10px] text-primary/80 font-medium tracking-tight">+ <svg+ width="13"+ height="13"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2.5"+ >+ <path d="M5 12h14M12 5l7 7-7 7" />+ </svg>+ <span>Extending previous Seedance 2.0 generation</span>+ </div>+ )}++ {/* Bottom row: controls + generate */}+ <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 pt-2 border-t border-white/[0.03] relative">+ <div className="flex items-center gap-2 relative flex-wrap pb-1 md:pb-0">+ {/* Model btn */}+ <div className="relative">+ <button+ type="button"+ onClick={toggleDropdown("model")}+ className="flex items-center gap-2 px-3 py-2 bg-white/[0.03] hover:bg-white/[0.06] rounded-md transition-all border border-white/[0.03] group whitespace-nowrap"+ >+ <div className="w-4 h-4 bg-[#d9ff00] rounded flex items-center justify-center shadow-lg shadow-[#d9ff00]/10">+ <span className="text-[9px] font-bold text-black uppercase">+ V+ </span>+ </div>+ <span className="text-xs font-semibold text-white/70 group-hover:text-[#d9ff00] transition-colors">+ {selectedModelName}+ </span>+ <svg+ width="8"+ height="8"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="4"+ className="opacity-20 group-hover:opacity-100 transition-opacity"+ >+ <path d="M6 9l6 6 6-6" />+ </svg>+ </button>+ {openDropdown === "model" && (+ <div+ ref={dropdownRef}+ onClick={(e) => e.stopPropagation()}+ className="absolute bottom-[calc(100%+12px)] left-0 z-50 bg-[#0a0a0a] rounded-[1.5rem] p-3 shadow-2xl border border-white/[0.05] w-[calc(100vw-3rem)] max-w-xs"+ >+ <ModelDropdown+ imageMode={imageMode}+ selectedModel={selectedModel}+ onSelect={handleModelSelect}+ onClose={() => setOpenDropdown(null)}+ />+ </div>+ )}+ </div>++ {/* Aspect ratio btn */}+ {showAr && (+ <div className="relative">+ <button+ type="button"+ onClick={toggleDropdown("ar")}+ className="flex items-center gap-2 px-3 py-2 bg-white/[0.03] hover:bg-white/[0.06] rounded-md transition-all border border-white/[0.03] group whitespace-nowrap"+ >+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ className="opacity-40 text-white"+ >+ <rect+ x="3"+ y="3"+ width="18"+ height="18"+ rx="2"+ ry="2"+ />+ </svg>+ <span className="text-[11px] font-semibold text-white/70 group-hover:text-[#d9ff00] transition-colors">+ {selectedAr}+ </span>+ </button>+ {openDropdown === "ar" && (+ <div+ ref={dropdownRef}+ onClick={(e) => e.stopPropagation()}+ className="absolute bottom-[calc(100%+12px)] left-0 z-50 bg-[#0a0a0a] rounded-lg p-3 shadow-2xl border border-white/[0.05] max-h-80 overflow-y-auto custom-scrollbar min-w-[160px]"+ >+ <div className="text-xs font-bold text-white/20 border-b border-white/[0.03] mb-2">+ Aspect Ratio+ </div>+ <div className="flex flex-col gap-1">+ {getCurrentAspectRatios(selectedModel).map((r) => (+ <div+ key={r}+ className="flex items-center justify-between p-3 hover:bg-white/5 rounded cursor-pointer transition-all group/opt"+ onClick={(e) => {+ e.stopPropagation();+ setSelectedAr(r);+ setOpenDropdown(null);+ }}+ >+ <span className="text-[11px] font-semibold text-white/70 group-hover/opt:text-white transition-opacity">+ {r}+ </span>+ {selectedAr === r && <CheckSvg />}+ </div>))}+ </div></div>+ )}</div>- )}-- {/* ── Canvas / Result View ── */}- {showCanvas && (- <div className="absolute inset-0 flex flex-col items-center justify-center p-4 min-[800px]:p-16 z-10 transition-all duration-1000">- <div className="relative group">- <video- ref={resultVideoRef}- key={canvasUrl}- src={canvasUrl}- className="max-h-[60vh] max-w-[80vw] rounded-3xl shadow-3xl border border-white/10 interactive-glow object-contain"- controls- loop- autoPlay- muted- playsInline- />+ )}++ {/* Duration btn */}+ {showDuration && (+ <div className="relative">+ <button+ type="button"+ onClick={toggleDropdown("duration")}+ className="flex items-center gap-2 px-3 py-2 bg-white/[0.03] hover:bg-white/[0.06] rounded-md transition-all border border-white/[0.03] group whitespace-nowrap"+ >+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ className="opacity-40 text-white"+ >+ <circle cx="12" cy="12" r="10" />+ <polyline points="12 6 12 12 16 14" />+ </svg>+ <span className="text-xs font-semibold text-white/70 group-hover:text-[#d9ff00] transition-colors">+ {selectedDuration}s+ </span>+ </button>+ {openDropdown === "duration" && (+ <div+ ref={dropdownRef}+ onClick={(e) => e.stopPropagation()}+ className="absolute bottom-[calc(100%+12px)] left-0 z-50 bg-[#0a0a0a] rounded-md p-3 shadow-2xl border border-white/10 min-w-[140px]"+ >+ <div className="text-xs font-bold text-white/20 border-b border-white/[0.03] mb-2">+ Duration+ </div>+ <div className="flex flex-col gap-1">+ {getCurrentDurations(selectedModel).map((d) => (+ <div+ key={d}+ className="flex items-center justify-between p-2 hover:bg-white/5 rounded-md cursor-pointer transition-all group/opt"+ onClick={(e) => {+ e.stopPropagation();+ setSelectedDuration(d);+ setOpenDropdown(null);+ }}+ >+ <span className="text-xs font-semibold text-white/70 group-hover/opt:text-white">+ {d}s+ </span>+ {selectedDuration === d && <CheckSvg />}+ </div>+ ))}+ </div></div>- <div className="mt-6 flex gap-3 justify-center">- <button- type="button"- onClick={handleGenerate}- disabled={generating}- className="bg-white/10 hover:bg-white/20 px-6 py-2.5 rounded-2xl text-xs font-bold transition-all border border-white/5 backdrop-blur-lg text-white"- >- ↻ Regenerate- </button>- {isSeedance2Canvas && (- <button- type="button"- onClick={handleExtend}- className="bg-white/10 hover:bg-white/20 px-6 py-2.5 rounded-2xl text-xs font-bold transition-all border border-primary/30 text-primary backdrop-blur-lg"- title="Extend this video using Seedance 2.0 Extend"- >- ↗ Extend- </button>- )}- <button- type="button"- onClick={() => {- const entry = history.find(e => e.url === canvasUrl);- downloadFile(canvasUrl, `video-${entry?.id || 'clip'}.mp4`);+ )}+ </div>+ )}++ {/* Resolution btn */}+ {showResolution && (+ <div className="relative">+ <button+ type="button"+ onClick={toggleDropdown("resolution")}+ className="flex items-center gap-2 px-3 py-2 bg-white/[0.03] hover:bg-white/[0.06] rounded-md transition-all border border-white/[0.03] group whitespace-nowrap"+ >+ <svg+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ className="opacity-40 text-white"+ >+ <path d="M6 2L3 6v15a2 2 0 002 2h14a2 2 0 002-2V6l-3-4H6z" />+ </svg>+ <span className="text-[11px] font-semibold text-white/70 group-hover:text-[#d9ff00] transition-colors">+ {selectedResolution || "720p"}+ </span>+ </button>+ {openDropdown === "resolution" && (+ <div+ ref={dropdownRef}+ onClick={(e) => e.stopPropagation()}+ className="absolute bottom-[calc(100%+12px)] left-0 z-50 bg-[#0a0a0a] rounded-md p-3 shadow-2xl border border-white/[0.05] min-w-[140px]"+ >+ <div className="text-xs font-bold text-white/20 border-b border-white/[0.03] mb-2">+ Resolution+ </div>+ <div className="flex flex-col gap-1">+ {getCurrentResolutions(selectedModel).map((r) => (+ <div+ key={r}+ className="flex items-center justify-between p-3 hover:bg-white/5 rounded cursor-pointer transition-all group/opt"+ onClick={(e) => {+ e.stopPropagation();+ setSelectedResolution(r);+ setOpenDropdown(null);}}- className="bg-primary text-black px-6 py-2.5 rounded-2xl text-xs font-bold transition-all shadow-glow active:scale-95"- >- ↓ Download- </button>- <button- type="button"- onClick={handleNewPrompt}- className="bg-white/10 hover:bg-white/20 px-6 py-2.5 rounded-2xl text-xs font-bold transition-all border border-white/5 backdrop-blur-lg text-white"- >- + New- </button>+ >+ <span className="text-[11px] font-semibold text-white/70 group-hover/opt:text-white">+ {r}+ </span>+ {selectedResolution === r && <CheckSvg />}+ </div>+ ))}+ </div></div>+ )}</div>- )}+ )}+ </div>- {/* ── Hero + Prompt Bar (hidden when canvas is showing) ── */}- {!showCanvas && (+ {/* Generate button */}+ <button+ type="button"+ onClick={handleGenerate}+ disabled={generating}+ className="bg-[#d9ff00] text-black px-4 py-2 rounded-md font-medium text-sm hover:bg-[#e5ff33] hover:scale-[1.02] active:scale-[0.98] transition-all flex items-center justify-center gap-2 w-full sm:w-auto shadow-lg shadow-[#d9ff00]/10 disabled:opacity-50 disabled:cursor-not-allowed"+ >+ {generating ? (<>- {/* Hero */}- <div className="flex flex-col items-center mb-10 md:mb-20 animate-fade-in-up transition-all duration-700">- <div className="mb-10 relative group">- <div className="absolute inset-0 bg-primary/20 blur-[100px] rounded-full opacity-40 group-hover:opacity-70 transition-opacity duration-1000" />- <div className="relative w-24 h-24 md:w-32 md:h-32 bg-teal-900/40 rounded-3xl flex items-center justify-center border border-white/5 overflow-hidden">- <svg width="80" height="80" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1" className="text-primary opacity-20 absolute -right-4 -bottom-4">- <polygon points="23 7 16 12 23 17 23 7" /><rect x="1" y="5" width="15" height="14" rx="2" ry="2" />- </svg>- <div className="w-16 h-16 bg-primary/10 rounded-2xl flex items-center justify-center border border-primary/20 shadow-glow relative z-10">- <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" className="text-primary">- <polygon points="23 7 16 12 23 17 23 7" /><rect x="1" y="5" width="15" height="14" rx="2" ry="2" />- </svg>- </div>- <div className="absolute top-4 right-4 text-primary animate-pulse">✨</div>- </div>- </div>- <h1 className="text-2xl sm:text-4xl md:text-7xl font-black text-white tracking-widest uppercase mb-4 selection:bg-primary selection:text-black text-center px-4">- Video Studio- </h1>- <p className="text-secondary text-sm font-medium tracking-wide opacity-60">- Animate images into stunning AI videos with motion effects- </p>- </div>-- {/* Prompt Bar */}- <div className="w-full max-w-4xl relative z-40 animate-fade-in-up" style={{ animationDelay: '0.2s' }}>- <div className="w-full bg-[#111]/90 backdrop-blur-xl border border-white/10 rounded-[1.5rem] md:rounded-[2.5rem] p-3 md:p-5 flex flex-col gap-3 md:gap-5 shadow-3xl">-- {/* Top row: image picker + video picker + textarea */}- <div className="flex items-start gap-5 px-2">-- {/* Image upload button */}- <div className="relative mt-1.5">- <input- ref={imageFileInputRef}- type="file"- accept="image/*"- className="hidden"- onChange={handleImageFileChange}- />- <button- type="button"- title={uploadedImageUrl ? 'Clear image' : 'Upload image for Image-to-Video'}- onClick={() => uploadedImageUrl ? clearImageUpload() : imageFileInputRef.current?.click()}- className={`w-10 h-10 shrink-0 rounded-xl border transition-all flex items-center justify-center relative overflow-hidden ${uploadedImageUrl ? 'border-primary/60 bg-primary/10' : 'bg-white/5 border-white/10 hover:bg-white/10 hover:border-primary/40'} group`}- >- {imageUploading ? (- <div className="absolute inset-0 flex flex-col items-center justify-center bg-black/60 z-10">- <div className="w-4 h-4 rounded-full border border-primary/30 border-t-primary animate-spin mb-0.5" />- <span className="text-[8px] font-black text-primary">{imageProgress}%</span>- </div>- ) : null}-- {uploadedImageUrl ? (- <img src={uploadedImageUrl} alt="" className={`w-full h-full object-cover rounded-xl ${imageUploading ? 'opacity-40 blur-[2px]' : 'opacity-100'}`} />- ) : !imageUploading && (- <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" className="text-muted group-hover:text-primary transition-colors">- <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>- )}- </button>- </div>-- {/* Video upload button */}- <div className="relative mt-1.5">- <input- ref={videoFileInputRef}- type="file"- accept="video/*"- className="hidden"- onChange={handleVideoFileChange}- />- <button- type="button"- title={uploadedVideoUrl ? `${uploadedVideoName} — click to clear` : 'Upload video to remove watermark'}- onClick={() => uploadedVideoUrl ? clearVideoUpload() : videoFileInputRef.current?.click()}- className={`w-10 h-10 shrink-0 rounded-xl border transition-all flex items-center justify-center relative overflow-hidden ${uploadedVideoUrl ? 'border-primary/60 bg-white/5' : 'bg-white/5 border-white/10 hover:bg-white/10 hover:border-primary/40'} group`}- >- {videoUploading ? (- <div className="absolute inset-0 flex flex-col items-center justify-center bg-black/60 z-10">- <div className="w-4 h-4 rounded-full border border-primary/30 border-t-primary animate-spin mb-0.5" />- <span className="text-[8px] font-black text-primary">{videoProgress}%</span>- </div>- ) : uploadedVideoUrl ? (- <video src={uploadedVideoUrl} className={`w-full h-full object-cover rounded-xl ${videoUploading ? 'opacity-40 blur-[2px]' : 'opacity-100'}`} muted />- ) : (- <VideoIconSvg className="text-muted group-hover:text-primary transition-colors" />- )}- </button>- </div>-- {/* Prompt textarea */}- <textarea- ref={textareaRef}- value={prompt}- onChange={handlePromptInput}- placeholder={promptPlaceholder}- disabled={promptDisabled}- rows={1}- className="flex-1 bg-transparent border-none text-white text-base md:text-xl placeholder:text-muted focus:outline-none resize-none pt-2.5 leading-relaxed min-h-[40px] max-h-[150px] md:max-h-[250px] overflow-y-auto custom-scrollbar disabled:opacity-40"- />- </div>-- {/* Extend banner */}- {isExtendMode && (- <div className="flex items-center gap-2 px-4 py-2 mx-2 mt-2 bg-primary/10 border border-primary/20 rounded-xl text-xs text-primary">- <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5">- <path d="M5 12h14M12 5l7 7-7 7" />- </svg>- <span>Extending previous Seedance 2.0 generation — add an optional prompt to guide the continuation</span>- </div>- )}-- {/* Bottom row: controls + generate */}- <div className="flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 px-2 pt-4 border-t border-white/5">- <div className="flex items-center gap-1.5 md:gap-2.5 relative flex-wrap">-- {/* Model btn */}- <div className="relative">- <ControlBtn- icon={- <div className="w-5 h-5 bg-primary rounded-md flex items-center justify-center shadow-lg shadow-primary/20">- <span className="text-[10px] font-black text-black">V</span>- </div>- }- label={selectedModelName}- onClick={toggleDropdown('model')}- />- {openDropdown === 'model' && (- <div ref={dropdownRef} onClick={e => e.stopPropagation()} className="absolute bottom-[calc(100%+8px)] left-0 z-50 bg-[#111] rounded-3xl p-3 border border-white/10 flex flex-col w-[calc(100vw-3rem)] max-w-xs">- <ModelDropdown- imageMode={imageMode}- selectedModel={selectedModel}- onSelect={handleModelSelect}- onClose={() => setOpenDropdown(null)}- />- </div>- )}- </div>-- {/* Aspect ratio btn */}- {showAr && (- <div className="relative">- <ControlBtn- icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="opacity-60 text-secondary"><rect x="3" y="3" width="18" height="18" rx="2" ry="2" /></svg>}- label={selectedAr}- onClick={toggleDropdown('ar')}- />- {openDropdown === 'ar' && (- <div ref={dropdownRef} onClick={e => e.stopPropagation()} className="absolute bottom-[calc(100%+8px)] left-0 z-50 bg-[#111] rounded-3xl p-3 border border-white/10 flex flex-col w-52 max-w-[240px]">- <div className="text-[10px] font-bold text-muted uppercase tracking-widest px-3 py-2 border-b border-white/5 mb-2">Aspect Ratio</div>- <div className="flex flex-col gap-1">- {getCurrentAspectRatios(selectedModel).map(r => (- <div- key={r}- className="flex items-center justify-between p-3.5 hover:bg-white/5 rounded-2xl cursor-pointer transition-all group"- onClick={(e) => { e.stopPropagation(); setSelectedAr(r); setOpenDropdown(null); }}- >- <div className="flex items-center gap-4">- <div className="w-6 h-6 border-2 border-white/20 rounded-md shadow-inner flex items-center justify-center group-hover:border-primary/50 transition-colors">- <div className="w-3 h-3 bg-white/10 rounded-sm" />- </div>- <span className="text-xs font-bold text-white opacity-80 group-hover:opacity-100 transition-opacity">{r}</span>- </div>- {selectedAr === r && <CheckSvg />}- </div>- ))}- </div>- </div>- )}- </div>- )}-- {/* Duration btn */}- {showDuration && (- <div className="relative">- <ControlBtn- icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="opacity-60 text-secondary"><circle cx="12" cy="12" r="10" /><polyline points="12 6 12 12 16 14" /></svg>}- label={`${selectedDuration}s`}- onClick={toggleDropdown('duration')}- />- {openDropdown === 'duration' && (- <div ref={dropdownRef} onClick={e => e.stopPropagation()} className="absolute bottom-[calc(100%+8px)] left-0 z-50 bg-[#111] rounded-3xl p-3 border border-white/10 flex flex-col w-52 max-w-[240px]">- <div className="text-[10px] font-bold text-secondary uppercase tracking-widest px-3 py-2 border-b border-white/5 mb-2">Duration</div>- <div className="flex flex-col gap-1">- {getCurrentDurations(selectedModel).map(d => (- <DropdownItem key={d} label={`${d}s`} selected={selectedDuration === d} onClick={(e) => { e.stopPropagation(); setSelectedDuration(d); setOpenDropdown(null); }} />- ))}- </div>- </div>- )}- </div>- )}-- {/* Resolution btn */}- {showResolution && (- <div className="relative">- <ControlBtn- icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="opacity-60 text-secondary"><path d="M6 2L3 6v15a2 2 0 002 2h14a2 2 0 002-2V6l-3-4H6z" /></svg>}- label={selectedResolution || '720p'}- onClick={toggleDropdown('resolution')}- />- {openDropdown === 'resolution' && (- <div ref={dropdownRef} onClick={e => e.stopPropagation()} className="absolute bottom-[calc(100%+8px)] left-0 z-50 bg-[#111] rounded-3xl p-3 border border-white/10 flex flex-col w-52 max-w-[240px]">- <div className="text-[10px] font-bold text-secondary uppercase tracking-widest px-3 py-2 border-b border-white/5 mb-2">Resolution</div>- <div className="flex flex-col gap-1">- {getCurrentResolutions(selectedModel).map(r => (- <DropdownItem key={r} label={r} selected={selectedResolution === r} onClick={(e) => { e.stopPropagation(); setSelectedResolution(r); setOpenDropdown(null); }} />- ))}- </div>- </div>- )}- </div>- )}-- {/* Quality btn */}- {showQuality && (- <div className="relative">- <ControlBtn- icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="opacity-60 text-secondary"><path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z" /></svg>}- label={selectedQuality || 'basic'}- onClick={toggleDropdown('quality')}- />- {openDropdown === 'quality' && (- <div ref={dropdownRef} onClick={e => e.stopPropagation()} className="absolute bottom-[calc(100%+8px)] left-0 z-50 bg-[#111] rounded-3xl p-3 border border-white/10 flex flex-col w-52 max-w-[240px]">- <div className="text-[10px] font-bold text-secondary uppercase tracking-widest px-3 py-2 border-b border-white/5 mb-2">Quality</div>- <div className="flex flex-col gap-1">- {getQualitiesForModel(getCurrentModels(), selectedModel).map(q => (- <DropdownItem key={q} label={q} selected={selectedQuality === q} onClick={(e) => { e.stopPropagation(); setSelectedQuality(q); setOpenDropdown(null); }} />- ))}- </div>- </div>- )}- </div>- )}-- {/* Mode btn */}- {showMode && (- <div className="relative">- <ControlBtn- icon={<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="opacity-60 text-secondary"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" /></svg>}- label={selectedMode || 'normal'}- onClick={toggleDropdown('mode')}- />- {openDropdown === 'mode' && (- <div ref={dropdownRef} onClick={e => e.stopPropagation()} className="absolute bottom-[calc(100%+8px)] left-0 z-50 bg-[#111] rounded-3xl p-3 border border-white/10 flex flex-col w-52 max-w-[240px]">- <div className="text-[10px] font-bold text-secondary uppercase tracking-widest px-3 py-2 border-b border-white/5 mb-2">Mode</div>- <div className="flex flex-col gap-1">- {getModesForModel(selectedModel).map(m => (- <DropdownItem key={m} label={m} selected={selectedMode === m} onClick={(e) => { e.stopPropagation(); setSelectedMode(m); setOpenDropdown(null); }} />- ))}- </div>- </div>- )}- </div>- )}- </div>-- {/* Generate button */}- <button- type="button"- onClick={handleGenerate}- disabled={generating}- className="bg-primary text-black px-6 md:px-8 py-3 md:py-3.5 rounded-xl md:rounded-[1.5rem] font-black text-sm md:text-base hover:shadow-glow hover:scale-105 active:scale-95 transition-all flex items-center justify-center gap-2.5 w-full sm:w-auto shadow-lg disabled:opacity-60 disabled:scale-100"- >- {generating ? (- <><span className="animate-spin inline-block text-black">◌</span> Generating...</>- ) : generateError ? (- `Error: ${generateError}`- ) : (- 'Generate ✨'- )}- </button>- </div>- </div>- </div>+ <span className="animate-spin inline-block text-black">+ ◌+ </span>{" "}+ Generating...</>- )}+ ) : generateError ? (+ `Error: ${generateError}`+ ) : (+ <>+ <span>Generate</span>+ </>+ )}+ </button>+ </div>+ </div>+ </div>++ {/* ── FULLSCREEN VIDEO MODAL ── */}+ {fullscreenUrl && (+ <div+ className="fixed inset-0 z-[100] flex items-center justify-center bg-black/95 backdrop-blur-sm animate-fade-in"+ onClick={() => setFullscreenUrl(null)}+ >+ <button+ type="button"+ className="absolute top-6 right-6 p-3 bg-white/10 hover:bg-white/20 rounded-full text-white transition-colors border border-white/10"+ onClick={(e) => {+ e.stopPropagation();+ setFullscreenUrl(null);+ }}+ >+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">+ <line x1="18" y1="6" x2="6" y2="18" />+ <line x1="6" y1="6" x2="18" y2="18" />+ </svg>+ </button>+ <video+ src={fullscreenUrl}+ controls+ autoPlay+ loop+ className="max-w-[95vw] max-h-[95vh] rounded-2xl shadow-2xl object-contain animate-scale-up"+ onClick={(e) => e.stopPropagation()}+ /></div>- );+ )}+ </div>+ );}diff --git a/packages/studio/src/index.js b/packages/studio/src/index.jsindex 4219c6eb..998eee0b 100644--- a/packages/studio/src/index.js+++ b/packages/studio/src/index.js@@ -4,3 +4,4 @@ export { default as ImageStudio } from './components/ImageStudio';export { default as VideoStudio } from './components/VideoStudio';export { default as LipSyncStudio } from './components/LipSyncStudio';export { default as CinemaStudio } from './components/CinemaStudio';+export * from './muapi';diff --git a/packages/studio/src/muapi.js b/packages/studio/src/muapi.jsindex 26799299..7aee1c9d 100644--- a/packages/studio/src/muapi.js+++ b/packages/studio/src/muapi.js@@ -170,3 +170,16 @@ export function uploadFile(apiKey, file, onProgress) {});}+export async function getUserBalance(apiKey) {+ const response = await fetch(`${BASE_URL}/api/v1/account/balance`, {+ headers: {+ 'Content-Type': 'application/json',+ 'x-api-key': apiKey+ }+ });+ if (!response.ok) {+ const errText = await response.text();+ throw new Error(`Failed to fetch balance: ${response.status} - ${errText.slice(0, 100)}`);+ }+ return await response.json();+}