base.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  1. // Player status bar functionality - Updated to fix logMessage errors
  2. // Update LED nav label based on provider
  3. async function updateLedNavLabel() {
  4. try {
  5. const response = await fetch('/get_led_config');
  6. if (response.ok) {
  7. const data = await response.json();
  8. const navLabel = document.getElementById('led-nav-label');
  9. if (navLabel) {
  10. if (data.provider === 'wled') {
  11. navLabel.textContent = 'WLED';
  12. } else if (data.provider === 'dw_leds') {
  13. navLabel.textContent = 'DW LEDs';
  14. } else {
  15. navLabel.textContent = 'LED';
  16. }
  17. }
  18. }
  19. } catch (error) {
  20. console.error('Error updating LED nav label:', error);
  21. }
  22. }
  23. // Call on page load
  24. document.addEventListener('DOMContentLoaded', updateLedNavLabel);
  25. // Pattern files cache for improved performance with localStorage persistence
  26. const PATTERN_CACHE_KEY = 'dune_weaver_pattern_files_cache';
  27. const PATTERN_CACHE_EXPIRY = 30 * 60 * 1000; // 30 minutes cache (longer since it persists)
  28. // Function to get cached pattern files or fetch fresh data
  29. async function getCachedPatternFiles(forceRefresh = false) {
  30. const now = Date.now();
  31. // Try to load from localStorage first
  32. if (!forceRefresh) {
  33. try {
  34. const cachedData = localStorage.getItem(PATTERN_CACHE_KEY);
  35. if (cachedData) {
  36. const { files, timestamp } = JSON.parse(cachedData);
  37. if (files && timestamp && (now - timestamp) < PATTERN_CACHE_EXPIRY) {
  38. console.log('Using cached pattern files from localStorage');
  39. return files;
  40. }
  41. }
  42. } catch (error) {
  43. console.warn('Error reading pattern files cache from localStorage:', error);
  44. }
  45. }
  46. try {
  47. console.log('Fetching fresh pattern files from server');
  48. const response = await fetch('/list_theta_rho_files');
  49. if (!response.ok) {
  50. throw new Error(`Failed to fetch pattern files: ${response.status}`);
  51. }
  52. const files = await response.json();
  53. // Store in localStorage
  54. try {
  55. const cacheData = { files, timestamp: now };
  56. localStorage.setItem(PATTERN_CACHE_KEY, JSON.stringify(cacheData));
  57. } catch (error) {
  58. console.warn('Error storing pattern files cache in localStorage:', error);
  59. }
  60. return files;
  61. } catch (error) {
  62. console.error('Error fetching pattern files:', error);
  63. // Try to return any cached data as fallback, even if expired
  64. try {
  65. const cachedData = localStorage.getItem(PATTERN_CACHE_KEY);
  66. if (cachedData) {
  67. const { files } = JSON.parse(cachedData);
  68. if (files) {
  69. console.log('Using expired cached pattern files as fallback');
  70. return files;
  71. }
  72. }
  73. } catch (fallbackError) {
  74. console.warn('Error reading fallback cache:', fallbackError);
  75. }
  76. return [];
  77. }
  78. }
  79. // Function to invalidate pattern files cache
  80. function invalidatePatternFilesCache() {
  81. try {
  82. localStorage.removeItem(PATTERN_CACHE_KEY);
  83. console.log('Pattern files cache invalidated');
  84. } catch (error) {
  85. console.warn('Error invalidating pattern files cache:', error);
  86. }
  87. }
  88. // Helper function to normalize file paths for cross-platform compatibility
  89. function normalizeFilePath(filePath) {
  90. if (!filePath) return '';
  91. // First normalize path separators
  92. let normalized = filePath.replace(/\\/g, '/');
  93. // Remove only the patterns directory prefix, not patterns within the path
  94. if (normalized.startsWith('./patterns/')) {
  95. normalized = normalized.substring(11);
  96. } else if (normalized.startsWith('patterns/')) {
  97. normalized = normalized.substring(9);
  98. }
  99. return normalized;
  100. }
  101. let ws = null;
  102. let reconnectAttempts = 0;
  103. const maxReconnectAttempts = 5;
  104. const reconnectDelay = 3000; // 3 seconds
  105. let isEditingSpeed = false; // Track if user is editing speed
  106. let playerPreviewData = null; // Store the current pattern's preview data for modal
  107. let playerPreviewCtx = null; // Store the canvas context for modal preview
  108. let playerAnimationId = null; // Store animation frame ID for modal
  109. let lastProgress = 0; // Last known progress from backend
  110. let targetProgress = 0; // Target progress to animate towards
  111. let animationStartTime = 0; // Start time of current animation
  112. let animationDuration = 1000; // Duration of interpolation in ms
  113. let smoothAnimationStartTime = 0; // Start time for smooth coordinate animation
  114. let smoothAnimationActive = false; // Whether smooth animation is running
  115. let modalAnimationId = null; // Store animation frame ID for modal
  116. let modalLastProgress = 0; // Last known progress for modal
  117. let modalTargetProgress = 0; // Target progress for modal
  118. let modalAnimationStartTime = 0; // Start time for modal animation
  119. let userDismissedModal = false; // Track if user has manually dismissed the modal
  120. // Function to set modal visibility
  121. function setModalVisibility(show, userAction = false) {
  122. const modal = document.getElementById('playerPreviewModal');
  123. if (!modal) return;
  124. if (show) {
  125. modal.classList.remove('hidden');
  126. } else {
  127. modal.classList.add('hidden');
  128. }
  129. if (userAction) {
  130. userDismissedModal = !show;
  131. }
  132. }
  133. let currentPreviewFile = null; // Track the current file for preview data
  134. function connectWebSocket() {
  135. if (ws) {
  136. ws.close();
  137. }
  138. ws = new WebSocket(`ws://${window.location.host}/ws/status`);
  139. ws.onopen = function() {
  140. console.log("WebSocket connection established");
  141. reconnectAttempts = 0;
  142. };
  143. ws.onclose = function() {
  144. console.log("WebSocket connection closed");
  145. if (reconnectAttempts < maxReconnectAttempts) {
  146. reconnectAttempts++;
  147. setTimeout(connectWebSocket, reconnectDelay);
  148. }
  149. };
  150. ws.onerror = function(error) {
  151. console.error("WebSocket error:", error);
  152. };
  153. ws.onmessage = function(event) {
  154. try {
  155. const data = JSON.parse(event.data);
  156. if (data.type === 'status_update') {
  157. // Update modal status with the full data
  158. syncModalControls(data.data);
  159. // Update speed input field on table control page if it exists
  160. if (data.data && data.data.speed) {
  161. const currentSpeedDisplay = document.getElementById('currentSpeedDisplay');
  162. if (currentSpeedDisplay) {
  163. currentSpeedDisplay.textContent = `${data.data.speed} mm/s`;
  164. }
  165. }
  166. // Update connection status dot using 'connection_status' or fallback to 'connected'
  167. if (data.data.hasOwnProperty('connection_status')) {
  168. updateConnectionStatus(data.data.connection_status);
  169. }
  170. // Check if current file has changed and reload preview data if needed
  171. if (data.data.current_file) {
  172. const newFile = normalizeFilePath(data.data.current_file);
  173. if (newFile !== currentPreviewFile) {
  174. currentPreviewFile = newFile;
  175. // Only preload if we're on the browse page (index.html)
  176. // Other pages (playlists, table_control, LED, settings) will load on-demand
  177. const modal = document.getElementById('playerPreviewModal');
  178. const browsePage = document.getElementById('browseSortFieldSelect');
  179. if (modal && browsePage) {
  180. // We're on the browse page with the modal - preload coordinates
  181. loadPlayerPreviewData(data.data.current_file);
  182. }
  183. }
  184. } else {
  185. currentPreviewFile = null;
  186. playerPreviewData = null;
  187. }
  188. // Update progress for modal animation with smooth interpolation
  189. if (playerPreviewData && data.data.progress && data.data.progress.percentage !== null) {
  190. const newProgress = data.data.progress.percentage / 100;
  191. targetProgress = newProgress;
  192. // Update modal if open with smooth animation
  193. const modal = document.getElementById('playerPreviewModal');
  194. if (modal && !modal.classList.contains('hidden')) {
  195. updateModalPreviewSmooth(newProgress);
  196. }
  197. }
  198. // Reset userDismissedModal flag if no pattern is playing
  199. if (!data.data.current_file || !data.data.is_running) {
  200. userDismissedModal = false;
  201. }
  202. }
  203. } catch (error) {
  204. console.error("Error processing WebSocket message:", error);
  205. }
  206. };
  207. }
  208. function updateConnectionStatus(isConnected) {
  209. const statusDot = document.getElementById("connectionStatusDot");
  210. if (statusDot) {
  211. // Update dot color
  212. statusDot.className = `inline-block size-2 rounded-full ml-2 align-middle ${
  213. isConnected ? "bg-green-500" : "bg-red-500"
  214. }`;
  215. }
  216. }
  217. // Setup player preview with expand button
  218. function setupPlayerPreview() {
  219. const previewContainer = document.getElementById('player-pattern-preview');
  220. if (!previewContainer) return;
  221. // Get current background image URL
  222. const currentBgImage = previewContainer.style.backgroundImage;
  223. // Clear container
  224. previewContainer.innerHTML = '';
  225. previewContainer.style.backgroundImage = '';
  226. // Create preview image container
  227. const imageContainer = document.createElement('div');
  228. imageContainer.className = 'relative aspect-square rounded-full overflow-hidden w-full h-full';
  229. // Create image element
  230. const img = document.createElement('img');
  231. img.className = 'w-full h-full object-cover';
  232. // img.alt = 'Pattern Preview';
  233. // Extract URL from background-image CSS
  234. img.src = currentBgImage.replace(/^url\(['"](.+)['"]\)$/, '$1');
  235. // Add expand button overlay
  236. const expandOverlay = document.createElement('div');
  237. expandOverlay.className = 'absolute inset-0 flex items-center justify-center opacity-0 hover:opacity-100 transition-opacity duration-200 cursor-pointer z-20 bg-black bg-opacity-20 hover:bg-opacity-30';
  238. expandOverlay.innerHTML = '<div class="bg-white rounded-full p-3 shadow-lg flex items-center justify-center w-12 h-12"><span class="material-icons text-xl text-gray-800">fullscreen</span></div>';
  239. // Add click handler for expand button
  240. expandOverlay.addEventListener('click', (e) => {
  241. e.stopPropagation();
  242. openPlayerPreviewModal();
  243. });
  244. // Add image and overlay to image container
  245. imageContainer.appendChild(img);
  246. imageContainer.appendChild(expandOverlay);
  247. // Add image container to preview container
  248. previewContainer.appendChild(imageContainer);
  249. }
  250. // Open player preview modal
  251. async function openPlayerPreviewModal() {
  252. try {
  253. const modal = document.getElementById('playerPreviewModal');
  254. const title = document.getElementById('playerPreviewTitle');
  255. const canvas = document.getElementById('playerPreviewCanvas');
  256. const ctx = canvas.getContext('2d');
  257. const toggleBtn = document.getElementById('toggle-preview-modal-btn');
  258. // Show modal immediately for instant feedback
  259. modal.classList.remove('hidden');
  260. // Setup canvas (so it's ready to display loading state)
  261. setupPlayerPreviewCanvas(ctx);
  262. // Load preview data on-demand if not already loaded
  263. if (!playerPreviewData && currentPreviewFile) {
  264. // Show loading state
  265. title.textContent = 'Loading pattern...';
  266. drawLoadingState(ctx);
  267. // Load data in background
  268. await loadPlayerPreviewData(`./patterns/${currentPreviewFile}`);
  269. // Update title when loaded
  270. title.textContent = 'Live Pattern Preview';
  271. } else {
  272. // Data already loaded
  273. title.textContent = 'Live Pattern Preview';
  274. }
  275. // Draw the pattern (either immediately if cached, or after loading)
  276. drawPlayerPreview(ctx, targetProgress);
  277. } catch (error) {
  278. console.error(`Error opening player preview modal: ${error.message}`);
  279. showStatusMessage('Failed to load pattern for animation', 'error');
  280. }
  281. }
  282. // Setup player preview canvas for modal
  283. function setupPlayerPreviewCanvas(ctx) {
  284. const canvas = ctx.canvas;
  285. const container = canvas.parentElement; // This is the div with max-w and max-h constraints
  286. const modal = document.getElementById('playerPreviewModal');
  287. if (!container || !modal) return;
  288. // Calculate available viewport space directly
  289. const viewportWidth = window.innerWidth;
  290. const viewportHeight = window.innerHeight;
  291. // Calculate maximum canvas size based on viewport and fixed estimates
  292. // Modal uses max-w-5xl (1024px) but we want to be responsive to actual viewport
  293. const modalMaxWidth = Math.min(1024, viewportWidth * 0.9); // Account for modal padding
  294. const modalMaxHeight = viewportHeight * 0.95; // max-h-[95vh]
  295. // Reserve space for modal header (~80px) and controls (~200px) and padding
  296. const reservedSpace = 320; // Header + controls + padding
  297. const availableModalHeight = modalMaxHeight - reservedSpace;
  298. // Calculate canvas constraints (stay within original 800px max, but be responsive)
  299. const maxCanvasSize = Math.min(800, modalMaxWidth - 64, availableModalHeight); // 64px for canvas area padding
  300. // Ensure minimum size
  301. const finalSize = Math.max(200, maxCanvasSize);
  302. // Update container to exact size (override CSS constraints)
  303. container.style.width = `${finalSize}px`;
  304. container.style.height = `${finalSize}px`;
  305. container.style.maxWidth = `${finalSize}px`;
  306. container.style.maxHeight = `${finalSize}px`;
  307. container.style.minWidth = `${finalSize}px`;
  308. container.style.minHeight = `${finalSize}px`;
  309. // Set the internal canvas size for high-DPI rendering
  310. const pixelRatio = (window.devicePixelRatio || 1) * 2;
  311. canvas.width = finalSize * pixelRatio;
  312. canvas.height = finalSize * pixelRatio;
  313. // Set the display size (canvas fills its container)
  314. canvas.style.width = '100%';
  315. canvas.style.height = '100%';
  316. console.log('Canvas resized:', {
  317. viewport: `${viewportWidth}x${viewportHeight}`,
  318. modalMaxWidth,
  319. availableModalHeight,
  320. finalSize: finalSize
  321. });
  322. }
  323. // Get interpolated coordinate at specific progress
  324. function getInterpolatedCoordinate(progress) {
  325. if (!playerPreviewData || playerPreviewData.length === 0) return null;
  326. const totalPoints = playerPreviewData.length;
  327. const exactIndex = progress * (totalPoints - 1);
  328. const index = Math.floor(exactIndex);
  329. const fraction = exactIndex - index;
  330. // Ensure we don't go out of bounds
  331. if (index >= totalPoints - 1) {
  332. return playerPreviewData[totalPoints - 1];
  333. }
  334. if (index < 0) {
  335. return playerPreviewData[0];
  336. }
  337. // Get the two coordinates to interpolate between
  338. const [theta1, rho1] = playerPreviewData[index];
  339. const [theta2, rho2] = playerPreviewData[index + 1];
  340. // Interpolate theta (handle angle wrapping)
  341. let deltaTheta = theta2 - theta1;
  342. if (deltaTheta > Math.PI) deltaTheta -= 2 * Math.PI;
  343. if (deltaTheta < -Math.PI) deltaTheta += 2 * Math.PI;
  344. const interpolatedTheta = theta1 + deltaTheta * fraction;
  345. const interpolatedRho = rho1 + (rho2 - rho1) * fraction;
  346. return [interpolatedTheta, interpolatedRho];
  347. }
  348. // Draw loading state on canvas
  349. function drawLoadingState(ctx) {
  350. if (!ctx) return;
  351. const canvas = ctx.canvas;
  352. const pixelRatio = (window.devicePixelRatio || 1) * 2;
  353. const containerSize = canvas.width / pixelRatio;
  354. const center = containerSize / 2;
  355. ctx.save();
  356. // Clear canvas
  357. ctx.clearRect(0, 0, canvas.width, canvas.height);
  358. // Create circular clipping path
  359. ctx.beginPath();
  360. ctx.arc(canvas.width/2, canvas.height/2, canvas.width/2, 0, Math.PI * 2);
  361. ctx.clip();
  362. // Setup coordinate system
  363. ctx.scale(pixelRatio, pixelRatio);
  364. // Draw loading text
  365. ctx.fillStyle = '#9ca3af';
  366. ctx.font = '16px sans-serif';
  367. ctx.textAlign = 'center';
  368. ctx.textBaseline = 'middle';
  369. ctx.fillText('Loading pattern...', center, center);
  370. // Draw spinning circle
  371. const time = Date.now() / 1000;
  372. const radius = 30;
  373. ctx.strokeStyle = '#0c7ff2';
  374. ctx.lineWidth = 3;
  375. ctx.lineCap = 'round';
  376. ctx.beginPath();
  377. ctx.arc(center, center - 40, radius, time * 2, time * 2 + Math.PI * 1.5);
  378. ctx.stroke();
  379. ctx.restore();
  380. }
  381. // Draw player preview for modal
  382. function drawPlayerPreview(ctx, progress) {
  383. if (!ctx || !playerPreviewData || playerPreviewData.length === 0) return;
  384. const canvas = ctx.canvas;
  385. const pixelRatio = (window.devicePixelRatio || 1) * 2;
  386. const containerSize = canvas.width / pixelRatio;
  387. const center = containerSize / 2;
  388. const scale = (containerSize / 2) - 30;
  389. ctx.save();
  390. // Clear canvas for fresh drawing
  391. ctx.clearRect(0, 0, canvas.width, canvas.height);
  392. // Create circular clipping path
  393. ctx.beginPath();
  394. ctx.arc(canvas.width/2, canvas.height/2, canvas.width/2, 0, Math.PI * 2);
  395. ctx.clip();
  396. // Setup coordinate system for drawing
  397. ctx.scale(pixelRatio, pixelRatio);
  398. // Calculate how many points to draw
  399. const totalPoints = playerPreviewData.length;
  400. const pointsToDraw = Math.floor(totalPoints * progress);
  401. if (pointsToDraw < 2) {
  402. ctx.restore();
  403. return;
  404. }
  405. // Draw the pattern
  406. ctx.beginPath();
  407. ctx.strokeStyle = '#808080';
  408. ctx.lineWidth = 1;
  409. ctx.lineCap = 'round';
  410. ctx.lineJoin = 'round';
  411. // Enable high quality rendering
  412. ctx.imageSmoothingEnabled = true;
  413. ctx.imageSmoothingQuality = 'high';
  414. // Draw pattern lines up to the last complete segment
  415. for (let i = 0; i < pointsToDraw - 1; i++) {
  416. const [theta1, rho1] = playerPreviewData[i];
  417. const [theta2, rho2] = playerPreviewData[i + 1];
  418. const x1 = center + rho1 * scale * Math.cos(theta1);
  419. const y1 = center + rho1 * scale * Math.sin(theta1);
  420. const x2 = center + rho2 * scale * Math.cos(theta2);
  421. const y2 = center + rho2 * scale * Math.sin(theta2);
  422. if (i === 0) {
  423. ctx.moveTo(x1, y1);
  424. }
  425. ctx.lineTo(x2, y2);
  426. }
  427. // Draw the final partial segment to the interpolated position
  428. if (pointsToDraw > 0) {
  429. const interpolatedCoord = getInterpolatedCoordinate(progress);
  430. if (interpolatedCoord && pointsToDraw > 1) {
  431. // Get the last complete coordinate
  432. const [lastTheta, lastRho] = playerPreviewData[pointsToDraw - 1];
  433. const lastX = center + lastRho * scale * Math.cos(lastTheta);
  434. const lastY = center + lastRho * scale * Math.sin(lastTheta);
  435. // Draw line to interpolated position
  436. const [interpTheta, interpRho] = interpolatedCoord;
  437. const interpX = center + interpRho * scale * Math.cos(interpTheta);
  438. const interpY = center + interpRho * scale * Math.sin(interpTheta);
  439. ctx.lineTo(interpX, interpY);
  440. }
  441. }
  442. ctx.stroke();
  443. // Draw current position dot with interpolated position
  444. if (pointsToDraw > 0) {
  445. const interpolatedCoord = getInterpolatedCoordinate(progress);
  446. if (interpolatedCoord) {
  447. const [theta, rho] = interpolatedCoord;
  448. const x = center + rho * scale * Math.cos(theta);
  449. const y = center + rho * scale * Math.sin(theta);
  450. // Draw white border
  451. ctx.beginPath();
  452. ctx.fillStyle = '#ffffff';
  453. ctx.arc(x, y, 7.5, 0, Math.PI * 2);
  454. ctx.fill();
  455. // Draw red dot
  456. ctx.beginPath();
  457. ctx.fillStyle = '#ff0000';
  458. ctx.arc(x, y, 6, 0, Math.PI * 2);
  459. ctx.fill();
  460. }
  461. }
  462. ctx.restore();
  463. }
  464. // Load pattern coordinates for player preview
  465. async function loadPlayerPreviewData(pattern) {
  466. try {
  467. const response = await fetch('/get_theta_rho_coordinates', {
  468. method: 'POST',
  469. headers: { 'Content-Type': 'application/json' },
  470. body: JSON.stringify({ file_name: pattern })
  471. });
  472. if (!response.ok) {
  473. throw new Error(`HTTP error! status: ${response.status}`);
  474. }
  475. const data = await response.json();
  476. if (data.error) {
  477. throw new Error(data.error);
  478. }
  479. playerPreviewData = data.coordinates;
  480. // Store the filename for comparison
  481. playerPreviewData.fileName = normalizeFilePath(pattern);
  482. } catch (error) {
  483. console.error(`Error loading player preview data: ${error.message}`);
  484. playerPreviewData = null;
  485. }
  486. }
  487. // Ultra-smooth animation function for modal
  488. function animateModalPreview() {
  489. const modal = document.getElementById('playerPreviewModal');
  490. if (!modal || modal.classList.contains('hidden')) return;
  491. const canvas = document.getElementById('playerPreviewCanvas');
  492. const ctx = canvas.getContext('2d');
  493. if (!ctx || !playerPreviewData) return;
  494. const currentTime = Date.now();
  495. const elapsed = currentTime - modalAnimationStartTime;
  496. const totalDuration = animationDuration;
  497. // Calculate smooth progress with easing
  498. const rawProgress = Math.min(elapsed / totalDuration, 1);
  499. const easeProgress = rawProgress < 0.5
  500. ? 2 * rawProgress * rawProgress
  501. : 1 - Math.pow(-2 * rawProgress + 2, 2) / 2;
  502. // Interpolate between last and target progress
  503. const currentProgress = modalLastProgress + (modalTargetProgress - modalLastProgress) * easeProgress;
  504. // Draw the pattern up to current progress
  505. drawPlayerPreview(ctx, currentProgress);
  506. // Continue animation if not at target
  507. if (rawProgress < 1) {
  508. modalAnimationId = requestAnimationFrame(animateModalPreview);
  509. }
  510. }
  511. // Update modal preview with smooth animation
  512. function updateModalPreviewSmooth(newProgress) {
  513. if (newProgress === modalTargetProgress) return; // No change needed
  514. // Stop any existing animation
  515. if (modalAnimationId) {
  516. cancelAnimationFrame(modalAnimationId);
  517. }
  518. // Update animation parameters
  519. modalLastProgress = modalTargetProgress;
  520. modalTargetProgress = newProgress;
  521. modalAnimationStartTime = Date.now();
  522. // Start smooth animation
  523. animateModalPreview();
  524. }
  525. // Setup player preview modal events
  526. function setupPlayerPreviewModalEvents() {
  527. const modal = document.getElementById('playerPreviewModal');
  528. const closeBtn = document.getElementById('closePlayerPreview');
  529. const toggleBtn = document.getElementById('toggle-preview-modal-btn');
  530. if (!modal || !closeBtn || !toggleBtn) return;
  531. // Remove any existing event listeners to prevent conflicts
  532. const newToggleBtn = toggleBtn.cloneNode(true);
  533. toggleBtn.parentNode.replaceChild(newToggleBtn, toggleBtn);
  534. // Toggle button click handler
  535. newToggleBtn.addEventListener('click', () => {
  536. const isHidden = modal.classList.contains('hidden');
  537. if (isHidden) {
  538. openPlayerPreviewModal();
  539. } else {
  540. modal.classList.add('hidden');
  541. }
  542. });
  543. // Close modal when clicking close button
  544. closeBtn.addEventListener('click', () => {
  545. setModalVisibility(false, true);
  546. });
  547. // Close modal when clicking outside
  548. modal.addEventListener('click', (e) => {
  549. if (e.target === modal) {
  550. setModalVisibility(false, true);
  551. }
  552. });
  553. // Close modal with Escape key
  554. document.addEventListener('keydown', (e) => {
  555. if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
  556. setModalVisibility(false, true);
  557. }
  558. });
  559. // Setup modal control buttons
  560. setupModalControls();
  561. }
  562. // Handle pause/resume toggle
  563. async function togglePauseResume() {
  564. const pauseButton = document.getElementById('modal-pause-button');
  565. if (!pauseButton) return;
  566. try {
  567. const pauseIcon = pauseButton.querySelector('.material-icons');
  568. const isCurrentlyPaused = pauseIcon.textContent === 'play_arrow';
  569. // Show immediate feedback
  570. showStatusMessage(isCurrentlyPaused ? 'Resuming...' : 'Pausing...', 'info');
  571. const endpoint = isCurrentlyPaused ? '/resume_execution' : '/pause_execution';
  572. const response = await fetch(endpoint, { method: 'POST' });
  573. if (!response.ok) throw new Error(`Failed to ${isCurrentlyPaused ? 'resume' : 'pause'}`);
  574. // Show success message
  575. showStatusMessage(isCurrentlyPaused ? 'Pattern resumed' : 'Pattern paused', 'success');
  576. } catch (error) {
  577. console.error('Error toggling pause:', error);
  578. showStatusMessage('Failed to pause/resume pattern', 'error');
  579. }
  580. }
  581. // Setup modal controls
  582. function setupModalControls() {
  583. const pauseButton = document.getElementById('modal-pause-button');
  584. const skipButton = document.getElementById('modal-skip-button');
  585. const stopButton = document.getElementById('modal-stop-button');
  586. const speedDisplay = document.getElementById('modal-speed-display');
  587. const speedInput = document.getElementById('modal-speed-input');
  588. if (!pauseButton || !skipButton || !stopButton || !speedDisplay || !speedInput) return;
  589. // Pause button click handler
  590. pauseButton.addEventListener('click', togglePauseResume);
  591. // Skip button click handler
  592. skipButton.addEventListener('click', async () => {
  593. try {
  594. // Show immediate feedback
  595. showStatusMessage('Skipping to next pattern...', 'info');
  596. const response = await fetch('/skip_pattern', { method: 'POST' });
  597. if (!response.ok) throw new Error('Failed to skip pattern');
  598. // Show success message
  599. showStatusMessage('Skipped to next pattern', 'success');
  600. } catch (error) {
  601. console.error('Error skipping pattern:', error);
  602. showStatusMessage('Failed to skip pattern', 'error');
  603. }
  604. });
  605. // Stop button click handler
  606. stopButton.addEventListener('click', async () => {
  607. try {
  608. // Show immediate feedback
  609. showStatusMessage('Stopping...', 'info');
  610. const response = await fetch('/stop_execution', { method: 'POST' });
  611. if (!response.ok) throw new Error('Failed to stop pattern');
  612. else {
  613. // Show success message
  614. showStatusMessage('Pattern stopped', 'success');
  615. // Hide modal when stopping
  616. const modal = document.getElementById('playerPreviewModal');
  617. if (modal) modal.classList.add('hidden');
  618. }
  619. } catch (error) {
  620. console.error('Error stopping pattern:', error);
  621. showStatusMessage('Failed to stop pattern', 'error');
  622. }
  623. });
  624. // Speed display click to edit
  625. speedDisplay.addEventListener('click', () => {
  626. isEditingSpeed = true;
  627. speedDisplay.classList.add('hidden');
  628. speedInput.value = speedDisplay.textContent;
  629. speedInput.classList.remove('hidden');
  630. speedInput.focus();
  631. speedInput.select();
  632. });
  633. // Speed input handlers
  634. speedInput.addEventListener('keydown', (e) => {
  635. if (e.key === 'Enter') {
  636. e.preventDefault();
  637. exitModalSpeedEditMode(true);
  638. } else if (e.key === 'Escape') {
  639. e.preventDefault();
  640. exitModalSpeedEditMode(false);
  641. }
  642. });
  643. speedInput.addEventListener('blur', () => {
  644. exitModalSpeedEditMode(true);
  645. });
  646. }
  647. // Exit modal speed edit mode
  648. async function exitModalSpeedEditMode(save = false) {
  649. const speedDisplay = document.getElementById('modal-speed-display');
  650. const speedInput = document.getElementById('modal-speed-input');
  651. if (!speedDisplay || !speedInput) return;
  652. isEditingSpeed = false;
  653. speedInput.classList.add('hidden');
  654. speedDisplay.classList.remove('hidden');
  655. if (save) {
  656. const speed = parseInt(speedInput.value);
  657. if (!isNaN(speed) && speed >= 1 && speed <= 5000) {
  658. try {
  659. const response = await fetch('/set_speed', {
  660. method: 'POST',
  661. headers: { 'Content-Type': 'application/json' },
  662. body: JSON.stringify({ speed: speed })
  663. });
  664. const data = await response.json();
  665. if (data.success) {
  666. speedDisplay.textContent = speed;
  667. showStatusMessage(`Speed set to ${speed} mm/s`, 'success');
  668. } else {
  669. throw new Error(data.detail || 'Failed to set speed');
  670. }
  671. } catch (error) {
  672. console.error('Error setting speed:', error);
  673. showStatusMessage('Failed to set speed', 'error');
  674. }
  675. } else {
  676. showStatusMessage('Please enter a valid speed (1-5000)', 'error');
  677. }
  678. }
  679. }
  680. // Helper function to clean up pattern names
  681. function getCleanPatternName(filePath) {
  682. if (!filePath) return '';
  683. const fileName = normalizeFilePath(filePath);
  684. return fileName.split('/').pop().replace('.thr', '');
  685. }
  686. // Sync modal controls with player status
  687. function syncModalControls(status) {
  688. // Pattern name - clean up to show only filename
  689. const modalPatternName = document.getElementById('modal-pattern-name');
  690. if (modalPatternName && status.current_file) {
  691. modalPatternName.textContent = getCleanPatternName(status.current_file);
  692. }
  693. // Pattern preview image
  694. const modalPatternPreviewImg = document.getElementById('modal-pattern-preview-img');
  695. if (modalPatternPreviewImg && status.current_file) {
  696. const encodedFilename = normalizeFilePath(status.current_file).replace(/[\\/]/g, '--');
  697. const previewUrl = `/preview/${encodedFilename}`;
  698. modalPatternPreviewImg.src = previewUrl;
  699. }
  700. // ETA
  701. const modalEta = document.getElementById('modal-eta');
  702. if (modalEta) {
  703. if (status.progress && status.progress.remaining_time !== null) {
  704. const minutes = Math.floor(status.progress.remaining_time / 60);
  705. const seconds = Math.floor(status.progress.remaining_time % 60);
  706. modalEta.textContent = `ETA: ${minutes}:${seconds.toString().padStart(2, '0')}`;
  707. } else {
  708. modalEta.textContent = 'ETA: calculating...';
  709. }
  710. }
  711. // Progress bar
  712. const modalProgressBar = document.getElementById('modal-progress-bar');
  713. if (modalProgressBar) {
  714. if (status.progress && status.progress.percentage !== null) {
  715. modalProgressBar.style.width = `${status.progress.percentage}%`;
  716. } else {
  717. modalProgressBar.style.width = '0%';
  718. }
  719. }
  720. // Next pattern - clean up to show only filename
  721. const modalNextPattern = document.getElementById('modal-next-pattern');
  722. if (modalNextPattern) {
  723. if (status.playlist && status.playlist.next_file) {
  724. modalNextPattern.textContent = getCleanPatternName(status.playlist.next_file);
  725. } else {
  726. modalNextPattern.textContent = 'None';
  727. }
  728. }
  729. // Pause button
  730. const modalPauseBtn = document.getElementById('modal-pause-button');
  731. if (modalPauseBtn) {
  732. const pauseIcon = modalPauseBtn.querySelector('.material-icons');
  733. if (status.is_paused) {
  734. pauseIcon.textContent = 'play_arrow';
  735. } else {
  736. pauseIcon.textContent = 'pause';
  737. }
  738. }
  739. // Skip button visibility
  740. const modalSkipBtn = document.getElementById('modal-skip-button');
  741. if (modalSkipBtn) {
  742. if (status.playlist && status.playlist.next_file) {
  743. modalSkipBtn.classList.remove('invisible');
  744. } else {
  745. modalSkipBtn.classList.add('invisible');
  746. }
  747. }
  748. // Speed display
  749. const modalSpeedDisplay = document.getElementById('modal-speed-display');
  750. if (modalSpeedDisplay && status.speed && !isEditingSpeed) {
  751. modalSpeedDisplay.textContent = status.speed;
  752. }
  753. }
  754. // Toggle modal visibility
  755. function togglePreviewModal() {
  756. const modal = document.getElementById('playerPreviewModal');
  757. const toggleBtn = document.getElementById('toggle-preview-modal-btn');
  758. if (!modal || !toggleBtn) return;
  759. const isHidden = modal.classList.contains('hidden');
  760. if (isHidden) {
  761. openPlayerPreviewModal();
  762. } else {
  763. setModalVisibility(false, true);
  764. toggleBtn.classList.remove('active-tab');
  765. toggleBtn.classList.add('inactive-tab');
  766. }
  767. }
  768. // Button event handlers
  769. document.addEventListener('DOMContentLoaded', async () => {
  770. try {
  771. // Initialize WebSocket connection
  772. initializeWebSocket();
  773. // Setup player preview modal events
  774. setupPlayerPreviewModalEvents();
  775. console.log('Player initialized successfully');
  776. } catch (error) {
  777. console.error(`Error during initialization: ${error.message}`);
  778. }
  779. });
  780. // Initialize WebSocket connection
  781. function initializeWebSocket() {
  782. connectWebSocket();
  783. }
  784. // Clean up WebSocket when page unloads to prevent memory leaks
  785. window.addEventListener('beforeunload', () => {
  786. if (ws) {
  787. // Disable reconnection before closing
  788. ws.onclose = null;
  789. ws.close();
  790. ws = null;
  791. }
  792. });
  793. // Add resize handler for responsive canvas with debouncing
  794. let resizeTimeout;
  795. window.addEventListener('resize', () => {
  796. const canvas = document.getElementById('playerPreviewCanvas');
  797. const modal = document.getElementById('playerPreviewModal');
  798. if (canvas && modal && !modal.classList.contains('hidden')) {
  799. // Clear previous timeout
  800. clearTimeout(resizeTimeout);
  801. // Debounce resize calls to avoid excessive updates
  802. resizeTimeout = setTimeout(() => {
  803. const ctx = canvas.getContext('2d');
  804. setupPlayerPreviewCanvas(ctx);
  805. drawPlayerPreview(ctx, targetProgress);
  806. }, 16); // ~60fps update rate
  807. }
  808. });
  809. // Handle file changes and reload preview data
  810. function handleFileChange(newFile) {
  811. if (newFile !== currentPreviewFile) {
  812. currentPreviewFile = newFile;
  813. if (newFile) {
  814. loadPlayerPreviewData(`./patterns/${newFile}`);
  815. } else {
  816. playerPreviewData = null;
  817. }
  818. }
  819. }
  820. // Cache All Previews Prompt functionality
  821. let cacheAllInProgress = false;
  822. function shouldShowCacheAllPrompt() {
  823. // Check if we've already shown the prompt
  824. const promptShown = localStorage.getItem('cacheAllPromptShown');
  825. console.log('shouldShowCacheAllPrompt - promptShown:', promptShown);
  826. return !promptShown;
  827. }
  828. function showCacheAllPrompt(forceShow = false) {
  829. console.log('showCacheAllPrompt called, forceShow:', forceShow);
  830. if (!forceShow && !shouldShowCacheAllPrompt()) {
  831. console.log('Cache all prompt already shown, skipping');
  832. return;
  833. }
  834. const modal = document.getElementById('cacheAllPromptModal');
  835. if (modal) {
  836. console.log('Showing cache all prompt modal');
  837. modal.classList.remove('hidden');
  838. // Store whether this was forced (manually triggered)
  839. modal.dataset.manuallyTriggered = forceShow.toString();
  840. } else {
  841. console.log('Cache all prompt modal not found');
  842. }
  843. }
  844. function hideCacheAllPrompt() {
  845. const modal = document.getElementById('cacheAllPromptModal');
  846. if (modal) {
  847. modal.classList.add('hidden');
  848. }
  849. }
  850. function markCacheAllPromptAsShown() {
  851. localStorage.setItem('cacheAllPromptShown', 'true');
  852. }
  853. function initializeCacheAllPrompt() {
  854. const modal = document.getElementById('cacheAllPromptModal');
  855. const skipBtn = document.getElementById('skipCacheAllBtn');
  856. const startBtn = document.getElementById('startCacheAllBtn');
  857. const closeBtn = document.getElementById('closeCacheAllBtn');
  858. if (!modal || !skipBtn || !startBtn || !closeBtn) {
  859. return;
  860. }
  861. // Skip button handler
  862. skipBtn.addEventListener('click', () => {
  863. const wasManuallyTriggered = modal.dataset.manuallyTriggered === 'true';
  864. hideCacheAllPrompt();
  865. // Only mark as shown if it was automatically shown (not manually triggered)
  866. if (!wasManuallyTriggered) {
  867. markCacheAllPromptAsShown();
  868. }
  869. });
  870. // Close button handler (after completion)
  871. closeBtn.addEventListener('click', () => {
  872. const wasManuallyTriggered = modal.dataset.manuallyTriggered === 'true';
  873. hideCacheAllPrompt();
  874. // Always mark as shown after successful completion
  875. if (!wasManuallyTriggered) {
  876. markCacheAllPromptAsShown();
  877. }
  878. });
  879. // Start caching button handler
  880. startBtn.addEventListener('click', async () => {
  881. if (cacheAllInProgress) {
  882. return;
  883. }
  884. cacheAllInProgress = true;
  885. // Hide buttons and show progress
  886. document.getElementById('cacheAllButtons').classList.add('hidden');
  887. document.getElementById('cacheAllProgress').classList.remove('hidden');
  888. try {
  889. await startCacheAllProcess();
  890. // Show completion message
  891. document.getElementById('cacheAllProgress').classList.add('hidden');
  892. document.getElementById('cacheAllComplete').classList.remove('hidden');
  893. } catch (error) {
  894. console.error('Error caching all previews:', error);
  895. // Show error and reset
  896. document.getElementById('cacheAllProgressText').textContent = 'Error occurred during caching';
  897. setTimeout(() => {
  898. hideCacheAllPrompt();
  899. markCacheAllPromptAsShown();
  900. }, 3000);
  901. } finally {
  902. cacheAllInProgress = false;
  903. }
  904. });
  905. }
  906. async function startCacheAllProcess() {
  907. try {
  908. // Get list of patterns using cached function
  909. const patterns = await getCachedPatternFiles();
  910. if (!patterns || patterns.length === 0) {
  911. throw new Error('No patterns found');
  912. }
  913. const progressBar = document.getElementById('cacheAllProgressBar');
  914. const progressText = document.getElementById('cacheAllProgressText');
  915. const progressPercentage = document.getElementById('cacheAllProgressPercentage');
  916. let completed = 0;
  917. const batchSize = 5; // Process in small batches to avoid overwhelming the server
  918. for (let i = 0; i < patterns.length; i += batchSize) {
  919. const batch = patterns.slice(i, i + batchSize);
  920. // Update progress text
  921. progressText.textContent = `Caching previews... (${Math.min(i + batchSize, patterns.length)}/${patterns.length})`;
  922. // Process batch
  923. const batchPromises = batch.map(async (pattern) => {
  924. try {
  925. const previewResponse = await fetch('/preview_thr', {
  926. method: 'POST',
  927. headers: {
  928. 'Content-Type': 'application/json',
  929. },
  930. body: JSON.stringify({ file_name: pattern })
  931. });
  932. if (previewResponse.ok) {
  933. const data = await previewResponse.json();
  934. if (data.preview_url) {
  935. // Pre-load the image to cache it
  936. return new Promise((resolve) => {
  937. const img = new Image();
  938. img.onload = () => resolve();
  939. img.onerror = () => resolve(); // Continue even if image fails
  940. img.src = data.preview_url;
  941. });
  942. }
  943. }
  944. return Promise.resolve();
  945. } catch (error) {
  946. console.warn(`Failed to cache preview for ${pattern}:`, error);
  947. return Promise.resolve(); // Continue with other patterns
  948. }
  949. });
  950. await Promise.all(batchPromises);
  951. completed += batch.length;
  952. // Update progress bar
  953. const progress = Math.round((completed / patterns.length) * 100);
  954. progressBar.style.width = `${progress}%`;
  955. progressPercentage.textContent = `${progress}%`;
  956. // Small delay between batches to prevent overwhelming the server
  957. if (i + batchSize < patterns.length) {
  958. await new Promise(resolve => setTimeout(resolve, 100));
  959. }
  960. }
  961. progressText.textContent = `Completed! Cached ${patterns.length} previews.`;
  962. } catch (error) {
  963. throw error;
  964. }
  965. }
  966. // Function to be called after initial cache generation completes
  967. function onInitialCacheComplete() {
  968. console.log('onInitialCacheComplete called');
  969. // Show the cache all prompt after a short delay
  970. setTimeout(() => {
  971. console.log('Triggering cache all prompt after delay');
  972. showCacheAllPrompt();
  973. }, 1000);
  974. }
  975. // Initialize on DOM load
  976. document.addEventListener('DOMContentLoaded', () => {
  977. initializeCacheAllPrompt();
  978. });
  979. // Make functions available globally for debugging
  980. window.onInitialCacheComplete = onInitialCacheComplete;
  981. window.showCacheAllPrompt = showCacheAllPrompt;
  982. window.testCacheAllPrompt = function() {
  983. console.log('Manual test trigger');
  984. // Clear localStorage for testing
  985. localStorage.removeItem('cacheAllPromptShown');
  986. showCacheAllPrompt();
  987. };