app.js 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  1. // GrabZilla 2.1 - Application Entry Point
  2. // Modular architecture with clear separation of concerns
  3. class GrabZillaApp {
  4. constructor() {
  5. this.state = null;
  6. this.eventBus = null;
  7. this.initialized = false;
  8. this.modules = new Map();
  9. }
  10. // Initialize the application
  11. async init() {
  12. try {
  13. console.log('🚀 Initializing GrabZilla 2.1...');
  14. // Initialize event bus
  15. this.eventBus = window.eventBus;
  16. if (!this.eventBus) {
  17. throw new Error('EventBus not available');
  18. }
  19. // Initialize application state
  20. this.state = new window.AppState();
  21. if (!this.state) {
  22. throw new Error('AppState not available');
  23. }
  24. // Set up error handling
  25. this.setupErrorHandling();
  26. // Initialize UI components
  27. await this.initializeUI();
  28. // Set up event listeners
  29. this.setupEventListeners();
  30. // Load saved state if available
  31. await this.loadState();
  32. // Ensure save directory exists
  33. await this.ensureSaveDirectoryExists();
  34. // Check binary status and validate
  35. await this.checkAndValidateBinaries();
  36. // Initialize keyboard navigation
  37. this.initializeKeyboardNavigation();
  38. this.initialized = true;
  39. console.log('✅ GrabZilla 2.1 initialized successfully');
  40. // Notify that the app is ready
  41. this.eventBus.emit('app:ready', { app: this });
  42. } catch (error) {
  43. console.error('❌ Failed to initialize GrabZilla:', error);
  44. this.handleInitializationError(error);
  45. }
  46. }
  47. // Set up global error handling
  48. setupErrorHandling() {
  49. // Handle unhandled errors
  50. window.addEventListener('error', (event) => {
  51. console.error('Global error:', event.error);
  52. this.eventBus.emit('app:error', {
  53. type: 'global',
  54. error: event.error,
  55. filename: event.filename,
  56. lineno: event.lineno
  57. });
  58. });
  59. // Handle unhandled promise rejections
  60. window.addEventListener('unhandledrejection', (event) => {
  61. console.error('Unhandled promise rejection:', event.reason);
  62. this.eventBus.emit('app:error', {
  63. type: 'promise',
  64. error: event.reason
  65. });
  66. });
  67. // Listen for application errors
  68. this.eventBus.on('app:error', (errorData) => {
  69. // Handle errors appropriately
  70. this.displayError(errorData);
  71. });
  72. }
  73. // Initialize UI components
  74. async initializeUI() {
  75. // Update save path display
  76. this.updateSavePathDisplay();
  77. // Initialize dropdown values
  78. this.initializeDropdowns();
  79. // Set up video list
  80. this.initializeVideoList();
  81. // Set up status display
  82. this.updateStatusMessage('Ready to download videos');
  83. }
  84. // Set up main event listeners
  85. setupEventListeners() {
  86. // State change listeners
  87. this.state.on('videoAdded', (data) => this.onVideoAdded(data));
  88. this.state.on('videoRemoved', (data) => this.onVideoRemoved(data));
  89. this.state.on('videoUpdated', (data) => this.onVideoUpdated(data));
  90. this.state.on('videosReordered', (data) => this.onVideosReordered(data));
  91. this.state.on('videosCleared', (data) => this.onVideosCleared(data));
  92. this.state.on('configUpdated', (data) => this.onConfigUpdated(data));
  93. // UI event listeners
  94. this.setupButtonEventListeners();
  95. this.setupInputEventListeners();
  96. this.setupVideoListEventListeners();
  97. }
  98. // Set up button event listeners
  99. setupButtonEventListeners() {
  100. // Add Video button
  101. const addVideoBtn = document.getElementById('addVideoBtn');
  102. if (addVideoBtn) {
  103. addVideoBtn.addEventListener('click', () => this.handleAddVideo());
  104. }
  105. // Import URLs button
  106. const importUrlsBtn = document.getElementById('importUrlsBtn');
  107. if (importUrlsBtn) {
  108. importUrlsBtn.addEventListener('click', () => this.handleImportUrls());
  109. }
  110. // Save Path button
  111. const savePathBtn = document.getElementById('savePathBtn');
  112. if (savePathBtn) {
  113. savePathBtn.addEventListener('click', () => this.handleSelectSavePath());
  114. }
  115. // Cookie File button
  116. const cookieFileBtn = document.getElementById('cookieFileBtn');
  117. if (cookieFileBtn) {
  118. cookieFileBtn.addEventListener('click', () => this.handleSelectCookieFile());
  119. }
  120. // Control panel buttons
  121. const clearListBtn = document.getElementById('clearListBtn');
  122. if (clearListBtn) {
  123. clearListBtn.addEventListener('click', () => this.handleClearList());
  124. }
  125. const downloadVideosBtn = document.getElementById('downloadVideosBtn');
  126. if (downloadVideosBtn) {
  127. downloadVideosBtn.addEventListener('click', () => this.handleDownloadVideos());
  128. }
  129. const cancelDownloadsBtn = document.getElementById('cancelDownloadsBtn');
  130. if (cancelDownloadsBtn) {
  131. cancelDownloadsBtn.addEventListener('click', () => this.handleCancelDownloads());
  132. }
  133. const updateDepsBtn = document.getElementById('updateDepsBtn');
  134. if (updateDepsBtn) {
  135. updateDepsBtn.addEventListener('click', () => this.handleUpdateDependencies());
  136. }
  137. }
  138. // Set up input event listeners
  139. setupInputEventListeners() {
  140. // URL input - no paste handler needed, user clicks "Add Video" button
  141. const urlInput = document.getElementById('urlInput');
  142. if (urlInput) {
  143. // Optional: could add real-time validation feedback here
  144. }
  145. // Configuration inputs
  146. const defaultQuality = document.getElementById('defaultQuality');
  147. if (defaultQuality) {
  148. defaultQuality.addEventListener('change', (e) => {
  149. this.state.updateConfig({ defaultQuality: e.target.value });
  150. });
  151. }
  152. const defaultFormat = document.getElementById('defaultFormat');
  153. if (defaultFormat) {
  154. defaultFormat.addEventListener('change', (e) => {
  155. this.state.updateConfig({ defaultFormat: e.target.value });
  156. });
  157. }
  158. const filenamePattern = document.getElementById('filenamePattern');
  159. if (filenamePattern) {
  160. filenamePattern.addEventListener('change', (e) => {
  161. this.state.updateConfig({ filenamePattern: e.target.value });
  162. });
  163. }
  164. }
  165. // Set up video list event listeners
  166. setupVideoListEventListeners() {
  167. const videoList = document.getElementById('videoList');
  168. if (videoList) {
  169. videoList.addEventListener('click', (e) => this.handleVideoListClick(e));
  170. videoList.addEventListener('change', (e) => this.handleVideoListChange(e));
  171. this.setupDragAndDrop(videoList);
  172. }
  173. }
  174. // Set up drag-and-drop reordering
  175. setupDragAndDrop(videoList) {
  176. let draggedElement = null;
  177. let draggedVideoId = null;
  178. videoList.addEventListener('dragstart', (e) => {
  179. const videoItem = e.target.closest('.video-item');
  180. if (!videoItem) return;
  181. draggedElement = videoItem;
  182. draggedVideoId = videoItem.dataset.videoId;
  183. videoItem.classList.add('opacity-50');
  184. e.dataTransfer.effectAllowed = 'move';
  185. e.dataTransfer.setData('text/html', videoItem.innerHTML);
  186. });
  187. videoList.addEventListener('dragover', (e) => {
  188. e.preventDefault();
  189. const videoItem = e.target.closest('.video-item');
  190. if (!videoItem || videoItem === draggedElement) return;
  191. e.dataTransfer.dropEffect = 'move';
  192. // Visual feedback - show where it will drop
  193. const rect = videoItem.getBoundingClientRect();
  194. const midpoint = rect.top + rect.height / 2;
  195. if (e.clientY < midpoint) {
  196. videoItem.classList.add('border-t-2', 'border-[#155dfc]');
  197. videoItem.classList.remove('border-b-2');
  198. } else {
  199. videoItem.classList.add('border-b-2', 'border-[#155dfc]');
  200. videoItem.classList.remove('border-t-2');
  201. }
  202. });
  203. videoList.addEventListener('dragleave', (e) => {
  204. const videoItem = e.target.closest('.video-item');
  205. if (videoItem) {
  206. videoItem.classList.remove('border-t-2', 'border-b-2', 'border-[#155dfc]');
  207. }
  208. });
  209. videoList.addEventListener('drop', (e) => {
  210. e.preventDefault();
  211. const targetItem = e.target.closest('.video-item');
  212. if (!targetItem || !draggedVideoId) return;
  213. const targetVideoId = targetItem.dataset.videoId;
  214. // Calculate drop position
  215. const rect = targetItem.getBoundingClientRect();
  216. const midpoint = rect.top + rect.height / 2;
  217. const dropBefore = e.clientY < midpoint;
  218. // Reorder in state
  219. this.handleVideoReorder(draggedVideoId, targetVideoId, dropBefore);
  220. // Clean up visual feedback
  221. targetItem.classList.remove('border-t-2', 'border-b-2', 'border-[#155dfc]');
  222. });
  223. videoList.addEventListener('dragend', (e) => {
  224. const videoItem = e.target.closest('.video-item');
  225. if (videoItem) {
  226. videoItem.classList.remove('opacity-50');
  227. }
  228. // Clean up all visual feedback
  229. document.querySelectorAll('.video-item').forEach(item => {
  230. item.classList.remove('border-t-2', 'border-b-2', 'border-[#155dfc]');
  231. });
  232. draggedElement = null;
  233. draggedVideoId = null;
  234. });
  235. }
  236. handleVideoReorder(draggedId, targetId, insertBefore) {
  237. const videos = this.state.getVideos();
  238. const draggedIndex = videos.findIndex(v => v.id === draggedId);
  239. const targetIndex = videos.findIndex(v => v.id === targetId);
  240. if (draggedIndex === -1 || targetIndex === -1) return;
  241. let newIndex = targetIndex;
  242. if (draggedIndex < targetIndex && !insertBefore) {
  243. newIndex = targetIndex;
  244. } else if (draggedIndex > targetIndex && insertBefore) {
  245. newIndex = targetIndex;
  246. } else if (insertBefore) {
  247. newIndex = targetIndex;
  248. } else {
  249. newIndex = targetIndex + 1;
  250. }
  251. this.state.reorderVideos(draggedIndex, newIndex);
  252. }
  253. // Handle clicks in video list (checkboxes, delete buttons)
  254. handleVideoListClick(event) {
  255. const target = event.target;
  256. const videoItem = target.closest('.video-item');
  257. if (!videoItem) return;
  258. const videoId = videoItem.dataset.videoId;
  259. if (!videoId) return;
  260. // Handle checkbox click
  261. if (target.closest('.video-checkbox')) {
  262. event.preventDefault();
  263. this.toggleVideoSelection(videoId);
  264. return;
  265. }
  266. // Handle delete button click (if we add one later)
  267. if (target.closest('.delete-video-btn')) {
  268. event.preventDefault();
  269. this.handleRemoveVideo(videoId);
  270. return;
  271. }
  272. }
  273. // Handle dropdown changes in video list (quality, format)
  274. handleVideoListChange(event) {
  275. const target = event.target;
  276. const videoItem = target.closest('.video-item');
  277. if (!videoItem) return;
  278. const videoId = videoItem.dataset.videoId;
  279. if (!videoId) return;
  280. // Handle quality dropdown change
  281. if (target.classList.contains('quality-select')) {
  282. const quality = target.value;
  283. this.state.updateVideo(videoId, { quality });
  284. console.log(`Updated video ${videoId} quality to ${quality}`);
  285. return;
  286. }
  287. // Handle format dropdown change
  288. if (target.classList.contains('format-select')) {
  289. const format = target.value;
  290. this.state.updateVideo(videoId, { format });
  291. console.log(`Updated video ${videoId} format to ${format}`);
  292. return;
  293. }
  294. }
  295. // Toggle video selection
  296. toggleVideoSelection(videoId) {
  297. this.state.toggleVideoSelection(videoId);
  298. this.updateVideoCheckbox(videoId);
  299. }
  300. // Update checkbox visual state
  301. updateVideoCheckbox(videoId) {
  302. const videoItem = document.querySelector(`[data-video-id="${videoId}"]`);
  303. if (!videoItem) return;
  304. const checkbox = videoItem.querySelector('.video-checkbox');
  305. if (!checkbox) return;
  306. const isSelected = this.state.ui.selectedVideos.includes(videoId);
  307. checkbox.setAttribute('aria-checked', isSelected ? 'true' : 'false');
  308. // Update checkbox SVG
  309. const svg = checkbox.querySelector('svg');
  310. if (svg) {
  311. if (isSelected) {
  312. svg.innerHTML = `<rect x="3" y="3" width="10" height="10" stroke="currentColor" stroke-width="1.5" fill="currentColor" rx="2" />
  313. <path d="M5 8L7 10L11 6" stroke="white" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round"/>`;
  314. } else {
  315. svg.innerHTML = `<rect x="3" y="3" width="10" height="10" stroke="currentColor" stroke-width="1.5" fill="none" rx="2" />`;
  316. }
  317. }
  318. }
  319. // Remove video from list
  320. handleRemoveVideo(videoId) {
  321. try {
  322. const video = this.state.getVideo(videoId);
  323. if (video && confirm(`Remove "${video.getDisplayName()}"?`)) {
  324. this.state.removeVideo(videoId);
  325. this.updateStatusMessage('Video removed');
  326. }
  327. } catch (error) {
  328. console.error('Error removing video:', error);
  329. this.showError(`Failed to remove video: ${error.message}`);
  330. }
  331. }
  332. // Event handlers
  333. async handleAddVideo() {
  334. const urlInput = document.getElementById('urlInput');
  335. const inputText = urlInput?.value.trim();
  336. if (!inputText) {
  337. this.showError('Please enter a URL');
  338. return;
  339. }
  340. try {
  341. this.updateStatusMessage('Adding videos...');
  342. // Validate URLs
  343. const validation = window.URLValidator.validateMultipleUrls(inputText);
  344. if (validation.invalid.length > 0) {
  345. this.showError(`Invalid URLs found: ${validation.invalid.join(', ')}`);
  346. return;
  347. }
  348. if (validation.valid.length === 0) {
  349. this.showError('No valid URLs found');
  350. return;
  351. }
  352. // Add videos to state
  353. const results = await this.state.addVideosFromUrls(validation.valid);
  354. // Clear input on success
  355. if (urlInput) {
  356. urlInput.value = '';
  357. }
  358. // Show results
  359. const successCount = results.successful.length;
  360. const duplicateCount = results.duplicates.length;
  361. const failedCount = results.failed.length;
  362. let message = `Added ${successCount} video(s)`;
  363. if (duplicateCount > 0) {
  364. message += `, ${duplicateCount} duplicate(s) skipped`;
  365. }
  366. if (failedCount > 0) {
  367. message += `, ${failedCount} failed`;
  368. }
  369. this.updateStatusMessage(message);
  370. } catch (error) {
  371. console.error('Error adding videos:', error);
  372. this.showError(`Failed to add videos: ${error.message}`);
  373. }
  374. }
  375. async handleImportUrls() {
  376. if (!window.electronAPI) {
  377. this.showError('File import requires Electron environment');
  378. return;
  379. }
  380. try {
  381. // Implementation would use Electron file dialog
  382. this.updateStatusMessage('Import URLs functionality coming soon');
  383. } catch (error) {
  384. this.showError(`Failed to import URLs: ${error.message}`);
  385. }
  386. }
  387. async handleSelectSavePath() {
  388. if (!window.IPCManager || !window.IPCManager.isAvailable()) {
  389. this.showError('Path selection requires Electron environment');
  390. return;
  391. }
  392. try {
  393. this.updateStatusMessage('Select download directory...');
  394. const result = await window.IPCManager.selectSaveDirectory();
  395. if (result && result.success && result.path) {
  396. this.state.updateConfig({ savePath: result.path });
  397. await this.ensureSaveDirectoryExists(); // Auto-create directory
  398. this.updateSavePathDisplay();
  399. this.updateStatusMessage(`Save path set to: ${result.path}`);
  400. } else if (result && result.error) {
  401. this.showError(result.error);
  402. } else {
  403. this.updateStatusMessage('No directory selected');
  404. }
  405. } catch (error) {
  406. console.error('Error selecting save path:', error);
  407. this.showError(`Failed to select save path: ${error.message}`);
  408. }
  409. }
  410. async handleSelectCookieFile() {
  411. if (!window.IPCManager || !window.IPCManager.isAvailable()) {
  412. this.showError('File selection requires Electron environment');
  413. return;
  414. }
  415. try {
  416. this.updateStatusMessage('Select cookie file...');
  417. const result = await window.IPCManager.selectCookieFile();
  418. if (result && result.success && result.path) {
  419. this.state.updateConfig({ cookieFile: result.path });
  420. this.updateStatusMessage(`Cookie file set: ${result.path}`);
  421. } else if (result && result.error) {
  422. this.showError(result.error);
  423. } else {
  424. this.updateStatusMessage('No file selected');
  425. }
  426. } catch (error) {
  427. console.error('Error selecting cookie file:', error);
  428. this.showError(`Failed to select cookie file: ${error.message}`);
  429. }
  430. }
  431. handleClearList() {
  432. if (this.state.getVideos().length === 0) {
  433. this.updateStatusMessage('No videos to clear');
  434. return;
  435. }
  436. const removedVideos = this.state.clearVideos();
  437. this.updateStatusMessage(`Cleared ${removedVideos.length} video(s)`);
  438. }
  439. async handleDownloadVideos() {
  440. // Check if IPC is available
  441. if (!window.IPCManager || !window.IPCManager.isAvailable()) {
  442. this.showError('Download functionality requires Electron environment');
  443. return;
  444. }
  445. // Get downloadable videos (either selected or all ready videos)
  446. const selectedVideos = this.state.getSelectedVideos().filter(v => v.isDownloadable());
  447. const videos = selectedVideos.length > 0
  448. ? selectedVideos
  449. : this.state.getVideos().filter(v => v.isDownloadable());
  450. if (videos.length === 0) {
  451. this.showError('No videos ready for download');
  452. return;
  453. }
  454. // Validate save path
  455. if (!this.state.config.savePath) {
  456. this.showError('Please select a save directory first');
  457. return;
  458. }
  459. this.state.updateUI({ isDownloading: true });
  460. this.updateStatusMessage(`Starting download of ${videos.length} video(s)...`);
  461. // Set up download progress listener
  462. window.IPCManager.onDownloadProgress('app', (progressData) => {
  463. this.handleDownloadProgress(progressData);
  464. });
  465. // Download videos sequentially
  466. let successCount = 0;
  467. let failedCount = 0;
  468. for (const video of videos) {
  469. try {
  470. // Update video status to downloading
  471. this.state.updateVideo(video.id, { status: 'downloading', progress: 0 });
  472. const result = await window.IPCManager.downloadVideo({
  473. videoId: video.id,
  474. url: video.url,
  475. quality: video.quality,
  476. format: video.format,
  477. savePath: this.state.config.savePath,
  478. cookieFile: this.state.config.cookieFile
  479. });
  480. if (result.success) {
  481. this.state.updateVideo(video.id, {
  482. status: 'completed',
  483. progress: 100,
  484. filename: result.filename
  485. });
  486. successCount++;
  487. // Show notification for successful download
  488. this.showDownloadNotification(video, 'success');
  489. } else {
  490. this.state.updateVideo(video.id, {
  491. status: 'error',
  492. error: result.error || 'Download failed'
  493. });
  494. failedCount++;
  495. // Show notification for failed download
  496. this.showDownloadNotification(video, 'error', result.error);
  497. }
  498. } catch (error) {
  499. console.error(`Error downloading video ${video.id}:`, error);
  500. this.state.updateVideo(video.id, {
  501. status: 'error',
  502. error: error.message
  503. });
  504. failedCount++;
  505. }
  506. }
  507. // Clean up progress listener
  508. window.IPCManager.removeDownloadProgressListener('app');
  509. this.state.updateUI({ isDownloading: false });
  510. // Show final status
  511. let message = `Download complete: ${successCount} succeeded`;
  512. if (failedCount > 0) {
  513. message += `, ${failedCount} failed`;
  514. }
  515. this.updateStatusMessage(message);
  516. }
  517. // Handle download progress updates from IPC
  518. handleDownloadProgress(progressData) {
  519. const { url, progress, status, stage, message } = progressData;
  520. // Find video by URL
  521. const video = this.state.getVideos().find(v => v.url === url);
  522. if (!video) return;
  523. // Update video progress
  524. this.state.updateVideo(video.id, {
  525. progress: Math.round(progress),
  526. status: status || 'downloading'
  527. });
  528. }
  529. // Show download notification
  530. async showDownloadNotification(video, type, errorMessage = null) {
  531. if (!window.electronAPI) return;
  532. try {
  533. const notificationOptions = {
  534. title: type === 'success' ? 'Download Complete' : 'Download Failed',
  535. message: type === 'success'
  536. ? `${video.getDisplayName()}`
  537. : `${video.getDisplayName()}: ${errorMessage || 'Unknown error'}`,
  538. sound: true
  539. };
  540. await window.electronAPI.showNotification(notificationOptions);
  541. } catch (error) {
  542. console.warn('Failed to show notification:', error);
  543. }
  544. }
  545. async handleCancelDownloads() {
  546. const activeDownloads = this.state.getVideosByStatus('downloading').length +
  547. this.state.getVideosByStatus('converting').length;
  548. if (activeDownloads === 0) {
  549. this.updateStatusMessage('No active downloads to cancel');
  550. return;
  551. }
  552. if (!window.IPCManager || !window.IPCManager.isAvailable()) {
  553. this.showError('Cancel functionality requires Electron environment');
  554. return;
  555. }
  556. try {
  557. this.updateStatusMessage(`Cancelling ${activeDownloads} active download(s)...`);
  558. // Cancel all conversions via IPC
  559. await window.electronAPI.cancelAllConversions();
  560. // Update video statuses to ready
  561. const downloadingVideos = this.state.getVideosByStatus('downloading');
  562. const convertingVideos = this.state.getVideosByStatus('converting');
  563. [...downloadingVideos, ...convertingVideos].forEach(video => {
  564. this.state.updateVideo(video.id, {
  565. status: 'ready',
  566. progress: 0,
  567. error: 'Cancelled by user'
  568. });
  569. });
  570. this.state.updateUI({ isDownloading: false });
  571. this.updateStatusMessage('Downloads cancelled');
  572. } catch (error) {
  573. console.error('Error cancelling downloads:', error);
  574. this.showError(`Failed to cancel downloads: ${error.message}`);
  575. }
  576. }
  577. async handleUpdateDependencies() {
  578. if (!window.IPCManager || !window.IPCManager.isAvailable()) {
  579. this.showError('Update functionality requires Electron environment');
  580. return;
  581. }
  582. try {
  583. this.updateStatusMessage('Checking binary versions...');
  584. const versions = await window.IPCManager.checkBinaryVersions();
  585. // Handle both ytDlp (from main.js) and ytdlp (legacy) formats
  586. const ytdlp = versions.ytDlp || versions.ytdlp;
  587. const ffmpeg = versions.ffmpeg;
  588. if (versions && (ytdlp || ffmpeg)) {
  589. // Update both button status and version display
  590. const ytdlpMissing = !ytdlp || !ytdlp.available;
  591. const ffmpegMissing = !ffmpeg || !ffmpeg.available;
  592. if (ytdlpMissing || ffmpegMissing) {
  593. this.updateDependenciesButtonStatus('missing');
  594. this.updateBinaryVersionDisplay(null);
  595. } else {
  596. this.updateDependenciesButtonStatus('ok');
  597. // Normalize the format for display
  598. const normalizedVersions = {
  599. ytdlp: ytdlp,
  600. ffmpeg: ffmpeg
  601. };
  602. this.updateBinaryVersionDisplay(normalizedVersions);
  603. }
  604. } else {
  605. this.showError('Could not check binary versions');
  606. }
  607. } catch (error) {
  608. console.error('Error checking dependencies:', error);
  609. this.showError(`Failed to check dependencies: ${error.message}`);
  610. }
  611. }
  612. // State change handlers
  613. onVideoAdded(data) {
  614. this.renderVideoList();
  615. this.updateStatsDisplay();
  616. }
  617. onVideoRemoved(data) {
  618. this.renderVideoList();
  619. this.updateStatsDisplay();
  620. }
  621. onVideoUpdated(data) {
  622. this.updateVideoElement(data.video);
  623. this.updateStatsDisplay();
  624. }
  625. onVideosReordered(data) {
  626. // Re-render entire list to reflect new order
  627. this.renderVideoList();
  628. console.log('Video order updated:', data);
  629. }
  630. onVideosCleared(data) {
  631. this.renderVideoList();
  632. this.updateStatsDisplay();
  633. }
  634. onConfigUpdated(data) {
  635. this.updateConfigUI(data.config);
  636. }
  637. // UI update methods
  638. updateSavePathDisplay() {
  639. const savePathElement = document.getElementById('savePath');
  640. if (savePathElement) {
  641. savePathElement.textContent = this.state.config.savePath;
  642. }
  643. }
  644. initializeDropdowns() {
  645. // Set dropdown values from config
  646. const defaultQuality = document.getElementById('defaultQuality');
  647. if (defaultQuality) {
  648. defaultQuality.value = this.state.config.defaultQuality;
  649. }
  650. const defaultFormat = document.getElementById('defaultFormat');
  651. if (defaultFormat) {
  652. defaultFormat.value = this.state.config.defaultFormat;
  653. }
  654. const filenamePattern = document.getElementById('filenamePattern');
  655. if (filenamePattern) {
  656. filenamePattern.value = this.state.config.filenamePattern;
  657. }
  658. }
  659. initializeVideoList() {
  660. this.renderVideoList();
  661. }
  662. renderVideoList() {
  663. const videoList = document.getElementById('videoList');
  664. if (!videoList) return;
  665. const videos = this.state.getVideos();
  666. // Clear all existing videos (including mockups)
  667. videoList.innerHTML = '';
  668. // If no videos, show empty state
  669. if (videos.length === 0) {
  670. videoList.innerHTML = `
  671. <div class="text-center py-12 text-[#90a1b9]">
  672. <p class="text-lg mb-2">No videos yet</p>
  673. <p class="text-sm">Paste YouTube or Vimeo URLs above to get started</p>
  674. </div>
  675. `;
  676. return;
  677. }
  678. // Render each video
  679. videos.forEach(video => {
  680. const videoElement = this.createVideoElement(video);
  681. videoList.appendChild(videoElement);
  682. });
  683. }
  684. createVideoElement(video) {
  685. const div = document.createElement('div');
  686. div.className = 'video-item grid grid-cols-[40px_40px_1fr_120px_100px_120px_100px_40px] gap-4 items-center p-2 rounded bg-[#314158] hover:bg-[#3a4a68] transition-colors duration-200';
  687. div.dataset.videoId = video.id;
  688. div.setAttribute('draggable', 'true'); // Make video item draggable
  689. div.innerHTML = `
  690. <!-- Checkbox -->
  691. <div class="flex items-center justify-center">
  692. <button class="video-checkbox w-6 h-6 rounded flex items-center justify-center hover:bg-[#45556c] transition-colors"
  693. role="checkbox" aria-checked="false" aria-label="Select ${video.getDisplayName()}">
  694. <svg width="16" height="16" viewBox="0 0 16 16" fill="none" class="text-white">
  695. <rect x="3" y="3" width="10" height="10" stroke="currentColor" stroke-width="1.5" fill="none" rx="2" />
  696. </svg>
  697. </button>
  698. </div>
  699. <!-- Drag Handle -->
  700. <div class="flex items-center justify-center text-[#90a1b9] hover:text-white cursor-grab transition-colors">
  701. <svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
  702. <circle cx="4" cy="4" r="1" />
  703. <circle cx="4" cy="8" r="1" />
  704. <circle cx="4" cy="12" r="1" />
  705. <circle cx="8" cy="4" r="1" />
  706. <circle cx="8" cy="8" r="1" />
  707. <circle cx="8" cy="12" r="1" />
  708. <circle cx="12" cy="4" r="1" />
  709. <circle cx="12" cy="8" r="1" />
  710. <circle cx="12" cy="12" r="1" />
  711. </svg>
  712. </div>
  713. <!-- Video Info -->
  714. <div class="flex items-center gap-3 min-w-0">
  715. <div class="w-16 h-12 bg-[#45556c] rounded overflow-hidden flex-shrink-0">
  716. ${video.isFetchingMetadata ?
  717. `<div class="w-full h-full bg-gradient-to-br from-[#4a5568] to-[#2d3748] flex items-center justify-center">
  718. <svg class="animate-spin h-5 w-5 text-[#155dfc]" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
  719. <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
  720. <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
  721. </svg>
  722. </div>` :
  723. video.thumbnail ?
  724. `<img src="${video.thumbnail}" alt="${video.getDisplayName()}" class="w-full h-full object-cover">` :
  725. `<div class="w-full h-full bg-gradient-to-br from-[#4a5568] to-[#2d3748] flex items-center justify-center">
  726. <svg width="24" height="24" viewBox="0 0 24 24" fill="none" class="text-[#90a1b9]">
  727. <path d="M8 5V19L19 12L8 5Z" stroke="currentColor" stroke-width="2" stroke-linejoin="round" />
  728. </svg>
  729. </div>`
  730. }
  731. </div>
  732. <div class="min-w-0 flex-1">
  733. <div class="text-sm text-white truncate font-medium">${video.getDisplayName()}</div>
  734. ${video.isFetchingMetadata ?
  735. `<div class="text-xs text-[#155dfc] animate-pulse">Fetching info...</div>` :
  736. ''
  737. }
  738. </div>
  739. </div>
  740. <!-- Duration -->
  741. <div class="text-sm text-[#cad5e2] text-center">${video.duration || '--:--'}</div>
  742. <!-- Quality Dropdown -->
  743. <div class="flex justify-center">
  744. <select class="quality-select bg-[#314158] border border-[#45556c] text-[#cad5e2] px-2 py-1 rounded text-xs font-medium min-w-0 w-full text-center"
  745. aria-label="Quality for ${video.getDisplayName()}">
  746. <option value="4K" ${video.quality === '4K' ? 'selected' : ''}>4K</option>
  747. <option value="1440p" ${video.quality === '1440p' ? 'selected' : ''}>1440p</option>
  748. <option value="1080p" ${video.quality === '1080p' ? 'selected' : ''}>1080p</option>
  749. <option value="720p" ${video.quality === '720p' ? 'selected' : ''}>720p</option>
  750. </select>
  751. </div>
  752. <!-- Format Dropdown -->
  753. <div class="flex justify-center">
  754. <select class="format-select bg-[#314158] border border-[#45556c] text-[#cad5e2] px-2 py-1 rounded text-xs font-medium min-w-0 w-full text-center"
  755. aria-label="Format for ${video.getDisplayName()}">
  756. <option value="None" ${video.format === 'None' ? 'selected' : ''}>None</option>
  757. <option value="H264" ${video.format === 'H264' ? 'selected' : ''}>H264</option>
  758. <option value="ProRes" ${video.format === 'ProRes' ? 'selected' : ''}>ProRes</option>
  759. <option value="DNxHR" ${video.format === 'DNxHR' ? 'selected' : ''}>DNxHR</option>
  760. <option value="Audio only" ${video.format === 'Audio only' ? 'selected' : ''}>Audio only</option>
  761. </select>
  762. </div>
  763. <!-- Status Badge -->
  764. <div class="flex justify-center status-column">
  765. <span class="status-badge ${video.status}" role="status" aria-live="polite">
  766. ${this.getStatusText(video)}
  767. </span>
  768. </div>
  769. <!-- Delete Button -->
  770. <div class="flex items-center justify-center">
  771. <button class="delete-video-btn w-6 h-6 rounded flex items-center justify-center hover:bg-red-600 hover:text-white text-[#90a1b9] transition-colors duration-200"
  772. aria-label="Delete ${video.getDisplayName()}" title="Remove from queue">
  773. <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5">
  774. <path d="M3 4h10M5 4V3a1 1 0 011-1h4a1 1 0 011 1v1M6 7v4M10 7v4M4 4l1 9a1 1 0 001 1h4a1 1 0 001-1l1-9"
  775. stroke-linecap="round" stroke-linejoin="round"/>
  776. </svg>
  777. </button>
  778. </div>
  779. `;
  780. return div;
  781. }
  782. getStatusText(video) {
  783. switch (video.status) {
  784. case 'downloading':
  785. return `Downloading ${video.progress || 0}%`;
  786. case 'converting':
  787. return `Converting ${video.progress || 0}%`;
  788. case 'completed':
  789. return 'Completed';
  790. case 'error':
  791. return 'Error';
  792. case 'ready':
  793. default:
  794. return 'Ready';
  795. }
  796. }
  797. updateVideoElement(video) {
  798. const videoElement = document.querySelector(`[data-video-id="${video.id}"]`);
  799. if (!videoElement) return;
  800. // Update thumbnail - show loading spinner if fetching metadata
  801. const thumbnailContainer = videoElement.querySelector('.w-16.h-12');
  802. if (thumbnailContainer) {
  803. if (video.isFetchingMetadata) {
  804. thumbnailContainer.innerHTML = `
  805. <div class="w-full h-full bg-gradient-to-br from-[#4a5568] to-[#2d3748] flex items-center justify-center">
  806. <svg class="animate-spin h-5 w-5 text-[#155dfc]" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
  807. <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
  808. <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
  809. </svg>
  810. </div>`;
  811. } else if (video.thumbnail) {
  812. thumbnailContainer.innerHTML = `<img src="${video.thumbnail}" alt="${video.getDisplayName()}" class="w-full h-full object-cover">`;
  813. } else {
  814. thumbnailContainer.innerHTML = `
  815. <div class="w-full h-full bg-gradient-to-br from-[#4a5568] to-[#2d3748] flex items-center justify-center">
  816. <svg width="24" height="24" viewBox="0 0 24 24" fill="none" class="text-[#90a1b9]">
  817. <path d="M8 5V19L19 12L8 5Z" stroke="currentColor" stroke-width="2" stroke-linejoin="round" />
  818. </svg>
  819. </div>`;
  820. }
  821. }
  822. // Update title and loading message
  823. const titleContainer = videoElement.querySelector('.min-w-0.flex-1');
  824. if (titleContainer) {
  825. const titleElement = titleContainer.querySelector('.text-sm.text-white.truncate');
  826. if (titleElement) {
  827. titleElement.textContent = video.getDisplayName();
  828. }
  829. // Update or remove "Fetching info..." message
  830. const existingLoadingMsg = titleContainer.querySelector('.text-xs.text-\\[\\#155dfc\\]');
  831. if (video.isFetchingMetadata && !existingLoadingMsg) {
  832. const loadingMsg = document.createElement('div');
  833. loadingMsg.className = 'text-xs text-[#155dfc] animate-pulse';
  834. loadingMsg.textContent = 'Fetching info...';
  835. titleContainer.appendChild(loadingMsg);
  836. } else if (!video.isFetchingMetadata && existingLoadingMsg) {
  837. existingLoadingMsg.remove();
  838. }
  839. }
  840. // Update duration
  841. const durationElement = videoElement.querySelector('.text-sm.text-\\[\\#cad5e2\\].text-center');
  842. if (durationElement) {
  843. durationElement.textContent = video.duration || '--:--';
  844. }
  845. // Update quality dropdown
  846. const qualitySelect = videoElement.querySelector('.quality-select');
  847. if (qualitySelect) {
  848. qualitySelect.value = video.quality;
  849. }
  850. // Update format dropdown
  851. const formatSelect = videoElement.querySelector('.format-select');
  852. if (formatSelect) {
  853. formatSelect.value = video.format;
  854. }
  855. // Update status badge with progress
  856. const statusBadge = videoElement.querySelector('.status-badge');
  857. if (statusBadge) {
  858. statusBadge.className = `status-badge ${video.status}`;
  859. statusBadge.textContent = this.getStatusText(video);
  860. // Add progress bar for downloading/converting states
  861. if (video.status === 'downloading' || video.status === 'converting') {
  862. const progress = video.progress || 0;
  863. statusBadge.style.background = `linear-gradient(to right, #155dfc ${progress}%, #314158 ${progress}%)`;
  864. } else {
  865. statusBadge.style.background = '';
  866. }
  867. }
  868. }
  869. updateStatsDisplay() {
  870. const stats = this.state.getStats();
  871. // Update UI with current statistics
  872. }
  873. updateConfigUI(config) {
  874. this.updateSavePathDisplay();
  875. this.initializeDropdowns();
  876. }
  877. updateStatusMessage(message) {
  878. const statusElement = document.getElementById('statusMessage');
  879. if (statusElement) {
  880. statusElement.textContent = message;
  881. }
  882. // Auto-clear success messages
  883. if (!message.toLowerCase().includes('error') && !message.toLowerCase().includes('failed')) {
  884. setTimeout(() => {
  885. if (statusElement && statusElement.textContent === message) {
  886. statusElement.textContent = 'Ready to download videos';
  887. }
  888. }, 5000);
  889. }
  890. }
  891. showError(message) {
  892. this.updateStatusMessage(`Error: ${message}`);
  893. console.error('App Error:', message);
  894. this.eventBus.emit('app:error', { type: 'user', message });
  895. }
  896. displayError(errorData) {
  897. const message = errorData.error?.message || errorData.message || 'An error occurred';
  898. this.updateStatusMessage(`Error: ${message}`);
  899. }
  900. // Keyboard navigation
  901. initializeKeyboardNavigation() {
  902. // Basic keyboard navigation setup
  903. document.addEventListener('keydown', (e) => {
  904. if (e.ctrlKey || e.metaKey) {
  905. switch (e.key) {
  906. case 'a':
  907. e.preventDefault();
  908. this.state.selectAllVideos();
  909. break;
  910. case 'd':
  911. e.preventDefault();
  912. this.handleDownloadVideos();
  913. break;
  914. }
  915. }
  916. });
  917. }
  918. // Ensure save directory exists
  919. async ensureSaveDirectoryExists() {
  920. const savePath = this.state.config.savePath;
  921. if (!savePath || !window.electronAPI) return;
  922. try {
  923. const result = await window.electronAPI.createDirectory(savePath);
  924. if (!result.success) {
  925. console.warn('Failed to create save directory:', result.error);
  926. } else {
  927. console.log('Save directory ready:', result.path);
  928. }
  929. } catch (error) {
  930. console.error('Error creating directory:', error);
  931. }
  932. }
  933. // Check binary status and validate with blocking dialog if missing
  934. async checkAndValidateBinaries() {
  935. if (!window.IPCManager || !window.IPCManager.isAvailable()) return;
  936. try {
  937. const versions = await window.IPCManager.checkBinaryVersions();
  938. // Handle both ytDlp (from main.js) and ytdlp (legacy) formats
  939. const ytdlp = versions.ytDlp || versions.ytdlp;
  940. const ffmpeg = versions.ffmpeg;
  941. if (!versions || !ytdlp || !ytdlp.available || !ffmpeg || !ffmpeg.available) {
  942. this.updateDependenciesButtonStatus('missing');
  943. this.updateBinaryVersionDisplay(null);
  944. // Show blocking dialog to warn user
  945. await this.showMissingBinariesDialog(ytdlp, ffmpeg);
  946. } else {
  947. this.updateDependenciesButtonStatus('ok');
  948. // Normalize the format for display
  949. const normalizedVersions = {
  950. ytdlp: ytdlp,
  951. ffmpeg: ffmpeg
  952. };
  953. this.updateBinaryVersionDisplay(normalizedVersions);
  954. }
  955. } catch (error) {
  956. console.error('Error checking binary status:', error);
  957. // Set missing status on error
  958. this.updateDependenciesButtonStatus('missing');
  959. this.updateBinaryVersionDisplay(null);
  960. // Show dialog on error too
  961. await this.showMissingBinariesDialog(null, null);
  962. }
  963. }
  964. // Show blocking dialog when binaries are missing
  965. async showMissingBinariesDialog(ytdlp, ffmpeg) {
  966. // Determine which binaries are missing
  967. const missingBinaries = [];
  968. if (!ytdlp || !ytdlp.available) missingBinaries.push('yt-dlp');
  969. if (!ffmpeg || !ffmpeg.available) missingBinaries.push('ffmpeg');
  970. const missingList = missingBinaries.length > 0
  971. ? missingBinaries.join(', ')
  972. : 'yt-dlp and ffmpeg';
  973. if (window.electronAPI && window.electronAPI.showErrorDialog) {
  974. // Use native Electron dialog
  975. await window.electronAPI.showErrorDialog({
  976. title: 'Required Binaries Missing',
  977. message: `The following required binaries are missing: ${missingList}`,
  978. detail: 'Please run "npm run setup" in the terminal to download the required binaries.\n\n' +
  979. 'Without these binaries, GrabZilla cannot download or convert videos.\n\n' +
  980. 'After running "npm run setup", restart the application.'
  981. });
  982. } else {
  983. // Fallback to browser alert
  984. alert(
  985. `⚠️ Required Binaries Missing\n\n` +
  986. `Missing: ${missingList}\n\n` +
  987. `Please run "npm run setup" to download the required binaries.\n\n` +
  988. `Without these binaries, GrabZilla cannot download or convert videos.`
  989. );
  990. }
  991. }
  992. // Check binary status and update UI (non-blocking version for updates)
  993. async checkBinaryStatus() {
  994. if (!window.IPCManager || !window.IPCManager.isAvailable()) return;
  995. try {
  996. const versions = await window.IPCManager.checkBinaryVersions();
  997. // Handle both ytDlp (from main.js) and ytdlp (legacy) formats
  998. const ytdlp = versions.ytDlp || versions.ytdlp;
  999. const ffmpeg = versions.ffmpeg;
  1000. if (!versions || !ytdlp || !ytdlp.available || !ffmpeg || !ffmpeg.available) {
  1001. this.updateDependenciesButtonStatus('missing');
  1002. this.updateBinaryVersionDisplay(null);
  1003. } else {
  1004. this.updateDependenciesButtonStatus('ok');
  1005. // Normalize the format for display
  1006. const normalizedVersions = {
  1007. ytdlp: ytdlp,
  1008. ffmpeg: ffmpeg
  1009. };
  1010. this.updateBinaryVersionDisplay(normalizedVersions);
  1011. }
  1012. } catch (error) {
  1013. console.error('Error checking binary status:', error);
  1014. // Set missing status on error
  1015. this.updateDependenciesButtonStatus('missing');
  1016. this.updateBinaryVersionDisplay(null);
  1017. }
  1018. }
  1019. updateBinaryVersionDisplay(versions) {
  1020. const statusMessage = document.getElementById('statusMessage');
  1021. if (!statusMessage) return;
  1022. if (!versions) {
  1023. // Binaries missing
  1024. statusMessage.textContent = 'Ready to download videos - Binaries required';
  1025. return;
  1026. }
  1027. // Format version strings
  1028. const ytdlpVersion = versions.ytdlp?.version || 'unknown';
  1029. const ffmpegVersion = versions.ffmpeg?.version || 'unknown';
  1030. // Check for updates
  1031. const hasUpdates = (versions.ytdlp?.updateAvailable || versions.ffmpeg?.updateAvailable);
  1032. const updateText = hasUpdates ? ' - Newer version available' : '';
  1033. // Build status message
  1034. statusMessage.textContent = `Ready | yt-dlp: ${ytdlpVersion} | ffmpeg: ${ffmpegVersion}${updateText}`;
  1035. }
  1036. updateDependenciesButtonStatus(status) {
  1037. const btn = document.getElementById('updateDepsBtn');
  1038. if (!btn) return;
  1039. if (status === 'missing') {
  1040. btn.classList.add('bg-red-600', 'animate-pulse');
  1041. btn.classList.remove('bg-[#314158]');
  1042. btn.innerHTML = '<img src="assets/icons/refresh.svg" alt="" width="16" height="16" loading="lazy">⚠️ Required';
  1043. } else {
  1044. btn.classList.remove('bg-red-600', 'animate-pulse');
  1045. btn.classList.add('bg-[#314158]');
  1046. btn.innerHTML = '<img src="assets/icons/refresh.svg" alt="" width="16" height="16" loading="lazy">Check for Updates';
  1047. }
  1048. }
  1049. // State persistence
  1050. async loadState() {
  1051. try {
  1052. const savedState = localStorage.getItem('grabzilla-state');
  1053. if (savedState) {
  1054. const data = JSON.parse(savedState);
  1055. this.state.fromJSON(data);
  1056. console.log('✅ Loaded saved state');
  1057. // Re-render video list to show restored videos
  1058. this.renderVideoList();
  1059. this.updateSavePathDisplay();
  1060. this.updateStatsDisplay();
  1061. }
  1062. } catch (error) {
  1063. console.warn('Failed to load saved state:', error);
  1064. }
  1065. }
  1066. async saveState() {
  1067. try {
  1068. const stateData = this.state.toJSON();
  1069. localStorage.setItem('grabzilla-state', JSON.stringify(stateData));
  1070. } catch (error) {
  1071. console.warn('Failed to save state:', error);
  1072. }
  1073. }
  1074. // Lifecycle methods
  1075. handleInitializationError(error) {
  1076. // Show fallback UI or error message
  1077. const statusElement = document.getElementById('statusMessage');
  1078. if (statusElement) {
  1079. statusElement.textContent = 'Failed to initialize application';
  1080. }
  1081. }
  1082. destroy() {
  1083. // Clean up resources
  1084. if (this.state) {
  1085. this.saveState();
  1086. }
  1087. // Remove event listeners
  1088. this.eventBus?.removeAllListeners();
  1089. this.initialized = false;
  1090. console.log('🧹 GrabZilla app destroyed');
  1091. }
  1092. }
  1093. // Initialize function to be called after all scripts are loaded
  1094. window.initializeGrabZilla = function() {
  1095. window.app = new GrabZillaApp();
  1096. window.app.init();
  1097. };
  1098. // Auto-save state on page unload
  1099. window.addEventListener('beforeunload', () => {
  1100. if (window.app?.initialized) {
  1101. window.app.saveState();
  1102. }
  1103. });
  1104. // Export the app class
  1105. if (typeof module !== 'undefined' && module.exports) {
  1106. module.exports = GrabZillaApp;
  1107. } else {
  1108. window.GrabZillaApp = GrabZillaApp;
  1109. }