main.js 67 KB

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