main.js 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  1. // Global variables
  2. let selectedFile = null;
  3. let playlist = [];
  4. let selectedPlaylistIndex = null;
  5. let allFiles = [];
  6. // Define constants for log message types
  7. const LOG_TYPE = {
  8. SUCCESS: 'success',
  9. WARNING: 'warning',
  10. ERROR: 'error',
  11. INFO: 'info',
  12. DEBUG: 'debug'
  13. };
  14. // Enhanced logMessage with notification system
  15. function logMessage(message, type = LOG_TYPE.DEBUG, clickTargetId = null) {
  16. const log = document.getElementById('status_log');
  17. const header = document.querySelector('header');
  18. if (!header) {
  19. console.error('Error: <header> element not found');
  20. return;
  21. }
  22. // Debug messages only go to the status log
  23. if (type === LOG_TYPE.DEBUG) {
  24. if (!log) {
  25. console.error('Error: #status_log element not found');
  26. return;
  27. }
  28. const entry = document.createElement('p');
  29. entry.textContent = message;
  30. log.appendChild(entry);
  31. log.scrollTop = log.scrollHeight; // Scroll to the bottom of the log
  32. return;
  33. }
  34. // Clear any existing notifications
  35. const existingNotification = header.querySelector('.notification');
  36. if (existingNotification) {
  37. existingNotification.remove();
  38. }
  39. // Create a notification for other message types
  40. const notification = document.createElement('div');
  41. notification.className = `notification ${type}`;
  42. notification.textContent = message;
  43. // Add a close button
  44. const closeButton = document.createElement('button');
  45. closeButton.innerHTML = '<i class="fa-solid fa-xmark"></i>';
  46. closeButton.className = 'close-button no-bg';
  47. closeButton.onclick = (e) => {
  48. e.stopPropagation(); // Prevent triggering the clickTarget when the close button is clicked
  49. notification.classList.remove('show');
  50. setTimeout(() => notification.remove(), 250); // Match transition duration
  51. };
  52. notification.appendChild(closeButton);
  53. // Attach click event to the notification if a clickTargetId is provided
  54. if (clickTargetId) {
  55. notification.onclick = () => {
  56. const target = document.getElementById(clickTargetId);
  57. if (target) {
  58. // Find the closest <main> parent
  59. const parentMain = target.closest('main');
  60. if (parentMain) {
  61. // Remove 'active' class from all <main> elements
  62. document.querySelectorAll('main').forEach((main) => {
  63. main.classList.remove('active');
  64. });
  65. // Add 'active' class to the parent <main>
  66. parentMain.classList.add('active');
  67. target.click();
  68. // Update tab buttons based on the parent <main> ID
  69. const parentId = parentMain.id; // e.g., "patterns-tab"
  70. const tabId = `nav-${parentId.replace('-tab', '')}`; // e.g., "nav-patterns"
  71. document.querySelectorAll('.tab-button').forEach((button) => {
  72. button.classList.remove('active');
  73. });
  74. const tabButton = document.getElementById(tabId);
  75. if (tabButton) {
  76. tabButton.classList.add('active');
  77. }
  78. }
  79. }
  80. };
  81. }
  82. // Append the notification to the header
  83. header.appendChild(notification);
  84. // Trigger the transition
  85. requestAnimationFrame(() => {
  86. notification.classList.add('show');
  87. });
  88. // Auto-remove the notification after 5 seconds
  89. setTimeout(() => {
  90. if (notification.parentNode) {
  91. notification.classList.remove('show');
  92. setTimeout(() => notification.remove(), 250); // Match transition duration
  93. }
  94. }, 5000);
  95. // Also log the message to the status log if available
  96. if (log) {
  97. const entry = document.createElement('p');
  98. entry.textContent = message;
  99. log.appendChild(entry);
  100. log.scrollTop = log.scrollHeight; // Scroll to the bottom of the log
  101. }
  102. }
  103. function toggleDebugLog() {
  104. const statusLog = document.getElementById('status_log');
  105. const debugButton = document.getElementById('debug_button');
  106. if (statusLog.style.display === 'block') {
  107. statusLog.style.display = 'none';
  108. debugButton.classList.remove('active');
  109. } else {
  110. statusLog.style.display = 'block';
  111. debugButton.classList.add( 'active');
  112. statusLog.scrollIntoView({ behavior: 'smooth', block: 'start' }); // Smooth scrolling to the log
  113. }
  114. }
  115. // File selection logic
  116. async function selectFile(file, listItem) {
  117. selectedFile = file;
  118. // Highlight the selected file
  119. document.querySelectorAll('#theta_rho_files li').forEach(li => li.classList.remove('selected'));
  120. listItem.classList.add('selected');
  121. // Update the Remove button visibility
  122. const removeButton = document.querySelector('#pattern-preview-container .remove-button');
  123. if (file.startsWith('custom_patterns/')) {
  124. removeButton.classList.remove('hidden');
  125. } else {
  126. removeButton.classList.add('hidden');
  127. }
  128. logMessage(`Selected file: ${file}`);
  129. await previewPattern(file);
  130. // Populate the playlist dropdown after selecting a pattern
  131. await populatePlaylistDropdown();
  132. }
  133. // Fetch and display Theta-Rho files
  134. async function loadThetaRhoFiles() {
  135. try {
  136. logMessage('Loading Theta-Rho files...');
  137. const response = await fetch('/list_theta_rho_files');
  138. let files = await response.json();
  139. files = files.filter(file => file.endsWith('.thr'));
  140. // Sort files with custom_patterns on top and all alphabetically sorted
  141. const sortedFiles = files.sort((a, b) => {
  142. const isCustomA = a.startsWith('custom_patterns/');
  143. const isCustomB = b.startsWith('custom_patterns/');
  144. if (isCustomA && !isCustomB) return -1; // a comes first
  145. if (!isCustomA && isCustomB) return 1; // b comes first
  146. return a.localeCompare(b); // Alphabetical comparison
  147. });
  148. allFiles = sortedFiles; // Update global files
  149. displayFiles(sortedFiles); // Display sorted files
  150. logMessage('Theta-Rho files loaded and sorted successfully.');
  151. } catch (error) {
  152. logMessage(`Error loading Theta-Rho files: ${error.message}`, 'error');
  153. }
  154. }
  155. // Display files in the UI
  156. function displayFiles(files) {
  157. const ul = document.getElementById('theta_rho_files');
  158. if (!ul) {
  159. logMessage('Error: File list container not found');
  160. return;
  161. }
  162. ul.innerHTML = ''; // Clear existing list
  163. files.forEach(file => {
  164. const li = document.createElement('li');
  165. li.textContent = file;
  166. li.classList.add('file-item');
  167. // Attach file selection handler
  168. li.onclick = () => selectFile(file, li);
  169. ul.appendChild(li);
  170. });
  171. }
  172. // Filter files by search input
  173. function searchPatternFiles() {
  174. const searchInput = document.getElementById('search_pattern').value.toLowerCase();
  175. const filteredFiles = allFiles.filter(file => file.toLowerCase().includes(searchInput));
  176. displayFiles(filteredFiles);
  177. }
  178. // Upload a new Theta-Rho file
  179. async function uploadThetaRho() {
  180. const fileInput = document.getElementById('upload_file');
  181. const file = fileInput.files[0];
  182. if (!file) {
  183. logMessage('No file selected for upload.', LOG_TYPE.ERROR);
  184. return;
  185. }
  186. try {
  187. logMessage(`Uploading file: ${file.name}...`);
  188. const formData = new FormData();
  189. formData.append('file', file);
  190. const response = await fetch('/upload_theta_rho', {
  191. method: 'POST',
  192. body: formData
  193. });
  194. const result = await response.json();
  195. if (result.success) {
  196. logMessage(`File uploaded successfully: ${file.name}`, LOG_TYPE.SUCCESS);
  197. fileInput.value = '';
  198. await loadThetaRhoFiles();
  199. } else {
  200. logMessage(`Failed to upload file: ${file.name}`, LOG_TYPE.ERROR);
  201. }
  202. } catch (error) {
  203. logMessage(`Error uploading file: ${error.message}`);
  204. }
  205. }
  206. async function runThetaRho() {
  207. if (!selectedFile) {
  208. logMessage("No file selected to run.");
  209. return;
  210. }
  211. // Get the selected pre-execution action
  212. const preExecutionAction = document.getElementById('pre_execution').value;
  213. logMessage(`Running file: ${selectedFile} with pre-execution action: ${preExecutionAction}...`);
  214. try {
  215. const response = await fetch('/run_theta_rho', {
  216. method: 'POST',
  217. headers: { 'Content-Type': 'application/json' },
  218. body: JSON.stringify({
  219. file_name: selectedFile,
  220. pre_execution: preExecutionAction
  221. })
  222. });
  223. const result = await response.json();
  224. if (response.ok) {
  225. // Show the currently playing UI immediately
  226. document.body.classList.add('playing');
  227. const currentlyPlayingFile = document.getElementById('currently-playing-file');
  228. if (currentlyPlayingFile) {
  229. currentlyPlayingFile.textContent = selectedFile.replace('./patterns/', '');
  230. }
  231. // Show initial preview
  232. previewPattern(selectedFile.replace('./patterns/', ''), 'currently-playing-container');
  233. logMessage(`Pattern running: ${selectedFile}`, LOG_TYPE.SUCCESS);
  234. } else {
  235. if (response.status === 409) {
  236. logMessage("Cannot start pattern: Another pattern is already running", LOG_TYPE.WARNING);
  237. } else {
  238. logMessage(`Failed to run file: ${result.detail || 'Unknown error'}`, LOG_TYPE.ERROR);
  239. }
  240. }
  241. } catch (error) {
  242. logMessage(`Error running pattern: ${error.message}`, LOG_TYPE.ERROR);
  243. }
  244. }
  245. async function stopExecution() {
  246. logMessage('Stopping execution...');
  247. const response = await fetch('/stop_execution', { method: 'POST' });
  248. const result = await response.json();
  249. if (result.success) {
  250. logMessage('Execution stopped.',LOG_TYPE.SUCCESS);
  251. } else {
  252. logMessage('Failed to stop execution.',LOG_TYPE.ERROR);
  253. }
  254. }
  255. let isPaused = false;
  256. function togglePausePlay() {
  257. const button = document.getElementById("pausePlayCurrent");
  258. if (isPaused) {
  259. // Resume execution
  260. fetch('/resume_execution', { method: 'POST' })
  261. .then(response => response.json())
  262. .then(data => {
  263. if (data.success) {
  264. isPaused = false;
  265. button.innerHTML = "<i class=\"fa-solid fa-pause\"></i>"; // Change to pause icon
  266. }
  267. })
  268. .catch(error => console.error("Error resuming execution:", error));
  269. } else {
  270. // Pause execution
  271. fetch('/pause_execution', { method: 'POST' })
  272. .then(response => response.json())
  273. .then(data => {
  274. if (data.success) {
  275. isPaused = true;
  276. button.innerHTML = "<i class=\"fa-solid fa-play\"></i>"; // Change to play icon
  277. }
  278. })
  279. .catch(error => console.error("Error pausing execution:", error));
  280. }
  281. }
  282. function removeCurrentPattern() {
  283. if (!selectedFile) {
  284. logMessage('No file selected to remove.', LOG_TYPE.ERROR);
  285. return;
  286. }
  287. if (!selectedFile.startsWith('custom_patterns/')) {
  288. logMessage('Only custom patterns can be removed.', LOG_TYPE.WARNING);
  289. return;
  290. }
  291. removeCustomPattern(selectedFile);
  292. }
  293. // Delete the selected file
  294. async function removeCustomPattern(fileName) {
  295. const userConfirmed = confirm(`Are you sure you want to delete the pattern "${fileName}"?`);
  296. if (!userConfirmed) return;
  297. try {
  298. logMessage(`Deleting pattern: ${fileName}...`);
  299. const response = await fetch('/delete_theta_rho_file', {
  300. method: 'POST',
  301. headers: { 'Content-Type': 'application/json' },
  302. body: JSON.stringify({ file_name: fileName })
  303. });
  304. const result = await response.json();
  305. if (result.success) {
  306. logMessage(`File deleted successfully: ${selectedFile}`, LOG_TYPE.SUCCESS);
  307. // Close the preview container
  308. const previewContainer = document.getElementById('pattern-preview-container');
  309. if (previewContainer) {
  310. previewContainer.classList.add('hidden');
  311. previewContainer.classList.remove('visible');
  312. }
  313. // Clear the selected file and refresh the file list
  314. selectedFile = null;
  315. await loadThetaRhoFiles(); // Refresh the file list
  316. } else {
  317. logMessage(`Failed to delete pattern "${fileName}": ${result.error}`, LOG_TYPE.ERROR);
  318. }
  319. } catch (error) {
  320. logMessage(`Error deleting pattern: ${error.message}`);
  321. }
  322. }
  323. // Preview a Theta-Rho file
  324. async function previewPattern(fileName, containerId = 'pattern-preview-container') {
  325. try {
  326. logMessage(`Fetching data to preview file: ${fileName}...`);
  327. const response = await fetch('/preview_thr', {
  328. method: 'POST',
  329. headers: { 'Content-Type': 'application/json' },
  330. body: JSON.stringify({ file_name: fileName })
  331. });
  332. const result = await response.json();
  333. if (result.success) {
  334. // Mirror the theta values in the coordinates
  335. const coordinates = result.coordinates.map(coord => [
  336. (coord[0] < Math.PI) ?
  337. Math.PI - coord[0] : // For first half
  338. 3 * Math.PI - coord[0], // For second half
  339. coord[1]
  340. ]);
  341. // Render the pattern in the specified container
  342. const canvasId = containerId === 'currently-playing-container'
  343. ? 'currentlyPlayingCanvas'
  344. : 'patternPreviewCanvas';
  345. renderPattern(coordinates, canvasId);
  346. // Update coordinate display
  347. const firstCoordElement = document.getElementById('first_coordinate');
  348. const lastCoordElement = document.getElementById('last_coordinate');
  349. if (firstCoordElement) {
  350. const firstCoord = coordinates[0];
  351. firstCoordElement.textContent = `First Coordinate: θ=${firstCoord[0]}, ρ=${firstCoord[1]}`;
  352. } else {
  353. logMessage('First coordinate element not found.', LOG_TYPE.WARNING);
  354. }
  355. if (lastCoordElement) {
  356. const lastCoord = coordinates[coordinates.length - 1];
  357. lastCoordElement.textContent = `Last Coordinate: θ=${lastCoord[0]}, ρ=${lastCoord[1]}`;
  358. } else {
  359. logMessage('Last coordinate element not found.', LOG_TYPE.WARNING);
  360. }
  361. // Show the preview container
  362. const previewContainer = document.getElementById(containerId);
  363. if (previewContainer) {
  364. previewContainer.classList.remove('hidden');
  365. previewContainer.classList.add('visible');
  366. } else {
  367. logMessage(`Preview container not found: ${containerId}`, LOG_TYPE.ERROR);
  368. }
  369. } else {
  370. logMessage(`Failed to fetch preview for file: ${fileName}`, LOG_TYPE.WARNING);
  371. }
  372. } catch (error) {
  373. logMessage(`Error previewing pattern: ${error.message}`, LOG_TYPE.ERROR);
  374. }
  375. }
  376. // Render the pattern on a canvas
  377. function renderPattern(coordinates, canvasId) {
  378. const canvas = document.getElementById(canvasId);
  379. if (!canvas) {
  380. logMessage(`Canvas element not found: ${canvasId}`, LOG_TYPE.ERROR);
  381. return;
  382. }
  383. if (!(canvas instanceof HTMLCanvasElement)) {
  384. logMessage(`Element with ID "${canvasId}" is not a canvas.`, LOG_TYPE.ERROR);
  385. return;
  386. }
  387. const ctx = canvas.getContext('2d');
  388. if (!ctx) {
  389. logMessage(`Could not get 2D context for canvas: ${canvasId}`, LOG_TYPE.ERROR);
  390. return;
  391. }
  392. // Account for device pixel ratio
  393. const dpr = window.devicePixelRatio || 1;
  394. const rect = canvas.getBoundingClientRect();
  395. canvas.width = rect.width * dpr; // Scale canvas width for high DPI
  396. canvas.height = rect.height * dpr; // Scale canvas height for high DPI
  397. ctx.scale(dpr, dpr); // Scale drawing context
  398. ctx.clearRect(0, 0, canvas.width, canvas.height);
  399. const centerX = rect.width / 2; // Use bounding client rect dimensions
  400. const centerY = rect.height / 2;
  401. const maxRho = Math.max(...coordinates.map(coord => coord[1]));
  402. const scale = Math.min(rect.width, rect.height) / (2 * maxRho); // Scale to fit
  403. ctx.beginPath();
  404. ctx.strokeStyle = 'white';
  405. coordinates.forEach(([theta, rho], index) => {
  406. const x = centerX + rho * Math.cos(theta) * scale;
  407. const y = centerY - rho * Math.sin(theta) * scale;
  408. if (index === 0) ctx.moveTo(x, y);
  409. else ctx.lineTo(x, y);
  410. });
  411. ctx.stroke();
  412. }
  413. async function moveToCenter() {
  414. logMessage('Moving to center...', LOG_TYPE.INFO);
  415. const response = await fetch('/move_to_center', { method: 'POST' });
  416. const result = await response.json();
  417. if (result.success) {
  418. logMessage('Moved to center successfully.', LOG_TYPE.SUCCESS);
  419. } else {
  420. logMessage(`Failed to move to center: ${result.error}`, LOG_TYPE.ERROR);
  421. }
  422. }
  423. async function moveToPerimeter() {
  424. logMessage('Moving to perimeter...', LOG_TYPE.INFO);
  425. const response = await fetch('/move_to_perimeter', { method: 'POST' });
  426. const result = await response.json();
  427. if (result.success) {
  428. logMessage('Moved to perimeter successfully.', LOG_TYPE.SUCCESS);
  429. } else {
  430. logMessage(`Failed to move to perimeter: ${result.error}`, LOG_TYPE.ERROR);
  431. }
  432. }
  433. async function sendCoordinate() {
  434. const theta = parseFloat(document.getElementById('theta_input').value);
  435. const rho = parseFloat(document.getElementById('rho_input').value);
  436. if (isNaN(theta) || isNaN(rho)) {
  437. logMessage('Invalid input: θ and ρ must be numbers.', LOG_TYPE.ERROR);
  438. return;
  439. }
  440. logMessage(`Sending coordinate: θ=${theta}, ρ=${rho}...`);
  441. const response = await fetch('/send_coordinate', {
  442. method: 'POST',
  443. headers: { 'Content-Type': 'application/json' },
  444. body: JSON.stringify({ theta, rho })
  445. });
  446. const result = await response.json();
  447. if (result.success) {
  448. logMessage(`Coordinate executed successfully: θ=${theta}, ρ=${rho}`, LOG_TYPE.SUCCESS);
  449. } else {
  450. logMessage(`Failed to execute coordinate: ${result.error}`, LOG_TYPE.ERROR);
  451. }
  452. }
  453. async function sendHomeCommand() {
  454. const response = await fetch('/send_home', { method: 'POST' });
  455. const result = await response.json();
  456. if (result.success) {
  457. logMessage('HOME command sent successfully.', LOG_TYPE.SUCCESS);
  458. } else {
  459. logMessage('Failed to send HOME command.', LOG_TYPE.ERROR);
  460. }
  461. }
  462. async function runClearIn() {
  463. await runFile('clear_from_in.thr');
  464. }
  465. async function runClearOut() {
  466. await runFile('clear_from_out.thr');
  467. }
  468. async function runClearSide() {
  469. await runFile('clear_sideway.thr');
  470. }
  471. let scrollPosition = 0;
  472. function scrollSelection(direction) {
  473. const container = document.getElementById('clear_selection');
  474. const itemHeight = 50; // Adjust based on CSS height
  475. const maxScroll = container.children.length - 1;
  476. // Update scroll position
  477. scrollPosition += direction;
  478. scrollPosition = Math.max(0, Math.min(scrollPosition, maxScroll));
  479. // Update the transform to scroll items
  480. container.style.transform = `translateY(-${scrollPosition * itemHeight}px)`;
  481. setCookie('clear_action_index', scrollPosition, 365);
  482. }
  483. function executeClearAction(actionFunction) {
  484. // Save the new action to a cookie (optional)
  485. setCookie('clear_action', actionFunction, 365);
  486. if (actionFunction && typeof window[actionFunction] === 'function') {
  487. window[actionFunction](); // Execute the selected clear action
  488. } else {
  489. logMessage('No clear action selected or function not found.', LOG_TYPE.ERROR);
  490. }
  491. }
  492. async function runFile(fileName) {
  493. const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
  494. const result = await response.json();
  495. if (result.success) {
  496. logMessage(`Running file: ${fileName}`, LOG_TYPE.SUCCESS);
  497. } else {
  498. logMessage(`Failed to run file: ${fileName}`, LOG_TYPE.ERROR);
  499. }
  500. }
  501. // Connection Status
  502. async function checkSerialStatus() {
  503. const response = await fetch('/serial_status');
  504. const status = await response.json();
  505. const statusElement = document.getElementById('serial_status');
  506. const statusHeaderElement = document.getElementById('connection_status_header');
  507. const serialPortsContainer = document.getElementById('serial_ports_container');
  508. const selectElement = document.getElementById('serial_ports');
  509. const connectButton = document.querySelector('button[onclick="connectSerial()"]');
  510. const disconnectButton = document.querySelector('button[onclick="disconnectSerial()"]');
  511. const restartButton = document.querySelector('button[onclick="restartSerial()"]');
  512. if (status.connected) {
  513. const port = status.port || 'Unknown'; // Fallback if port is undefined
  514. statusElement.textContent = `Connected to ${port}`;
  515. statusElement.classList.add('connected');
  516. statusElement.classList.remove('not-connected');
  517. logMessage(`Connected to serial port: ${port}`);
  518. // Update header status
  519. statusHeaderElement.classList.add('connected');
  520. statusHeaderElement.classList.remove('not-connected');
  521. // Hide Available Ports and show disconnect/restart buttons
  522. serialPortsContainer.style.display = 'none';
  523. connectButton.style.display = 'none';
  524. disconnectButton.style.display = 'flex';
  525. restartButton.style.display = 'flex';
  526. // Preselect the connected port in the dropdown
  527. const newOption = document.createElement('option');
  528. newOption.value = port;
  529. newOption.textContent = port;
  530. selectElement.appendChild(newOption);
  531. selectElement.value = port;
  532. } else {
  533. statusElement.textContent = 'Not connected';
  534. statusElement.classList.add('not-connected');
  535. statusElement.classList.remove('connected');
  536. logMessage('No active connection.');
  537. // Update header status
  538. statusHeaderElement.classList.add('not-connected');
  539. statusHeaderElement.classList.remove('connected');
  540. // Show Available Ports and the connect button
  541. serialPortsContainer.style.display = 'block';
  542. connectButton.style.display = 'flex';
  543. disconnectButton.style.display = 'none';
  544. restartButton.style.display = 'none';
  545. // Attempt to auto-load available ports
  546. await loadSerialPorts();
  547. }
  548. }
  549. async function loadSerialPorts() {
  550. const response = await fetch('/list_serial_ports');
  551. const ports = await response.json();
  552. const select = document.getElementById('serial_ports');
  553. select.innerHTML = '';
  554. ports.forEach(port => {
  555. const option = document.createElement('option');
  556. option.value = port;
  557. option.textContent = port;
  558. select.appendChild(option);
  559. });
  560. logMessage('Serial ports loaded.');
  561. }
  562. async function connectSerial() {
  563. const port = document.getElementById('serial_ports').value;
  564. const response = await fetch('/connect', {
  565. method: 'POST',
  566. headers: { 'Content-Type': 'application/json' },
  567. body: JSON.stringify({ port })
  568. });
  569. const result = await response.json();
  570. if (result.success) {
  571. logMessage(`Connected to serial port: ${port}`, LOG_TYPE.SUCCESS);
  572. // Refresh the status
  573. await checkSerialStatus();
  574. } else {
  575. logMessage(`Error connecting to serial port: ${result.error}`, LOG_TYPE.ERROR);
  576. }
  577. }
  578. async function disconnectSerial() {
  579. const response = await fetch('/disconnect', { method: 'POST' });
  580. const result = await response.json();
  581. if (result.success) {
  582. logMessage('Serial port disconnected.', LOG_TYPE.SUCCESS);
  583. // Refresh the status
  584. await checkSerialStatus();
  585. } else {
  586. logMessage(`Error disconnecting: ${result.error}`, LOG_TYPE.ERROR);
  587. }
  588. }
  589. async function restartSerial() {
  590. const port = document.getElementById('serial_ports').value;
  591. const response = await fetch('/restart_connection', {
  592. method: 'POST',
  593. headers: { 'Content-Type': 'application/json' },
  594. body: JSON.stringify({ port })
  595. });
  596. const result = await response.json();
  597. if (result.success) {
  598. document.getElementById('serial_status').textContent = `Restarted connection to ${port}`;
  599. logMessage('Connection restarted.', LOG_TYPE.SUCCESS);
  600. // No need to change visibility for restart
  601. } else {
  602. logMessage(`Error restarting Connection: ${result.error}`, LOG_TYPE.ERROR);
  603. }
  604. }
  605. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  606. // Firmware / Software Updater
  607. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  608. async function checkForUpdates() {
  609. try {
  610. const response = await fetch('/check_software_update');
  611. const data = await response.json();
  612. // Handle updates available logic
  613. if (data.updates_available) {
  614. const updateButton = document.getElementById('update-software-btn');
  615. const updateLinkElement = document.getElementById('update_link');
  616. const tagLink = `https://github.com/tuanchris/dune-weaver/releases/tag/${data.latest_remote_tag}`;
  617. updateButton.classList.remove('hidden'); // Show the button
  618. logMessage("Software Update Available", LOG_TYPE.INFO, 'open-settings-button')
  619. updateLinkElement.innerHTML = `<a href="${tagLink}" target="_blank">View Release Notes </a>`;
  620. updateLinkElement.classList.remove('hidden'); // Show the link
  621. }
  622. // Update current and latest version in the UI
  623. const currentVersionElem = document.getElementById('current_git_version');
  624. const latestVersionElem = document.getElementById('latest_git_version');
  625. currentVersionElem.textContent = `Current Version: ${data.latest_local_tag || 'Unknown'}`;
  626. latestVersionElem.textContent = data.updates_available
  627. ? `Latest Version: ${data.latest_remote_tag}`
  628. : 'You are up to date!';
  629. } catch (error) {
  630. console.error('Error checking for updates:', error);
  631. }
  632. }
  633. async function updateSoftware() {
  634. const updateButton = document.getElementById('update-software-btn');
  635. try {
  636. // Disable the button and update the text
  637. updateButton.disabled = true;
  638. updateButton.querySelector('span').textContent = 'Updating...';
  639. const response = await fetch('/update_software', { method: 'POST' });
  640. const data = await response.json();
  641. if (data.success) {
  642. logMessage('Software updated successfully!', LOG_TYPE.SUCCESS);
  643. window.location.reload(); // Reload the page after update
  644. } else {
  645. logMessage('Failed to update software: ' + data.error, LOG_TYPE.ERROR);
  646. }
  647. } catch (error) {
  648. console.error('Error updating software:', error);
  649. logMessage('Failed to update software', LOG_TYPE.ERROR);
  650. } finally {
  651. // Re-enable the button and reset the text
  652. updateButton.disabled = false;
  653. updateButton.textContent = 'Update Software'; // Adjust to the original text
  654. }
  655. }
  656. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  657. // PART A: Loading / listing playlists from the server
  658. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  659. async function loadAllPlaylists() {
  660. try {
  661. const response = await fetch('/list_all_playlists'); // GET
  662. const allPlaylists = await response.json(); // e.g. ["My Playlist", "Summer", ...]
  663. displayAllPlaylists(allPlaylists);
  664. } catch (err) {
  665. logMessage(`Error loading playlists: ${err}`, LOG_TYPE.ERROR);
  666. }
  667. }
  668. // Function to display all playlists with Load, Run, and Delete buttons
  669. function displayAllPlaylists(playlists) {
  670. const ul = document.getElementById('all_playlists');
  671. ul.innerHTML = ''; // Clear current list
  672. if (playlists.length === 0) {
  673. // Add a placeholder if the list is empty
  674. const emptyLi = document.createElement('li');
  675. emptyLi.textContent = "You don't have any playlists yet.";
  676. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  677. ul.appendChild(emptyLi);
  678. return;
  679. }
  680. playlists.forEach(playlistName => {
  681. const li = document.createElement('li');
  682. li.textContent = playlistName;
  683. li.classList.add('playlist-item'); // Add a class for styling
  684. // Attach click event to handle selection
  685. li.onclick = () => {
  686. // Remove 'selected' class from all items
  687. document.querySelectorAll('#all_playlists li').forEach(item => {
  688. item.classList.remove('selected');
  689. });
  690. // Add 'selected' class to the clicked item
  691. li.classList.add('selected');
  692. // Open the playlist editor for the selected playlist
  693. openPlaylistEditor(playlistName);
  694. };
  695. ul.appendChild(li);
  696. });
  697. }
  698. // Cancel changes and close the editor
  699. function cancelPlaylistChanges() {
  700. playlist = [...originalPlaylist]; // Revert to the original playlist
  701. isPlaylistChanged = false;
  702. toggleSaveCancelButtons(false); // Hide the save and cancel buttons
  703. refreshPlaylistUI(); // Refresh the UI with the original state
  704. closeStickySection('playlist-editor'); // Close the editor
  705. }
  706. // Open the playlist editor
  707. function openPlaylistEditor(playlistName) {
  708. logMessage(`Opening editor for playlist: ${playlistName}`);
  709. const editorSection = document.getElementById('playlist-editor');
  710. // Update the displayed playlist name
  711. document.getElementById('playlist_name_display').textContent = playlistName;
  712. // Store the current playlist name for renaming
  713. document.getElementById('playlist_name_input').value = playlistName;
  714. editorSection.classList.remove('hidden');
  715. editorSection.classList.add('visible');
  716. loadPlaylist(playlistName);
  717. }
  718. function clearSchedule() {
  719. document.getElementById("start_time").value = "";
  720. document.getElementById("end_time").value = "";
  721. document.getElementById('clear_time').style.display = 'none';
  722. setCookie('start_time', '', 365);
  723. setCookie('end_time', '', 365);
  724. }
  725. // Function to run the selected playlist with specified parameters
  726. async function runPlaylist() {
  727. const playlistName = document.getElementById('playlist_name_display').textContent;
  728. if (!playlistName) {
  729. logMessage('No playlist selected', 'error');
  730. return;
  731. }
  732. const pauseTime = parseFloat(document.getElementById('pause_time').value) || 0;
  733. const clearPattern = document.getElementById('clear_pattern').value;
  734. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  735. const shuffle = document.getElementById('shuffle_playlist').checked;
  736. try {
  737. const response = await fetch('/run_playlist', {
  738. method: 'POST',
  739. headers: {
  740. 'Content-Type': 'application/json',
  741. },
  742. body: JSON.stringify({
  743. playlist_name: playlistName,
  744. pause_time: pauseTime,
  745. clear_pattern: clearPattern,
  746. run_mode: runMode,
  747. shuffle: shuffle
  748. })
  749. });
  750. if (!response.ok) {
  751. if (response.status === 409) {
  752. logMessage('Another pattern is already running', 'warning');
  753. } else {
  754. const errorData = await response.json();
  755. logMessage(errorData.detail || 'Failed to run playlist', 'error');
  756. }
  757. return;
  758. }
  759. logMessage(`Started playlist: ${playlistName}`, 'success');
  760. } catch (error) {
  761. logMessage('Error running playlist: ' + error, 'error');
  762. }
  763. }
  764. // Track changes in the playlist
  765. let originalPlaylist = [];
  766. let isPlaylistChanged = false;
  767. // Load playlist and set the original state
  768. async function loadPlaylist(playlistName) {
  769. try {
  770. logMessage(`Loading playlist: ${playlistName}`);
  771. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  772. const data = await response.json();
  773. if (!data.name) {
  774. throw new Error('Playlist name is missing in the response.');
  775. }
  776. // Populate playlist items and set original state
  777. playlist = data.files || [];
  778. originalPlaylist = [...playlist]; // Clone the playlist as the original
  779. isPlaylistChanged = false; // Reset change tracking
  780. toggleSaveCancelButtons(false); // Hide the save and cancel buttons initially
  781. refreshPlaylistUI();
  782. logMessage(`Loaded playlist: "${playlistName}" with ${playlist.length} file(s).`);
  783. } catch (err) {
  784. logMessage(`Error loading playlist: ${err.message}`, LOG_TYPE.ERROR);
  785. console.error('Error details:', err);
  786. }
  787. }
  788. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  789. // PART B: Creating or Saving (Overwriting) a Playlist
  790. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  791. // Instead of separate create/modify functions, we'll unify them:
  792. async function savePlaylist() {
  793. const name = document.getElementById('playlist_name_display').textContent
  794. if (!name) {
  795. logMessage("Please enter a playlist name.");
  796. return;
  797. }
  798. if (playlist.length === 0) {
  799. logMessage("No files in this playlist. Add files first.");
  800. return;
  801. }
  802. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  803. try {
  804. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  805. // Let's use /create_playlist to always overwrite or create anew.
  806. const response = await fetch('/create_playlist', {
  807. method: 'POST',
  808. headers: { 'Content-Type': 'application/json' },
  809. body: JSON.stringify({
  810. playlist_name: name,
  811. files: playlist
  812. })
  813. });
  814. const result = await response.json();
  815. if (result.success) {
  816. logMessage(`Playlist "${name}" with ${playlist.length} patterns saved`, LOG_TYPE.SUCCESS);
  817. // Reload the entire list of playlists to reflect changes
  818. // Check for changes and refresh the UI
  819. detectPlaylistChanges();
  820. refreshPlaylistUI();
  821. // Restore default action buttons
  822. toggleSaveCancelButtons(false);
  823. } else {
  824. logMessage(`Failed to save playlist: ${result.error}`, LOG_TYPE.ERROR);
  825. }
  826. } catch (err) {
  827. logMessage(`Error saving playlist: ${err}`);
  828. }
  829. }
  830. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  831. // PART C: Renaming and Deleting a playlist
  832. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  833. // Toggle the rename playlist input
  834. function populatePlaylistDropdown() {
  835. return fetch('/list_all_playlists')
  836. .then(response => response.json())
  837. .then(playlists => {
  838. const select = document.getElementById('select-playlist');
  839. select.innerHTML = ''; // Clear existing options
  840. // Retrieve the saved playlist from the cookie
  841. const savedPlaylist = getCookie('selected_playlist');
  842. // Check if there are playlists available
  843. if (playlists.length === 0) {
  844. // Add a placeholder option if no playlists are available
  845. const placeholderOption = document.createElement('option');
  846. placeholderOption.value = '';
  847. placeholderOption.textContent = 'No playlists available';
  848. placeholderOption.disabled = true; // Prevent selection
  849. placeholderOption.selected = true; // Set as default
  850. select.appendChild(placeholderOption);
  851. return;
  852. }
  853. playlists.forEach(playlist => {
  854. const option = document.createElement('option');
  855. option.value = playlist;
  856. option.textContent = playlist;
  857. // Mark the saved playlist as selected
  858. if (playlist === savedPlaylist) {
  859. option.selected = true;
  860. }
  861. select.appendChild(option);
  862. });
  863. // Attach the onchange event listener after populating the dropdown
  864. select.addEventListener('change', function () {
  865. const selectedPlaylist = this.value;
  866. setCookie('selected_playlist', selectedPlaylist, 365); // Save to cookie
  867. logMessage(`Selected playlist saved: ${selectedPlaylist}`);
  868. });
  869. logMessage('Playlist dropdown populated, event listener attached, and saved playlist restored.');
  870. })
  871. .catch(error => logMessage(`Error fetching playlists: ${error.message}`));
  872. }
  873. populatePlaylistDropdown().then(() => {
  874. loadSettingsFromCookies(); // Restore selected playlist after populating the dropdown
  875. });
  876. // Confirm and save the renamed playlist
  877. async function confirmAddPlaylist() {
  878. const playlistNameInput = document.getElementById('new_playlist_name');
  879. const playlistName = playlistNameInput.value.trim();
  880. if (!playlistName) {
  881. logMessage('Playlist name cannot be empty.', LOG_TYPE.ERROR);
  882. return;
  883. }
  884. try {
  885. logMessage(`Adding new playlist: "${playlistName}"...`);
  886. const response = await fetch('/create_playlist', {
  887. method: 'POST',
  888. headers: { 'Content-Type': 'application/json' },
  889. body: JSON.stringify({
  890. playlist_name: playlistName,
  891. files: [] // New playlist starts empty
  892. })
  893. });
  894. const result = await response.json();
  895. if (result.success) {
  896. logMessage(`Playlist "${playlistName}" created successfully.`, LOG_TYPE.SUCCESS);
  897. // Clear the input field
  898. playlistNameInput.value = '';
  899. // Refresh the playlist list
  900. loadAllPlaylists();
  901. populatePlaylistDropdown();
  902. // Hide the add playlist container
  903. toggleSecondaryButtons('add-playlist-container');
  904. } else {
  905. logMessage(`Failed to create playlist: ${result.error}`, LOG_TYPE.ERROR);
  906. }
  907. } catch (error) {
  908. logMessage(`Error creating playlist: ${error.message}`);
  909. }
  910. }
  911. async function confirmRenamePlaylist() {
  912. const newName = document.getElementById('playlist_name_input').value.trim();
  913. const currentName = document.getElementById('playlist_name_display').textContent;
  914. if (!newName) {
  915. logMessage("New playlist name cannot be empty.", LOG_TYPE.ERROR);
  916. return;
  917. }
  918. if (newName === currentName) {
  919. logMessage("New playlist name is the same as the current name. No changes made.", LOG_TYPE.WARNING);
  920. toggleSecondaryButtons('rename-playlist-container'); // Close the rename container
  921. return;
  922. }
  923. try {
  924. // Step 1: Create/Modify the playlist with the new name
  925. const createResponse = await fetch('/modify_playlist', {
  926. method: 'POST',
  927. headers: { 'Content-Type': 'application/json' },
  928. body: JSON.stringify({
  929. playlist_name: newName,
  930. files: playlist // Ensure `playlist` contains the current list of files
  931. })
  932. });
  933. const createResult = await createResponse.json();
  934. if (createResult.success) {
  935. logMessage(createResult.message, LOG_TYPE.SUCCESS);
  936. // Step 2: Delete the old playlist
  937. const deleteResponse = await fetch('/delete_playlist', {
  938. method: 'DELETE',
  939. headers: { 'Content-Type': 'application/json' },
  940. body: JSON.stringify({ playlist_name: currentName })
  941. });
  942. const deleteResult = await deleteResponse.json();
  943. if (deleteResult.success) {
  944. logMessage(deleteResult.message);
  945. // Update the UI with the new name
  946. document.getElementById('playlist_name_display').textContent = newName;
  947. // Refresh playlists list
  948. loadAllPlaylists();
  949. // Close the rename container and restore original action buttons
  950. toggleSecondaryButtons('rename-playlist-container');
  951. } else {
  952. logMessage(`Failed to delete old playlist: ${deleteResult.error}`, LOG_TYPE.ERROR);
  953. }
  954. } else {
  955. logMessage(`Failed to rename playlist: ${createResult.error}`, LOG_TYPE.ERROR);
  956. }
  957. } catch (error) {
  958. logMessage(`Error renaming playlist: ${error.message}`);
  959. }
  960. }
  961. // Delete the currently opened playlist
  962. async function deleteCurrentPlaylist() {
  963. const playlistName = document.getElementById('playlist_name_display').textContent;
  964. if (!confirm(`Are you sure you want to delete the playlist "${playlistName}"? This action cannot be undone.`)) {
  965. return;
  966. }
  967. try {
  968. const response = await fetch('/delete_playlist', {
  969. method: 'DELETE',
  970. headers: { 'Content-Type': 'application/json' },
  971. body: JSON.stringify({ playlist_name: playlistName })
  972. });
  973. const result = await response.json();
  974. if (result.success) {
  975. logMessage(`Playlist "${playlistName}" deleted.`, LOG_TYPE.INFO);
  976. closeStickySection('playlist-editor');
  977. loadAllPlaylists();
  978. populatePlaylistDropdown();
  979. } else {
  980. logMessage(`Failed to delete playlist: ${result.error}`, LOG_TYPE.ERROR);
  981. }
  982. } catch (error) {
  983. logMessage(`Error deleting playlist: ${error.message}`);
  984. }
  985. }
  986. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  987. // PART D: Local playlist array UI
  988. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  989. // Refresh the playlist UI and detect changes
  990. function refreshPlaylistUI() {
  991. const ul = document.getElementById('playlist_items');
  992. if (!ul) {
  993. logMessage('Error: Playlist container not found');
  994. return;
  995. }
  996. ul.innerHTML = ''; // Clear existing items
  997. if (playlist.length === 0) {
  998. // Add a placeholder if the playlist is empty
  999. const emptyLi = document.createElement('li');
  1000. emptyLi.textContent = 'No items in the playlist.';
  1001. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  1002. ul.appendChild(emptyLi);
  1003. return;
  1004. }
  1005. playlist.forEach((file, index) => {
  1006. const li = document.createElement('li');
  1007. // Add filename in a span
  1008. const filenameSpan = document.createElement('span');
  1009. filenameSpan.textContent = file;
  1010. filenameSpan.classList.add('filename'); // Add a class for styling
  1011. li.appendChild(filenameSpan);
  1012. // Move Up button
  1013. const moveUpBtn = document.createElement('button');
  1014. moveUpBtn.innerHTML = '<i class="fa-solid fa-turn-up"></i>'; // Up arrow symbol
  1015. moveUpBtn.classList.add('move-button');
  1016. moveUpBtn.onclick = () => {
  1017. if (index > 0) {
  1018. const temp = playlist[index - 1];
  1019. playlist[index - 1] = playlist[index];
  1020. playlist[index] = temp;
  1021. detectPlaylistChanges(); // Check for changes
  1022. refreshPlaylistUI();
  1023. }
  1024. };
  1025. li.appendChild(moveUpBtn);
  1026. // Move Down button
  1027. const moveDownBtn = document.createElement('button');
  1028. moveDownBtn.innerHTML = '<i class="fa-solid fa-turn-down"></i>'; // Down arrow symbol
  1029. moveDownBtn.classList.add('move-button');
  1030. moveDownBtn.onclick = () => {
  1031. if (index < playlist.length - 1) {
  1032. const temp = playlist[index + 1];
  1033. playlist[index + 1] = playlist[index];
  1034. playlist[index] = temp;
  1035. detectPlaylistChanges(); // Check for changes
  1036. refreshPlaylistUI();
  1037. }
  1038. };
  1039. li.appendChild(moveDownBtn);
  1040. // Remove button
  1041. const removeBtn = document.createElement('button');
  1042. removeBtn.innerHTML = '<i class="fa-solid fa-trash"></i>';
  1043. removeBtn.classList.add('remove-button');
  1044. removeBtn.onclick = () => {
  1045. playlist.splice(index, 1);
  1046. detectPlaylistChanges(); // Check for changes
  1047. refreshPlaylistUI();
  1048. };
  1049. li.appendChild(removeBtn);
  1050. ul.appendChild(li);
  1051. });
  1052. }
  1053. // Toggle the visibility of the save and cancel buttons
  1054. function toggleSaveCancelButtons(show) {
  1055. const actionButtons = document.querySelector('#playlist-editor .action-buttons');
  1056. if (actionButtons) {
  1057. // Show/hide all buttons except Save and Cancel
  1058. actionButtons.querySelectorAll('button:not(.save-cancel)').forEach(button => {
  1059. button.style.display = show ? 'none' : 'flex';
  1060. });
  1061. // Show/hide Save and Cancel buttons
  1062. actionButtons.querySelectorAll('.save-cancel').forEach(button => {
  1063. button.style.display = show ? 'flex' : 'none';
  1064. });
  1065. } else {
  1066. logMessage('Error: Action buttons container not found.', LOG_TYPE.ERROR);
  1067. }
  1068. }
  1069. // Detect changes in the playlist
  1070. function detectPlaylistChanges() {
  1071. isPlaylistChanged = JSON.stringify(originalPlaylist) !== JSON.stringify(playlist);
  1072. toggleSaveCancelButtons(isPlaylistChanged);
  1073. }
  1074. // Toggle the "Add to Playlist" section
  1075. function toggleSecondaryButtons(containerId, onShowCallback = null) {
  1076. const container = document.getElementById(containerId);
  1077. if (!container) {
  1078. logMessage(`Error: Element with ID "${containerId}" not found`);
  1079. return;
  1080. }
  1081. // Find the .action-buttons element preceding the container
  1082. const previousActionButtons = container.previousElementSibling?.classList.contains('action-buttons')
  1083. ? container.previousElementSibling
  1084. : null;
  1085. if (container.classList.contains('hidden')) {
  1086. // Show the container
  1087. container.classList.remove('hidden');
  1088. // Hide the previous .action-buttons element
  1089. if (previousActionButtons) {
  1090. previousActionButtons.style.display = 'none';
  1091. }
  1092. // Optional callback for custom logic when showing the container
  1093. if (onShowCallback) {
  1094. onShowCallback();
  1095. }
  1096. } else {
  1097. // Hide the container
  1098. container.classList.add('hidden');
  1099. // Restore the previous .action-buttons element
  1100. if (previousActionButtons) {
  1101. previousActionButtons.style.display = 'flex';
  1102. }
  1103. }
  1104. }
  1105. // Add the selected pattern to the selected playlist
  1106. async function saveToPlaylist() {
  1107. const playlist = document.getElementById('select-playlist').value;
  1108. if (!playlist) {
  1109. logMessage('No playlist selected.', LOG_TYPE.ERROR);
  1110. return;
  1111. }
  1112. if (!selectedFile) {
  1113. logMessage('No pattern selected to add.', LOG_TYPE.ERROR);
  1114. return;
  1115. }
  1116. try {
  1117. logMessage(`Adding pattern "${selectedFile}" to playlist "${playlist}"...`);
  1118. const response = await fetch('/add_to_playlist', {
  1119. method: 'POST',
  1120. headers: { 'Content-Type': 'application/json' },
  1121. body: JSON.stringify({ playlist_name: playlist, pattern: selectedFile })
  1122. });
  1123. const result = await response.json();
  1124. if (result.success) {
  1125. logMessage(`Pattern "${selectedFile}" successfully added to playlist "${playlist}".`, LOG_TYPE.SUCCESS);
  1126. // Reset the UI state via toggleSecondaryButtons
  1127. toggleSecondaryButtons('add-to-playlist-container', () => {
  1128. const selectPlaylist = document.getElementById('select-playlist');
  1129. selectPlaylist.value = ''; // Clear the selection
  1130. });
  1131. } else {
  1132. logMessage(`Failed to add pattern to playlist: ${result.error}`, LOG_TYPE.ERROR);
  1133. }
  1134. } catch (error) {
  1135. logMessage(`Error adding pattern to playlist: ${error.message}`);
  1136. }
  1137. }
  1138. async function changeSpeed() {
  1139. const speedInput = document.getElementById('speed_input');
  1140. const speed = parseFloat(speedInput.value);
  1141. if (isNaN(speed) || speed <= 0) {
  1142. logMessage('Invalid speed. Please enter a positive number.');
  1143. return;
  1144. }
  1145. logMessage(`Setting speed to: ${speed}...`);
  1146. const response = await fetch('/set_speed', {
  1147. method: 'POST',
  1148. headers: { 'Content-Type': 'application/json' },
  1149. body: JSON.stringify({ speed })
  1150. });
  1151. const result = await response.json();
  1152. if (result.success) {
  1153. document.getElementById('speed_status').textContent = `Current Speed: ${speed}`;
  1154. logMessage(`Speed set to: ${speed}`, LOG_TYPE.SUCCESS);
  1155. } else {
  1156. logMessage(`Failed to set speed: ${result.error}`, LOG_TYPE.ERROR);
  1157. }
  1158. }
  1159. // Function to close any sticky section
  1160. function closeStickySection(sectionId) {
  1161. const section = document.getElementById(sectionId);
  1162. if (section) {
  1163. section.classList.remove('visible');
  1164. section.classList.remove('fullscreen');
  1165. section.classList.add('hidden');
  1166. // Reset the fullscreen button text if it exists
  1167. const fullscreenButton = section.querySelector('.fullscreen-button');
  1168. if (fullscreenButton) {
  1169. fullscreenButton.innerHtml = '<i class="fa-solid fa-compress"></i>'; // Reset to enter fullscreen icon/text
  1170. }
  1171. logMessage(`Closed section: ${sectionId}`);
  1172. if(sectionId === 'playlist-editor') {
  1173. document.querySelectorAll('#all_playlists .playlist-item').forEach(item => {
  1174. item.classList.remove('selected');
  1175. });
  1176. }
  1177. if(sectionId === 'pattern-preview-container') {
  1178. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1179. item.classList.remove('selected');
  1180. });
  1181. }
  1182. } else {
  1183. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1184. }
  1185. }
  1186. // Function to open any sticky section
  1187. function openStickySection(sectionId) {
  1188. const section = document.getElementById(sectionId);
  1189. if (section) {
  1190. // Toggle the 'open' class
  1191. section.classList.toggle('open');
  1192. } else {
  1193. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1194. }
  1195. }
  1196. function attachFullScreenListeners() {
  1197. // Add event listener to all fullscreen buttons
  1198. document.querySelectorAll('.fullscreen-button').forEach(button => {
  1199. button.addEventListener('click', function () {
  1200. const stickySection = this.closest('.sticky'); // Find the closest sticky section
  1201. if (stickySection) {
  1202. // Close all other sections
  1203. document.querySelectorAll('.sticky:not(#currently-playing-container)').forEach(section => {
  1204. if (section !== stickySection) {
  1205. section.classList.remove('fullscreen');
  1206. section.classList.remove('visible');
  1207. section.classList.add('hidden');
  1208. // Reset the fullscreen button text for other sections
  1209. const otherFullscreenButton = section.querySelector('.fullscreen-button');
  1210. if (otherFullscreenButton) {
  1211. otherFullscreenButton.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1212. }
  1213. }
  1214. });
  1215. stickySection.classList.toggle('fullscreen'); // Toggle fullscreen class
  1216. // Update button icon or text
  1217. if (stickySection.classList.contains('fullscreen')) {
  1218. this.innerHTML = '<i class="fa-solid fa-compress"></i>'; // Exit fullscreen icon/text
  1219. } else {
  1220. this.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1221. }
  1222. } else {
  1223. console.error('Error: Fullscreen button is not inside a sticky section.');
  1224. }
  1225. });
  1226. });
  1227. }
  1228. let lastPreviewedFile = null; // Track the last previewed file
  1229. function formatSecondsToHMS(seconds) {
  1230. const hrs = Math.floor(seconds / 3600);
  1231. const mins = Math.floor((seconds % 3600) / 60);
  1232. const secs = Math.floor(seconds % 60);
  1233. return `${String(hrs).padStart(2, '0')}:${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  1234. }
  1235. // Function to start or stop updates based on visibility
  1236. function toggleSettings() {
  1237. const settingsContainer = document.getElementById('settings-container');
  1238. if (settingsContainer) {
  1239. settingsContainer.classList.toggle('open');
  1240. }
  1241. }
  1242. // Utility function to manage cookies
  1243. function setCookie(name, value, days) {
  1244. const date = new Date();
  1245. date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  1246. document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
  1247. }
  1248. function getCookie(name) {
  1249. const nameEQ = `${name}=`;
  1250. const cookies = document.cookie.split(';');
  1251. for (let i = 0; i < cookies.length; i++) {
  1252. let cookie = cookies[i].trim();
  1253. if (cookie.startsWith(nameEQ)) {
  1254. return cookie.substring(nameEQ.length);
  1255. }
  1256. }
  1257. return null;
  1258. }
  1259. // Save settings to cookies
  1260. function saveSettingsToCookies() {
  1261. const pauseTime = document.getElementById('pause_time').value;
  1262. const clearPattern = document.getElementById('clear_pattern').value;
  1263. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  1264. const shuffle = document.getElementById('shuffle_playlist').checked;
  1265. setCookie('pause_time', pauseTime, 365);
  1266. setCookie('clear_pattern', clearPattern, 365);
  1267. setCookie('run_mode', runMode, 365);
  1268. setCookie('shuffle', shuffle, 365);
  1269. }
  1270. // Load settings from cookies
  1271. function loadSettingsFromCookies() {
  1272. const pauseTime = getCookie('pause_time');
  1273. if (pauseTime !== '') {
  1274. document.getElementById('pause_time').value = pauseTime;
  1275. }
  1276. const clearPattern = getCookie('clear_pattern');
  1277. if (clearPattern !== '') {
  1278. document.getElementById('clear_pattern').value = clearPattern;
  1279. }
  1280. const runMode = getCookie('run_mode');
  1281. if (runMode !== '') {
  1282. document.querySelector(`input[name="run_mode"][value="${runMode}"]`).checked = true;
  1283. }
  1284. const shuffle = getCookie('shuffle');
  1285. if (shuffle !== '') {
  1286. document.getElementById('shuffle_playlist').checked = shuffle === 'true';
  1287. }
  1288. logMessage('Settings loaded from cookies.');
  1289. }
  1290. // Call this function to save settings when a value is changed
  1291. function attachSettingsSaveListeners() {
  1292. // Add event listeners to inputs
  1293. document.getElementById('pause_time').addEventListener('change', saveSettingsToCookies);
  1294. document.getElementById('clear_pattern').addEventListener('change', saveSettingsToCookies);
  1295. document.querySelectorAll('input[name="run_mode"]').forEach(input => {
  1296. input.addEventListener('change', saveSettingsToCookies);
  1297. });
  1298. document.getElementById('shuffle_playlist').addEventListener('change', saveSettingsToCookies);
  1299. }
  1300. // Tab switching logic with cookie storage
  1301. function switchTab(tabName) {
  1302. // Store the active tab in a cookie
  1303. setCookie('activeTab', tabName, 365); // Store for 7 days
  1304. // Deactivate all tab content
  1305. document.querySelectorAll('.tab-content').forEach(tab => {
  1306. tab.classList.remove('active');
  1307. });
  1308. // Activate the selected tab content
  1309. const activeTab = document.getElementById(`${tabName}-tab`);
  1310. if (activeTab) {
  1311. activeTab.classList.add('active');
  1312. } else {
  1313. console.error(`Error: Tab "${tabName}" not found.`);
  1314. }
  1315. // Deactivate all nav buttons
  1316. document.querySelectorAll('.bottom-nav .tab-button').forEach(button => {
  1317. button.classList.remove('active');
  1318. });
  1319. // Activate the selected nav button
  1320. const activeNavButton = document.getElementById(`nav-${tabName}`);
  1321. if (activeNavButton) {
  1322. activeNavButton.classList.add('active');
  1323. } else {
  1324. console.error(`Error: Nav button for "${tabName}" not found.`);
  1325. }
  1326. }
  1327. // Update the small UI segment to show the IP or hide it if none
  1328. function updateWledUI() {
  1329. const wledIp = localStorage.getItem('wled_ip');
  1330. const wledContainer = document.getElementById('wled-container');
  1331. const wledFrame = document.getElementById('wled-frame');
  1332. const wledStatus = document.getElementById('wled-status');
  1333. if (!wledIp) {
  1334. wledContainer.classList.add('hidden');
  1335. return;
  1336. }
  1337. // Show the container and load WLED UI
  1338. wledContainer.classList.remove('hidden');
  1339. wledFrame.src = `http://${wledIp}`;
  1340. }
  1341. // Save or clear the WLED IP, updating both the browser and backend
  1342. async function saveWledIp() {
  1343. const ipInput = document.getElementById('wled_ip');
  1344. const saveButton = document.querySelector('.wled-settings button.cta');
  1345. const currentIp = localStorage.getItem('wled_ip');
  1346. if (currentIp) {
  1347. // Clear the saved IP if one is already set
  1348. localStorage.removeItem('wled_ip');
  1349. ipInput.disabled = false;
  1350. ipInput.value = '';
  1351. saveButton.innerHTML = '<i class="fa-solid fa-save"></i><span>Save</span>';
  1352. logMessage('WLED IP cleared.', LOG_TYPE.INFO);
  1353. // Also clear the IP on the backend
  1354. try {
  1355. const response = await fetch('/set_wled_ip', {
  1356. method: 'POST',
  1357. headers: { 'Content-Type': 'application/json' },
  1358. body: JSON.stringify({ wled_ip: null })
  1359. });
  1360. const data = await response.json();
  1361. if (data.success) {
  1362. logMessage('Backend IP cleared successfully.', LOG_TYPE.INFO);
  1363. } else {
  1364. logMessage('Failed to clear backend IP.', LOG_TYPE.ERROR);
  1365. }
  1366. } catch (error) {
  1367. logMessage(`Error clearing backend IP: ${error.message}`, LOG_TYPE.ERROR);
  1368. }
  1369. } else {
  1370. // Validate and save the new IP
  1371. const ip = ipInput.value.trim();
  1372. if (!validateIp(ip)) {
  1373. logMessage('Invalid IP address format.', LOG_TYPE.ERROR);
  1374. return;
  1375. }
  1376. localStorage.setItem('wled_ip', ip);
  1377. ipInput.disabled = true;
  1378. saveButton.innerHTML = '<i class="fa-solid fa-xmark"></i><span>Clear</span>';
  1379. logMessage(`WLED IP saved: ${ip}`, LOG_TYPE.SUCCESS);
  1380. // Also save the IP to the backend
  1381. try {
  1382. const response = await fetch('/set_wled_ip', {
  1383. method: 'POST',
  1384. headers: { 'Content-Type': 'application/json' },
  1385. body: JSON.stringify({ wled_ip: ip })
  1386. });
  1387. const data = await response.json();
  1388. if (data.success) {
  1389. logMessage('Backend IP saved successfully.', LOG_TYPE.SUCCESS);
  1390. } else {
  1391. logMessage('Failed to save backend IP.', LOG_TYPE.ERROR);
  1392. }
  1393. } catch (error) {
  1394. logMessage(`Error saving backend IP: ${error.message}`, LOG_TYPE.ERROR);
  1395. }
  1396. }
  1397. updateWledUI(); // Refresh any UI elements that depend on the IP
  1398. }
  1399. // Load the WLED IP from localStorage; if not available, retrieve it from the backend
  1400. async function loadWledIp() {
  1401. const ipInput = document.getElementById('wled_ip');
  1402. const saveButton = document.querySelector('.wled-settings button.cta');
  1403. let savedIp = localStorage.getItem('wled_ip');
  1404. if (!savedIp) {
  1405. // Attempt to load from the backend if not found in localStorage
  1406. try {
  1407. const response = await fetch('/get_wled_ip');
  1408. const data = await response.json();
  1409. if (data.wled_ip) {
  1410. savedIp = data.wled_ip;
  1411. localStorage.setItem('wled_ip', savedIp);
  1412. }
  1413. } catch (error) {
  1414. logMessage(`Error fetching WLED IP from backend: ${error.message}`, LOG_TYPE.ERROR);
  1415. }
  1416. }
  1417. if (savedIp) {
  1418. ipInput.value = savedIp;
  1419. ipInput.disabled = true;
  1420. saveButton.innerHTML = '<i class="fa-solid fa-xmark"></i><span>Clear</span>';
  1421. } else {
  1422. ipInput.disabled = false;
  1423. saveButton.innerHTML = '<i class="fa-solid fa-save"></i><span>Save</span>';
  1424. }
  1425. updateWledUI(); // Update any dependent UI segments
  1426. }
  1427. function validateIp(ip) {
  1428. const ipRegex = /^(25[0-5]|2[0-4]\d|1\d\d|\d?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|\d?\d)){3}$/;
  1429. return ipRegex.test(ip);
  1430. }
  1431. // Theme toggle functionality
  1432. const themeToggle = document.getElementById('theme-toggle');
  1433. const themeIcon = themeToggle.querySelector('i');
  1434. themeToggle.addEventListener('click', () => {
  1435. const root = document.documentElement;
  1436. const currentTheme = root.getAttribute('data-theme');
  1437. const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
  1438. root.setAttribute('data-theme', newTheme);
  1439. localStorage.setItem('theme', newTheme);
  1440. // Toggle the icon
  1441. themeIcon.className = newTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
  1442. });
  1443. // Set initial theme and icon based on saved theme
  1444. const savedTheme = localStorage.getItem('theme') || 'light';
  1445. document.documentElement.setAttribute('data-theme', savedTheme);
  1446. themeIcon.className = savedTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
  1447. // Add WebSocket connection for status updates
  1448. let statusSocket = null;
  1449. let reconnectAttempts = 0;
  1450. const MAX_RECONNECT_ATTEMPTS = 5;
  1451. let statusUpdateInterval = null;
  1452. function connectStatusWebSocket() {
  1453. // Close existing connection and clear interval if any
  1454. if (statusSocket) {
  1455. statusSocket.close();
  1456. }
  1457. if (statusUpdateInterval) {
  1458. clearInterval(statusUpdateInterval);
  1459. }
  1460. // Create WebSocket connection
  1461. const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  1462. statusSocket = new WebSocket(`${protocol}//${window.location.host}/ws/status`);
  1463. statusSocket.onopen = () => {
  1464. console.log('Status WebSocket connected');
  1465. reconnectAttempts = 0; // Reset reconnect attempts on successful connection
  1466. // Immediately request initial status
  1467. if (statusSocket.readyState === WebSocket.OPEN) {
  1468. console.log('Requesting initial status...');
  1469. statusSocket.send('get_status');
  1470. }
  1471. // Set up periodic status updates
  1472. statusUpdateInterval = setInterval(() => {
  1473. if (statusSocket && statusSocket.readyState === WebSocket.OPEN) {
  1474. statusSocket.send('get_status');
  1475. }
  1476. }, 1000);
  1477. };
  1478. statusSocket.onmessage = (event) => {
  1479. try {
  1480. console.log('Status data received:', event.data);
  1481. const message = JSON.parse(event.data);
  1482. if (message.type === 'status_update' && message.data) {
  1483. updateCurrentlyPlayingUI(message.data);
  1484. }
  1485. } catch (error) {
  1486. console.error('Error processing status update:', error);
  1487. console.error('Raw data that caused error:', event.data);
  1488. }
  1489. };
  1490. statusSocket.onclose = () => {
  1491. console.log('Status WebSocket disconnected');
  1492. clearInterval(statusUpdateInterval);
  1493. if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
  1494. reconnectAttempts++;
  1495. const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
  1496. console.log(`Reconnecting in ${delay/1000}s (Attempt ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`);
  1497. setTimeout(connectStatusWebSocket, delay);
  1498. } else {
  1499. console.error('Max reconnection attempts reached. Please refresh the page.');
  1500. }
  1501. };
  1502. statusSocket.onerror = (error) => {
  1503. console.error('WebSocket error:', error);
  1504. statusSocket.close();
  1505. };
  1506. }
  1507. // Replace the polling mechanism with WebSocket
  1508. document.addEventListener('DOMContentLoaded', () => {
  1509. const activeTab = getCookie('activeTab') || 'patterns'; // Default to 'patterns' tab
  1510. switchTab(activeTab); // Load the active tab
  1511. checkSerialStatus(); // Check connection status
  1512. loadThetaRhoFiles(); // Load files on page load
  1513. loadAllPlaylists(); // Load all playlists on page load
  1514. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1515. attachFullScreenListeners();
  1516. loadWledIp();
  1517. updateWledUI();
  1518. // Initialize WebSocket connection for status updates
  1519. connectStatusWebSocket();
  1520. // Handle visibility change
  1521. document.addEventListener('visibilitychange', () => {
  1522. if (document.visibilityState === 'visible' && statusSocket && statusSocket.readyState !== WebSocket.OPEN) {
  1523. connectStatusWebSocket();
  1524. }
  1525. });
  1526. checkForUpdates();
  1527. });
  1528. // Track the last time we had a file playing
  1529. let lastPlayingTime = 0;
  1530. const HIDE_DELAY = 5000; // 1 second delay before hiding
  1531. // Update the updateCurrentlyPlayingUI function to handle WebSocket updates
  1532. // Track the last played file to detect when a new pattern starts
  1533. let lastPlayedFile = null;
  1534. function updateCurrentlyPlayingUI(status) {
  1535. console.log('Updating UI with status:', status);
  1536. // Get all required DOM elements once
  1537. const container = document.getElementById('currently-playing-container');
  1538. const fileNameElement = document.getElementById('currently-playing-file');
  1539. const progressBar = document.getElementById('play_progress');
  1540. const progressText = document.getElementById('play_progress_text');
  1541. const pausePlayButton = document.getElementById('pausePlayCurrent');
  1542. // Check if all required elements exist
  1543. if (!container || !fileNameElement || !progressBar || !progressText) {
  1544. console.log('Required DOM elements not found:', {
  1545. container: !!container,
  1546. fileNameElement: !!fileNameElement,
  1547. progressBar: !!progressBar,
  1548. progressText: !!progressText
  1549. });
  1550. setTimeout(() => updateCurrentlyPlayingUI(status), 100);
  1551. return;
  1552. }
  1553. // Update container visibility based on status
  1554. if (status.current_file && status.is_running) {
  1555. console.log('Pattern is running, showing container');
  1556. document.body.classList.add('playing');
  1557. container.style.display = 'flex';
  1558. } else {
  1559. console.log('No pattern running, hiding container');
  1560. document.body.classList.remove('playing');
  1561. container.style.display = 'none';
  1562. return;
  1563. }
  1564. // Update file name display
  1565. const fileName = status.current_file.replace('./patterns/', '');
  1566. fileNameElement.textContent = fileName;
  1567. // Update next file display
  1568. const nextFileElement = document.getElementById('next-file');
  1569. if (nextFileElement) {
  1570. if (status.playlist && status.playlist.next_file) {
  1571. const nextFileName = status.playlist.next_file.replace('./patterns/', '');
  1572. nextFileElement.textContent = `(Next: ${nextFileName})`;
  1573. nextFileElement.style.display = 'block';
  1574. } else {
  1575. nextFileElement.style.display = 'none';
  1576. }
  1577. }
  1578. // Update pattern preview if it's a new pattern
  1579. if (lastPlayedFile !== status.current_file) {
  1580. lastPlayedFile = status.current_file;
  1581. const cleanFileName = status.current_file.replace('./patterns/', '');
  1582. previewPattern(cleanFileName, 'currently-playing-container');
  1583. }
  1584. // Update progress information
  1585. if (status.progress) {
  1586. const { percentage, remaining_time, elapsed_time } = status.progress;
  1587. const formattedPercentage = percentage.toFixed(1);
  1588. const remainingText = remaining_time === null ? 'calculating...' : formatSecondsToHMS(remaining_time);
  1589. const elapsedText = formatSecondsToHMS(elapsed_time);
  1590. progressBar.value = formattedPercentage;
  1591. progressText.textContent = `${formattedPercentage}% (Elapsed: ${elapsedText} | Remaining: ${remainingText})`;
  1592. } else {
  1593. progressBar.value = 0;
  1594. progressText.textContent = '0%';
  1595. }
  1596. // Update pause/play button if it exists
  1597. if (pausePlayButton) {
  1598. pausePlayButton.innerHTML = status.is_paused ?
  1599. '<i class="fa-solid fa-play"></i>' :
  1600. '<i class="fa-solid fa-pause"></i>';
  1601. }
  1602. // Update playlist UI if the function exists
  1603. if (typeof updatePlaylistUI === 'function') {
  1604. updatePlaylistUI(status);
  1605. }
  1606. }