main.js 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854
  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. 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. 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. 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({ 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({ 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. function connectStatusWebSocket() {
  1452. // Close existing connection if any
  1453. if (statusSocket) {
  1454. statusSocket.close();
  1455. }
  1456. // Create WebSocket connection
  1457. const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  1458. statusSocket = new WebSocket(`${protocol}//${window.location.host}/ws/status`);
  1459. statusSocket.onopen = () => {
  1460. console.log('Status WebSocket connected');
  1461. reconnectAttempts = 0; // Reset reconnect attempts on successful connection
  1462. // Request initial status
  1463. statusSocket.send('get_status');
  1464. // Request status updates periodically
  1465. setInterval(() => {
  1466. if (statusSocket.readyState === WebSocket.OPEN) {
  1467. statusSocket.send('get_status');
  1468. }
  1469. }, 1000); // Request update every second
  1470. };
  1471. // Add debouncing for UI updates
  1472. let updateTimeout;
  1473. statusSocket.onmessage = (event) => {
  1474. try {
  1475. const status = JSON.parse(event.data);
  1476. console.log('Received status update:', status);
  1477. clearTimeout(updateTimeout);
  1478. updateTimeout = setTimeout(() => {
  1479. console.log('Updating UI with status:', status);
  1480. updateCurrentlyPlayingUI(status);
  1481. }, 100); // Debounce updates to 100ms
  1482. } catch (error) {
  1483. console.error('Error processing status update:', error);
  1484. }
  1485. };
  1486. statusSocket.onclose = () => {
  1487. console.log('Status WebSocket disconnected.');
  1488. if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS) {
  1489. reconnectAttempts++;
  1490. const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000); // Exponential backoff, max 30 seconds
  1491. console.log(`Attempting to reconnect in ${delay/1000} seconds... (Attempt ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`);
  1492. setTimeout(connectStatusWebSocket, delay);
  1493. } else {
  1494. console.error('Max reconnection attempts reached. Please refresh the page.');
  1495. }
  1496. };
  1497. statusSocket.onerror = (error) => {
  1498. console.error('WebSocket error:', error);
  1499. statusSocket.close();
  1500. };
  1501. }
  1502. // Replace the polling mechanism with WebSocket
  1503. document.addEventListener('DOMContentLoaded', () => {
  1504. const activeTab = getCookie('activeTab') || 'patterns'; // Default to 'patterns' tab
  1505. switchTab(activeTab); // Load the active tab
  1506. checkSerialStatus(); // Check connection status
  1507. loadThetaRhoFiles(); // Load files on page load
  1508. loadAllPlaylists(); // Load all playlists on page load
  1509. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1510. attachFullScreenListeners();
  1511. loadWledIp();
  1512. updateWledUI();
  1513. // Initialize WebSocket connection for status updates
  1514. connectStatusWebSocket();
  1515. // Handle visibility change
  1516. document.addEventListener('visibilitychange', () => {
  1517. if (document.visibilityState === 'visible' && statusSocket && statusSocket.readyState !== WebSocket.OPEN) {
  1518. connectStatusWebSocket();
  1519. }
  1520. });
  1521. checkForUpdates();
  1522. });
  1523. // Track the last time we had a file playing
  1524. let lastPlayingTime = 0;
  1525. const HIDE_DELAY = 5000; // 1 second delay before hiding
  1526. // Update the updateCurrentlyPlayingUI function to handle WebSocket updates
  1527. // Track the last played file to detect when a new pattern starts
  1528. let lastPlayedFile = null;
  1529. function updateCurrentlyPlayingUI(status) {
  1530. const currentlyPlayingContainer = document.getElementById('currently-playing-container');
  1531. const currentlyPlayingFile = document.getElementById('currently-playing-file');
  1532. const progressBar = document.getElementById('play_progress');
  1533. const progressText = document.getElementById('play_progress_text');
  1534. const pausePlayButton = document.getElementById('pausePlayCurrent');
  1535. if (!currentlyPlayingContainer || !currentlyPlayingFile || !progressBar || !progressText) return;
  1536. const now = Date.now();
  1537. if (status.current_file) {
  1538. // Update last playing time
  1539. lastPlayingTime = now;
  1540. // Show the container and update file name
  1541. document.body.classList.add('playing');
  1542. const fileName = status.current_file.replace('./patterns/', '');
  1543. currentlyPlayingFile.textContent = fileName;
  1544. // Only update preview when a new pattern starts playing
  1545. if (lastPlayedFile !== status.current_file) {
  1546. lastPlayedFile = status.current_file;
  1547. // Remove the ./patterns/ prefix since previewPattern will add it
  1548. const cleanFileName = status.current_file.replace('./patterns/', '');
  1549. // Use the existing preview_thr endpoint
  1550. previewPattern(cleanFileName, 'currently-playing-container');
  1551. }
  1552. // Update progress information if available
  1553. if (status.progress) {
  1554. const progress = status.progress;
  1555. const percentage = progress.percentage.toFixed(1);
  1556. const remainingTime = progress.remaining_time === null ? 'calculating...' : formatSecondsToHMS(progress.remaining_time);
  1557. const elapsedTime = formatSecondsToHMS(progress.elapsed_time);
  1558. progressBar.value = percentage;
  1559. progressText.textContent = `${percentage}% (Elapsed: ${elapsedTime} | Remaining: ${remainingTime})`;
  1560. } else {
  1561. progressBar.value = 0;
  1562. progressText.textContent = '0%';
  1563. }
  1564. // Update pause/play button
  1565. if (pausePlayButton) {
  1566. pausePlayButton.innerHTML = status.is_paused ?
  1567. '<i class="fa-solid fa-play"></i>' :
  1568. '<i class="fa-solid fa-pause"></i>';
  1569. }
  1570. } else if (now - lastPlayingTime > HIDE_DELAY) {
  1571. // Only hide the container if we haven't had a playing file for more than HIDE_DELAY
  1572. document.body.classList.remove('playing');
  1573. progressBar.value = 0;
  1574. progressText.textContent = '0%';
  1575. }
  1576. // Update other UI elements based on status
  1577. if (typeof updatePlaylistUI === 'function') {
  1578. updatePlaylistUI(status);
  1579. }
  1580. }