Art555777

Скрипт Grok Video

Jul 24th, 2026
208
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 129.59 KB | Cybersecurity | 0 0
  1. // ==UserScript==
  2. // @name xAI Pro Studio Frontend by Grok (v41.1 - Quality + Video 1.5 / 1080p)
  3. // @namespace http://tampermonkey.net/
  4. // @version 41.1
  5. // @description Full-Screen UI by Grok | Image Quality Mode | Video Model Classic/1.5 + 1080p | 1.5 ref fix | EXIF Fix | Multi-Image | Auto-Retry | Adaptive AR | Auto-Download | Extend | Anti-Throttling | Auto-Resume
  6. // @match https://console.x.ai/playground/image*
  7. // @match https://console.x.ai/team/*/image*
  8. // @match https://console.x.ai/playground/imagine*
  9. // @match https://console.x.ai/team/*/imagine*
  10. // @grant GM_xmlhttpRequest
  11. // @grant GM_cookie
  12. // @grant GM_download
  13. // @connect console.x.ai
  14. // @connect vidgen.x.ai
  15. // @connect *.x.ai
  16. // @run-at document-start
  17. // ==/UserScript==
  18.  
  19. (function() {
  20. 'use strict';
  21.  
  22. // ─── LOGGING & DEBUG ENGINE ───────────────────────────────────────────────
  23. const appLogs = [];
  24. const MAX_LOGS = 500;
  25.  
  26. function stripHeavyData(val) {
  27. if (val === null || val === undefined) return val;
  28. if (typeof val === 'string') {
  29. if (val.startsWith('data:image') || val.startsWith('data:video') || val.length > 2000) {
  30. return `[TRUNCATED_DATA_LEN_${val.length}]`;
  31. }
  32. return val;
  33. }
  34. if (typeof val !== 'object') return val;
  35. if (Array.isArray(val)) return val.map(stripHeavyData);
  36. const copy = {};
  37. for (const k in val) {
  38. if (Object.prototype.hasOwnProperty.call(val, k)) {
  39. copy[k] = stripHeavyData(val[k]);
  40. }
  41. }
  42. return copy;
  43. }
  44.  
  45. function addLog(level, msg, data = null) {
  46. try {
  47. const ts = new Date().toISOString().replace('T', ' ').substring(0, 23);
  48. const safeData = data ? stripHeavyData(data) : null;
  49. appLogs.push({ ts, level, msg, data: safeData });
  50. if (appLogs.length > MAX_LOGS) appLogs.shift();
  51.  
  52. const consoleMsg = `[xAI Studio] [${level}] ${msg}`;
  53. if (level === 'ERROR') console.error(consoleMsg, safeData || '');
  54. else if (level === 'WARN') console.warn(consoleMsg, safeData || '');
  55. else console.log(consoleMsg, safeData || '');
  56. } catch(e) {}
  57. }
  58.  
  59. function formatLogsForExport() {
  60. return appLogs.map(l => {
  61. let text = `[${l.ts}] [${l.level}] ${l.msg}`;
  62. if (l.data) {
  63. try { text += `\n${JSON.stringify(l.data, null, 2)}`; }
  64. catch(e) { text += `\n[Unserializable Data]`; }
  65. }
  66. return text;
  67. }).join('\n\n----------------------------------------\n\n');
  68. }
  69.  
  70. addLog('INFO', 'Script started executing');
  71.  
  72. // ─── UTILITIES & DATA STORAGE ─────────────────────────────────────────────
  73. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  74. function pad2(n) { return String(n).padStart(2, '0'); }
  75. function makeTimestamp() {
  76. const d = new Date();
  77. return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} ${pad2(d.getHours())}-${pad2(d.getMinutes())}-${pad2(d.getSeconds())}`;
  78. }
  79. function base64ToBlobUrl(b64) {
  80. if (!b64 || !b64.startsWith('data:')) return b64;
  81. try {
  82. const parts = b64.split(',');
  83. const mime = parts[0].match(/:(.*?);/)[1];
  84. const bstr = atob(parts[1]);
  85. let n = bstr.length;
  86. const u8arr = new Uint8Array(n);
  87. while (n--) u8arr[n] = bstr.charCodeAt(n);
  88. return URL.createObjectURL(new Blob([u8arr], { type: mime }));
  89. } catch(e) { return b64; }
  90. }
  91. const DOWNLOAD_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>`;
  92. const EDIT_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`;
  93. const EXTEND_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>`;
  94.  
  95. // ─── SETTINGS SCHEMA & MANAGER ───────────────────────────────────────────
  96. const SETTINGS_SCHEMA = {
  97. retries: { id: 'set-retries', type: 'number', default: 20 },
  98. delayMin: { id: 'set-delay-min', type: 'number', default: 2000 },
  99. delayMax: { id: 'set-delay-max', type: 'number', default: 4000 },
  100. rateLimitDelay: { id: 'set-rate-limit-delay', type: 'number', default: 20 },
  101. notifications: { id: 'set-notifications', type: 'checkbox', default: true },
  102. customCSS: { id: 'set-custom-css', type: 'text', default: "" },
  103. saveAsPng: { id: 'set-save-png', type: 'checkbox', default: false },
  104. apiBaseUrl: { id: 'set-api-base-url', type: 'text', default: "" },
  105. videoPollTimeout: { id: 'set-video-timeout', type: 'number', default: 300 },
  106. autoRetryStuckVideo: { id: 'set-auto-retry-video', type: 'checkbox', default: false },
  107. breakLoopOnFailure: { id: 'set-break-loop-on-failure', type:'checkbox', default: true },
  108. referenceARTrick: { id: 'set-reference-ar-trick', type: 'checkbox', default: true },
  109. maximumGreedMode: { id: 'set-maximum-greed-mode', type: 'checkbox', default: false },
  110. suppressEditWarning: { id: 'set-suppress-warning', type: 'checkbox', default: false },
  111. videoAutoplay: { id: 'set-video-autoplay', type: 'checkbox', default: true },
  112. videoMuted: { id: 'set-video-muted', type: 'checkbox', default: false },
  113. uiFontSize: { id: 'set-font-size', type: 'number', default: 13 },
  114. autoDownload: { id: 'set-auto-download', type: 'checkbox', default: false },
  115. antiThrottling: { id: 'set-anti-throttling', type: 'checkbox', default: true }
  116. };
  117.  
  118. const SettingsManager = {
  119. load: function() {
  120. let stored = JSON.parse(localStorage.getItem('xai_api_settings') || '{}');
  121. let parsed = {};
  122. for (const [key, config] of Object.entries(SETTINGS_SCHEMA)) {
  123. let val = stored[key] !== undefined ? stored[key] : config.default;
  124. if (config.type === 'number') val = parseInt(val) || config.default;
  125. parsed[key] = val;
  126. }
  127. parsed.delayMax = Math.max(parsed.delayMin, parsed.delayMax); // Enforce logic
  128. return parsed;
  129. },
  130. populateUI: function(currentSettings) {
  131. for (const [key, config] of Object.entries(SETTINGS_SCHEMA)) {
  132. const el = document.getElementById(config.id);
  133. if (!el) continue;
  134. if (config.type === 'checkbox') el.checked = currentSettings[key];
  135. else el.value = currentSettings[key];
  136. }
  137. },
  138. saveFromUI: function() {
  139. let newSettings = {};
  140. for (const [key, config] of Object.entries(SETTINGS_SCHEMA)) {
  141. const el = document.getElementById(config.id);
  142. if (!el) { newSettings[key] = config.default; continue; }
  143.  
  144. if (config.type === 'checkbox') {
  145. newSettings[key] = el.checked;
  146. } else if (config.type === 'number') {
  147. newSettings[key] = parseInt(el.value) || config.default;
  148. } else {
  149. newSettings[key] = el.value.trim();
  150. }
  151. }
  152. newSettings.delayMax = Math.max(newSettings.delayMin, newSettings.delayMax);
  153. localStorage.setItem('xai_api_settings', JSON.stringify(newSettings));
  154. return newSettings;
  155. }
  156. };
  157.  
  158. // Initialize global settings
  159. let appSettings = SettingsManager.load();
  160.  
  161. let favoritePrompts = JSON.parse(localStorage.getItem('xai_api_favs') || '[]');
  162.  
  163. function getApiUrl(path) {
  164. let base = appSettings.apiBaseUrl || '';
  165. if (base.endsWith('/')) base = base.slice(0, -1);
  166. if (!path.startsWith('/') && base) path = '/' + path;
  167. return base + path;
  168. }
  169.  
  170. function parseDynamicPrompt(text) {
  171. if (!text) return text;
  172. let parsed = text; let prev;
  173. do {
  174. prev = parsed;
  175. parsed = parsed.replace(/\{([^{}]+)\}/g, (m, c) => { const o = c.split('|'); return o[Math.floor(Math.random() * o.length)]; });
  176. } while (parsed !== prev);
  177. parsed = parsed.replace(/@randomseed/gi, () => Math.floor(1000000000 + Math.random() * 9000000000).toString());
  178. return parsed.trim();
  179. }
  180.  
  181. let sharedAudioCtx = null;
  182. let awakeOsc = null;
  183. let titleBlinkInterval = null;
  184. const originalTitle = document.title || "xAI Pro Studio";
  185.  
  186. function initAudio() {
  187. if (!sharedAudioCtx) {
  188. try { sharedAudioCtx = new (window.AudioContext || window.webkitAudioContext)(); } catch(e) {}
  189. }
  190. if (sharedAudioCtx && sharedAudioCtx.state === 'suspended') sharedAudioCtx.resume();
  191. }
  192.  
  193. function toggleKeepAwake(enable) {
  194. if (enable && !appSettings.antiThrottling) return;
  195. if (enable) {
  196. initAudio();
  197. if (sharedAudioCtx) {
  198. if (!awakeOsc) {
  199. try {
  200. awakeOsc = sharedAudioCtx.createOscillator();
  201. //Сделай звук активности вкладки типа 21 кГц -90 дБ.
  202. awakeOsc.frequency.value = 21000;
  203. awakeOsc.type = 'sine';
  204. const gain = sharedAudioCtx.createGain();
  205. //gain.gain.value = 0.001;
  206. gain.gain.value = 0.000031622776601683795; //Math.pow(10, -90/20);
  207. awakeOsc.connect(gain);
  208. gain.connect(sharedAudioCtx.destination);
  209. awakeOsc.start();
  210. } catch(e) {}
  211. }
  212. }
  213. } else {
  214. if (awakeOsc) {
  215. try { awakeOsc.stop(); awakeOsc.disconnect(); } catch(e) {}
  216. awakeOsc = null;
  217. }
  218. }
  219. }
  220.  
  221. function notifyUser(isError = false) {
  222. if (!appSettings.notifications) return;
  223. initAudio();
  224. if (sharedAudioCtx) {
  225. try {
  226. const osc = sharedAudioCtx.createOscillator(); const gain = sharedAudioCtx.createGain();
  227. osc.connect(gain); gain.connect(sharedAudioCtx.destination);
  228. if (isError) {
  229. osc.type = 'sawtooth'; osc.frequency.setValueAtTime(300, sharedAudioCtx.currentTime); osc.frequency.exponentialRampToValueAtTime(100, sharedAudioCtx.currentTime + 0.3);
  230. } else {
  231. osc.type = 'sine'; osc.frequency.setValueAtTime(500, sharedAudioCtx.currentTime); osc.frequency.exponentialRampToValueAtTime(1000, sharedAudioCtx.currentTime + 0.2);
  232. }
  233. gain.gain.setValueAtTime(0.1, sharedAudioCtx.currentTime); gain.gain.exponentialRampToValueAtTime(0.01, sharedAudioCtx.currentTime + 0.5);
  234. osc.start(sharedAudioCtx.currentTime); osc.stop(sharedAudioCtx.currentTime + 0.5);
  235. } catch(e) {}
  236. }
  237. if (!document.hasFocus()) {
  238. if (titleBlinkInterval) clearInterval(titleBlinkInterval);
  239. let toggle = true;
  240. titleBlinkInterval = setInterval(() => { document.title = toggle ? (isError ? "❌ FAILED" : "✅ DONE") : originalTitle; toggle = !toggle; }, 1000);
  241. const clearBlink = () => { clearInterval(titleBlinkInterval); document.title = originalTitle; window.removeEventListener('focus', clearBlink); };
  242. window.addEventListener('focus', clearBlink);
  243. }
  244. }
  245.  
  246. // ─── NUCLEAR SESSION WIPE ENGINE ──────────────────────────────────────────
  247. async function nuclearSessionReset(remainingLoops = 0) {
  248. addLog('INFO', `Nuclear Reset triggered.`);
  249.  
  250. // 1. Wipe EVERY single cookie (xAI, Cloudflare, Stripe, HttpOnly) for local domain
  251. if (typeof GM_cookie !== 'undefined') {
  252. await new Promise(resolve => {
  253. GM_cookie.list({ url: window.location.href }, (cookies, error) => {
  254. if (!error && cookies && cookies.length > 0) {
  255. let deletedCount = 0;
  256. cookies.forEach(c => {
  257. GM_cookie.delete({ url: window.location.href, name: c.name }, () => {
  258. deletedCount++;
  259. if (deletedCount === cookies.length) resolve();
  260. });
  261. });
  262. } else resolve();
  263. });
  264. });
  265. // Also wipe root domain .x.ai just in case
  266. await new Promise(resolve => {
  267. GM_cookie.list({ url: 'https://x.ai' }, (cookies, error) => {
  268. if (!error && cookies && cookies.length > 0) {
  269. let deletedCount = 0;
  270. cookies.forEach(c => {
  271. GM_cookie.delete({ url: 'https://x.ai', name: c.name }, () => {
  272. deletedCount++;
  273. if (deletedCount === cookies.length) resolve();
  274. });
  275. });
  276. } else resolve();
  277. });
  278. });
  279. }
  280.  
  281. // 2. Clear Local and Session Storage (leaving our script's custom UI settings intact)
  282. for (let i = localStorage.length - 1; i >= 0; i--) {
  283. const k = localStorage.key(i);
  284. if (k && !k.startsWith('xai_api_')) localStorage.removeItem(k);
  285. }
  286. sessionStorage.clear();
  287.  
  288. if ( appSettings.maximumGreedMode && remainingLoops > 0) {
  289. sessionStorage.setItem('xai_resume_loops', remainingLoops.toString());
  290. } else {
  291. // Requesting new cookies.
  292. await fetch('https://console.x.ai/playground/imagine');
  293. }
  294. }
  295.  
  296. let piexifPromise = null;
  297. function loadPiexif() {
  298. if (piexifPromise) return piexifPromise;
  299.  
  300. piexifPromise = new Promise((resolve, reject) => {
  301. const getPiexif = () => window.piexif || (typeof unsafeWindow !== 'undefined' ? unsafeWindow.piexif : null);
  302.  
  303. let px = getPiexif();
  304. if (px) { resolve(px); return; }
  305.  
  306. const script = document.createElement('script');
  307. script.src = 'https://cdnjs.cloudflare.com/ajax/libs/piexifjs/1.0.6/piexif.min.js';
  308.  
  309. script.onload = () => {
  310. px = getPiexif();
  311. if (px) {
  312. resolve(px);
  313. } else {
  314. piexifPromise = null;
  315. reject(new Error("piexifjs loaded, but 'piexif' object not found in window context."));
  316. }
  317. };
  318.  
  319. script.onerror = () => {
  320. piexifPromise = null;
  321. reject(new Error('Failed to load piexifjs script from CDN.'));
  322. };
  323.  
  324. document.head.appendChild(script);
  325. });
  326.  
  327. return piexifPromise;
  328. }
  329.  
  330. function toUTF16LE(str) {
  331. const arr =[];
  332. for (let i = 0; i < str.length; i++) { const code = str.charCodeAt(i); arr.push(code & 0xFF); arr.push((code >> 8) & 0xFF); }
  333. arr.push(0, 0); return arr;
  334. }
  335.  
  336. function convertToJpegWithExif(base64PngUri, prompt) {
  337. console.log(prompt);
  338. return new Promise((resolve, reject) => {
  339. const img = new Image();
  340. img.onload = async () => {
  341. const canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height;
  342. const ctx = canvas.getContext('2d'); ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(img, 0, 0);
  343. let jpegUri = canvas.toDataURL('image/jpeg', 0.95);
  344. if (prompt) {
  345. try {
  346. const piexif = await loadPiexif();
  347. const exifObj = {"0th": {}, "Exif": {}, "GPS": {}, "1st": {}, "Interop": {}};
  348.  
  349. exifObj['0th'][piexif.ImageIFD.ImageDescription] = unescape(encodeURIComponent(prompt));
  350.  
  351. jpegUri = piexif.insert(piexif.dump(exifObj), jpegUri);
  352. } catch (e) { addLog('ERROR', 'EXIF Injection Failed', e); }
  353. }
  354. resolve(jpegUri);
  355. };
  356. img.onerror = reject; img.src = base64PngUri;
  357. });
  358. }
  359.  
  360. async function extractPromptFromImage(file) {
  361. if (!file || !file.type.includes('image')) return null;
  362. try {
  363. const piexif = await loadPiexif();
  364. return new Promise((resolve) => {
  365. const reader = new FileReader();
  366. reader.onload = (e) => {
  367. try {
  368. const exifData = piexif.load(e.target.result);
  369.  
  370. let prompt = exifData['0th'] && exifData['0th'][piexif.ImageIFD.ImageDescription];
  371. if (Array.isArray(prompt)) prompt = String.fromCharCode.apply(null, prompt).replace(/\0/g, '');
  372. if (prompt) { try { prompt = decodeURIComponent(escape(prompt)); } catch(err) {} }
  373.  
  374. if (!prompt && exifData['0th'] && exifData['0th'][40091]) {
  375. const xpTitleArr = exifData['0th'][40091]; let str = '';
  376. for (let i = 0; i < xpTitleArr.length; i += 2) {
  377. const charCode = xpTitleArr[i] | (xpTitleArr[i+1] << 8);
  378. if (charCode === 0) break;
  379. str += String.fromCharCode(charCode);
  380. }
  381. prompt = str;
  382. }
  383. resolve(prompt ? prompt.trim() : null);
  384. } catch (err) { resolve(null); }
  385. };
  386. reader.onerror = () => resolve(null);
  387. reader.readAsDataURL(file);
  388. });
  389. } catch (e) { return null; }
  390. }
  391.  
  392. function generateVideoThumbnail(file) {
  393. return new Promise((resolve) => {
  394. const video = document.createElement('video'); video.preload = 'metadata'; video.muted = true; video.playsInline = true;
  395. const url = URL.createObjectURL(file); video.src = url; let isSeeked = false;
  396. video.onloadeddata = () => { video.currentTime = Math.min(0.5, video.duration / 2 || 0); file._w = video.videoWidth; file._h = video.videoHeight; };
  397. video.onseeked = () => {
  398. if (isSeeked) return; isSeeked = true;
  399. try {
  400. const canvas = document.createElement('canvas'); canvas.width = video.videoWidth || 140; canvas.height = video.videoHeight || 140;
  401. const ctx = canvas.getContext('2d'); ctx.drawImage(video, 0, 0, canvas.width, canvas.height); URL.revokeObjectURL(url); resolve(canvas.toDataURL('image/jpeg', 0.8));
  402. } catch(e) { URL.revokeObjectURL(url); resolve(null); }
  403. };
  404. video.onerror = () => { URL.revokeObjectURL(url); resolve(null); };
  405. setTimeout(() => { if (!isSeeked) { URL.revokeObjectURL(url); resolve(null); } }, 2000);
  406. });
  407. }
  408.  
  409. function updateFontSize(size) {
  410. let el = document.getElementById('xai-custom-font-size');
  411. if (!el) { el = document.createElement('style'); el.id = 'xai-custom-font-size'; document.head.appendChild(el); }
  412. if (size === 13) { el.innerHTML = ''; return; }
  413.  
  414. el.innerHTML = `
  415. #xai-pro-app textarea, #xai-pro-app #prompt-backdrop, #xai-pro-app select, #xai-pro-app input[type="text"], #xai-pro-app input[type="number"], #xai-pro-app .btn-primary, #xai-pro-app .btn-secondary, #xai-pro-app .ar-select-box, #xai-pro-app .action-select { font-size: ${size}px !important; }
  416. #xai-pro-app .ar-option, #xai-pro-app .fav-text, #xai-pro-app #xai-api-status { font-size: ${size - 1}px !important; }
  417. #xai-pro-app .panel-title, #xai-pro-app label, #xai-pro-app .toggle-btn, #xai-pro-app .slider-header, #xai-pro-app .history-card p, #xai-pro-app .warning-box, #xai-pro-app .ref-info span { font-size: ${size - 2}px !important; }
  418. #xai-pro-app .slider-ticks, #xai-pro-app .slider-ticks span, #xai-pro-app .ref-action-btn, #xai-pro-app .ref-toggle-label, #xai-pro-app .ref-thumb span, #xai-pro-app button[style*="font-size: 10px"] { font-size: ${size - 3}px !important; }
  419. #xai-pro-app .ref-handle { font-size: ${size + 1}px !important; }
  420. #xai-pro-app h3 { font-size: ${size + 2}px !important; }
  421. `;
  422. }
  423.  
  424. // ─── DATA MAPS FOR UI SLIDERS ─────────────────────────────────────────────
  425. const MAPS = {
  426. batch: [1, 2, 3, 4, 5, 8, 10],
  427. durGen: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
  428. durExt: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  429. };
  430.  
  431. const arData =[
  432. { label: 'Auto', w: 1, h: 1, isAuto: true },
  433. { label: 'By First Ref', w: 1, h: 1, isAuto: true, isRef: true },
  434. { label: '1:1', w: 1, h: 1 }, { label: '1:1', w: 1, h: 1 }, { label: '3:4', w: 3, h: 4 }, { label: '4:3', w: 4, h: 3 },
  435. { label: '9:16', w: 9, h: 16 }, { label: '16:9', w: 16, h: 9 }, { label: '2:3', w: 2, h: 3 },
  436. { label: '3:2', w: 3, h: 2 }, { label: '9:19.5', w: 9, h: 19.5 }, { label: '19.5:9', w: 19.5, h: 9 },
  437. { label: '9:20', w: 9, h: 20 }, { label: '20:9', w: 20, h: 9 }, { label: '1:2', w: 1, h: 2 }, { label: '2:1', w: 2, h: 1 }
  438. ];
  439.  
  440. function createArIcon(w, h, isAuto, isRef) {
  441. if (isRef) return `<div style="width: 12px; height: 12px; border: 1px dashed #10b981; border-radius: 2px; display: flex; align-items: center; justify-content: center; font-size: 8px; color: #10b981; font-weight:bold;">R</div>`;
  442. if (isAuto) return `<div style="width: 12px; height: 12px; border: 1px dashed #64748b; border-radius: 2px; display: flex; align-items: center; justify-content: center; font-size: 9px; color: #94a3b8;">A</div>`;
  443. const scale = 12 / Math.max(w, h);
  444. return `<div style="width: 14px; height: 14px; display: flex; align-items: center; justify-content: center;"><div style="width: ${w * scale}px; height: ${h * scale}px; border: 1.5px solid #cbd5e1; border-radius: 2px;"></div></div>`;
  445. }
  446.  
  447. // ─── UI INJECTION ─────────────────────────────────────────────────────────
  448. const UI_CSS = `
  449. ::-webkit-scrollbar { width: 6px; }
  450. ::-webkit-scrollbar-track { background: #0f172a; }
  451. ::-webkit-scrollbar-thumb { background: #475569; border-radius: 6px; }
  452.  
  453. @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
  454. @keyframes pulse { 0% { opacity: 0.5; } 50% { opacity: 1; } 100% { opacity: 0.5; } }
  455.  
  456. .loading-spinner { width: 14px; height: 14px; border: 2px solid rgba(255,255,255,0.3); border-top-color: #fff; border-radius: 50%; animation: spin 1s linear infinite; flex-shrink: 0; }
  457. .btn-content { display: flex; align-items: center; justify-content: center; gap: 6px; }
  458. .status-pulsing { animation: pulse 2s ease-in-out infinite; color: #3b82f6 !important; font-weight: 600; }
  459.  
  460. #xai-pro-app { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: 9999999; background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%); font-family: 'Inter', -apple-system, sans-serif; color: #e2e8f0; display: flex; gap: 10px; padding: 10px; box-sizing: border-box; }
  461. #xai-pro-app * { box-sizing: border-box; }
  462.  
  463. .panel { background: #1e293b; border-radius: 10px; border: 1px solid #334155; box-shadow: 0 4px 15px rgba(0,0,0,0.4); display: flex; flex-direction: column; overflow: hidden; }
  464. .panel-title { font-size: 11px; font-weight: 700; color: #94a3b8; letter-spacing: 0.5px; padding: 10px; border-bottom: 1px solid #334155; text-transform: uppercase; }
  465.  
  466. .col-left { width: 310px; display: flex; flex-direction: column; gap: 10px; flex-shrink: 0; }
  467. .col-center { flex: 1; display: flex; flex-direction: column; gap: 10px; min-width: 0; min-height: 0; }
  468. .col-right { width: 310px; display: flex; flex-direction: column; gap: 10px; flex-shrink: 0; transition: 0.2s; }
  469. .col-right.drag-over { background: #064e3b; border-color: #10b981; box-shadow: 0 0 0 4px rgba(16,185,129,0.15); border-radius: 10px; }
  470.  
  471. textarea, select, input[type="text"], input[type="number"], input[type="checkbox"] { background: #0f172a; border: 1px solid #334155; border-radius: 6px; padding: 8px; color: #f8fafc; font-size: 13px; outline: none; transition: 0.2s; color-scheme: dark; }
  472. textarea, select, input[type="text"], input[type="number"] { width: 100%; }
  473. textarea:focus, select:focus, input[type="text"]:focus, input[type="number"]:focus { border-color: #64748b; background: #1e293b; box-shadow: 0 0 0 2px rgba(100,116,139,0.2); }
  474. label { font-size: 11px; font-weight: 600; color: #94a3b8; margin-bottom: 4px; display: block; }
  475.  
  476. .btn-primary { background: linear-gradient(180deg, #6366f1 0%, #4f46e5 100%); color: #fff; border: none; border-radius: 6px; padding: 8px 14px; font-size: 13px; font-weight: 600; cursor: pointer; transition: 0.2s; box-shadow: 0 2px 4px rgba(0,0,0,0.3); display: flex; justify-content: center; align-items: center; }
  477. .btn-primary:hover:not(:disabled) { background: linear-gradient(180deg, #4f46e5 0%, #4338ca 100%); transform: translateY(-1px); }
  478. .btn-primary:disabled { opacity: 0.8; cursor: not-allowed; }
  479. .btn-secondary { background: #1e293b; color: #cbd5e1; border: 1px solid #475569; border-radius: 6px; padding: 8px 14px; font-size: 13px; font-weight: 600; cursor: pointer; transition: 0.2s; display: flex; justify-content: center; align-items: center; }
  480. .btn-secondary:hover:not(:disabled) { background: #334155; border-color: #64748b; }
  481.  
  482. .action-select { width: 100%; font-weight: 600; font-size: 13px; color: #f8fafc; background: transparent; border: none; outline: none; overflow-y: hidden; }
  483. .action-select option { padding: 8px 10px; margin-bottom: 4px; border-radius: 6px; cursor: pointer; transition: 0.1s; background: #0f172a; border: 1px solid #334155; }
  484. .action-select option:checked { background: linear-gradient(180deg, #6366f1 0%, #4f46e5 100%); border-color: #4f46e5; color: #fff; box-shadow: 0 2px 4px rgba(0,0,0,0.3); }
  485. .action-select option:hover:not(:checked) { background: #334155; }
  486.  
  487. .slider-block { display: flex; flex-direction: column; margin-bottom: 12px; }
  488. .toggle-btn { background: #0f172a; border: 1px solid #334155; color: #94a3b8; padding: 6px 12px; border-radius: 6px; font-size: 11px; font-weight: 600; cursor: pointer; transition: 0.2s; box-shadow: inset 0 2px 4px rgba(0,0,0,0.2); }
  489. .toggle-btn.active { background: linear-gradient(180deg, #10b981 0%, #059669 100%); color: #fff; border-color: #047857; box-shadow: 0 2px 4px rgba(0,0,0,0.3); }
  490. .slider-header { display: flex; justify-content: space-between; font-size: 11px; margin-bottom: 6px; font-weight: 600; color: #94a3b8; }
  491. .slider-header span { color: #f8fafc; }
  492. .slider-ticks { position: relative; height: 14px; width: 100%; font-size: 10px; color: #64748b; margin-top: 4px; padding: 0; }
  493. .slider-ticks span { position: absolute; transform: translateX(-50%); text-align: center; white-space: nowrap; line-height: 1; }
  494.  
  495. input[type=range] { -webkit-appearance: none; width: 100%; background: transparent; margin: 4px 0; outline: none; transform: scaleY(1.6); }
  496. input[type=range]::-webkit-slider-runnable-track { width: 100%; height: 6px; cursor: pointer; background: #334155; border-radius: 3px; box-shadow: inset 0 1px 3px rgba(0,0,0,0.6); }
  497. input[type=range]::-moz-range-track { width: 100%; height: 6px; cursor: pointer; background: #334155; border-radius: 3px; box-shadow: inset 0 1px 3px rgba(0,0,0,0.6); }
  498. input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; height: 16px; width: 16px; border-radius: 50%; background: #10b981; cursor: pointer; margin-top: -5px; box-shadow: 0 2px 5px rgba(0,0,0,0.6); }
  499. input[type=range]::-moz-range-thumb { height: 16px; width: 16px; border-radius: 50%; background: #10b981; cursor: pointer; border: none; box-shadow: 0 2px 5px rgba(0,0,0,0.6); }
  500. input[type=range]:focus::-webkit-slider-thumb { box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.4); }
  501. input[type=range]:focus::-moz-range-thumb { box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.4); }
  502.  
  503. .ar-select-box { background: #1e293b; border: 1px solid #475569; border-radius: 6px; padding: 8px; display: flex; align-items: center; gap: 8px; cursor: pointer; color: #f8fafc; font-size: 13px; }
  504. #ar-options-container { position: fixed; background: #1e293b; border: 1px solid #334155; border-radius: 6px; box-shadow: 0 10px 25px rgba(0,0,0,0.4); max-height: 265px; overflow-y: auto; display: none; z-index: 99999999; grid-template-columns: 1fr 1fr; }
  505. .ar-option { display: flex; align-items: center; gap: 8px; padding: 6px 8px; cursor: pointer; font-size: 12px; color: #cbd5e1; }
  506. .ar-option:hover { background: #334155; color: #f8fafc; }
  507.  
  508. .img-wrapper { position: relative; display: block; }
  509. .zoomable { cursor: zoom-in; transition: transform 0.2s; width: 100%; display: block; }
  510. .overlay-btn { position: absolute; top: 6px; background: rgba(15, 23, 42, 0.6); color: white; border-radius: 6px; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; text-decoration: none; backdrop-filter: blur(4px); transition: 0.2s; opacity: 0.75; z-index: 50; cursor: pointer; border: none; padding: 0; }
  511. .overlay-btn:hover { background: rgba(15, 23, 42, 0.9); opacity: 1; transform: scale(1.05); }
  512. .overlay-dl-btn { right: 6px; }
  513. .overlay-edit-btn { right: 40px; color: #10b981; }
  514. .overlay-extend-btn { right: 74px; color: #3b82f6; }
  515.  
  516. .ref-item { display: flex; align-items: center; gap: 10px; padding: 8px; background: #1e293b; border: 1px solid #334155; border-radius: 6px; margin-bottom: 6px; cursor: grab; box-shadow: 0 2px 4px rgba(0,0,0,0.2); transition: 0.1s; }
  517. .ref-item.inactive { opacity: 0.6; filter: grayscale(0.8); }
  518. .ref-item:active { cursor: grabbing; }
  519. .ref-item.dragging { opacity: 0.4; }
  520. .ref-handle { font-size: 14px; color: #475569; cursor: grab; padding: 0 4px; }
  521. .ref-thumb { width: 90px; height: 90px; border-radius: 4px; object-fit: cover; border: 1px solid #334155; background: #0f172a; transition: 0.2s; }
  522. .ref-info { flex: 1; display: flex; flex-direction: column; justify-content: center; gap: 6px; min-width: 0; }
  523. .ref-toggle-label { font-size: 11px; color: #cbd5e1; display: flex; align-items: center; gap: 4px; cursor: pointer; user-select: none; }
  524. .ref-toggle-label input { width: 12px; height: 12px; cursor: pointer; accent-color: #10b981; margin: 0; padding: 0; }
  525. .ref-btn-group { display: flex; gap: 4px; width: 100%; margin-top: auto; }
  526. .ref-action-btn { flex: 1; border-radius: 4px; padding: 4px 0; cursor: pointer; font-size: 10px; transition: 0.2s; font-weight: bold; text-align: center; }
  527. .ref-insert { background: #0f766e; color: #ccfbf1; border: 1px solid #115e59; }
  528. .ref-insert:hover { background: #115e59; color: #f0fdfa; }
  529. .ref-del { background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d; }
  530. .ref-del:hover { background: #7f1d1d; color: #fee2e2; }
  531. .drag-over-top { border-top: 2px solid #22c55e !important; }
  532. .drag-over-bottom { border-bottom: 2px solid #22c55e !important; }
  533.  
  534. .history-card { background: #0f172a; border: 1px solid #334155; border-radius: 6px; overflow: hidden; margin-bottom: 10px; }
  535. .history-card .overlay-btn { width: 24px; height: 24px; top: 4px; border-radius: 4px; }
  536. .history-card .overlay-dl-btn { right: 4px; }
  537. .history-card .overlay-edit-btn { right: 32px; }
  538. .history-card .overlay-extend-btn { right: 60px; }
  539. .history-card p { padding: 8px; margin: 0; font-size: 11px; color: #94a3b8; cursor: pointer; transition: 0.2s; }
  540. .history-card p:hover { background: #1e293b; color: #e2e8f0; }
  541.  
  542. .current-card { border-radius: 8px; overflow: hidden; box-shadow: 0 4px 10px rgba(0,0,0,0.3); border: 1px solid #334155; background: #1e293b; transition: all 0.3s ease; }
  543. .current-card.downloaded { border-color: #10b981 !important; box-shadow: 0 0 10px rgba(16,185,129,0.3) !important; }
  544. .current-card img, .current-card video { max-height: 50vh; object-fit: contain; background: #0f172a; }
  545.  
  546. .modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.8); z-index: 999999999; display: none; justify-content: center; align-items: center; backdrop-filter: blur(5px); }
  547. .modal-box { background: #1e293b; border-radius: 10px; width: 500px; max-width: 90vw; padding: 15px; display: flex; flex-direction: column; gap: 12px; box-shadow: 0 10px 40px rgba(0,0,0,0.5); border: 1px solid #334155; max-height: 90vh; overflow-y: auto; }
  548. .fav-item { display: flex; justify-content: space-between; align-items: center; background: #0f172a; padding: 8px; border-radius: 6px; border: 1px solid #334155; }
  549. .fav-text { flex: 1; font-size: 12px; color: #cbd5e1; cursor: pointer; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-right: 10px; transition: color 0.2s; }
  550. .fav-text:hover { color: #10b981; }
  551.  
  552. #settings-btn { position: fixed; top: 10px; right: 15px; font-size: 20px; cursor: pointer; z-index: 100; transition: transform 0.2s; opacity: 0.8;}
  553. #settings-btn:hover { transform: rotate(45deg); opacity: 1; }
  554. #logs-btn { position: fixed; top: 10px; right: 45px; font-size: 20px; cursor: pointer; z-index: 100; transition: transform 0.2s; opacity: 0.8;}
  555. #logs-btn:hover { transform: scale(1.15); opacity: 1; }
  556.  
  557. #xai-lightbox { cursor: zoom-out; }
  558. #xai-lightbox-wrapper { position: relative; display: inline-block; max-width: 95vw; max-height: 95vh; }
  559. #xai-lightbox-img { max-width: 100%; max-height: 95vh; display: block; border-radius: 8px; box-shadow: 0 10px 40px rgba(0,0,0,0.5); }
  560.  
  561. .prompt-container { position: relative; width: 100%; height: 100px; min-height: 70px; margin-bottom: 10px; resize: vertical; overflow: hidden; border: 1px solid #334155; border-radius: 6px; background: #0f172a; transition: 0.2s; box-sizing: border-box; font-family: 'Inter', -apple-system, sans-serif; }
  562. .prompt-container:focus-within { border-color: #64748b; background: #1e293b; box-shadow: 0 0 0 2px rgba(100,116,139,0.2); }
  563. .prompt-container.prompt-drag-over { border-color: #10b981 !important; background: #064e3b !important; box-shadow: 0 0 0 2px rgba(16,185,129,0.15) !important; }
  564. #prompt-backdrop { position: absolute; top: 0; left: 0; right: 0; bottom: 0; padding: 8px; font-size: 13px; font-family: inherit; white-space: pre-wrap; word-wrap: break-word; overflow-y: auto; color: transparent; z-index: 1; opacity: 0; box-sizing: border-box; pointer-events: none; }
  565. .prompt-tag { pointer-events: auto; }
  566. #xai-api-prompt { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 2; resize: none; background: transparent; border: none; box-shadow: none; outline: none; padding: 8px; font-size: 13px; font-family: inherit; color: #f8fafc; box-sizing: border-box; margin: 0; }
  567. #xai-api-prompt:focus { background: transparent; border: none; box-shadow: none; }
  568.  
  569. .warning-box { border-radius: 6px; padding: 6px 10px; font-size: 11px; margin-bottom: 8px; font-weight: 500; display: block; }
  570. .warning-red { background: #450a0a; color: #fca5a5; border: 1px solid #7f1d1d; }
  571. .warning-yellow { background: #422006; color: #fcd34d; border: 1px solid #78350f; }
  572. `;
  573.  
  574. const UI_HTML = `
  575. <div id="xai-pro-app">
  576. <div id="settings-btn" title="Studio Settings">⚙️</div>
  577. <div id="logs-btn" title="Debug Logs">🐛</div>
  578.  
  579. <!-- LEFT COLUMN -->
  580. <div class="col-left">
  581. <div class="panel" style="flex-shrink: 0;">
  582. <div style="display: flex; background: transparent; border-radius: 0 0 6px 6px; margin-bottom: 6px; padding: 10px; padding-bottom: 0;">
  583. <select id="master-action" size="4" class="action-select">
  584. <option value="gen_image" selected>🖼️ Generate Image</option>
  585. <option value="gen_video">🎥 Generate Video</option>
  586. <option value="edit_video">✂️ Edit Video</option>
  587. <option value="extend_video">➡️ Extend Video</option>
  588. </select>
  589. </div>
  590.  
  591. <div style="padding: 10px; display: flex; flex-direction: column; overflow-y: auto;">
  592. <div id="setting-ar" class="slider-block">
  593. <div class="slider-header"><label style="margin:0;">Aspect Ratio</label></div>
  594. <div class="ar-select-box" id="ar-select-box">
  595. <div id="ar-selected-icon"></div>
  596. <span id="ar-selected-text">Auto</span>
  597. </div>
  598. </div>
  599.  
  600. <div id="setting-high-res" class="slider-block" style="flex-direction: row; justify-content: space-between; align-items: center;">
  601. <div class="slider-header" style="margin-bottom:0;"><label style="margin:0;">High Resolution</label></div>
  602. <button id="high-res-btn" class="toggle-btn active">ON (2K / 720p)</button>
  603. </div>
  604.  
  605. <div id="setting-quality" class="slider-block" style="flex-direction: row; justify-content: space-between; align-items: center;">
  606. <div class="slider-header" style="margin-bottom:0;"><label style="margin:0;" title="Quality = grok-imagine-image-quality (better realism & text). Speed = grok-imagine-image">Quality Mode</label></div>
  607. <button id="quality-btn" class="toggle-btn">OFF (Speed)</button>
  608. </div>
  609.  
  610. <div id="setting-video-model" class="slider-block" style="flex-direction: row; justify-content: space-between; align-items: center; display: none;">
  611. <div class="slider-header" style="margin-bottom:0;"><label style="margin:0;" title="Classic = grok-imagine-video | 1.5 = grok-imagine-video-1.5 (better motion, 1080p when High Res ON)">Video Model</label></div>
  612. <button id="video-model-btn" class="toggle-btn">Classic</button>
  613. </div>
  614.  
  615. <div id="setting-batch" class="slider-block">
  616. <div class="slider-header"><label style="margin:0;">Batch Size</label> <span id="val-batch">1 Image</span></div>
  617. <input type="range" id="xai-api-n" min="0" max="6" value="0">
  618. <div class="slider-ticks" id="ticks-batch"></div>
  619. </div>
  620.  
  621. <div id="setting-duration" class="slider-block" style="display: none;">
  622. <div class="slider-header"><label style="margin:0;">Duration</label> <span id="val-duration">5 Seconds</span></div>
  623. <input type="range" id="xai-api-duration" min="0" max="14" value="4">
  624. <div class="slider-ticks" id="ticks-duration"></div>
  625. </div>
  626.  
  627. <div id="setting-loops" class="slider-block">
  628. <div class="slider-header" style="margin-bottom:0;"><label style="margin:0;" title="How many consecutive API calls to perform in a row">Loops</label></div>
  629. <div style="display: flex; gap: 10px; align-items: center; margin-top: 4px;">
  630. <input type="range" id="slider-loops" min="1" max="20" value="1" style="flex: 1; margin:0;">
  631. <input type="number" id="xai-api-loops" value="1" min="1" max="100" style="width: 50px; height: 26px; padding: 2px 4px; text-align: center; border-radius: 4px; border: 1px solid #334155; background: #1e293b; color: #f8fafc;">
  632. </div>
  633. </div>
  634. </div>
  635. </div>
  636.  
  637. <div class="panel" style="flex: 1; min-height: 0;">
  638. <div class="panel-title" style="display:flex; justify-content: space-between; align-items: center;">
  639. <span>Previous Results</span>
  640. <span id="xai-reset-btn" style="cursor: pointer; color: #ef4444; text-transform: none; text-decoration: underline;">Wipe Cache</span>
  641. </div>
  642. <div id="xai-history" style="flex: 1; overflow-y: auto; padding: 10px;">
  643. <div style="color: #94a3b8; font-size: 11px; text-align: center; margin-top: 20px;">No history yet.</div>
  644. </div>
  645. </div>
  646. </div>
  647.  
  648. <!-- CENTER COLUMN -->
  649. <div class="col-center">
  650. <div class="panel" style="flex: 1; background: transparent; border: none; box-shadow: none; min-height: 0;">
  651. <div class="panel-title" style="background: #1e293b; border-radius: 8px; border: 1px solid #334155; margin-bottom: 10px; flex-shrink: 0;">Current Generation</div>
  652. <div id="xai-current-images" style="flex: 1; overflow-y: auto; display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 10px; align-content: start; padding-bottom: 10px;"></div>
  653. </div>
  654.  
  655. <div class="panel" style="flex-shrink: 0; padding: 12px;">
  656. <label style="font-size: 13px; color: #e2e8f0; display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;">
  657. <span style="display: flex; align-items: center; gap: 8px;">
  658. <span>Prompt</span>
  659. <button id="fav-prompts-btn" class="btn-secondary" style="padding: 2px 8px; font-size: 10px; height: 22px;">⭐ Favorites</button>
  660. </span>
  661. <span style="font-size: 10px; font-weight: 400; color: #94a3b8;">(Drop image here for EXIF)</span>
  662. </label>
  663. <div id="warnings-container" style="display: flex; flex-direction: column; gap: 0px;"></div>
  664. <div class="prompt-container">
  665. <div id="prompt-backdrop"></div>
  666. <textarea id="xai-api-prompt" placeholder="Describe what you want to see... Supports Spintax {cat|dog} and @randomseed"></textarea>
  667. </div>
  668. <div style="display: flex; align-items: center; justify-content: space-between;">
  669. <div id="xai-api-status" style="font-size: 12px; color: #64748b; font-weight: 500;">Ready</div>
  670. <div style="display: flex; gap: 8px;">
  671. <button id="xai-preview-btn" class="btn-secondary">🔍 Payload</button>
  672. <button id="xai-cancel-btn" class="btn-secondary" style="display: none; color: #ef4444; border-color: #ef4444;">🛑 Cancel</button>
  673. <button id="xai-api-generate" class="btn-primary" style="width: 120px;"><div class="btn-content">Generate</div></button>
  674. </div>
  675. </div>
  676. </div>
  677. </div>
  678.  
  679. <!-- RIGHT COLUMN -->
  680. <div class="col-right" id="col-right-dropzone">
  681. <div class="panel" style="flex: 1; display: flex; flex-direction: column; min-height: 0;">
  682. <div class="panel-title" id="ref-panel-title">Reference Media</div>
  683. <div style="padding: 10px; flex: 1; display: flex; flex-direction: column; overflow: hidden;">
  684. <div id="xai-upload-placeholder" style="border: 2px dashed #475569; border-radius: 8px; width: 100%; padding: 15px 10px; color: #94a3b8; cursor: pointer; text-align: center; transition: 0.2s; margin-bottom: 10px; background: rgba(0,0,0,0.1);">
  685. <div style="font-size: 20px; margin-bottom: 4px;">📥</div>
  686. <div style="font-size: 12px; font-weight: 600;">Drag & Drop / Ctrl+V</div>
  687. </div>
  688. <input type="file" id="xai-api-file" accept="image/*, video/mp4, video/webm" multiple style="display: none;">
  689. <div style="font-size: 10px; color: #94a3b8; margin-bottom: 4px; text-transform: uppercase; font-weight: bold; flex-shrink: 0;">Upload Order (Top = First)</div>
  690. <div id="xai-ref-list" style="flex: 1; overflow-y: auto; padding-right: 4px;"></div>
  691. </div>
  692. </div>
  693. </div>
  694.  
  695. <div id="ar-options-container"></div>
  696.  
  697. <!-- MODALS -->
  698. <div id="xai-lightbox" class="modal-overlay">
  699. <div id="xai-lightbox-wrapper">
  700. <img id="xai-lightbox-img" src="">
  701. <a id="xai-lightbox-dl" href="#" download="" target="_blank" class="overlay-btn overlay-dl-btn" style="top: 15px; right: 15px; width: 44px; height: 44px; border-radius: 50%; background: rgba(0,0,0,0.7);" title="Download File">${DOWNLOAD_ICON}</a>
  702. </div>
  703. </div>
  704.  
  705. <div id="tag-preview-box" style="position: fixed; display: none; z-index: 99999999; background: #1e293b; border: 1px solid #334155; border-radius: 6px; padding: 4px; box-shadow: 0 4px 15px rgba(0,0,0,0.5); pointer-events: none;">
  706. <img id="tag-preview-img" style="max-width: 150px; max-height: 150px; border-radius: 4px; display: block; object-fit: cover;">
  707. </div>
  708.  
  709. <!-- LOGS MODAL -->
  710. <div id="xai-logs-modal" class="modal-overlay">
  711. <div class="modal-box" style="width: 800px; max-width: 95vw; height: 80vh;">
  712. <div style="display: flex; justify-content: space-between; align-items: center;">
  713. <h3 style="margin:0; font-size: 15px; color: #f8fafc;">🐛 Debug Logs</h3>
  714. <button id="close-logs-btn" style="background: #ef4444; color: #fff; border: none; border-radius: 6px; padding: 4px 8px; cursor: pointer; font-weight: bold; font-size: 11px;">Close</button>
  715. </div>
  716. <textarea id="logs-textarea" readonly style="flex: 1; width: 100%; background: #0f172a; color: #e2e8f0; font-family: monospace; font-size: 11px; border: 1px solid #334155; border-radius: 6px; padding: 10px; resize: none; white-space: pre;"></textarea>
  717. <div style="display: flex; gap: 8px;">
  718. <button id="copy-logs-btn" class="btn-primary" style="flex: 1;">📋 Copy Logs to Clipboard</button>
  719. <button id="clear-logs-btn" class="btn-secondary" style="flex: 1; color: #ef4444; border-color: #ef4444;">🗑️ Clear Logs</button>
  720. </div>
  721. </div>
  722. </div>
  723.  
  724. <!-- SETTINGS MODAL -->
  725. <div id="xai-settings-modal" class="modal-overlay">
  726. <div class="modal-box" style="width: 500px;">
  727. <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⚙️ Studio Settings</h3>
  728. <div style="display:flex; gap:10px;">
  729. <div style="flex:1;"><label>Max Retries</label><input type="number" id="set-retries" min="1" max="100"></div>
  730. <div style="flex:1;"><label>Delay Min (ms)</label><input type="number" id="set-delay-min" min="500" step="500"></div>
  731. <div style="flex:1;"><label>Delay Max (ms)</label><input type="number" id="set-delay-max" min="1000" step="500"></div>
  732. </div>
  733. <div><label>API Base URL (Leave empty for default console.x.ai)</label><input type="text" id="set-api-base-url" placeholder="e.g., https://api.proxy.com"></div>
  734. <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-notifications" style="width: 16px; height: 16px;"><label for="set-notifications" style="margin: 0; cursor: pointer;">Enable Notifications (Sound & Tab Blink)</label></div>
  735. <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-save-png" style="width: 16px; height: 16px;"><label for="set-save-png" style="margin: 0; cursor: pointer;">Save as Original PNG (Disable JPEG / EXIF Prompt)</label></div>
  736. <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-auto-download" style="width: 16px; height: 16px;"><label for="set-auto-download" style="margin: 0; cursor: pointer;">Auto-Download Generated Media</label></div>
  737. <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-anti-throttling" style="width: 16px; height: 16px;"><label for="set-anti-throttling" style="margin: 0; cursor: pointer;">Prevent Background Throttling (Plays silent audio)</label></div>
  738. <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-auto-retry-video" style="width: 16px; height: 16px;"><label for="set-auto-retry-video" style="margin: 0; cursor: pointer;">Auto-Retry Stuck Videos (Timeout / Moderated)</label></div>
  739. <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-break-loop-on-failure" style="width: 16px; height: 16px;"><label for="set-break-loop-on-failure" style="margin: 0; cursor: pointer;">Break loops if one iteration fails entirely.</label></div>
  740. <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-reference-ar-trick" style="width: 16px; height: 16px;"><label for="set-reference-ar-trick" style="margin: 0; cursor: pointer;">Single reference aspect ratio fix hack.</label></div>
  741. <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-maximum-greed-mode" style="width: 16px; height: 16px;"><label for="set-maximum-greed-mode" style="margin: 0; cursor: pointer;">MAXIUMUM GREED mode: reload tab on rate limit instead of waiting</label></div>
  742. <div style="display:flex; gap:10px; margin-top: 4px;">
  743. <div style="flex:1;"><label>Video Poll Timeout (s)</label><input type="number" id="set-video-timeout" min="10" step="10"></div>
  744. <div style="flex:1;"><label title="When 'Rate limit exceeded' occurs">Rate Limit Delay (s)</label><input type="number" id="set-rate-limit-delay" min="1" step="1"></div>
  745. <div style="flex:1;"><label>Base Font Size (px)</label><input type="number" id="set-font-size" min="10" max="24"></div>
  746. </div>
  747. <div style="border-top: 1px solid #334155; margin-top: 6px; padding-top: 6px;"></div>
  748. <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-suppress-warning" style="width: 16px; height: 16px;"><label for="set-suppress-warning" style="margin: 0; cursor: pointer; color: #fcd34d;">Suppress yellow ">8s video edit" warning</label></div>
  749. <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-video-autoplay" style="width: 16px; height: 16px;"><label for="set-video-autoplay" style="margin: 0; cursor: pointer;">Autoplay generated videos in gallery</label></div>
  750. <div style="display:flex; align-items:center; gap: 8px; margin-top: 4px;"><input type="checkbox" id="set-video-muted" style="width: 16px; height: 16px;"><label for="set-video-muted" style="margin: 0; cursor: pointer;">Start generated videos muted</label></div>
  751. <div style="border-top: 1px solid #334155; margin-top: 6px; padding-top: 6px;">
  752. <label>Custom CSS Overrides</label>
  753. <textarea id="set-custom-css" style="font-family: monospace; height: 60px; font-size: 11px;" placeholder="/* e.g., #xai-pro-app { background: red; } */"></textarea>
  754. </div>
  755. <div style="display: flex; gap: 8px; margin-top: 5px; border-top: 1px solid #334155; padding-top: 10px;">
  756. <button id="export-data-btn" class="btn-secondary" style="flex:1;">📤 Export Data</button>
  757. <button id="import-data-btn" class="btn-secondary" style="flex:1;">📥 Import Data</button>
  758. <input type="file" id="import-data-file" accept=".json" style="display: none;">
  759. </div>
  760. <div style="display: flex; gap: 8px; margin-top: 5px;">
  761. <button id="save-settings-btn" class="btn-primary" style="flex:1;">Save Settings</button>
  762. <button id="close-settings-btn" class="btn-secondary" style="flex:1;">Cancel</button>
  763. </div>
  764. </div>
  765. </div>
  766.  
  767. <!-- FAVORITES MODAL -->
  768. <div id="xai-fav-modal" class="modal-overlay">
  769. <div class="modal-box" style="width: 550px;">
  770. <div style="display: flex; justify-content: space-between; align-items: center;">
  771. <h3 style="margin:0; color: #f8fafc; font-size: 15px;">⭐ Favorite Prompts</h3>
  772. <button id="close-fav-btn" style="background: none; border: none; color: #ef4444; font-size: 20px; cursor: pointer; font-weight: bold; line-height: 1;">&times;</button>
  773. </div>
  774. <button id="add-current-fav-btn" class="btn-primary" style="background: linear-gradient(180deg, #10b981 0%, #059669 100%);">➕ Save Current Prompt to Favorites</button>
  775. <div id="fav-list" style="flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; padding-right: 4px;"></div>
  776. </div>
  777. </div>
  778.  
  779. <!-- PAYLOAD MODAL -->
  780. <div id="xai-payload-modal" class="modal-overlay">
  781. <div class="modal-box" style="width: 550px;">
  782. <div style="display: flex; justify-content: space-between; align-items: center;">
  783. <h3 style="margin:0; font-size: 15px; color: #f8fafc;">API Payload Debugger</h3>
  784. <button id="close-payload-btn" style="background: #ef4444; color: #fff; border: none; border-radius: 6px; padding: 4px 8px; cursor: pointer; font-weight: bold; font-size: 11px;">Close</button>
  785. </div>
  786. <div><label>Endpoint URL:</label><input type="text" id="payload-endpoint" style="font-family: monospace;" value="/v1/images/generations"></div>
  787. <div><label>JSON Payload (Editable):</label><textarea id="payload-code" style="background: #0f172a; color: #e2e8f0; padding: 10px; border-radius: 6px; font-family: monospace; font-size: 12px; height: 250px; resize: vertical; border: 1px solid #334155;"></textarea></div>
  788. <button id="send-custom-payload-btn" class="btn-primary" style="background: linear-gradient(180deg, #10b981 0%, #059669 100%);"><div class="btn-content">🚀 Send Custom Payload</div></button>
  789. <div id="custom-payload-status" style="font-size: 11px; color: #64748b; text-align: center;">Ready</div>
  790. </div>
  791. </div>
  792. </div>
  793. `;
  794.  
  795. // ─── DOM ELEMENT CACHE ───────────────────────────────────────────────────
  796. const els = {};
  797.  
  798. function initializeDOM() {
  799. Object.assign(els, {
  800. app: document.getElementById('xai-pro-app'),
  801. prompt: document.getElementById('xai-api-prompt'),
  802. promptBackdrop: document.getElementById('prompt-backdrop'),
  803. warningsContainer: document.getElementById('warnings-container'),
  804. promptContainer: document.querySelector('.prompt-container'),
  805. action: document.getElementById('master-action'),
  806. highResBtn: document.getElementById('high-res-btn'),
  807. qualityBtn: document.getElementById('quality-btn'),
  808. settingQuality: document.getElementById('setting-quality'),
  809. videoModelBtn: document.getElementById('video-model-btn'),
  810. settingVideoModel: document.getElementById('setting-video-model'),
  811. n: document.getElementById('xai-api-n'),
  812. duration: document.getElementById('xai-api-duration'),
  813. loopsSlider: document.getElementById('slider-loops'),
  814. loopsNum: document.getElementById('xai-api-loops'),
  815. settingAr: document.getElementById('setting-ar'),
  816. settingHighRes: document.getElementById('setting-high-res'),
  817. settingBatch: document.getElementById('setting-batch'),
  818. settingDuration: document.getElementById('setting-duration'),
  819. fileInput: document.getElementById('xai-api-file'),
  820. dropzone: document.getElementById('col-right-dropzone'),
  821. uploadPlaceholder: document.getElementById('xai-upload-placeholder'),
  822. refList: document.getElementById('xai-ref-list'),
  823. refTitle: document.getElementById('ref-panel-title'),
  824. btn: document.getElementById('xai-api-generate'),
  825. previewBtn: document.getElementById('xai-preview-btn'),
  826. cancelBtn: document.getElementById('xai-cancel-btn'),
  827. status: document.getElementById('xai-api-status'),
  828. history: document.getElementById('xai-history'),
  829. currentImages: document.getElementById('xai-current-images'),
  830. reset: document.getElementById('xai-reset-btn'),
  831. arSelectBox: document.getElementById('ar-select-box'),
  832. arOptionsCont: document.getElementById('ar-options-container'),
  833. arSelectedIcon: document.getElementById('ar-selected-icon'),
  834. arSelectedText: document.getElementById('ar-selected-text'),
  835. lightbox: document.getElementById('xai-lightbox'),
  836. lightboxImg: document.getElementById('xai-lightbox-img'),
  837. lightboxDl: document.getElementById('xai-lightbox-dl'),
  838. previewBox: document.getElementById('tag-preview-box'),
  839. previewImg: document.getElementById('tag-preview-img'),
  840. payloadModal: document.getElementById('xai-payload-modal'),
  841. payloadEndpoint: document.getElementById('payload-endpoint'),
  842. payloadCode: document.getElementById('payload-code'),
  843. closePayloadBtn: document.getElementById('close-payload-btn'),
  844. sendCustomBtn: document.getElementById('send-custom-payload-btn'),
  845. customStatus: document.getElementById('custom-payload-status'),
  846. settingsBtn: document.getElementById('settings-btn'),
  847. settingsModal: document.getElementById('xai-settings-modal'),
  848. closeSettingsBtn: document.getElementById('close-settings-btn'),
  849. saveSettingsBtn: document.getElementById('save-settings-btn'),
  850. exportDataBtn: document.getElementById('export-data-btn'),
  851. importDataBtn: document.getElementById('import-data-btn'),
  852. importDataFile: document.getElementById('import-data-file'),
  853. favBtn: document.getElementById('fav-prompts-btn'),
  854. favModal: document.getElementById('xai-fav-modal'),
  855. closeFavBtn: document.getElementById('close-fav-btn'),
  856. addFavBtn: document.getElementById('add-current-fav-btn'),
  857. favList: document.getElementById('fav-list'),
  858. logsBtn: document.getElementById('logs-btn'),
  859. logsModal: document.getElementById('xai-logs-modal'),
  860. closeLogsBtn: document.getElementById('close-logs-btn'),
  861. copyLogsBtn: document.getElementById('copy-logs-btn'),
  862. clearLogsBtn: document.getElementById('clear-logs-btn'),
  863. logsTextarea: document.getElementById('logs-textarea')
  864. });
  865. }
  866.  
  867. // ─── INITIALIZATION ───────────────────────────────────────────────────────
  868. let updateUIForEditMedia = null;
  869. let activeDurationMap = MAPS.durGen;
  870.  
  871. const initApp = () => {
  872. if (!document.body) return setTimeout(initApp, 50);
  873. const hideNode = (node) => {
  874. if (node.nodeType === 1 && node.id !== 'xai-pro-app' && !['SCRIPT', 'STYLE', 'LINK'].includes(node.tagName)) {
  875. node.style.display = 'none';
  876. }
  877. };
  878. Array.from(document.body.children).forEach(hideNode);
  879. new MutationObserver((mutations) => {
  880. mutations.forEach(m => m.addedNodes.forEach(hideNode));
  881. }).observe(document.body, { childList: true });
  882.  
  883. if (!document.getElementById('xai-pro-app')) {
  884. const style = document.createElement('style'); style.innerHTML = UI_CSS; document.head.appendChild(style);
  885. const customStyle = document.createElement('style'); customStyle.id = 'xai-custom-css-block'; customStyle.innerHTML = appSettings.customCSS; document.head.appendChild(customStyle);
  886. document.body.insertAdjacentHTML('beforeend', UI_HTML);
  887. updateFontSize(appSettings.uiFontSize);
  888. initializeDOM();
  889. bindLogic();
  890. }
  891. };
  892.  
  893. let referenceMedia =[];
  894. let currentAr = localStorage.getItem('xai_api_ar') || 'Auto';
  895. let fullPayloadMemory = {};
  896. let currentAbortController = null;
  897. let isRequestCancelled = false;
  898.  
  899. // ─── INDEXEDDB MANAGER ───────────────────────────────────────────────────
  900. const DB_NAME = 'xAIProStudioDB';
  901. const STORE_NAME = 'refsStore';
  902.  
  903. const DBManager = {
  904. init: function() {
  905. return new Promise((resolve, reject) => {
  906. const request = indexedDB.open(DB_NAME, 1);
  907. request.onupgradeneeded = (e) => {
  908. const db = e.target.result;
  909. if (!db.objectStoreNames.contains(STORE_NAME)) db.createObjectStore(STORE_NAME);
  910. };
  911. request.onsuccess = () => resolve(request.result);
  912. request.onerror = () => reject(request.error);
  913. });
  914. },
  915. setRefs: async function(data) {
  916. const db = await this.init();
  917. return new Promise((resolve, reject) => {
  918. const transaction = db.transaction([STORE_NAME], 'readwrite');
  919. const store = transaction.objectStore(STORE_NAME);
  920. const request = store.put(data, 'refs');
  921. request.onsuccess = () => resolve();
  922. request.onerror = () => reject(request.error);
  923. });
  924. },
  925. getRefs: async function() {
  926. const db = await this.init();
  927. return new Promise((resolve, reject) => {
  928. const transaction = db.transaction([STORE_NAME], 'readonly');
  929. const store = transaction.objectStore(STORE_NAME);
  930. const request = store.get('refs');
  931. request.onsuccess = () => resolve(request.result || null);
  932. request.onerror = () => reject(request.error);
  933. });
  934. }
  935. };
  936.  
  937. let saveRefsTimeout = null;
  938. function saveRefs(immediate = false) {
  939. const executeSave = async () => {
  940. try {
  941. const cleanRefs = referenceMedia.map(m => {
  942. const copy = { ...m };
  943. delete copy.blobUrl; // Do not save session-bound URLs
  944. return copy;
  945. });
  946. await DBManager.setRefs(cleanRefs);
  947. } catch(e) { addLog('ERROR', 'Failed to save refs to IDB', e); }
  948. };
  949.  
  950. if (saveRefsTimeout) clearTimeout(saveRefsTimeout);
  951. // Return the promise if immediate, so we can await it during critical reloads
  952. if (immediate) return executeSave();
  953. else saveRefsTimeout = setTimeout(executeSave, 400);
  954. }
  955.  
  956. function findMapIndex(arr, val) {
  957. let idx = arr.findIndex(item => (item.v || item).toString() === val.toString());
  958. return idx !== -1 ? idx : 0;
  959. }
  960.  
  961. function drawTicks(containerId, map, colorFn) {
  962. const cont = document.getElementById(containerId);
  963. if (!cont) return;
  964. cont.innerHTML = map.map((item, index) => {
  965. let val = item.v || item; let label = item.t || val;
  966. let color = colorFn ? colorFn(val) : '#64748b';
  967.  
  968. let percent = map.length > 1 ? (index / (map.length - 1)) * 100 : 50;
  969. let offset = 8 - (percent / 100) * 16;
  970.  
  971. return `<span style="color:${color}; left:calc(${percent}% + ${offset}px);">${label}</span>`;
  972. }).join('');
  973. }
  974.  
  975. function getDurationColor(val) {
  976. const v = parseInt(val);
  977. if (v <= 8) return '#f8fafc';
  978. if (v <= 10) return '#94a3b8';
  979. return '#ef4444';
  980. }
  981.  
  982. function syncSlider(sliderEl, textEl, mapArr, formatFn) {
  983. const val = mapArr[sliderEl.value];
  984. textEl.innerText = formatFn ? formatFn(val) : (val.l || val);
  985. }
  986.  
  987. // ─── SHARED UI HELPERS ───────────────────────────────────────────────────
  988.  
  989. let isHighRes = true; // Moved to global scope
  990. let isQuality = localStorage.getItem('xai_api_quality') === 'true';
  991. let isVideo15 = localStorage.getItem('xai_api_video15') === 'true';
  992.  
  993. let genSettingsTimeout = null;
  994. function updateGenSettingsMemory() {
  995. if (genSettingsTimeout) clearTimeout(genSettingsTimeout);
  996. genSettingsTimeout = setTimeout(() => {
  997. localStorage.setItem('xai_api_gen_settings', JSON.stringify({
  998. action: els.action.value, isHighRes: isHighRes, isQuality: isQuality, isVideo15: isVideo15,
  999. n: MAPS.batch[els.n.value], duration: activeDurationMap[els.duration.value], loops: els.loopsNum.value
  1000. }));
  1001. }, 300);
  1002. }
  1003.  
  1004. function updateWarnings() {
  1005. els.warningsContainer.innerHTML = ''; let html = '';
  1006. if (/--[a-zA-Z0-9_-]+=/.test(els.prompt.value)) html += `<div class="warning-box warning-red">⚠️ A gentle reminder that --parameter=value has never been shown to do anything at all, including --seed and --sid, but you do you!</div>`;
  1007. const action = els.action.value; const duration = activeDurationMap[els.duration.value] || 0; const activeRefs = referenceMedia.filter(m => m.active).length;
  1008. if (action === 'gen_video') {
  1009. if (typeof isVideo15 !== 'undefined' && isVideo15 && activeRefs > 1) {
  1010. html += `<div class="warning-box warning-yellow">⚠️ Video 1.5 uses only the first reference (image-to-video). Extra refs are ignored.</div>`;
  1011. }
  1012. if (activeRefs > 0 && duration > 10 && !(typeof isVideo15 !== 'undefined' && isVideo15)) {
  1013. const currentAr = localStorage.getItem('xai_api_ar');
  1014. if ( currentAr != 'Auto' && currentAr != 'By First Ref' ) {
  1015. html += `<div class="warning-box warning-red">⚠️ Warning: videos longer than 10 seconds seem to stretch the reference to the desired aspect ratio instead of properly resizing them. You might get better results with auto.</div>`;
  1016. }
  1017. if ( activeRefs > 1 ) {
  1018. html += `<div class="warning-box warning-red">⚠️ Warning: only the first reference is going to be used for videos longer than 10 seconds.</div>`;
  1019. }
  1020. }
  1021. if (duration > 8 && !appSettings.suppressEditWarning) html += `<div class="warning-box warning-yellow">⚠️ Note: edit won't work on videos longer than 8s like the one you are about to generate. You can suppress this warning in options.</div>`;
  1022. }
  1023. els.warningsContainer.innerHTML = html;
  1024. }
  1025.  
  1026. function syncPromptBackdrop() {
  1027. const val = els.prompt.value; updateWarnings();
  1028. let html = val.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  1029. const activeRefs = referenceMedia.filter(m => m.active);
  1030. html = html.replace(/&lt;IMAGE_(\d+)&gt;/g, (match, idxStr) => { const idx = parseInt(idxStr); return activeRefs[idx] ? `<span class="prompt-tag" data-idx="${idx}">${match}</span>` : match; });
  1031. els.promptBackdrop.innerHTML = html.replace(/\n/g, '<br>') + '<br>';
  1032. els.promptBackdrop.scrollTop = els.prompt.scrollTop; els.promptBackdrop.scrollLeft = els.prompt.scrollLeft;
  1033. }
  1034.  
  1035. function setPromptVal(val) {
  1036. els.prompt.focus();
  1037. els.prompt.setSelectionRange(0, els.prompt.value.length);
  1038. document.execCommand('insertText', false, val);
  1039. localStorage.setItem('xai_api_prompt', val);
  1040. syncPromptBackdrop();
  1041. }
  1042.  
  1043. // ─── MODALS & AUXILIARY UI SETUP ─────────────────────────────────────────
  1044. function renderFavList() {
  1045. els.favList.innerHTML = '';
  1046. if (favoritePrompts.length === 0) { els.favList.innerHTML = '<div style="color: #64748b; font-size: 12px; text-align: center; margin-top: 15px;">No favorite prompts yet.</div>'; return; }
  1047. favoritePrompts.forEach((promptText, idx) => {
  1048. const div = document.createElement('div'); div.className = 'fav-item'; div.innerHTML = `<div class="fav-text" title="${promptText.replace(/"/g, '&quot;')}">${promptText}</div><button class="btn-secondary" style="padding: 2px 6px; font-size: 10px; border-color: #ef4444; color: #ef4444;">Del</button>`;
  1049. div.querySelector('.fav-text').addEventListener('click', () => { setPromptVal(promptText); els.favModal.style.display = 'none'; });
  1050. div.querySelector('button').addEventListener('click', () => { favoritePrompts.splice(idx, 1); localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts)); renderFavList(); });
  1051. els.favList.appendChild(div);
  1052. });
  1053. }
  1054.  
  1055. function setupModalsAndAuxUI() {
  1056. // --- Logs Modal ---
  1057. els.logsBtn.addEventListener('click', () => { els.logsTextarea.value = formatLogsForExport(); els.logsModal.style.display = 'flex'; els.logsTextarea.scrollTop = els.logsTextarea.scrollHeight; });
  1058. els.closeLogsBtn.addEventListener('click', () => els.logsModal.style.display = 'none');
  1059. els.copyLogsBtn.addEventListener('click', () => { els.logsTextarea.select(); document.execCommand('copy'); alert('Logs copied to clipboard!'); });
  1060. els.clearLogsBtn.addEventListener('click', () => { if (confirm("Clear all logs?")) { appLogs.length = 0; els.logsTextarea.value = ''; } });
  1061.  
  1062. // --- Settings Modal (from Block 1) ---
  1063. els.settingsBtn.addEventListener('click', () => { SettingsManager.populateUI(appSettings); els.settingsModal.style.display = 'flex'; });
  1064. els.saveSettingsBtn.addEventListener('click', () => { appSettings = SettingsManager.saveFromUI(); document.getElementById('xai-custom-css-block').innerHTML = appSettings.customCSS; updateFontSize(appSettings.uiFontSize); updateWarnings(); els.settingsModal.style.display = 'none'; });
  1065. els.closeSettingsBtn.addEventListener('click', () => els.settingsModal.style.display = 'none');
  1066.  
  1067. // --- Export / Import ---
  1068. els.exportDataBtn.addEventListener('click', () => {
  1069. const blob = new Blob([JSON.stringify({settings: appSettings, refs: referenceMedia}, null, 2)], { type: 'application/json' });
  1070. const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `xAI_Pro_Studio_Backup_${makeTimestamp()}.json`; a.click(); URL.revokeObjectURL(url);
  1071. });
  1072. els.importDataBtn.addEventListener('click', () => els.importDataFile.click());
  1073. els.importDataFile.addEventListener('change', (e) => {
  1074. const file = e.target.files[0]; if (!file) return; const reader = new FileReader();
  1075. reader.onload = async (evt) => {
  1076. try {
  1077. const parsed = JSON.parse(evt.target.result);
  1078. if (parsed.settings) { appSettings = { ...appSettings, ...parsed.settings }; localStorage.setItem('xai_api_settings', JSON.stringify(appSettings)); }
  1079. if (parsed.refs && Array.isArray(parsed.refs)) {
  1080. referenceMedia = parsed.refs;
  1081. await saveRefs(true);
  1082. }
  1083. alert("Import successful! Page will reload."); location.reload();
  1084. } catch(err) { alert("Failed to parse the JSON file."); }
  1085. }; reader.readAsText(file); e.target.value = '';
  1086. });
  1087.  
  1088. // --- Favorites Modal ---
  1089. els.favBtn.addEventListener('click', () => { renderFavList(); els.favModal.style.display = 'flex'; });
  1090. els.closeFavBtn.addEventListener('click', () => els.favModal.style.display = 'none');
  1091. els.addFavBtn.addEventListener('click', () => {
  1092. const p = els.prompt.value.trim(); if (!p) return alert("Prompt is empty!"); if (favoritePrompts.includes(p)) return alert("Already in favorites!");
  1093. favoritePrompts.unshift(p); localStorage.setItem('xai_api_favs', JSON.stringify(favoritePrompts)); renderFavList();
  1094. });
  1095.  
  1096. // --- Lightbox & Global Esc Key ---
  1097. els.app.addEventListener('click', (e) => {
  1098. if (e.target && e.target.classList.contains('zoomable') && e.target.tagName === 'IMG') {
  1099. els.lightboxImg.src = e.target.src; els.lightboxDl.href = e.target.src; els.lightboxDl.download = e.target.dataset.filename || 'Reference_Image.jpg'; els.lightbox.style.display = 'flex';
  1100. els.lightboxDl.onclick = () => { if(e.target.closest('.current-card')) e.target.closest('.current-card').classList.add('downloaded'); };
  1101. }
  1102. });
  1103. els.lightbox.addEventListener('click', (e) => { if (!e.target.closest('#xai-lightbox-dl') && !e.target.closest('.modal-box')) els.lightbox.style.display = 'none'; });
  1104. document.addEventListener('keydown', (e) => { if(e.key === 'Escape') Array.from(document.querySelectorAll('.modal-overlay')).forEach(m => m.style.display = 'none'); });
  1105. }
  1106.  
  1107. // ─── PROMPT & ASPECT RATIO SETUP ─────────────────────────────────────────
  1108. function setupPromptListeners() {
  1109. if (localStorage.getItem('xai_api_prompt')) setPromptVal(localStorage.getItem('xai_api_prompt'));
  1110. let promptSaveTimeout = null;
  1111. els.prompt.addEventListener('input', () => {
  1112. if (promptSaveTimeout) clearTimeout(promptSaveTimeout);
  1113. promptSaveTimeout = setTimeout(() => localStorage.setItem('xai_api_prompt', els.prompt.value), 400);
  1114. syncPromptBackdrop();
  1115. });
  1116. els.prompt.addEventListener('scroll', () => { els.promptBackdrop.scrollTop = els.prompt.scrollTop; els.promptBackdrop.scrollLeft = els.prompt.scrollLeft; });
  1117.  
  1118. let hidePreviewTimeout;
  1119. els.prompt.addEventListener('mousemove', (e) => {
  1120. if (e.buttons !== 0) { els.previewBox.style.display = 'none'; return; }
  1121. els.prompt.style.pointerEvents = 'none'; const el = document.elementFromPoint(e.clientX, e.clientY); els.prompt.style.pointerEvents = 'auto';
  1122. if (el && el.classList.contains('prompt-tag')) {
  1123. const idx = el.getAttribute('data-idx'); const media = referenceMedia.filter(m => m.active)[parseInt(idx)];
  1124. if (media) {
  1125. els.previewBox.style.display = 'block';
  1126. els.previewImg.src = media.thumb || media.blobUrl || media.base64;
  1127. let tx = e.clientX + 15; let ty = e.clientY + 15;
  1128. if (tx + 160 > window.innerWidth) tx = e.clientX - 165; if (ty + 160 > window.innerHeight) ty = e.clientY - 165;
  1129. els.previewBox.style.left = tx + 'px'; els.previewBox.style.top = ty + 'px';
  1130. clearTimeout(hidePreviewTimeout);
  1131. }
  1132. } else hidePreviewTimeout = setTimeout(() => els.previewBox.style.display = 'none', 50);
  1133. });
  1134. els.prompt.addEventListener('mouseleave', () => els.previewBox.style.display = 'none');
  1135.  
  1136. els.prompt.addEventListener('keydown', (e) => {
  1137. if (e.key === 'Enter' && !e.shiftKey) {
  1138. e.preventDefault();
  1139. if (!els.btn.disabled) {
  1140. els.btn.click();
  1141. }
  1142. }
  1143. });
  1144.  
  1145. els.prompt.addEventListener('dragover', (e) => { e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.add('prompt-drag-over'); });
  1146. els.prompt.addEventListener('dragleave', (e) => { e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.remove('prompt-drag-over'); });
  1147. els.prompt.addEventListener('drop', async (e) => {
  1148. e.preventDefault(); e.stopPropagation(); els.promptContainer.classList.remove('prompt-drag-over');
  1149. if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
  1150. const file = e.dataTransfer.files[0]; const oldVal = els.prompt.value; setPromptVal("Extracting prompt from EXIF...");
  1151. const extractedPrompt = await extractPromptFromImage(file);
  1152. if (extractedPrompt) setPromptVal(extractedPrompt); else { setPromptVal(oldVal); alert("No prompt found in this image's EXIF data."); }
  1153. }
  1154. });
  1155. }
  1156.  
  1157. function setupAspectRatioUI() {
  1158. function renderArOptions() {
  1159. els.arOptionsCont.innerHTML = '';
  1160. arData.forEach(ar => {
  1161. const opt = document.createElement('div'); opt.className = 'ar-option';
  1162. opt.innerHTML = `${createArIcon(ar.w, ar.h, ar.isAuto, ar.isRef)} <span>${ar.label}</span>`;
  1163. opt.addEventListener('click', () => { setAr(ar); els.arOptionsCont.style.display = 'none'; });
  1164. els.arOptionsCont.appendChild(opt);
  1165. });
  1166. }
  1167. function setAr(arObj) {
  1168. currentAr = arObj.label; localStorage.setItem('xai_api_ar', currentAr);
  1169. els.arSelectedIcon.innerHTML = createArIcon(arObj.w, arObj.h, arObj.isAuto, arObj.isRef); els.arSelectedText.innerText = arObj.label;
  1170. }
  1171. renderArOptions();
  1172. const initialAr = arData.find(a => a.label === currentAr) || arData[0];
  1173. setAr(initialAr);
  1174.  
  1175. els.arSelectBox.addEventListener('click', (e) => {
  1176. e.stopPropagation(); if (els.arOptionsCont.style.display === 'grid') { els.arOptionsCont.style.display = 'none'; return; }
  1177. const rect = els.arSelectBox.getBoundingClientRect(); els.arOptionsCont.style.top = (rect.bottom + 5) + 'px'; els.arOptionsCont.style.left = rect.left + 'px'; els.arOptionsCont.style.width = rect.width + 'px'; els.arOptionsCont.style.display = 'grid';
  1178. });
  1179. document.addEventListener('click', (e) => { if (!els.arOptionsCont.contains(e.target)) els.arOptionsCont.style.display = 'none'; });
  1180. }
  1181.  
  1182. // ─── MEDIA & ACTION UI SETUP ─────────────────────────────────────────────
  1183. function getMaxMedia() {
  1184. const val = els.action.value;
  1185. return val === 'gen_image' ? 5 : (val === 'gen_video' ? 7 : 1);
  1186. }
  1187.  
  1188. function updateActionUI() {
  1189. const val = els.action.value;
  1190. if (val === 'gen_image') {
  1191. els.settingAr.style.display = 'flex'; els.settingHighRes.style.display = 'flex'; els.settingQuality.style.display = 'flex';
  1192. if (els.settingVideoModel) els.settingVideoModel.style.display = 'none';
  1193. els.settingBatch.style.display = 'flex'; els.settingDuration.style.display = 'none';
  1194. updateHighResBtnLabel();
  1195. } else if (val === 'gen_video') {
  1196. els.settingAr.style.display = 'flex'; els.settingHighRes.style.display = 'flex'; els.settingQuality.style.display = 'none';
  1197. if (els.settingVideoModel) els.settingVideoModel.style.display = 'flex';
  1198. els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'flex';
  1199. activeDurationMap = MAPS.durGen; els.duration.max = activeDurationMap.length - 1;
  1200. drawTicks('ticks-duration', activeDurationMap, getDurationColor);
  1201. syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds');
  1202. updateHighResBtnLabel();
  1203. } else if (val === 'edit_video') {
  1204. els.settingAr.style.display = 'none'; els.settingHighRes.style.display = 'none'; els.settingQuality.style.display = 'none';
  1205. if (els.settingVideoModel) els.settingVideoModel.style.display = 'flex';
  1206. els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'none';
  1207. } else if (val === 'extend_video') {
  1208. els.settingAr.style.display = 'none'; els.settingHighRes.style.display = 'none'; els.settingQuality.style.display = 'none';
  1209. if (els.settingVideoModel) els.settingVideoModel.style.display = 'flex';
  1210. els.settingBatch.style.display = 'none'; els.settingDuration.style.display = 'flex';
  1211. activeDurationMap = MAPS.durExt; els.duration.max = activeDurationMap.length - 1;
  1212. drawTicks('ticks-duration', activeDurationMap, getDurationColor);
  1213. syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds');
  1214. }
  1215.  
  1216. const max = getMaxMedia(); els.refTitle.innerText = `Reference Media (Max Active: ${max})`;
  1217. let activeCount = 0;
  1218. referenceMedia.forEach(m => {
  1219. let valid = true;
  1220. if ((val === 'gen_image' || val === 'gen_video') && m.isVideo) valid = false;
  1221. if ((val === 'edit_video' || val === 'extend_video') && !m.isVideo) valid = false;
  1222. if (!valid) m.active = false; else if (m.active) { activeCount++; if (activeCount > max) m.active = false; }
  1223. });
  1224. renderRefList(); updateWarnings();
  1225. }
  1226.  
  1227. let draggedIndex = null;
  1228. function updateRefActiveStates() {
  1229. const actionVal = els.action.value;
  1230. const disableInsert = actionVal === 'edit_video' || actionVal === 'extend_video';
  1231. const activeRefs = referenceMedia.filter(m => m.active);
  1232. const refNodes = Array.from(els.refList.children);
  1233.  
  1234. referenceMedia.forEach((media, index) => {
  1235. const item = refNodes[index];
  1236. if (!item) return;
  1237.  
  1238. // Update grayscale/opacity
  1239. if (media.active) item.classList.remove('inactive');
  1240. else item.classList.add('inactive');
  1241.  
  1242. // Update Insert Button Text & Status
  1243. if (!media.isVideo) {
  1244. const insertBtn = item.querySelector('.ref-insert');
  1245. if (insertBtn) {
  1246. if (disableInsert) {
  1247. insertBtn.disabled = true; insertBtn.style.opacity = '0.4'; insertBtn.style.filter = 'grayscale(1)'; insertBtn.style.cursor = 'not-allowed'; insertBtn.title = "Not available in this mode"; insertBtn.innerHTML = `➕ &lt;IMAGE_X&gt;`;
  1248. } else if (!media.active) {
  1249. insertBtn.disabled = true; insertBtn.style.opacity = '0.4'; insertBtn.style.filter = 'none'; insertBtn.style.cursor = 'not-allowed'; insertBtn.title = "Check 'Use in Payload' first"; insertBtn.innerHTML = `➕ &lt;IMAGE_?&gt;`;
  1250. } else {
  1251. const dynamicIndex = activeRefs.indexOf(media);
  1252. insertBtn.disabled = false; insertBtn.style.opacity = '1'; insertBtn.style.filter = 'none'; insertBtn.style.cursor = 'pointer'; insertBtn.title = "Insert into prompt"; insertBtn.innerHTML = `➕ &lt;IMAGE_${dynamicIndex}&gt;`;
  1253. }
  1254. }
  1255. }
  1256. });
  1257. }
  1258. function renderRefList() {
  1259. els.refList.innerHTML = '';
  1260. referenceMedia.forEach((media, index) => {
  1261. const item = document.createElement('div'); item.className = 'ref-item'; item.draggable = true;
  1262. const activeRefs = referenceMedia.filter(m => m.active); const dynamicIndex = media.active ? activeRefs.indexOf(media) : '?';
  1263. const actionVal = els.action.value; const disableInsert = actionVal === 'edit_video' || actionVal === 'extend_video';
  1264.  
  1265. let thumbHtml = '';
  1266. if (media.isVideo) {
  1267. if (media.thumb) thumbHtml = `<div style="position: relative; width: 90px; height: 90px; flex-shrink: 0;"><img src="${media.thumb}" class="ref-thumb" style="width: 100%; height: 100%;" title="${media.fileName || 'Video'}"><div style="position: absolute; top: 4px; right: 4px; background: rgba(0,0,0,0.7); color: white; border-radius: 4px; padding: 2px 4px; font-size: 10px;">🎥</div></div>`;
  1268. else thumbHtml = `<div class="ref-thumb" style="display:flex; align-items:center; justify-content:center; flex-direction:column; background:#1e293b; color:#94a3b8; font-size:24px;" title="${media.fileName || 'Video'}">🎥<span style="font-size:9px; margin-top:4px; max-width:80px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">${media.fileName || 'Video'}</span></div>`;
  1269. } else thumbHtml = `<img src="${media.blobUrl || media.base64}" class="ref-thumb zoomable" data-filename="${media.fileName || 'Reference_'+(index+1)+'.jpg'}" title="${media.fileName || 'Click to view'}">`;
  1270.  
  1271. let insertBtnHtml = '';
  1272. if (!media.isVideo) {
  1273. if (disableInsert) insertBtnHtml = `<button class="ref-action-btn ref-insert" disabled style="opacity: 0.4; filter: grayscale(1); cursor: not-allowed;" title="Not available in this mode">➕ &lt;IMAGE_X&gt;</button>`;
  1274. else if (!media.active) insertBtnHtml = `<button class="ref-action-btn ref-insert" disabled style="opacity: 0.4; cursor: not-allowed;" title="Check 'Use in Payload' first">➕ &lt;IMAGE_?&gt;</button>`;
  1275. else insertBtnHtml = `<button class="ref-action-btn ref-insert" title="Insert into prompt">➕ &lt;IMAGE_${dynamicIndex}&gt;</button>`;
  1276. }
  1277.  
  1278. item.innerHTML = `<div class="ref-handle">☰</div>${thumbHtml}<div class="ref-info"><span style="font-size: 12px; color: #e2e8f0; font-weight: 600;">Ref ${index + 1} ${media.isVideo ? '(Video)' : ''}</span><label class="ref-toggle-label"><input type="checkbox" class="ref-active-toggle" ${media.active ? 'checked' : ''}> Use in Payload</label><div class="ref-btn-group">${insertBtnHtml}<button class="ref-action-btn ref-del">Remove</button></div></div>`;
  1279.  
  1280. const insertBtn = item.querySelector('.ref-insert');
  1281. if (insertBtn) {
  1282. insertBtn.addEventListener('click', (e) => {
  1283. if (!media.active || insertBtn.disabled) return;
  1284. const currentAction = els.action.value; if (currentAction === 'edit_video' || currentAction === 'extend_video') { e.preventDefault(); return alert("<IMAGE_X> tags not supported here."); }
  1285.  
  1286. const dynIdx = referenceMedia.filter(m => m.active).indexOf(media);
  1287. const promptEl = els.prompt; const tag = `<IMAGE_${dynIdx}>`; const startPos = promptEl.selectionStart; const endPos = promptEl.selectionEnd;
  1288.  
  1289. setPromptVal(promptEl.value.substring(0, startPos) + tag + promptEl.value.substring(endPos, promptEl.value.length));
  1290. promptEl.selectionStart = promptEl.selectionEnd = startPos + tag.length; promptEl.focus();
  1291. });
  1292. }
  1293. if (!media.active) item.classList.add('inactive');
  1294.  
  1295. item.querySelector('.ref-active-toggle').addEventListener('change', (e) => {
  1296. const max = getMaxMedia(); const currentlyActive = referenceMedia.filter(r => r.active).length;
  1297. if (e.target.checked && currentlyActive >= max) { alert(`Up to ${max} active references allowed.`); e.target.checked = false; return; }
  1298. media.active = e.target.checked;
  1299. saveRefs();
  1300. updateRefActiveStates();
  1301. syncPromptBackdrop();
  1302. updateWarnings();
  1303. });
  1304.  
  1305. item.addEventListener('dragstart', (e) => { draggedIndex = index; e.dataTransfer.effectAllowed = 'move'; setTimeout(() => item.classList.add('dragging'), 0); });
  1306. item.addEventListener('dragend', () => { item.classList.remove('dragging'); draggedIndex = null; document.querySelectorAll('.ref-item').forEach(el => el.classList.remove('drag-over-top', 'drag-over-bottom')); });
  1307. item.addEventListener('dragover', (e) => { e.preventDefault(); if (draggedIndex === null || draggedIndex === index) return; const rect = item.getBoundingClientRect(); if (e.clientY - rect.top < rect.height / 2) { item.classList.add('drag-over-top'); item.classList.remove('drag-over-bottom'); } else { item.classList.add('drag-over-bottom'); item.classList.remove('drag-over-top'); } });
  1308. item.addEventListener('dragleave', () => item.classList.remove('drag-over-top', 'drag-over-bottom'));
  1309. item.addEventListener('drop', (e) => { e.preventDefault(); item.classList.remove('drag-over-top', 'drag-over-bottom'); if (draggedIndex === null || draggedIndex === index) return; const rect = item.getBoundingClientRect(); let insertIndex = (e.clientY - rect.top) < rect.height / 2 ? index : index + 1; if (draggedIndex < insertIndex) insertIndex--; const [movedImage] = referenceMedia.splice(draggedIndex, 1); referenceMedia.splice(insertIndex, 0, movedImage); renderRefList(); syncPromptBackdrop(); });
  1310. item.querySelector('.ref-del').addEventListener('click', () => {
  1311. const removed = referenceMedia.splice(index, 1)[0];
  1312. if (removed && removed.blobUrl) URL.revokeObjectURL(removed.blobUrl);
  1313. renderRefList(); syncPromptBackdrop(); updateWarnings();
  1314. });
  1315. els.refList.appendChild(item);
  1316. });
  1317. saveRefs();
  1318. }
  1319.  
  1320. async function processFile(file) {
  1321. const isVid = file.type.startsWith('video/'); const isImg = file.type.startsWith('image/');
  1322. if (!isVid && !isImg) return;
  1323. if (isVid && (els.action.value === 'gen_image' || els.action.value === 'gen_video')) { els.action.value = 'edit_video'; updateActionUI(); updateGenSettingsMemory(); }
  1324. else if (isImg && (els.action.value === 'edit_video' || els.action.value === 'extend_video')) { els.action.value = 'gen_image'; updateActionUI(); updateGenSettingsMemory(); }
  1325.  
  1326. const max = getMaxMedia(); const activeCount = referenceMedia.filter(m => m.active).length;
  1327. let thumbBase64 = null; if (isVid) thumbBase64 = await generateVideoThumbnail(file);
  1328.  
  1329. const blobUrl = URL.createObjectURL(file);
  1330. const reader = new FileReader();
  1331. reader.onload = async (event) => {
  1332. const b64 = event.target.result;
  1333. let w = 0, h = 0;
  1334. if (isVid && file._w && file._h) { w = file._w; h = file._h; }
  1335. else if (isImg) {
  1336. try {
  1337. const dims = await new Promise(r => { const i = new Image(); i.onload = () => r({w: i.width, h: i.height}); i.onerror = () => r({w: 0, h: 0}); i.src = blobUrl; });
  1338. w = dims.w; h = dims.h;
  1339. } catch(e) {}
  1340. }
  1341. referenceMedia.push({ id: Date.now() + Math.random(), base64: b64, blobUrl: blobUrl, isVideo: isVid, active: activeCount < max, thumb: thumbBase64, fileName: file.name, w, h });
  1342. renderRefList();
  1343. };
  1344. reader.readAsDataURL(file);
  1345. }
  1346.  
  1347. function setupMediaAndActionUI() {
  1348. drawTicks('ticks-batch', MAPS.batch);
  1349.  
  1350. (async () => {
  1351. try {
  1352. let storedRefs = await DBManager.getRefs();
  1353.  
  1354. // One-time migration from old localStorage to IndexedDB
  1355. if (!storedRefs) {
  1356. const legacyRefs = localStorage.getItem('xai_api_refs');
  1357. if (legacyRefs) {
  1358. storedRefs = JSON.parse(legacyRefs);
  1359. localStorage.removeItem('xai_api_refs'); // Clean up the bloat!
  1360. }
  1361. }
  1362.  
  1363. if (Array.isArray(storedRefs)) {
  1364. referenceMedia = storedRefs;
  1365. referenceMedia.forEach(m => {
  1366. if (m.base64) m.blobUrl = base64ToBlobUrl(m.base64);
  1367. });
  1368. // Refresh the UI now that data has arrived
  1369. updateActionUI();
  1370. renderRefList();
  1371. }
  1372. } catch(e) {}
  1373. })();
  1374.  
  1375. function updateHighResBtnLabel() {
  1376. if (!els.highResBtn) return;
  1377. const action = els.action ? els.action.value : 'gen_image';
  1378. els.highResBtn.className = isHighRes ? 'toggle-btn active' : 'toggle-btn';
  1379. if (action === 'gen_image') {
  1380. els.highResBtn.innerText = isHighRes ? 'ON (2K)' : 'OFF (1K)';
  1381. } else {
  1382. // Video: 480 / 720 / 1080 (1080 only meaningful with Video 1.5)
  1383. if (!isHighRes) els.highResBtn.innerText = '480p';
  1384. else if (isVideo15) els.highResBtn.innerText = 'ON (1080p)';
  1385. else els.highResBtn.innerText = 'ON (720p)';
  1386. }
  1387. }
  1388. function updateVideoModelBtn() {
  1389. if (!els.videoModelBtn) return;
  1390. els.videoModelBtn.className = isVideo15 ? 'toggle-btn active' : 'toggle-btn';
  1391. els.videoModelBtn.innerText = isVideo15 ? '1.5' : 'Classic';
  1392. }
  1393. els.highResBtn.addEventListener('click', () => {
  1394. isHighRes = !isHighRes;
  1395. updateHighResBtnLabel();
  1396. updateGenSettingsMemory();
  1397. });
  1398. function updateQualityBtn() {
  1399. if (!els.qualityBtn) return;
  1400. els.qualityBtn.className = isQuality ? 'toggle-btn active' : 'toggle-btn';
  1401. els.qualityBtn.innerText = isQuality ? 'ON (Quality)' : 'OFF (Speed)';
  1402. }
  1403. updateQualityBtn();
  1404. updateVideoModelBtn();
  1405. updateHighResBtnLabel();
  1406. if (els.qualityBtn) {
  1407. els.qualityBtn.addEventListener('click', () => {
  1408. isQuality = !isQuality;
  1409. localStorage.setItem('xai_api_quality', isQuality);
  1410. updateQualityBtn();
  1411. updateGenSettingsMemory();
  1412. });
  1413. }
  1414. if (els.videoModelBtn) {
  1415. els.videoModelBtn.addEventListener('click', () => {
  1416. isVideo15 = !isVideo15;
  1417. localStorage.setItem('xai_api_video15', isVideo15);
  1418. updateVideoModelBtn();
  1419. updateHighResBtnLabel();
  1420. updateGenSettingsMemory();
  1421. });
  1422. }
  1423. els.n.addEventListener('input', () => { syncSlider(els.n, document.getElementById('val-batch'), MAPS.batch, v => v + (v===1?' Image':' Images')); updateGenSettingsMemory(); });
  1424. els.duration.addEventListener('input', () => { syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds'); updateGenSettingsMemory(); updateWarnings(); });
  1425. els.loopsSlider.addEventListener('input', e => { els.loopsNum.value = e.target.value; updateGenSettingsMemory(); });
  1426. els.loopsNum.addEventListener('input', e => { let v = parseInt(e.target.value) || 1; els.loopsSlider.value = Math.min(v, 20); updateGenSettingsMemory(); });
  1427.  
  1428. els.action.addEventListener('change', () => { updateActionUI(); updateGenSettingsMemory(); });
  1429.  
  1430. try {
  1431. const storedGen = JSON.parse(localStorage.getItem('xai_api_gen_settings') || '{}');
  1432. if (storedGen.action) els.action.value = storedGen.action;
  1433. updateActionUI();
  1434.  
  1435. if (typeof storedGen.isHighRes !== 'undefined') isHighRes = storedGen.isHighRes;
  1436. else if (storedGen.resImg === '1k' || storedGen.resVid === '480p') isHighRes = false;
  1437. if (typeof storedGen.isQuality !== 'undefined') isQuality = !!storedGen.isQuality;
  1438. if (typeof storedGen.isVideo15 !== 'undefined') isVideo15 = !!storedGen.isVideo15;
  1439.  
  1440. updateQualityBtn();
  1441. updateVideoModelBtn();
  1442. updateHighResBtnLabel();
  1443.  
  1444. if (storedGen.n) els.n.value = findMapIndex(MAPS.batch, storedGen.n);
  1445.  
  1446. if (storedGen.duration) { let idx = activeDurationMap.indexOf(parseInt(storedGen.duration)); els.duration.value = idx !== -1 ? idx : 0; }
  1447. if (storedGen.loops) { els.loopsNum.value = storedGen.loops; els.loopsSlider.value = Math.min(storedGen.loops, 20); }
  1448.  
  1449. syncSlider(els.n, document.getElementById('val-batch'), MAPS.batch, v => v + (v===1?' Image':' Images'));
  1450. syncSlider(els.duration, document.getElementById('val-duration'), activeDurationMap, v => v + ' Seconds');
  1451. } catch(e) {}
  1452.  
  1453. updateUIForEditMedia = (mediaUrl, isVideo, fileName, actionOverride) => {
  1454. referenceMedia.forEach(m => m.active = false);
  1455. const blobUrl = base64ToBlobUrl(mediaUrl);
  1456. referenceMedia.unshift({ id: Date.now() + Math.random(), base64: mediaUrl, blobUrl: blobUrl, isVideo: isVideo, active: true, thumb: isVideo ? null : blobUrl, fileName: fileName || (isVideo ? 'Edited_Video.mp4' : 'Edited_Image.png'), w:0, h:0 });
  1457. };
  1458.  
  1459. els.uploadPlaceholder.addEventListener('click', () => { els.fileInput.click(); });
  1460. els.fileInput.addEventListener('change', (e) => { Array.from(e.target.files).forEach(processFile); els.fileInput.value = ''; });
  1461. document.addEventListener('paste', (e) => { if (e.target && (e.target.id === 'payload-code' || e.target.id === 'xai-api-prompt' || e.target.id === 'set-custom-css' || e.target.tagName === 'INPUT' && e.target.type !== 'range')) return; const items = e.clipboardData.items; for (let i = 0; i < items.length; i++) if (items[i].type.indexOf('image') !== -1) processFile(items[i].getAsFile()); });
  1462. els.dropzone.addEventListener('dragover', (e) => { e.preventDefault(); els.dropzone.classList.add('drag-over'); });
  1463. els.dropzone.addEventListener('dragleave', () => els.dropzone.classList.remove('drag-over'));
  1464. els.dropzone.addEventListener('drop', (e) => { e.preventDefault(); els.dropzone.classList.remove('drag-over'); if (e.dataTransfer.files) Array.from(e.dataTransfer.files).forEach(processFile); });
  1465. }
  1466.  
  1467. // ─── GENERATION & API CORE LOGIC ─────────────────────────────────────────
  1468. function getMediaDimensions(base64, isVideo) {
  1469. return new Promise(resolve => {
  1470. if (isVideo) {
  1471. const vid = document.createElement('video'); vid.onloadedmetadata = () => resolve({w: vid.videoWidth, h: vid.videoHeight}); vid.onerror = () => resolve({w: 0, h: 0}); vid.src = base64;
  1472. } else {
  1473. const img = new Image(); img.onload = () => resolve({w: img.width, h: img.height}); img.onerror = () => resolve({w: 0, h: 0}); img.src = base64;
  1474. }
  1475. });
  1476. }
  1477.  
  1478. async function buildPayloadData(dynamicPromptText) {
  1479. const action = els.action.value;
  1480. let modelName = "grok-imagine-video";
  1481. if (action === 'gen_image') {
  1482. modelName = isQuality ? "grok-imagine-image-quality" : "grok-imagine-image";
  1483. } else {
  1484. // Video: Classic or 1.5
  1485. modelName = isVideo15 ? "grok-imagine-video-1.5" : "grok-imagine-video";
  1486. }
  1487. const payload = { model: modelName, prompt: dynamicPromptText };
  1488. let ar = currentAr.toLowerCase(); const activeRefs = referenceMedia.filter(m => m.active);
  1489.  
  1490. if (currentAr === 'By First Ref') {
  1491. if (activeRefs.length > 0) {
  1492. let ref = activeRefs[0];
  1493. if (!ref.w || !ref.h) { const dims = await getMediaDimensions(ref.base64, ref.isVideo); ref.w = dims.w; ref.h = dims.h; saveRefs(); }
  1494. if (ref.w && ref.h) {
  1495. const targetRatio = ref.w / ref.h; let bestMatch = '1:1'; let minDiff = Infinity;
  1496. arData.forEach(a => {
  1497. if (a.isAuto || a.isRef) return;
  1498. const r = a.w / a.h; const diff = Math.abs(r - targetRatio);
  1499. if (diff < minDiff) { minDiff = diff; bestMatch = a.label; }
  1500. });
  1501. ar = bestMatch.toLowerCase(); addLog('INFO', 'Calculated AR by First Ref', { targetRatio, selectedAr: ar });
  1502. } else ar = 'auto';
  1503. } else ar = 'auto';
  1504. }
  1505.  
  1506. if (action === 'gen_image') {
  1507. payload.n = MAPS.batch[els.n.value]; payload.resolution = isHighRes ? "2k" : "1k"; payload.response_format = "b64_json";
  1508. if (ar !== 'auto') payload.aspect_ratio = ar;
  1509. if (activeRefs.length > 0) {
  1510. if (activeRefs.length === 1) {
  1511. if (appSettings.referenceARTrick && ar != 'auto') payload.images = [{ type: "image_url", url: activeRefs[0].base64 }, { type: "image_url", url: activeRefs[0].base64 }];
  1512. else payload.image = { url: activeRefs[0].base64 };
  1513. }
  1514. else payload.images = activeRefs.map(m => ({ type: "image_url", url: m.base64 }));
  1515. }
  1516. } else if (action === 'gen_video') {
  1517. payload.duration = activeDurationMap[els.duration.value];
  1518. // Resolution: 480p / 720p / 1080p (1080p when Video 1.5 + High Res)
  1519. if (!isHighRes) payload.resolution = "480p";
  1520. else if (isVideo15) payload.resolution = "1080p";
  1521. else payload.resolution = "720p";
  1522. if (ar !== 'auto') payload.aspect_ratio = ar;
  1523. if (activeRefs.length > 0) {
  1524. if (isVideo15) {
  1525. // Video 1.5: only single image input (image-to-video), no reference_images
  1526. payload.image = { url: activeRefs[0].base64 };
  1527. } else if (payload.duration > 10) {
  1528. // Classic long video: only first ref as image
  1529. payload.image = { url: activeRefs[0].base64 };
  1530. } else {
  1531. // Classic short: multi-ref via reference_images
  1532. payload.reference_images = activeRefs.map(m => ({ url: m.base64 }));
  1533. }
  1534. }
  1535. } else if (action === 'edit_video') {
  1536. if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
  1537. } else if (action === 'extend_video') {
  1538. payload.duration = activeDurationMap[els.duration.value];
  1539. if (activeRefs.length > 0) payload.video = { url: activeRefs[0].base64 };
  1540. }
  1541. return payload;
  1542. }
  1543.  
  1544. function injectBase64(editedObj, originalObj) {
  1545. if (!editedObj || typeof editedObj !== 'object') return;
  1546. for (let key in editedObj) {
  1547. if (typeof editedObj[key] === 'string' && editedObj[key] === '[BASE64_TRUNCATED_FOR_PREVIEW]') { if (originalObj && originalObj[key]) editedObj[key] = originalObj[key]; }
  1548. else if (typeof editedObj[key] === 'object') injectBase64(editedObj[key], originalObj ? originalObj[key] : null);
  1549. }
  1550. }
  1551.  
  1552. async function executeGenerationSingle(endpoint, payload, isImageAction, statusEl, currentLoop, totalLoops) {
  1553. let loopPrefix = totalLoops > 1 ? `[Run ${currentLoop}/${totalLoops}] ` : ''; statusEl.innerText = `${loopPrefix}Processing request...`; statusEl.className = "status-pulsing";
  1554. addLog('INFO', `Starting generation loop ${currentLoop}/${totalLoops}`, { endpoint, isImageAction });
  1555. currentAbortController = new AbortController(); let attempts = 0; let success = false; let rateLimitFails = 0;
  1556.  
  1557. try {
  1558. while (attempts < appSettings.retries && !success && !isRequestCancelled) {
  1559. try {
  1560. statusEl.innerText = `${loopPrefix}Sending request to xAI...`;
  1561. const fullEndpoint = getApiUrl(endpoint);
  1562. addLog('NETWORK_REQ', `POST ${fullEndpoint}`, payload);
  1563. const response = await fetch(fullEndpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload), signal: currentAbortController.signal });
  1564.  
  1565. if (response.status === 503 || response.status === 500 || response.status === 502) { attempts++; statusEl.innerText = `${loopPrefix}Busy (Error ${response.status}). Retrying... [${attempts}/${appSettings.retries}]`; addLog('WARN', `Gateway error ${response.status}. Retrying.`); await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin); continue; }
  1566. if (response.status === 401 || response.status === 403) {
  1567. statusEl.innerText = `${loopPrefix}Session Expired (${response.status}). Requesting new cookies...`; statusEl.className = ""; statusEl.style.color = "#d97706";
  1568. await nuclearSessionReset(); await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin); continue;
  1569. }
  1570. if (!response.ok) {
  1571. let errMsg = `HTTP ${response.status}`; let errData = null;
  1572. try { errData = await response.json(); addLog('NETWORK_ERR', `Response error JSON`, { status: response.status, data: errData });
  1573. if (errData.error && errData.error.message) errMsg += `\n${errData.error.message}`; else if (errData.error && typeof errData.error === 'string') errMsg += `\n${errData.error}`;
  1574. if (errData.code) errMsg += `\nCode: ${errData.code}`; if (errData.detail) errMsg += `\n${typeof errData.detail === 'string' ? errData.detail : JSON.stringify(errData.detail)}`;
  1575. } catch(e) { addLog('NETWORK_ERR', `Failed to parse error response`, { status: response.status }); }
  1576. throw new Error(errMsg);
  1577. }
  1578.  
  1579. const data = await response.json(); addLog('NETWORK_RES', `Successful response`, data);
  1580.  
  1581. if (isImageAction) {
  1582. if (data && data.data && Array.isArray(data.data)) {
  1583. success = true; statusEl.innerText = `${loopPrefix}Processing final images...`; statusEl.style.color = "#10b981"; statusEl.className = "";
  1584. await Promise.all(data.data.map((imgObj, index) => processAndRenderImage(imgObj, payload.prompt, index + 1, data.data.length, els.currentImages)));
  1585. statusEl.innerText = "Ready"; statusEl.style.color = "#64748b";
  1586. } else throw new Error("Invalid response format.");
  1587. } else {
  1588. const reqId = data.request_id; if (!reqId) throw new Error(data.error ? (data.error.message || JSON.stringify(data.error)) : "No Request ID returned.");
  1589. let videoReady = false; let pollCount = 0; const MAX_POLLS = Math.max(1, Math.ceil(appSettings.videoPollTimeout / 5));
  1590. while (!videoReady && !isRequestCancelled) {
  1591. pollCount++; if (pollCount > MAX_POLLS) throw new Error("Timeout: Video likely dropped by filters or stuck in queue."); await sleep(5000); if (isRequestCancelled) break;
  1592. addLog('POLL_REQ', `Polling video ID: ${reqId}`, { pollCount, MAX_POLLS });
  1593. const pollRes = await fetch(getApiUrl(`/v1/videos/${reqId}`), { signal: currentAbortController.signal });
  1594. if (!pollRes.ok) {
  1595. if (pollRes.status === 401 || pollRes.status === 403) {
  1596. addLog('POLL_WARN', `Poll got 401/403. Cross-tab wipe likely. Restoring...`); statusEl.innerText = `${loopPrefix}Polling interrupted (401). Restoring session...`;
  1597. try { await fetch('https://console.x.ai/playground/imagine', { credentials: 'include', cache: 'no-store' }); } catch(e) {} await sleep(3000); continue;
  1598. }
  1599. if (pollRes.status >= 400 && pollRes.status < 500) {
  1600. let errData; try { errData = await pollRes.json(); } catch(e) {} addLog('POLL_ERR', `Poll failed HTTP ${pollRes.status}`, errData);
  1601. if (pollRes.status === 404) throw new Error("video lost (404). Session wiped by another tab.");
  1602. if (errData && errData.error) throw new Error(typeof errData.error.message === 'string' ? errData.error.message : JSON.stringify(errData.error));
  1603. }
  1604. continue;
  1605. }
  1606. const pollData = await pollRes.json(); addLog('POLL_RES', `Poll Result`, pollData);
  1607. if (pollData.error) throw new Error(`API Error: ${pollData.error.message || JSON.stringify(pollData.error)}`);
  1608. const state = (pollData.status || pollData.state || 'processing').toLowerCase(); let progressText = typeof pollData.progress === 'number' ? ` ${pollData.progress}%` : "";
  1609. statusEl.innerText = `${loopPrefix}Polling video (Status: ${state}${progressText})...[${pollCount}/${MAX_POLLS}]`;
  1610.  
  1611. if (state === 'done' || state === 'completed') {
  1612. videoReady = true; success = true; statusEl.innerText = "Ready"; statusEl.className = ""; statusEl.style.color = "#94a3b8"; renderVideoToGallery(pollData.video.url, payload.prompt, els.currentImages);
  1613. } else if (['failed', 'expired', 'rejected', 'blocked', 'moderated', 'nsfw'].includes(state) || pollData.is_sensitive) {
  1614. if (pollData.video && pollData.video.url) {
  1615. videoReady = true; success = true; statusEl.innerText = `${loopPrefix}Warning: Flagged as ${state}, but recovered!`; statusEl.className = ""; statusEl.style.color = "#d97706"; renderVideoToGallery(pollData.video.url, payload.prompt, els.currentImages);
  1616. addLog('WARN', `Video flagged but recovered`, pollData);
  1617. } else throw new Error(`Generation halted. Reason: ${state}`);
  1618. }
  1619. }
  1620. }
  1621. } catch (err) {
  1622. const errStr = err.message.toLowerCase(); addLog('ERROR', `Generation logic exception`, { message: err.message });
  1623. if (err.name === 'AbortError' || isRequestCancelled) { statusEl.innerText = "Request Cancelled."; statusEl.className = ""; statusEl.style.color = "#ef4444"; return false; }
  1624. let isLongRateLimit = false; let isShortRateLimit = false;
  1625. if (errStr.includes("requests per second (actual/limit)")) {
  1626. const secMatch = errStr.match(/requests per second \(actual\/limit\):\s*(\d+)\s*\/\s*(\d+)/); const minMatch = errStr.match(/requests per minute \(actual\/limit\):\s*(\d+)\s*\/\s*(\d+)/);
  1627. if (minMatch && minMatch[1] === minMatch[2]) isLongRateLimit = true; else if (secMatch && secMatch[1] === secMatch[2]) isShortRateLimit = true; else isLongRateLimit = true;
  1628. } else if (errStr.includes("rate limit") || errStr.includes("resource has been exhausted") || errStr.includes("http 429") || errStr.includes("http 422")) isLongRateLimit = true;
  1629.  
  1630. if (isShortRateLimit || isLongRateLimit) {
  1631. if (appSettings.maximumGreedMode) {
  1632. statusEl.innerText = `${loopPrefix}Rate Limit Hit (429). Refreshing tab...`; statusEl.className = ""; statusEl.style.color = "#ef4444";
  1633. await nuclearSessionReset(totalLoops - currentLoop + 1); const u = new URL(window.location.href.split('?')[0]); u.searchParams.set('_rst', Date.now()); window.location.replace(u.toString()); await sleep(10000);
  1634. } else {
  1635. statusEl.innerText = `${loopPrefix}Rate Limit Hit (429). Resetting cookies...`; await nuclearSessionReset();
  1636. if (isShortRateLimit) {
  1637. attempts++; if (attempts >= appSettings.retries) { statusEl.innerText = `${loopPrefix}Failed: Max retries reached after per-second rate limits.`; statusEl.className = ""; statusEl.style.color = "#ef4444"; break; }
  1638. await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin);
  1639. } else {
  1640. attempts++; if (attempts >= appSettings.retries) { statusEl.innerText = `${loopPrefix}Failed: Max retries reached after rate limits.`; statusEl.className = ""; statusEl.style.color = "#ef4444"; break; }
  1641. let delaySeconds = parseInt(appSettings.rateLimitDelay) || 60; let countdown = delaySeconds;
  1642. if ((rateLimitFails++) < 1) { await sleep(1000); continue; }
  1643. rateLimitFails = 0; toggleKeepAwake(true);
  1644. while(countdown > 0 && !isRequestCancelled) { statusEl.innerText = `${loopPrefix}Rate Limit Hit. Retrying in ${countdown}s... [${attempts}/${appSettings.retries}]`; await sleep(1000); countdown--; }
  1645. toggleKeepAwake(false);
  1646. }
  1647. if (isRequestCancelled) return false; continue;
  1648. }
  1649. } else if (errStr.includes("video lost") || ((errStr.includes("timeout: video") || errStr.includes("generation halted.") || errStr.includes("video rejected")) && appSettings.autoRetryStuckVideo)) {
  1650. attempts++; if (attempts >= appSettings.retries) { statusEl.innerText = `${loopPrefix}Failed: Max retries reached for stuck video.`; statusEl.className = ""; statusEl.style.color = "#ef4444"; break; }
  1651. statusEl.innerText = `${loopPrefix}Video Stuck/Failed. Auto-retrying... [${attempts}/${appSettings.retries}]`; await sleep(Math.floor(Math.random() * (appSettings.delayMax - appSettings.delayMin + 1)) + appSettings.delayMin);
  1652. if (payload.prompt) payload.prompt += "\u200B"; continue;
  1653. } else { statusEl.innerText = `${loopPrefix}Error: ${err.message}`; statusEl.className = ""; statusEl.style.color = "#ef4444"; break; }
  1654. }
  1655. }
  1656. } finally { toggleKeepAwake(false); }
  1657.  
  1658. if (!success && !isRequestCancelled) {
  1659. if (!statusEl.innerText.includes("Failed:") && !statusEl.innerText.includes("Error:") && !statusEl.innerText.includes("Reloading")) statusEl.innerText = `${loopPrefix}Failed after ${attempts} retries.`;
  1660. statusEl.className = ""; statusEl.style.color = "#ef4444"; addLog('ERROR', 'Generation loop failed completely'); return false;
  1661. }
  1662. return success;
  1663. }
  1664.  
  1665. function setupGenerationUI() {
  1666. els.previewBtn.addEventListener('click', async () => {
  1667. els.previewBtn.disabled = true; els.previewBtn.innerHTML = `<div class="loading-spinner" style="border-top-color:#64748b; width:12px; height:12px;"></div>`;
  1668. fullPayloadMemory = await buildPayloadData(parseDynamicPrompt(els.prompt.value.trim()));
  1669. const displayP = JSON.parse(JSON.stringify(fullPayloadMemory)); const trunc = "[BASE64_TRUNCATED_FOR_PREVIEW]";
  1670. if (displayP.image) { if (Array.isArray(displayP.image)) displayP.image.forEach(img => (img.url = trunc)); else displayP.image.url = trunc; }
  1671. if (displayP.images && Array.isArray(displayP.images)) displayP.images.forEach(img => (img.url = trunc));
  1672. if (displayP.reference_images && Array.isArray(displayP.reference_images)) displayP.reference_images.forEach(img => (img.url = trunc));
  1673. if (displayP.video) displayP.video.url = trunc;
  1674. const activeRefs = referenceMedia.filter(m => m.active); let endpoint = '/v1/images/generations';
  1675. if (els.action.value === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
  1676. else if (els.action.value === 'gen_video') endpoint = '/v1/videos/generations';
  1677. else if (els.action.value === 'edit_video') endpoint = '/v1/videos/edits';
  1678. else if (els.action.value === 'extend_video') endpoint = '/v1/videos/extensions';
  1679. els.payloadEndpoint.value = endpoint; els.payloadCode.value = JSON.stringify(displayP, null, 2); els.payloadModal.style.display = 'flex';
  1680. els.previewBtn.innerHTML = `🔍 Payload`; els.previewBtn.disabled = false;
  1681. });
  1682.  
  1683. els.closePayloadBtn.addEventListener('click', () => els.payloadModal.style.display = 'none');
  1684.  
  1685. els.sendCustomBtn.addEventListener('click', async () => {
  1686. initAudio(); let customPayload; try { customPayload = JSON.parse(els.payloadCode.value); } catch(e) { return alert("Invalid JSON format in textarea!"); }
  1687. injectBase64(customPayload, fullPayloadMemory);
  1688. const endpoint = els.payloadEndpoint.value.trim();
  1689. const isImage = customPayload.model && String(customPayload.model).includes("image");
  1690. els.sendCustomBtn.disabled = true; els.sendCustomBtn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Processing...</div>`; isRequestCancelled = false;
  1691. const ok = await executeGenerationSingle(endpoint, customPayload, isImage, els.customStatus, 1, 1);
  1692. els.sendCustomBtn.disabled = false; els.sendCustomBtn.innerHTML = `<div class="btn-content">🚀 Send Custom Payload</div>`; if (ok) notifyUser(false); else notifyUser(true);
  1693. });
  1694.  
  1695. els.cancelBtn.addEventListener('click', () => {
  1696. isRequestCancelled = true; if (currentAbortController) currentAbortController.abort(); toggleKeepAwake(false);
  1697. els.cancelBtn.style.display = 'none'; els.previewBtn.style.display = 'flex'; els.btn.disabled = false; els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
  1698. els.status.innerText = "Request Cancelled."; els.status.className = ""; els.status.style.color = "#ef4444";
  1699. });
  1700.  
  1701. els.btn.addEventListener('click', async () => {
  1702. initAudio(); const basePrompt = els.prompt.value.trim(); if (!basePrompt) return alert("Please enter a prompt.");
  1703. addLog('UI', 'Generate button clicked', { basePrompt });
  1704. const oldImages = Array.from(els.currentImages.children);
  1705. if (oldImages.length > 0) {
  1706. if (els.history.innerText.includes("No history")) els.history.innerHTML = '';
  1707. oldImages.forEach(card => { card.className = 'history-card'; const promptEl = card.querySelector('p'); promptEl.title = "Click to copy prompt"; promptEl.onclick = () => setPromptVal(promptEl.innerText); els.history.prepend(card); });
  1708. }
  1709.  
  1710. const action = els.action.value; const activeRefs = referenceMedia.filter(m => m.active);
  1711. let endpoint = '/v1/images/generations';
  1712. if (action === 'gen_image' && activeRefs.length > 0) endpoint = '/v1/images/edits';
  1713. else if (action === 'gen_video') endpoint = '/v1/videos/generations';
  1714. else if (action === 'edit_video') endpoint = '/v1/videos/edits';
  1715. else if (action === 'extend_video') endpoint = '/v1/videos/extensions';
  1716.  
  1717. const isImage = action === 'gen_image'; const totalLoops = parseInt(els.loopsNum.value) || 1;
  1718. els.btn.disabled = true; els.cancelBtn.style.display = 'flex'; els.previewBtn.style.display = 'none'; isRequestCancelled = false;
  1719.  
  1720. let allSuccess = true;
  1721. for (let i = 1; i <= totalLoops; i++) {
  1722. if (isRequestCancelled) break; const dynamicPrompt = parseDynamicPrompt(basePrompt);
  1723. els.btn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Building...</div>`;
  1724. const payload = await buildPayloadData(dynamicPrompt);
  1725. els.btn.innerHTML = `<div class="btn-content"><div class="loading-spinner"></div> Gen ${i}/${totalLoops}...</div>`;
  1726. const ok = await executeGenerationSingle(endpoint, payload, isImage, els.status, i, totalLoops);
  1727. if (!ok) { allSuccess = false; if (appSettings.breakLoopOnFailure) break; }
  1728. }
  1729.  
  1730. if (!isRequestCancelled) {
  1731. els.cancelBtn.style.display = 'none'; els.previewBtn.style.display = 'flex'; els.btn.disabled = false; els.btn.innerHTML = `<div class="btn-content">Generate</div>`;
  1732. if (allSuccess) { els.status.innerText = "All runs complete."; els.status.className = ""; els.status.style.color = "#64748b"; notifyUser(false); addLog('INFO', 'All generation loops completed successfully'); }
  1733. else { notifyUser(true); addLog('ERROR', 'Generation sequence ended with errors'); }
  1734. }
  1735. });
  1736.  
  1737. els.reset.addEventListener('click', () => {
  1738. if (!confirm("Wipe cache? Your prompt and settings will be saved.")) return;
  1739. localStorage.setItem('xai_api_prompt', els.prompt.value); nuclearSessionReset();
  1740. });
  1741. }
  1742.  
  1743. function checkAutoResume() {
  1744. const resumeLoops = sessionStorage.getItem('xai_resume_loops');
  1745. if (resumeLoops) {
  1746. sessionStorage.removeItem('xai_resume_loops'); const loops = parseInt(resumeLoops);
  1747. if (loops > 0) {
  1748. els.loopsNum.value = loops; els.loopsSlider.value = Math.min(loops, 20); updateGenSettingsMemory();
  1749. els.status.innerText = `Auto-resuming ${loops} runs...`; els.status.className = "status-pulsing";
  1750. setTimeout(() => { if (!els.btn.disabled) els.btn.click(); }, 2500);
  1751. }
  1752. }
  1753. }
  1754.  
  1755. function bindLogic() {
  1756. setupModalsAndAuxUI(); // Initializes modals, logs, exports, and lightbox
  1757. setupPromptListeners();
  1758. setupAspectRatioUI();
  1759. setupMediaAndActionUI();
  1760. setupGenerationUI();
  1761. checkAutoResume();
  1762. }
  1763.  
  1764. async function processAndRenderImage(imgObj, originalPrompt, num, total, galleryEl) {
  1765. if (!imgObj.b64_json) return;
  1766. const mime = imgObj.mime_type || "image/png"; const b64 = imgObj.b64_json; const pngDataUri = `data:${mime};base64,${b64}`;
  1767. const finalPrompt = imgObj.revised_prompt || originalPrompt; let finalDataUri = pngDataUri;
  1768. const qTag = isQuality ? 'Quality' : 'Speed';
  1769. const resTag = isHighRes ? '2K' : '1K';
  1770. let filename = `Grok ${qTag} ${resTag} - ${makeTimestamp()} - ${num}of${total}.png`;
  1771. if (!appSettings.saveAsPng) { finalDataUri = await convertToJpegWithExif(pngDataUri, finalPrompt); filename = `Grok ${qTag} ${resTag} - ${makeTimestamp()} - ${num}of${total}.jpg`; }
  1772. const card = document.createElement('div'); card.className = 'current-card';
  1773. card.innerHTML = `<div class="img-wrapper"><img src="${finalDataUri}" class="zoomable" data-filename="${filename}" title="Click to view fullscreen"><a href="${finalDataUri}" download="${filename}" class="overlay-btn overlay-dl-btn" title="Download Full File">${DOWNLOAD_ICON}</a><button class="overlay-btn overlay-edit-btn" title="Edit this Image">${EDIT_ICON}</button></div><p style="padding: 10px; margin: 0; font-size: 12px; color: #cbd5e1; border-top: 1px solid #334155;">${finalPrompt}</p>`;
  1774.  
  1775. card.querySelector('.overlay-edit-btn').addEventListener('click', (e) => { e.preventDefault(); if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(finalDataUri, false, filename, 'gen_image'); });
  1776.  
  1777. const dlBtn = card.querySelector('.overlay-dl-btn');
  1778. dlBtn.addEventListener('click', () => { card.classList.add('downloaded'); });
  1779.  
  1780. galleryEl.prepend(card);
  1781.  
  1782. if (appSettings.autoDownload) {
  1783. //setTimeout(() => dlBtn.click(), 500);
  1784. setTimeout(() => {
  1785. GM_download({ url: finalDataUri, name: filename, saveAs: false });
  1786. card.classList.add('downloaded');
  1787. }, 500);
  1788. }
  1789. }
  1790.  
  1791. function renderVideoToGallery(videoUrl, originalPrompt, galleryEl) {
  1792. const filename = `Grok Video - ${makeTimestamp()}.mp4`; const auto = appSettings.videoAutoplay ? "autoplay" : ""; const muted = appSettings.videoMuted ? "muted" : "";
  1793. const card = document.createElement('div'); card.className = 'current-card';
  1794. card.innerHTML = `<div class="img-wrapper"><video src="${videoUrl}" controls ${auto} ${muted} loop style="width: 100%; display: block; max-height: 50vh; object-fit: contain; background: #000;"></video><button class="overlay-btn overlay-dl-btn force-dl" data-url="${videoUrl}" data-filename="${filename}" style="z-index: 50; right: 6px;" title="Download MP4">${DOWNLOAD_ICON}</button><button class="overlay-btn overlay-edit-btn" style="z-index: 50; right: 40px;" title="Edit this Video">${EDIT_ICON}</button><button class="overlay-btn overlay-extend-btn" style="z-index: 50; right: 74px;" title="Extend this Video">${EXTEND_ICON}</button></div><p style="padding: 10px; margin: 0; font-size: 12px; color: #cbd5e1; border-top: 1px solid #334155;">${originalPrompt}</p>`;
  1795.  
  1796. card.querySelector('.overlay-edit-btn').addEventListener('click', (e) => { e.preventDefault(); if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(videoUrl, true, filename, 'edit_video'); });
  1797. card.querySelector('.overlay-extend-btn').addEventListener('click', (e) => { e.preventDefault(); if (typeof updateUIForEditMedia === 'function') updateUIForEditMedia(videoUrl, true, filename, 'extend_video'); });
  1798.  
  1799. const dlBtn = card.querySelector('.overlay-dl-btn');
  1800. dlBtn.addEventListener('click', (e) => {
  1801. e.preventDefault(); const url = dlBtn.getAttribute('data-url'); const fname = dlBtn.getAttribute('data-filename'); const originalIcon = dlBtn.innerHTML;
  1802. dlBtn.innerHTML = '<div class="loading-spinner" style="border-top-color: #10b981;"></div>'; dlBtn.style.pointerEvents = 'none'; card.classList.add('downloaded');
  1803. if (typeof GM_xmlhttpRequest !== "undefined") {
  1804. GM_xmlhttpRequest({ method: 'GET', url: url, responseType: 'blob', onload: function(response) {
  1805. if (response.status >= 200 && response.status < 300) {
  1806. const blobUrl = URL.createObjectURL(response.response); const a = document.createElement('a'); a.style.display = 'none'; a.href = blobUrl; a.download = fname; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(blobUrl), 1000);
  1807. } else window.open(url, '_blank');
  1808. dlBtn.innerHTML = originalIcon; dlBtn.style.pointerEvents = 'auto';
  1809. }, onerror: function() { window.open(url, '_blank'); dlBtn.innerHTML = originalIcon; dlBtn.style.pointerEvents = 'auto'; } });
  1810. } else { window.open(url, '_blank'); dlBtn.innerHTML = originalIcon; dlBtn.style.pointerEvents = 'auto'; }
  1811. });
  1812.  
  1813. galleryEl.prepend(card);
  1814.  
  1815. if (appSettings.autoDownload) {
  1816. //setTimeout(() => dlBtn.click(), 500);
  1817. setTimeout(() => {
  1818. GM_download({ url: videoUrl, name: filename, saveAs: false });
  1819. card.classList.add('downloaded');
  1820. }, 500);
  1821. }
  1822. }
  1823.  
  1824. if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initApp); } else { initApp(); }
  1825. })();
Add Comment
Please, Sign In to add comment