main.js 71 KB

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