base.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181
  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 only
  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. ctx.restore();
  371. }
  372. // Draw player preview for modal
  373. function drawPlayerPreview(ctx, progress) {
  374. if (!ctx || !playerPreviewData || playerPreviewData.length === 0) return;
  375. const canvas = ctx.canvas;
  376. const pixelRatio = (window.devicePixelRatio || 1) * 2;
  377. const containerSize = canvas.width / pixelRatio;
  378. const center = containerSize / 2;
  379. const scale = (containerSize / 2) - 30;
  380. ctx.save();
  381. // Clear canvas for fresh drawing
  382. ctx.clearRect(0, 0, canvas.width, canvas.height);
  383. // Create circular clipping path
  384. ctx.beginPath();
  385. ctx.arc(canvas.width/2, canvas.height/2, canvas.width/2, 0, Math.PI * 2);
  386. ctx.clip();
  387. // Setup coordinate system for drawing
  388. ctx.scale(pixelRatio, pixelRatio);
  389. // Calculate how many points to draw
  390. const totalPoints = playerPreviewData.length;
  391. const pointsToDraw = Math.floor(totalPoints * progress);
  392. if (pointsToDraw < 2) {
  393. ctx.restore();
  394. return;
  395. }
  396. // Draw the pattern
  397. ctx.beginPath();
  398. ctx.strokeStyle = '#808080';
  399. ctx.lineWidth = 1;
  400. ctx.lineCap = 'round';
  401. ctx.lineJoin = 'round';
  402. // Enable high quality rendering
  403. ctx.imageSmoothingEnabled = true;
  404. ctx.imageSmoothingQuality = 'high';
  405. // Draw pattern lines up to the last complete segment
  406. for (let i = 0; i < pointsToDraw - 1; i++) {
  407. const [theta1, rho1] = playerPreviewData[i];
  408. const [theta2, rho2] = playerPreviewData[i + 1];
  409. const x1 = center + rho1 * scale * Math.cos(theta1);
  410. const y1 = center + rho1 * scale * Math.sin(theta1);
  411. const x2 = center + rho2 * scale * Math.cos(theta2);
  412. const y2 = center + rho2 * scale * Math.sin(theta2);
  413. if (i === 0) {
  414. ctx.moveTo(x1, y1);
  415. }
  416. ctx.lineTo(x2, y2);
  417. }
  418. // Draw the final partial segment to the interpolated position
  419. if (pointsToDraw > 0) {
  420. const interpolatedCoord = getInterpolatedCoordinate(progress);
  421. if (interpolatedCoord && pointsToDraw > 1) {
  422. // Get the last complete coordinate
  423. const [lastTheta, lastRho] = playerPreviewData[pointsToDraw - 1];
  424. const lastX = center + lastRho * scale * Math.cos(lastTheta);
  425. const lastY = center + lastRho * scale * Math.sin(lastTheta);
  426. // Draw line to interpolated position
  427. const [interpTheta, interpRho] = interpolatedCoord;
  428. const interpX = center + interpRho * scale * Math.cos(interpTheta);
  429. const interpY = center + interpRho * scale * Math.sin(interpTheta);
  430. ctx.lineTo(interpX, interpY);
  431. }
  432. }
  433. ctx.stroke();
  434. // Draw current position dot with interpolated position
  435. if (pointsToDraw > 0) {
  436. const interpolatedCoord = getInterpolatedCoordinate(progress);
  437. if (interpolatedCoord) {
  438. const [theta, rho] = interpolatedCoord;
  439. const x = center + rho * scale * Math.cos(theta);
  440. const y = center + rho * scale * Math.sin(theta);
  441. // Draw white border
  442. ctx.beginPath();
  443. ctx.fillStyle = '#ffffff';
  444. ctx.arc(x, y, 7.5, 0, Math.PI * 2);
  445. ctx.fill();
  446. // Draw red dot
  447. ctx.beginPath();
  448. ctx.fillStyle = '#ff0000';
  449. ctx.arc(x, y, 6, 0, Math.PI * 2);
  450. ctx.fill();
  451. }
  452. }
  453. ctx.restore();
  454. }
  455. // Load pattern coordinates for player preview
  456. async function loadPlayerPreviewData(pattern) {
  457. try {
  458. const response = await fetch('/get_theta_rho_coordinates', {
  459. method: 'POST',
  460. headers: { 'Content-Type': 'application/json' },
  461. body: JSON.stringify({ file_name: pattern })
  462. });
  463. if (!response.ok) {
  464. throw new Error(`HTTP error! status: ${response.status}`);
  465. }
  466. const data = await response.json();
  467. if (data.error) {
  468. throw new Error(data.error);
  469. }
  470. playerPreviewData = data.coordinates;
  471. // Store the filename for comparison
  472. playerPreviewData.fileName = normalizeFilePath(pattern);
  473. } catch (error) {
  474. console.error(`Error loading player preview data: ${error.message}`);
  475. playerPreviewData = null;
  476. }
  477. }
  478. // Ultra-smooth animation function for modal
  479. function animateModalPreview() {
  480. const modal = document.getElementById('playerPreviewModal');
  481. if (!modal || modal.classList.contains('hidden')) return;
  482. const canvas = document.getElementById('playerPreviewCanvas');
  483. const ctx = canvas.getContext('2d');
  484. if (!ctx || !playerPreviewData) return;
  485. const currentTime = Date.now();
  486. const elapsed = currentTime - modalAnimationStartTime;
  487. const totalDuration = animationDuration;
  488. // Calculate smooth progress with easing
  489. const rawProgress = Math.min(elapsed / totalDuration, 1);
  490. const easeProgress = rawProgress < 0.5
  491. ? 2 * rawProgress * rawProgress
  492. : 1 - Math.pow(-2 * rawProgress + 2, 2) / 2;
  493. // Interpolate between last and target progress
  494. const currentProgress = modalLastProgress + (modalTargetProgress - modalLastProgress) * easeProgress;
  495. // Draw the pattern up to current progress
  496. drawPlayerPreview(ctx, currentProgress);
  497. // Continue animation if not at target
  498. if (rawProgress < 1) {
  499. modalAnimationId = requestAnimationFrame(animateModalPreview);
  500. }
  501. }
  502. // Update modal preview with smooth animation
  503. function updateModalPreviewSmooth(newProgress) {
  504. if (newProgress === modalTargetProgress) return; // No change needed
  505. // Stop any existing animation
  506. if (modalAnimationId) {
  507. cancelAnimationFrame(modalAnimationId);
  508. }
  509. // Update animation parameters
  510. modalLastProgress = modalTargetProgress;
  511. modalTargetProgress = newProgress;
  512. modalAnimationStartTime = Date.now();
  513. // Start smooth animation
  514. animateModalPreview();
  515. }
  516. // Setup player preview modal events
  517. function setupPlayerPreviewModalEvents() {
  518. const modal = document.getElementById('playerPreviewModal');
  519. const closeBtn = document.getElementById('closePlayerPreview');
  520. const toggleBtn = document.getElementById('toggle-preview-modal-btn');
  521. if (!modal || !closeBtn || !toggleBtn) return;
  522. // Remove any existing event listeners to prevent conflicts
  523. const newToggleBtn = toggleBtn.cloneNode(true);
  524. toggleBtn.parentNode.replaceChild(newToggleBtn, toggleBtn);
  525. // Toggle button click handler
  526. newToggleBtn.addEventListener('click', () => {
  527. const isHidden = modal.classList.contains('hidden');
  528. if (isHidden) {
  529. openPlayerPreviewModal();
  530. } else {
  531. modal.classList.add('hidden');
  532. }
  533. });
  534. // Close modal when clicking close button
  535. closeBtn.addEventListener('click', () => {
  536. setModalVisibility(false, true);
  537. });
  538. // Close modal when clicking outside
  539. modal.addEventListener('click', (e) => {
  540. if (e.target === modal) {
  541. setModalVisibility(false, true);
  542. }
  543. });
  544. // Close modal with Escape key
  545. document.addEventListener('keydown', (e) => {
  546. if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
  547. setModalVisibility(false, true);
  548. }
  549. });
  550. // Setup modal control buttons
  551. setupModalControls();
  552. }
  553. // Handle pause/resume toggle
  554. async function togglePauseResume() {
  555. const pauseButton = document.getElementById('modal-pause-button');
  556. if (!pauseButton) return;
  557. try {
  558. const pauseIcon = pauseButton.querySelector('.material-icons');
  559. const isCurrentlyPaused = pauseIcon.textContent === 'play_arrow';
  560. // Show immediate feedback
  561. showStatusMessage(isCurrentlyPaused ? 'Resuming...' : 'Pausing...', 'info');
  562. const endpoint = isCurrentlyPaused ? '/resume_execution' : '/pause_execution';
  563. const response = await fetch(endpoint, { method: 'POST' });
  564. if (!response.ok) throw new Error(`Failed to ${isCurrentlyPaused ? 'resume' : 'pause'}`);
  565. // Show success message
  566. showStatusMessage(isCurrentlyPaused ? 'Pattern resumed' : 'Pattern paused', 'success');
  567. } catch (error) {
  568. console.error('Error toggling pause:', error);
  569. showStatusMessage('Failed to pause/resume pattern', 'error');
  570. }
  571. }
  572. // Setup modal controls
  573. function setupModalControls() {
  574. const pauseButton = document.getElementById('modal-pause-button');
  575. const skipButton = document.getElementById('modal-skip-button');
  576. const stopButton = document.getElementById('modal-stop-button');
  577. const speedDisplay = document.getElementById('modal-speed-display');
  578. const speedInput = document.getElementById('modal-speed-input');
  579. if (!pauseButton || !skipButton || !stopButton || !speedDisplay || !speedInput) return;
  580. // Pause button click handler
  581. pauseButton.addEventListener('click', togglePauseResume);
  582. // Skip button click handler
  583. skipButton.addEventListener('click', async () => {
  584. try {
  585. // Show immediate feedback
  586. showStatusMessage('Skipping to next pattern...', 'info');
  587. const response = await fetch('/skip_pattern', { method: 'POST' });
  588. if (!response.ok) throw new Error('Failed to skip pattern');
  589. // Show success message
  590. showStatusMessage('Skipped to next pattern', 'success');
  591. } catch (error) {
  592. console.error('Error skipping pattern:', error);
  593. showStatusMessage('Failed to skip pattern', 'error');
  594. }
  595. });
  596. // Stop button click handler
  597. stopButton.addEventListener('click', async () => {
  598. try {
  599. // Show immediate feedback
  600. showStatusMessage('Stopping...', 'info');
  601. const response = await fetch('/stop_execution', { method: 'POST' });
  602. if (!response.ok) throw new Error('Failed to stop pattern');
  603. else {
  604. // Show success message
  605. showStatusMessage('Pattern stopped', 'success');
  606. // Hide modal when stopping
  607. const modal = document.getElementById('playerPreviewModal');
  608. if (modal) modal.classList.add('hidden');
  609. }
  610. } catch (error) {
  611. console.error('Error stopping pattern:', error);
  612. showStatusMessage('Failed to stop pattern', 'error');
  613. }
  614. });
  615. // Speed display click to edit
  616. speedDisplay.addEventListener('click', () => {
  617. isEditingSpeed = true;
  618. speedDisplay.classList.add('hidden');
  619. speedInput.value = speedDisplay.textContent;
  620. speedInput.classList.remove('hidden');
  621. speedInput.focus();
  622. speedInput.select();
  623. });
  624. // Speed input handlers
  625. speedInput.addEventListener('keydown', (e) => {
  626. if (e.key === 'Enter') {
  627. e.preventDefault();
  628. exitModalSpeedEditMode(true);
  629. } else if (e.key === 'Escape') {
  630. e.preventDefault();
  631. exitModalSpeedEditMode(false);
  632. }
  633. });
  634. speedInput.addEventListener('blur', () => {
  635. exitModalSpeedEditMode(true);
  636. });
  637. }
  638. // Exit modal speed edit mode
  639. async function exitModalSpeedEditMode(save = false) {
  640. const speedDisplay = document.getElementById('modal-speed-display');
  641. const speedInput = document.getElementById('modal-speed-input');
  642. if (!speedDisplay || !speedInput) return;
  643. isEditingSpeed = false;
  644. speedInput.classList.add('hidden');
  645. speedDisplay.classList.remove('hidden');
  646. if (save) {
  647. const speed = parseInt(speedInput.value);
  648. if (!isNaN(speed) && speed >= 1 && speed <= 5000) {
  649. try {
  650. const response = await fetch('/set_speed', {
  651. method: 'POST',
  652. headers: { 'Content-Type': 'application/json' },
  653. body: JSON.stringify({ speed: speed })
  654. });
  655. const data = await response.json();
  656. if (data.success) {
  657. speedDisplay.textContent = speed;
  658. showStatusMessage(`Speed set to ${speed} mm/s`, 'success');
  659. } else {
  660. throw new Error(data.detail || 'Failed to set speed');
  661. }
  662. } catch (error) {
  663. console.error('Error setting speed:', error);
  664. showStatusMessage('Failed to set speed', 'error');
  665. }
  666. } else {
  667. showStatusMessage('Please enter a valid speed (1-5000)', 'error');
  668. }
  669. }
  670. }
  671. // Helper function to clean up pattern names
  672. function getCleanPatternName(filePath) {
  673. if (!filePath) return '';
  674. const fileName = normalizeFilePath(filePath);
  675. return fileName.split('/').pop().replace('.thr', '');
  676. }
  677. // Sync modal controls with player status
  678. function syncModalControls(status) {
  679. // Pattern name - clean up to show only filename
  680. const modalPatternName = document.getElementById('modal-pattern-name');
  681. if (modalPatternName && status.current_file) {
  682. modalPatternName.textContent = getCleanPatternName(status.current_file);
  683. }
  684. // Pattern preview image
  685. const modalPatternPreviewImg = document.getElementById('modal-pattern-preview-img');
  686. if (modalPatternPreviewImg && status.current_file) {
  687. const encodedFilename = normalizeFilePath(status.current_file).replace(/[\\/]/g, '--');
  688. const previewUrl = `/preview/${encodedFilename}`;
  689. modalPatternPreviewImg.src = previewUrl;
  690. }
  691. // ETA
  692. const modalEta = document.getElementById('modal-eta');
  693. if (modalEta) {
  694. if (status.progress && status.progress.remaining_time !== null) {
  695. const minutes = Math.floor(status.progress.remaining_time / 60);
  696. const seconds = Math.floor(status.progress.remaining_time % 60);
  697. modalEta.textContent = `ETA: ${minutes}:${seconds.toString().padStart(2, '0')}`;
  698. } else {
  699. modalEta.textContent = 'ETA: calculating...';
  700. }
  701. }
  702. // Progress bar
  703. const modalProgressBar = document.getElementById('modal-progress-bar');
  704. if (modalProgressBar) {
  705. if (status.progress && status.progress.percentage !== null) {
  706. modalProgressBar.style.width = `${status.progress.percentage}%`;
  707. } else {
  708. modalProgressBar.style.width = '0%';
  709. }
  710. }
  711. // Next pattern - clean up to show only filename
  712. const modalNextPattern = document.getElementById('modal-next-pattern');
  713. if (modalNextPattern) {
  714. if (status.playlist && status.playlist.next_file) {
  715. modalNextPattern.textContent = getCleanPatternName(status.playlist.next_file);
  716. } else {
  717. modalNextPattern.textContent = 'None';
  718. }
  719. }
  720. // Pause button
  721. const modalPauseBtn = document.getElementById('modal-pause-button');
  722. if (modalPauseBtn) {
  723. const pauseIcon = modalPauseBtn.querySelector('.material-icons');
  724. if (status.is_paused) {
  725. pauseIcon.textContent = 'play_arrow';
  726. } else {
  727. pauseIcon.textContent = 'pause';
  728. }
  729. }
  730. // Skip button visibility
  731. const modalSkipBtn = document.getElementById('modal-skip-button');
  732. if (modalSkipBtn) {
  733. if (status.playlist && status.playlist.next_file) {
  734. modalSkipBtn.classList.remove('invisible');
  735. } else {
  736. modalSkipBtn.classList.add('invisible');
  737. }
  738. }
  739. // Speed display
  740. const modalSpeedDisplay = document.getElementById('modal-speed-display');
  741. if (modalSpeedDisplay && status.speed && !isEditingSpeed) {
  742. modalSpeedDisplay.textContent = status.speed;
  743. }
  744. }
  745. // Toggle modal visibility
  746. function togglePreviewModal() {
  747. const modal = document.getElementById('playerPreviewModal');
  748. const toggleBtn = document.getElementById('toggle-preview-modal-btn');
  749. if (!modal || !toggleBtn) return;
  750. const isHidden = modal.classList.contains('hidden');
  751. if (isHidden) {
  752. openPlayerPreviewModal();
  753. } else {
  754. setModalVisibility(false, true);
  755. toggleBtn.classList.remove('active-tab');
  756. toggleBtn.classList.add('inactive-tab');
  757. }
  758. }
  759. // Button event handlers
  760. document.addEventListener('DOMContentLoaded', async () => {
  761. try {
  762. // Initialize WebSocket connection
  763. initializeWebSocket();
  764. // Setup player preview modal events
  765. setupPlayerPreviewModalEvents();
  766. console.log('Player initialized successfully');
  767. } catch (error) {
  768. console.error(`Error during initialization: ${error.message}`);
  769. }
  770. });
  771. // Initialize WebSocket connection
  772. function initializeWebSocket() {
  773. connectWebSocket();
  774. }
  775. // Clean up WebSocket when page unloads to prevent memory leaks
  776. window.addEventListener('beforeunload', () => {
  777. if (ws) {
  778. // Disable reconnection before closing
  779. ws.onclose = null;
  780. ws.close();
  781. ws = null;
  782. }
  783. });
  784. // Add resize handler for responsive canvas with debouncing
  785. let resizeTimeout;
  786. window.addEventListener('resize', () => {
  787. const canvas = document.getElementById('playerPreviewCanvas');
  788. const modal = document.getElementById('playerPreviewModal');
  789. if (canvas && modal && !modal.classList.contains('hidden')) {
  790. // Clear previous timeout
  791. clearTimeout(resizeTimeout);
  792. // Debounce resize calls to avoid excessive updates
  793. resizeTimeout = setTimeout(() => {
  794. const ctx = canvas.getContext('2d');
  795. setupPlayerPreviewCanvas(ctx);
  796. drawPlayerPreview(ctx, targetProgress);
  797. }, 16); // ~60fps update rate
  798. }
  799. });
  800. // Handle file changes and reload preview data
  801. function handleFileChange(newFile) {
  802. if (newFile !== currentPreviewFile) {
  803. currentPreviewFile = newFile;
  804. if (newFile) {
  805. loadPlayerPreviewData(`./patterns/${newFile}`);
  806. } else {
  807. playerPreviewData = null;
  808. }
  809. }
  810. }
  811. // Cache All Previews Prompt functionality
  812. let cacheAllInProgress = false;
  813. function shouldShowCacheAllPrompt() {
  814. // Check if we've already shown the prompt
  815. const promptShown = localStorage.getItem('cacheAllPromptShown');
  816. console.log('shouldShowCacheAllPrompt - promptShown:', promptShown);
  817. return !promptShown;
  818. }
  819. function showCacheAllPrompt(forceShow = false) {
  820. console.log('showCacheAllPrompt called, forceShow:', forceShow);
  821. if (!forceShow && !shouldShowCacheAllPrompt()) {
  822. console.log('Cache all prompt already shown, skipping');
  823. return;
  824. }
  825. const modal = document.getElementById('cacheAllPromptModal');
  826. if (modal) {
  827. console.log('Showing cache all prompt modal');
  828. modal.classList.remove('hidden');
  829. // Store whether this was forced (manually triggered)
  830. modal.dataset.manuallyTriggered = forceShow.toString();
  831. } else {
  832. console.log('Cache all prompt modal not found');
  833. }
  834. }
  835. function hideCacheAllPrompt() {
  836. const modal = document.getElementById('cacheAllPromptModal');
  837. if (modal) {
  838. modal.classList.add('hidden');
  839. }
  840. }
  841. function markCacheAllPromptAsShown() {
  842. localStorage.setItem('cacheAllPromptShown', 'true');
  843. }
  844. function initializeCacheAllPrompt() {
  845. const modal = document.getElementById('cacheAllPromptModal');
  846. const skipBtn = document.getElementById('skipCacheAllBtn');
  847. const startBtn = document.getElementById('startCacheAllBtn');
  848. const closeBtn = document.getElementById('closeCacheAllBtn');
  849. if (!modal || !skipBtn || !startBtn || !closeBtn) {
  850. return;
  851. }
  852. // Skip button handler
  853. skipBtn.addEventListener('click', () => {
  854. const wasManuallyTriggered = modal.dataset.manuallyTriggered === 'true';
  855. hideCacheAllPrompt();
  856. // Only mark as shown if it was automatically shown (not manually triggered)
  857. if (!wasManuallyTriggered) {
  858. markCacheAllPromptAsShown();
  859. }
  860. });
  861. // Close button handler (after completion)
  862. closeBtn.addEventListener('click', () => {
  863. const wasManuallyTriggered = modal.dataset.manuallyTriggered === 'true';
  864. hideCacheAllPrompt();
  865. // Always mark as shown after successful completion
  866. if (!wasManuallyTriggered) {
  867. markCacheAllPromptAsShown();
  868. }
  869. });
  870. // Start caching button handler
  871. startBtn.addEventListener('click', async () => {
  872. if (cacheAllInProgress) {
  873. return;
  874. }
  875. cacheAllInProgress = true;
  876. // Hide buttons and show progress
  877. document.getElementById('cacheAllButtons').classList.add('hidden');
  878. document.getElementById('cacheAllProgress').classList.remove('hidden');
  879. try {
  880. await startCacheAllProcess();
  881. // Show completion message
  882. document.getElementById('cacheAllProgress').classList.add('hidden');
  883. document.getElementById('cacheAllComplete').classList.remove('hidden');
  884. } catch (error) {
  885. console.error('Error caching all previews:', error);
  886. // Show error and reset
  887. document.getElementById('cacheAllProgressText').textContent = 'Error occurred during caching';
  888. setTimeout(() => {
  889. hideCacheAllPrompt();
  890. markCacheAllPromptAsShown();
  891. }, 3000);
  892. } finally {
  893. cacheAllInProgress = false;
  894. }
  895. });
  896. }
  897. async function startCacheAllProcess() {
  898. try {
  899. // Get list of patterns using cached function
  900. const patterns = await getCachedPatternFiles();
  901. if (!patterns || patterns.length === 0) {
  902. throw new Error('No patterns found');
  903. }
  904. const progressBar = document.getElementById('cacheAllProgressBar');
  905. const progressText = document.getElementById('cacheAllProgressText');
  906. const progressPercentage = document.getElementById('cacheAllProgressPercentage');
  907. let completed = 0;
  908. const batchSize = 5; // Process in small batches to avoid overwhelming the server
  909. for (let i = 0; i < patterns.length; i += batchSize) {
  910. const batch = patterns.slice(i, i + batchSize);
  911. // Update progress text
  912. progressText.textContent = `Caching previews... (${Math.min(i + batchSize, patterns.length)}/${patterns.length})`;
  913. // Process batch
  914. const batchPromises = batch.map(async (pattern) => {
  915. try {
  916. const previewResponse = await fetch('/preview_thr', {
  917. method: 'POST',
  918. headers: {
  919. 'Content-Type': 'application/json',
  920. },
  921. body: JSON.stringify({ file_name: pattern })
  922. });
  923. if (previewResponse.ok) {
  924. const data = await previewResponse.json();
  925. if (data.preview_url) {
  926. // Pre-load the image to cache it
  927. return new Promise((resolve) => {
  928. const img = new Image();
  929. img.onload = () => resolve();
  930. img.onerror = () => resolve(); // Continue even if image fails
  931. img.src = data.preview_url;
  932. });
  933. }
  934. }
  935. return Promise.resolve();
  936. } catch (error) {
  937. console.warn(`Failed to cache preview for ${pattern}:`, error);
  938. return Promise.resolve(); // Continue with other patterns
  939. }
  940. });
  941. await Promise.all(batchPromises);
  942. completed += batch.length;
  943. // Update progress bar
  944. const progress = Math.round((completed / patterns.length) * 100);
  945. progressBar.style.width = `${progress}%`;
  946. progressPercentage.textContent = `${progress}%`;
  947. // Small delay between batches to prevent overwhelming the server
  948. if (i + batchSize < patterns.length) {
  949. await new Promise(resolve => setTimeout(resolve, 100));
  950. }
  951. }
  952. progressText.textContent = `Completed! Cached ${patterns.length} previews.`;
  953. } catch (error) {
  954. throw error;
  955. }
  956. }
  957. // Function to be called after initial cache generation completes
  958. function onInitialCacheComplete() {
  959. console.log('onInitialCacheComplete called');
  960. // Show the cache all prompt after a short delay
  961. setTimeout(() => {
  962. console.log('Triggering cache all prompt after delay');
  963. showCacheAllPrompt();
  964. }, 1000);
  965. }
  966. // Initialize on DOM load
  967. document.addEventListener('DOMContentLoaded', () => {
  968. initializeCacheAllPrompt();
  969. });
  970. // Make functions available globally for debugging
  971. window.onInitialCacheComplete = onInitialCacheComplete;
  972. window.showCacheAllPrompt = showCacheAllPrompt;
  973. window.testCacheAllPrompt = function() {
  974. console.log('Manual test trigger');
  975. // Clear localStorage for testing
  976. localStorage.removeItem('cacheAllPromptShown');
  977. showCacheAllPrompt();
  978. };