main.js 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327
  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) {
  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.textContent = '×';
  46. closeButton.className = 'close-button';
  47. closeButton.onclick = () => {
  48. notification.classList.remove('show');
  49. setTimeout(() => notification.remove(), 250); // Match transition duration
  50. };
  51. notification.appendChild(closeButton);
  52. // Append the notification to the header
  53. header.appendChild(notification);
  54. // Trigger the transition
  55. requestAnimationFrame(() => {
  56. notification.classList.add('show');
  57. });
  58. // Auto-remove the notification after 5 seconds
  59. setTimeout(() => {
  60. if (notification.parentNode) {
  61. notification.classList.remove('show');
  62. setTimeout(() => notification.remove(), 250); // Match transition duration
  63. }
  64. }, 5000);
  65. // Also log the message to the status log if available
  66. if (log) {
  67. const entry = document.createElement('p');
  68. entry.textContent = message;
  69. log.appendChild(entry);
  70. log.scrollTop = log.scrollHeight; // Scroll to the bottom of the log
  71. }
  72. }
  73. function toggleDebugLog() {
  74. const statusLog = document.getElementById('status_log');
  75. const debugButton = document.getElementById('debug_button');
  76. if (statusLog.style.display === 'block') {
  77. statusLog.style.display = 'none';
  78. debugButton.classList.remove('active');
  79. } else {
  80. statusLog.style.display = 'block';
  81. debugButton.classList.add( 'active');
  82. statusLog.scrollIntoView({ behavior: 'smooth', block: 'start' }); // Smooth scrolling to the log
  83. }
  84. }
  85. // File selection logic
  86. async function selectFile(file, listItem) {
  87. selectedFile = file;
  88. // Highlight the selected file
  89. document.querySelectorAll('#theta_rho_files li').forEach(li => li.classList.remove('selected'));
  90. listItem.classList.add('selected');
  91. // Update the Remove button visibility
  92. const removeButton = document.querySelector('#pattern-preview-container .remove-button');
  93. if (file.startsWith('custom_patterns/')) {
  94. removeButton.classList.remove('hidden');
  95. } else {
  96. removeButton.classList.add('hidden');
  97. }
  98. logMessage(`Selected file: ${file}`);
  99. await previewPattern(file);
  100. // Populate the playlist dropdown after selecting a pattern
  101. await populatePlaylistDropdown();
  102. }
  103. // Fetch and display Theta-Rho files
  104. async function loadThetaRhoFiles() {
  105. try {
  106. logMessage('Loading Theta-Rho files...');
  107. const response = await fetch('/list_theta_rho_files');
  108. let files = await response.json();
  109. files = files.filter(file => file.endsWith('.thr'));
  110. // Sort files with custom_patterns on top and all alphabetically sorted
  111. const sortedFiles = files.sort((a, b) => {
  112. const isCustomA = a.startsWith('custom_patterns/');
  113. const isCustomB = b.startsWith('custom_patterns/');
  114. if (isCustomA && !isCustomB) return -1; // a comes first
  115. if (!isCustomA && isCustomB) return 1; // b comes first
  116. return a.localeCompare(b); // Alphabetical comparison
  117. });
  118. allFiles = sortedFiles; // Update global files
  119. displayFiles(sortedFiles); // Display sorted files
  120. logMessage('Theta-Rho files loaded and sorted successfully.');
  121. } catch (error) {
  122. logMessage(`Error loading Theta-Rho files: ${error.message}`, 'error');
  123. }
  124. }
  125. // Display files in the UI
  126. function displayFiles(files) {
  127. const ul = document.getElementById('theta_rho_files');
  128. if (!ul) {
  129. logMessage('Error: File list container not found');
  130. return;
  131. }
  132. ul.innerHTML = ''; // Clear existing list
  133. files.forEach(file => {
  134. const li = document.createElement('li');
  135. li.textContent = file;
  136. li.classList.add('file-item');
  137. // Attach file selection handler
  138. li.onclick = () => selectFile(file, li);
  139. ul.appendChild(li);
  140. });
  141. }
  142. // Filter files by search input
  143. function searchPatternFiles() {
  144. const searchInput = document.getElementById('search_pattern').value.toLowerCase();
  145. const filteredFiles = allFiles.filter(file => file.toLowerCase().includes(searchInput));
  146. displayFiles(filteredFiles);
  147. }
  148. // Upload a new Theta-Rho file
  149. async function uploadThetaRho() {
  150. const fileInput = document.getElementById('upload_file');
  151. const file = fileInput.files[0];
  152. if (!file) {
  153. logMessage('No file selected for upload.', LOG_TYPE.ERROR);
  154. return;
  155. }
  156. try {
  157. logMessage(`Uploading file: ${file.name}...`);
  158. const formData = new FormData();
  159. formData.append('file', file);
  160. const response = await fetch('/upload_theta_rho', {
  161. method: 'POST',
  162. body: formData
  163. });
  164. const result = await response.json();
  165. if (result.success) {
  166. logMessage(`File uploaded successfully: ${file.name}`, LOG_TYPE.SUCCESS);
  167. fileInput.value = '';
  168. await loadThetaRhoFiles();
  169. } else {
  170. logMessage(`Failed to upload file: ${file.name}`, LOG_TYPE.ERROR);
  171. }
  172. } catch (error) {
  173. logMessage(`Error uploading file: ${error.message}`);
  174. }
  175. }
  176. async function runThetaRho() {
  177. if (!selectedFile) {
  178. logMessage("No file selected to run.");
  179. return;
  180. }
  181. // Get the selected pre-execution action
  182. const preExecutionAction = document.querySelector('input[name="pre_execution"]:checked').value;
  183. logMessage(`Running file: ${selectedFile} with pre-execution action: ${preExecutionAction}...`);
  184. const response = await fetch('/run_theta_rho', {
  185. method: 'POST',
  186. headers: { 'Content-Type': 'application/json' },
  187. body: JSON.stringify({ file_name: selectedFile, pre_execution: preExecutionAction })
  188. });
  189. const result = await response.json();
  190. if (result.success) {
  191. logMessage(`Pattern running: ${selectedFile}`, LOG_TYPE.SUCCESS);
  192. } else {
  193. logMessage(`Failed to run file: ${selectedFile}`,LOG_TYPE.ERROR);
  194. }
  195. }
  196. async function stopExecution() {
  197. logMessage('Stopping execution...');
  198. const response = await fetch('/stop_execution', { method: 'POST' });
  199. const result = await response.json();
  200. if (result.success) {
  201. logMessage('Execution stopped.',LOG_TYPE.SUCCESS);
  202. } else {
  203. logMessage('Failed to stop execution.',LOG_TYPE.ERROR);
  204. }
  205. }
  206. function removeCurrentPattern() {
  207. if (!selectedFile) {
  208. logMessage('No file selected to remove.', LOG_TYPE.ERROR);
  209. return;
  210. }
  211. if (!selectedFile.startsWith('custom_patterns/')) {
  212. logMessage('Only custom patterns can be removed.', LOG_TYPE.WARNING);
  213. return;
  214. }
  215. removeCustomPattern(selectedFile);
  216. }
  217. // Delete the selected file
  218. async function removeCustomPattern(fileName) {
  219. const userConfirmed = confirm(`Are you sure you want to delete the pattern "${fileName}"?`);
  220. if (!userConfirmed) return;
  221. try {
  222. logMessage(`Deleting pattern: ${fileName}...`);
  223. const response = await fetch('/delete_theta_rho_file', {
  224. method: 'POST',
  225. headers: { 'Content-Type': 'application/json' },
  226. body: JSON.stringify({ file_name: fileName })
  227. });
  228. const result = await response.json();
  229. if (result.success) {
  230. logMessage(`File deleted successfully: ${selectedFile}`, LOG_TYPE.SUCCESS);
  231. // Close the preview container
  232. const previewContainer = document.getElementById('pattern-preview-container');
  233. if (previewContainer) {
  234. previewContainer.classList.add('hidden');
  235. previewContainer.classList.remove('visible');
  236. }
  237. // Clear the selected file and refresh the file list
  238. selectedFile = null;
  239. await loadThetaRhoFiles(); // Refresh the file list
  240. } else {
  241. logMessage(`Failed to delete pattern "${fileName}": ${result.error}`, LOG_TYPE.ERROR);
  242. }
  243. } catch (error) {
  244. logMessage(`Error deleting pattern: ${error.message}`);
  245. }
  246. }
  247. // Preview a Theta-Rho file
  248. async function previewPattern(fileName) {
  249. try {
  250. logMessage(`Fetching data to preview file: ${fileName}...`);
  251. const response = await fetch('/preview_thr', {
  252. method: 'POST',
  253. headers: { 'Content-Type': 'application/json' },
  254. body: JSON.stringify({ file_name: fileName })
  255. });
  256. const result = await response.json();
  257. if (result.success) {
  258. const coordinates = result.coordinates;
  259. renderPattern(coordinates);
  260. // Update coordinate display
  261. const firstCoord = coordinates[0];
  262. const lastCoord = coordinates[coordinates.length - 1];
  263. document.getElementById('first_coordinate').textContent = `First Coordinate: θ=${firstCoord[0]}, ρ=${firstCoord[1]}`;
  264. document.getElementById('last_coordinate').textContent = `Last Coordinate: θ=${lastCoord[0]}, ρ=${lastCoord[1]}`;
  265. // Show the preview container
  266. const previewContainer = document.getElementById('pattern-preview-container');
  267. if (previewContainer) {
  268. previewContainer.classList.remove('hidden');
  269. previewContainer.classList.add('visible');
  270. }
  271. // Close the "Add to Playlist" container if it is open
  272. const addToPlaylistContainer = document.getElementById('add-to-playlist-container');
  273. if (addToPlaylistContainer && !addToPlaylistContainer.classList.contains('hidden')) {
  274. toggleSecondaryButtons('add-to-playlist-container'); // Hide the container
  275. }
  276. } else {
  277. logMessage(`Failed to fetch preview for file: ${fileName}`, LOG_TYPE.WARNING);
  278. }
  279. } catch (error) {
  280. logMessage(`Error previewing pattern: ${error.message}`, LOG_TYPE.WARNING);
  281. }
  282. }
  283. // Render the pattern on a canvas
  284. function renderPattern(coordinates) {
  285. const canvas = document.getElementById('patternPreviewCanvas');
  286. if (!canvas) {
  287. logMessage('Error: Canvas not found');
  288. return;
  289. }
  290. const ctx = canvas.getContext('2d');
  291. // Account for device pixel ratio
  292. const dpr = window.devicePixelRatio || 1;
  293. const rect = canvas.getBoundingClientRect();
  294. canvas.width = rect.width * dpr; // Scale canvas width for high DPI
  295. canvas.height = rect.height * dpr; // Scale canvas height for high DPI
  296. ctx.scale(dpr, dpr); // Scale drawing context
  297. ctx.clearRect(0, 0, canvas.width, canvas.height);
  298. const centerX = rect.width / 2; // Use bounding client rect dimensions
  299. const centerY = rect.height / 2;
  300. const maxRho = Math.max(...coordinates.map(coord => coord[1]));
  301. const scale = Math.min(rect.width, rect.height) / (2 * maxRho); // Scale to fit
  302. ctx.beginPath();
  303. ctx.strokeStyle = 'white';
  304. coordinates.forEach(([theta, rho], index) => {
  305. const x = centerX + rho * Math.cos(theta) * scale;
  306. const y = centerY - rho * Math.sin(theta) * scale;
  307. if (index === 0) ctx.moveTo(x, y);
  308. else ctx.lineTo(x, y);
  309. });
  310. ctx.stroke();
  311. logMessage('Pattern preview rendered.');
  312. }
  313. async function moveToCenter() {
  314. logMessage('Moving to center...', LOG_TYPE.INFO);
  315. const response = await fetch('/move_to_center', { method: 'POST' });
  316. const result = await response.json();
  317. if (result.success) {
  318. logMessage('Moved to center successfully.', LOG_TYPE.SUCCESS);
  319. } else {
  320. logMessage(`Failed to move to center: ${result.error}`, LOG_TYPE.ERROR);
  321. }
  322. }
  323. async function moveToPerimeter() {
  324. logMessage('Moving to perimeter...', LOG_TYPE.INFO);
  325. const response = await fetch('/move_to_perimeter', { method: 'POST' });
  326. const result = await response.json();
  327. if (result.success) {
  328. logMessage('Moved to perimeter successfully.', LOG_TYPE.SUCCESS);
  329. } else {
  330. logMessage(`Failed to move to perimeter: ${result.error}`, LOG_TYPE.ERROR);
  331. }
  332. }
  333. async function sendCoordinate() {
  334. const theta = parseFloat(document.getElementById('theta_input').value);
  335. const rho = parseFloat(document.getElementById('rho_input').value);
  336. if (isNaN(theta) || isNaN(rho)) {
  337. logMessage('Invalid input: θ and ρ must be numbers.', LOG_TYPE.ERROR);
  338. return;
  339. }
  340. logMessage(`Sending coordinate: θ=${theta}, ρ=${rho}...`);
  341. const response = await fetch('/send_coordinate', {
  342. method: 'POST',
  343. headers: { 'Content-Type': 'application/json' },
  344. body: JSON.stringify({ theta, rho })
  345. });
  346. const result = await response.json();
  347. if (result.success) {
  348. logMessage(`Coordinate executed successfully: θ=${theta}, ρ=${rho}`, LOG_TYPE.SUCCESS);
  349. } else {
  350. logMessage(`Failed to execute coordinate: ${result.error}`, LOG_TYPE.ERROR);
  351. }
  352. }
  353. async function sendHomeCommand() {
  354. const response = await fetch('/send_home', { method: 'POST' });
  355. const result = await response.json();
  356. if (result.success) {
  357. logMessage('HOME command sent successfully.', LOG_TYPE.SUCCESS);
  358. } else {
  359. logMessage('Failed to send HOME command.', LOG_TYPE.ERROR);
  360. }
  361. }
  362. async function runClearIn() {
  363. await runFile('clear_from_in.thr');
  364. }
  365. async function runClearOut() {
  366. await runFile('clear_from_out.thr');
  367. }
  368. async function runFile(fileName) {
  369. const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
  370. const result = await response.json();
  371. if (result.success) {
  372. logMessage(`Running file: ${fileName}`, LOG_TYPE.SUCCESS);
  373. } else {
  374. logMessage(`Failed to run file: ${fileName}`, LOG_TYPE.ERROR);
  375. }
  376. }
  377. // Serial Connection Status
  378. async function checkSerialStatus() {
  379. const response = await fetch('/serial_status');
  380. const status = await response.json();
  381. const statusElement = document.getElementById('serial_status');
  382. const statusHeaderElement = document.getElementById('serial_status_header');
  383. const serialPortsContainer = document.getElementById('serial_ports_container');
  384. const connectButton = document.querySelector('button[onclick="connectSerial()"]');
  385. const disconnectButton = document.querySelector('button[onclick="disconnectSerial()"]');
  386. const restartButton = document.querySelector('button[onclick="restartSerial()"]');
  387. if (status.connected) {
  388. const port = status.port || 'Unknown'; // Fallback if port is undefined
  389. statusElement.textContent = `Connected to ${port}`;
  390. statusElement.classList.add('connected');
  391. statusElement.classList.remove('not-connected');
  392. logMessage(`Reconnected to serial port: ${port}`);
  393. // Update header status
  394. statusHeaderElement.classList.add('connected');
  395. statusHeaderElement.classList.remove('not-connected');
  396. // Hide Available Ports and show disconnect/restart buttons
  397. serialPortsContainer.style.display = 'none';
  398. connectButton.style.display = 'none';
  399. disconnectButton.style.display = 'inline-block';
  400. restartButton.style.display = 'inline-block';
  401. } else {
  402. statusElement.textContent = 'Not connected';
  403. statusElement.classList.add('not-connected');
  404. statusElement.classList.remove('connected');
  405. logMessage('No active serial connection.');
  406. // Update header status
  407. statusHeaderElement.classList.add('not-connected');
  408. statusHeaderElement.classList.remove('connected');
  409. // Show Available Ports and the connect button
  410. serialPortsContainer.style.display = 'block';
  411. connectButton.style.display = 'inline-block';
  412. disconnectButton.style.display = 'none';
  413. restartButton.style.display = 'none';
  414. // Attempt to auto-load available ports
  415. await loadSerialPorts();
  416. }
  417. }
  418. async function loadSerialPorts() {
  419. const response = await fetch('/list_serial_ports');
  420. const ports = await response.json();
  421. const select = document.getElementById('serial_ports');
  422. select.innerHTML = '';
  423. ports.forEach(port => {
  424. const option = document.createElement('option');
  425. option.value = port;
  426. option.textContent = port;
  427. select.appendChild(option);
  428. });
  429. logMessage('Serial ports loaded.');
  430. }
  431. async function connectSerial() {
  432. const port = document.getElementById('serial_ports').value;
  433. const response = await fetch('/connect_serial', {
  434. method: 'POST',
  435. headers: { 'Content-Type': 'application/json' },
  436. body: JSON.stringify({ port })
  437. });
  438. const result = await response.json();
  439. if (result.success) {
  440. logMessage(`Connected to serial port: ${port}`, LOG_TYPE.SUCCESS);
  441. // Refresh the status
  442. await checkSerialStatus();
  443. } else {
  444. logMessage(`Error connecting to serial port: ${result.error}`, LOG_TYPE.ERROR);
  445. }
  446. }
  447. async function disconnectSerial() {
  448. const response = await fetch('/disconnect_serial', { method: 'POST' });
  449. const result = await response.json();
  450. if (result.success) {
  451. logMessage('Serial port disconnected.', LOG_TYPE.SUCCESS);
  452. // Refresh the status
  453. await checkSerialStatus();
  454. } else {
  455. logMessage(`Error disconnecting: ${result.error}`, LOG_TYPE.ERROR);
  456. }
  457. }
  458. async function restartSerial() {
  459. const port = document.getElementById('serial_ports').value;
  460. const response = await fetch('/restart_serial', {
  461. method: 'POST',
  462. headers: { 'Content-Type': 'application/json' },
  463. body: JSON.stringify({ port })
  464. });
  465. const result = await response.json();
  466. if (result.success) {
  467. document.getElementById('serial_status').textContent = `Restarted connection to ${port}`;
  468. logMessage('Serial connection restarted.', LOG_TYPE.SUCCESS);
  469. // No need to change visibility for restart
  470. } else {
  471. logMessage(`Error restarting serial connection: ${result.error}`, LOG_TYPE.ERROR);
  472. }
  473. }
  474. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  475. // PART A: Loading / listing playlists from the server
  476. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  477. async function loadAllPlaylists() {
  478. try {
  479. const response = await fetch('/list_all_playlists'); // GET
  480. const allPlaylists = await response.json(); // e.g. ["My Playlist", "Summer", ...]
  481. displayAllPlaylists(allPlaylists);
  482. } catch (err) {
  483. logMessage(`Error loading playlists: ${err}`, LOG_TYPE.ERROR);
  484. }
  485. }
  486. // Function to display all playlists with Load, Run, and Delete buttons
  487. function displayAllPlaylists(playlists) {
  488. const ul = document.getElementById('all_playlists');
  489. ul.innerHTML = ''; // Clear current list
  490. playlists.forEach(playlistName => {
  491. const li = document.createElement('li');
  492. li.textContent = playlistName;
  493. li.classList.add('playlist-item'); // Add a class for styling
  494. // Attach click event to handle selection
  495. li.onclick = () => {
  496. // Remove 'selected' class from all items
  497. document.querySelectorAll('#all_playlists li').forEach(item => {
  498. item.classList.remove('selected');
  499. });
  500. // Add 'selected' class to the clicked item
  501. li.classList.add('selected');
  502. // Open the playlist editor for the selected playlist
  503. openPlaylistEditor(playlistName);
  504. };
  505. ul.appendChild(li);
  506. });
  507. }
  508. // Cancel changes and close the editor
  509. function cancelPlaylistChanges() {
  510. playlist = [...originalPlaylist]; // Revert to the original playlist
  511. isPlaylistChanged = false;
  512. toggleSaveCancelButtons(false); // Hide the save and cancel buttons
  513. refreshPlaylistUI(); // Refresh the UI with the original state
  514. closeStickySection('playlist-editor'); // Close the editor
  515. }
  516. // Open the playlist editor
  517. function openPlaylistEditor(playlistName) {
  518. logMessage(`Opening editor for playlist: ${playlistName}`);
  519. const editorSection = document.getElementById('playlist-editor');
  520. // Update the displayed playlist name
  521. document.getElementById('playlist_name_display').textContent = playlistName;
  522. // Store the current playlist name for renaming
  523. document.getElementById('playlist_name_input').value = playlistName;
  524. editorSection.classList.remove('hidden');
  525. editorSection.classList.add('visible');
  526. loadPlaylist(playlistName);
  527. }
  528. // Function to run the selected playlist with specified parameters
  529. async function runPlaylist() {
  530. const playlistName = document.getElementById('playlist_name_display').textContent;
  531. if (!playlistName) {
  532. logMessage("No playlist selected to run.");
  533. return;
  534. }
  535. const pauseTimeInput = document.getElementById('pause_time').value;
  536. const clearPatternSelect = document.getElementById('clear_pattern').value;
  537. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  538. const shuffle = document.getElementById('shuffle_playlist').checked;
  539. const pauseTime = parseFloat(pauseTimeInput);
  540. if (isNaN(pauseTime) || pauseTime < 0) {
  541. logMessage("Invalid pause time. Please enter a non-negative number.", LOG_TYPE.WARNING);
  542. return;
  543. }
  544. logMessage(`Running playlist: ${playlistName} with pause_time=${pauseTime}, clear_pattern=${clearPatternSelect}, run_mode=${runMode}, shuffle=${shuffle}.`);
  545. try {
  546. const response = await fetch('/run_playlist', {
  547. method: 'POST',
  548. headers: { 'Content-Type': 'application/json' },
  549. body: JSON.stringify({
  550. playlist_name: playlistName,
  551. pause_time: pauseTime,
  552. clear_pattern: clearPatternSelect,
  553. run_mode: runMode,
  554. shuffle: shuffle
  555. })
  556. });
  557. const result = await response.json();
  558. if (result.success) {
  559. logMessage(`Playlist "${playlistName}" is now running.`, LOG_TYPE.SUCCESS);
  560. } else {
  561. logMessage(`Failed to run playlist "${playlistName}": ${result.error}`, LOG_TYPE.ERROR);
  562. }
  563. } catch (error) {
  564. logMessage(`Error running playlist "${playlistName}": ${error.message}`, LOG_TYPE.ERROR);
  565. }
  566. }
  567. // Track changes in the playlist
  568. let originalPlaylist = [];
  569. let isPlaylistChanged = false;
  570. // Load playlist and set the original state
  571. async function loadPlaylist(playlistName) {
  572. try {
  573. logMessage(`Loading playlist: ${playlistName}`);
  574. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  575. if (!response.ok) {
  576. throw new Error(`HTTP error! Status: ${response.status}`);
  577. }
  578. const data = await response.json();
  579. if (!data.name) {
  580. throw new Error('Playlist name is missing in the response.');
  581. }
  582. // Populate playlist items and set original state
  583. playlist = data.files || [];
  584. originalPlaylist = [...playlist]; // Clone the playlist as the original
  585. isPlaylistChanged = false; // Reset change tracking
  586. toggleSaveCancelButtons(false); // Hide the save and cancel buttons initially
  587. refreshPlaylistUI();
  588. logMessage(`Loaded playlist: "${playlistName}" with ${playlist.length} file(s).`);
  589. } catch (err) {
  590. logMessage(`Error loading playlist: ${err.message}`, LOG_TYPE.ERROR);
  591. console.error('Error details:', err);
  592. }
  593. }
  594. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  595. // PART B: Creating or Saving (Overwriting) a Playlist
  596. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  597. // Instead of separate create/modify functions, we’ll unify them:
  598. async function savePlaylist() {
  599. const name = document.getElementById('playlist_name_display').textContent
  600. if (!name) {
  601. logMessage("Please enter a playlist name.");
  602. return;
  603. }
  604. if (playlist.length === 0) {
  605. logMessage("No files in this playlist. Add files first.");
  606. return;
  607. }
  608. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  609. try {
  610. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  611. // Let's use /create_playlist to always overwrite or create anew.
  612. const response = await fetch('/create_playlist', {
  613. method: 'POST',
  614. headers: { 'Content-Type': 'application/json' },
  615. body: JSON.stringify({
  616. name: name,
  617. files: playlist
  618. })
  619. });
  620. const result = await response.json();
  621. if (result.success) {
  622. logMessage(`Playlist "${name}" with ${playlist.length} patterns saved`, LOG_TYPE.SUCCESS);
  623. // Reload the entire list of playlists to reflect changes
  624. // Check for changes and refresh the UI
  625. detectPlaylistChanges();
  626. refreshPlaylistUI();
  627. // Restore default action buttons
  628. toggleSaveCancelButtons(false);
  629. } else {
  630. logMessage(`Failed to save playlist: ${result.error}`, LOG_TYPE.ERROR);
  631. }
  632. } catch (err) {
  633. logMessage(`Error saving playlist: ${err}`);
  634. }
  635. }
  636. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  637. // PART C: Renaming and Deleting a playlist
  638. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  639. // Toggle the rename playlist input
  640. function populatePlaylistDropdown() {
  641. return fetch('/list_all_playlists')
  642. .then(response => response.json())
  643. .then(playlists => {
  644. const select = document.getElementById('select-playlist');
  645. select.innerHTML = ''; // Clear existing options
  646. // Retrieve the saved playlist from the cookie
  647. const savedPlaylist = getCookie('selected_playlist');
  648. playlists.forEach(playlist => {
  649. const option = document.createElement('option');
  650. option.value = playlist;
  651. option.textContent = playlist;
  652. // Mark the saved playlist as selected
  653. if (playlist === savedPlaylist) {
  654. option.selected = true;
  655. }
  656. select.appendChild(option);
  657. });
  658. // Attach the onchange event listener after populating the dropdown
  659. select.addEventListener('change', function () {
  660. const selectedPlaylist = this.value;
  661. setCookie('selected_playlist', selectedPlaylist, 7); // Save to cookie
  662. logMessage(`Selected playlist saved: ${selectedPlaylist}`);
  663. });
  664. logMessage('Playlist dropdown populated, event listener attached, and saved playlist restored.');
  665. })
  666. .catch(error => logMessage(`Error fetching playlists: ${error.message}`, LOG_TYPE.ERROR));
  667. }
  668. populatePlaylistDropdown().then(() => {
  669. loadSettingsFromCookies(); // Restore selected playlist after populating the dropdown
  670. });
  671. // Confirm and save the renamed playlist
  672. async function confirmAddPlaylist() {
  673. const playlistNameInput = document.getElementById('new_playlist_name');
  674. const playlistName = playlistNameInput.value.trim();
  675. if (!playlistName) {
  676. logMessage('Playlist name cannot be empty.', LOG_TYPE.ERROR);
  677. return;
  678. }
  679. try {
  680. logMessage(`Adding new playlist: "${playlistName}"...`);
  681. const response = await fetch('/create_playlist', {
  682. method: 'POST',
  683. headers: { 'Content-Type': 'application/json' },
  684. body: JSON.stringify({
  685. name: playlistName,
  686. files: [] // New playlist starts empty
  687. })
  688. });
  689. const result = await response.json();
  690. if (result.success) {
  691. logMessage(`Playlist "${playlistName}" created successfully.`, LOG_TYPE.SUCCESS);
  692. // Clear the input field
  693. playlistNameInput.value = '';
  694. // Refresh the playlist list
  695. loadAllPlaylists();
  696. // Hide the add playlist container
  697. toggleSecondaryButtons('add-playlist-container');
  698. } else {
  699. logMessage(`Failed to create playlist: ${result.error}`, LOG_TYPE.ERROR);
  700. }
  701. } catch (error) {
  702. logMessage(`Error creating playlist: ${error.message}`);
  703. }
  704. }
  705. async function confirmRenamePlaylist() {
  706. const newName = document.getElementById('playlist_name_input').value.trim();
  707. const currentName = document.getElementById('playlist_name_display').textContent;
  708. if (!newName) {
  709. logMessage("New playlist name cannot be empty.", LOG_TYPE.ERROR);
  710. return;
  711. }
  712. if (newName === currentName) {
  713. logMessage("New playlist name is the same as the current name. No changes made.", LOG_TYPE.WARNING);
  714. toggleSecondaryButtons('rename-playlist-container'); // Close the rename container
  715. return;
  716. }
  717. try {
  718. // Step 1: Create/Modify the playlist with the new name
  719. const createResponse = await fetch('/modify_playlist', {
  720. method: 'POST',
  721. headers: { 'Content-Type': 'application/json' },
  722. body: JSON.stringify({
  723. name: newName,
  724. files: playlist // Ensure `playlist` contains the current list of files
  725. })
  726. });
  727. const createResult = await createResponse.json();
  728. if (createResult.success) {
  729. logMessage(createResult.message, LOG_TYPE.SUCCESS);
  730. // Step 2: Delete the old playlist
  731. const deleteResponse = await fetch('/delete_playlist', {
  732. method: 'DELETE',
  733. headers: { 'Content-Type': 'application/json' },
  734. body: JSON.stringify({ name: currentName })
  735. });
  736. const deleteResult = await deleteResponse.json();
  737. if (deleteResult.success) {
  738. logMessage(deleteResult.message);
  739. // Update the UI with the new name
  740. document.getElementById('playlist_name_display').textContent = newName;
  741. // Refresh playlists list
  742. loadAllPlaylists();
  743. // Close the rename container and restore original action buttons
  744. toggleSecondaryButtons('rename-playlist-container');
  745. } else {
  746. logMessage(`Failed to delete old playlist: ${deleteResult.error}`, LOG_TYPE.ERROR);
  747. }
  748. } else {
  749. logMessage(`Failed to rename playlist: ${createResult.error}`, LOG_TYPE.ERROR);
  750. }
  751. } catch (error) {
  752. logMessage(`Error renaming playlist: ${error.message}`);
  753. }
  754. }
  755. // Delete the currently opened playlist
  756. async function deleteCurrentPlaylist() {
  757. const playlistName = document.getElementById('playlist_name_display').textContent;
  758. if (!confirm(`Are you sure you want to delete the playlist "${playlistName}"? This action cannot be undone.`)) {
  759. return;
  760. }
  761. try {
  762. const response = await fetch('/delete_playlist', {
  763. method: 'DELETE',
  764. headers: { 'Content-Type': 'application/json' },
  765. body: JSON.stringify({ name: playlistName })
  766. });
  767. const result = await response.json();
  768. if (result.success) {
  769. logMessage(`Playlist "${playlistName}" deleted.`, LOG_TYPE.INFO);
  770. closeStickySection('playlist-editor');
  771. loadAllPlaylists();
  772. } else {
  773. logMessage(`Failed to delete playlist: ${result.error}`, LOG_TYPE.ERROR);
  774. }
  775. } catch (error) {
  776. logMessage(`Error deleting playlist: ${error.message}`);
  777. }
  778. }
  779. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  780. // PART D: Local playlist array UI
  781. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  782. // Refresh the playlist UI and detect changes
  783. function refreshPlaylistUI() {
  784. const ul = document.getElementById('playlist_items');
  785. if (!ul) {
  786. logMessage('Error: Playlist container not found');
  787. return;
  788. }
  789. ul.innerHTML = ''; // Clear existing items
  790. if (playlist.length === 0) {
  791. // Add a placeholder if the playlist is empty
  792. const emptyLi = document.createElement('li');
  793. emptyLi.textContent = 'No items in the playlist.';
  794. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  795. ul.appendChild(emptyLi);
  796. return;
  797. }
  798. playlist.forEach((file, index) => {
  799. const li = document.createElement('li');
  800. // Add filename in a span
  801. const filenameSpan = document.createElement('span');
  802. filenameSpan.textContent = file;
  803. filenameSpan.classList.add('filename'); // Add a class for styling
  804. li.appendChild(filenameSpan);
  805. // Move Up button
  806. const moveUpBtn = document.createElement('button');
  807. moveUpBtn.textContent = '▲'; // Up arrow symbol
  808. moveUpBtn.classList.add('move-button');
  809. moveUpBtn.onclick = () => {
  810. if (index > 0) {
  811. const temp = playlist[index - 1];
  812. playlist[index - 1] = playlist[index];
  813. playlist[index] = temp;
  814. detectPlaylistChanges(); // Check for changes
  815. refreshPlaylistUI();
  816. }
  817. };
  818. li.appendChild(moveUpBtn);
  819. // Move Down button
  820. const moveDownBtn = document.createElement('button');
  821. moveDownBtn.textContent = '▼'; // Down arrow symbol
  822. moveDownBtn.classList.add('move-button');
  823. moveDownBtn.onclick = () => {
  824. if (index < playlist.length - 1) {
  825. const temp = playlist[index + 1];
  826. playlist[index + 1] = playlist[index];
  827. playlist[index] = temp;
  828. detectPlaylistChanges(); // Check for changes
  829. refreshPlaylistUI();
  830. }
  831. };
  832. li.appendChild(moveDownBtn);
  833. // Remove button
  834. const removeBtn = document.createElement('button');
  835. removeBtn.textContent = '✖';
  836. removeBtn.classList.add('remove-button');
  837. removeBtn.onclick = () => {
  838. playlist.splice(index, 1);
  839. detectPlaylistChanges(); // Check for changes
  840. refreshPlaylistUI();
  841. };
  842. li.appendChild(removeBtn);
  843. ul.appendChild(li);
  844. });
  845. }
  846. // Toggle the visibility of the save and cancel buttons
  847. function toggleSaveCancelButtons(show) {
  848. const actionButtons = document.querySelector('#playlist-editor .action-buttons');
  849. if (actionButtons) {
  850. // Show/hide all buttons except Save and Cancel
  851. actionButtons.querySelectorAll('button:not(.save-cancel)').forEach(button => {
  852. button.style.display = show ? 'none' : 'inline-block';
  853. });
  854. // Show/hide Save and Cancel buttons
  855. actionButtons.querySelectorAll('.save-cancel').forEach(button => {
  856. button.style.display = show ? 'inline-block' : 'none';
  857. });
  858. } else {
  859. logMessage('Error: Action buttons container not found.', LOG_TYPE.ERROR);
  860. }
  861. }
  862. // Detect changes in the playlist
  863. function detectPlaylistChanges() {
  864. isPlaylistChanged = JSON.stringify(originalPlaylist) !== JSON.stringify(playlist);
  865. toggleSaveCancelButtons(isPlaylistChanged);
  866. }
  867. // Toggle the "Add to Playlist" section
  868. function toggleSecondaryButtons(containerId, onShowCallback = null) {
  869. const container = document.getElementById(containerId);
  870. if (!container) {
  871. logMessage(`Error: Element with ID "${containerId}" not found`);
  872. return;
  873. }
  874. // Find the .action-buttons element preceding the container
  875. const previousActionButtons = container.previousElementSibling?.classList.contains('action-buttons')
  876. ? container.previousElementSibling
  877. : null;
  878. if (container.classList.contains('hidden')) {
  879. // Show the container
  880. container.classList.remove('hidden');
  881. // Hide the previous .action-buttons element
  882. if (previousActionButtons) {
  883. previousActionButtons.style.display = 'none';
  884. }
  885. // Optional callback for custom logic when showing the container
  886. if (onShowCallback) {
  887. onShowCallback();
  888. }
  889. } else {
  890. // Hide the container
  891. container.classList.add('hidden');
  892. // Restore the previous .action-buttons element
  893. if (previousActionButtons) {
  894. previousActionButtons.style.display = 'flex';
  895. }
  896. }
  897. }
  898. // Add the selected pattern to the selected playlist
  899. async function saveToPlaylist() {
  900. const playlist = document.getElementById('select-playlist').value;
  901. if (!playlist) {
  902. logMessage('No playlist selected.', LOG_TYPE.ERROR);
  903. return;
  904. }
  905. if (!selectedFile) {
  906. logMessage('No pattern selected to add.', LOG_TYPE.ERROR);
  907. return;
  908. }
  909. try {
  910. logMessage(`Adding pattern "${selectedFile}" to playlist "${playlist}"...`);
  911. const response = await fetch('/add_to_playlist', {
  912. method: 'POST',
  913. headers: { 'Content-Type': 'application/json' },
  914. body: JSON.stringify({ playlist_name: playlist, pattern: selectedFile })
  915. });
  916. const result = await response.json();
  917. if (result.success) {
  918. logMessage(`Pattern "${selectedFile}" successfully added to playlist "${playlist}".`, LOG_TYPE.SUCCESS);
  919. // Reset the UI state via toggleSecondaryButtons
  920. toggleSecondaryButtons('add-to-playlist-container', () => {
  921. const selectPlaylist = document.getElementById('select-playlist');
  922. selectPlaylist.value = ''; // Clear the selection
  923. });
  924. } else {
  925. logMessage(`Failed to add pattern to playlist: ${result.error}`, LOG_TYPE.ERROR);
  926. }
  927. } catch (error) {
  928. logMessage(`Error adding pattern to playlist: ${error.message}`);
  929. }
  930. }
  931. async function changeSpeed() {
  932. const speedInput = document.getElementById('speed_input');
  933. const speed = parseFloat(speedInput.value);
  934. if (isNaN(speed) || speed <= 0) {
  935. logMessage('Invalid speed. Please enter a positive number.');
  936. return;
  937. }
  938. logMessage(`Setting speed to: ${speed}...`);
  939. const response = await fetch('/set_speed', {
  940. method: 'POST',
  941. headers: { 'Content-Type': 'application/json' },
  942. body: JSON.stringify({ speed })
  943. });
  944. const result = await response.json();
  945. if (result.success) {
  946. document.getElementById('speed_status').textContent = `Current Speed: ${speed}`;
  947. logMessage(`Speed set to: ${speed}`, LOG_TYPE.SUCCESS);
  948. } else {
  949. logMessage(`Failed to set speed: ${result.error}`, LOG_TYPE.ERROR);
  950. }
  951. }
  952. // Function to close any sticky section
  953. function closeStickySection(sectionId) {
  954. const section = document.getElementById(sectionId);
  955. if (section) {
  956. section.classList.remove('visible');
  957. section.classList.remove('fullscreen');
  958. section.classList.add('hidden');
  959. // Reset the fullscreen button text if it exists
  960. const fullscreenButton = section.querySelector('.fullscreen-button');
  961. if (fullscreenButton) {
  962. fullscreenButton.textContent = '⛶'; // Reset to enter fullscreen icon/text
  963. }
  964. logMessage(`Closed section: ${sectionId}`);
  965. if(sectionId === 'playlist-editor') {
  966. document.querySelectorAll('#all_playlists .playlist-item').forEach(item => {
  967. item.classList.remove('selected');
  968. });
  969. }
  970. if(sectionId === 'pattern-preview-container') {
  971. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  972. item.classList.remove('selected');
  973. });
  974. }
  975. } else {
  976. logMessage(`Error: Section with ID "${sectionId}" not found`);
  977. }
  978. }
  979. function attachFullScreenListeners() {
  980. // Add event listener to all fullscreen buttons
  981. document.querySelectorAll('.fullscreen-button').forEach(button => {
  982. button.addEventListener('click', function () {
  983. const stickySection = this.closest('.sticky'); // Find the closest sticky section
  984. if (stickySection) {
  985. stickySection.classList.toggle('fullscreen'); // Toggle fullscreen class
  986. // Update button icon or text
  987. if (stickySection.classList.contains('fullscreen')) {
  988. this.textContent = '-'; // Exit fullscreen icon/text
  989. } else {
  990. this.textContent = '⛶'; // Enter fullscreen icon/text
  991. }
  992. } else {
  993. console.error('Error: Fullscreen button is not inside a sticky section.');
  994. }
  995. });
  996. });
  997. }
  998. // Utility function to manage cookies
  999. function setCookie(name, value, days) {
  1000. const date = new Date();
  1001. date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  1002. document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
  1003. }
  1004. function getCookie(name) {
  1005. const nameEQ = `${name}=`;
  1006. const cookies = document.cookie.split(';');
  1007. for (let i = 0; i < cookies.length; i++) {
  1008. let cookie = cookies[i].trim();
  1009. if (cookie.startsWith(nameEQ)) {
  1010. return cookie.substring(nameEQ.length);
  1011. }
  1012. }
  1013. return null;
  1014. }
  1015. // Save settings to cookies
  1016. function saveSettingsToCookies() {
  1017. // Save the pause time
  1018. const pauseTime = document.getElementById('pause_time').value;
  1019. setCookie('pause_time', pauseTime, 7);
  1020. // Save the clear pattern
  1021. const clearPattern = document.getElementById('clear_pattern').value;
  1022. setCookie('clear_pattern', clearPattern, 7);
  1023. // Save the run mode
  1024. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  1025. setCookie('run_mode', runMode, 7);
  1026. // Save shuffle playlist checkbox state
  1027. const shufflePlaylist = document.getElementById('shuffle_playlist').checked;
  1028. setCookie('shuffle_playlist', shufflePlaylist, 7);
  1029. // Save pre-execution action
  1030. const preExecution = document.querySelector('input[name="pre_execution"]:checked').value;
  1031. setCookie('pre_execution', preExecution, 7);
  1032. logMessage('Settings saved.');
  1033. }
  1034. // Load settings from cookies
  1035. function loadSettingsFromCookies() {
  1036. // Load the pause time
  1037. const pauseTime = getCookie('pause_time');
  1038. if (pauseTime !== null) {
  1039. document.getElementById('pause_time').value = pauseTime;
  1040. }
  1041. // Load the clear pattern
  1042. const clearPattern = getCookie('clear_pattern');
  1043. if (clearPattern !== null) {
  1044. document.getElementById('clear_pattern').value = clearPattern;
  1045. }
  1046. // Load the run mode
  1047. const runMode = getCookie('run_mode');
  1048. if (runMode !== null) {
  1049. document.querySelector(`input[name="run_mode"][value="${runMode}"]`).checked = true;
  1050. }
  1051. // Load the shuffle playlist checkbox state
  1052. const shufflePlaylist = getCookie('shuffle_playlist');
  1053. if (shufflePlaylist !== null) {
  1054. document.getElementById('shuffle_playlist').checked = shufflePlaylist === 'true';
  1055. }
  1056. // Load the pre-execution action
  1057. const preExecution = getCookie('pre_execution');
  1058. if (preExecution !== null) {
  1059. document.querySelector(`input[name="pre_execution"][value="${preExecution}"]`).checked = true;
  1060. }
  1061. // Load the selected playlist
  1062. const selectedPlaylist = getCookie('selected_playlist');
  1063. if (selectedPlaylist !== null) {
  1064. const playlistDropdown = document.getElementById('select-playlist');
  1065. if (playlistDropdown && [...playlistDropdown.options].some(option => option.value === selectedPlaylist)) {
  1066. playlistDropdown.value = selectedPlaylist;
  1067. }
  1068. }
  1069. logMessage('Settings loaded from cookies.');
  1070. }
  1071. // Call this function to save settings when a value is changed
  1072. function attachSettingsSaveListeners() {
  1073. // Add event listeners to inputs
  1074. document.getElementById('pause_time').addEventListener('input', saveSettingsToCookies);
  1075. document.getElementById('clear_pattern').addEventListener('change', saveSettingsToCookies);
  1076. document.querySelectorAll('input[name="run_mode"]').forEach(input => {
  1077. input.addEventListener('change', saveSettingsToCookies);
  1078. });
  1079. document.getElementById('shuffle_playlist').addEventListener('change', saveSettingsToCookies);
  1080. document.querySelectorAll('input[name="pre_execution"]').forEach(input => {
  1081. input.addEventListener('change', saveSettingsToCookies);
  1082. });
  1083. }
  1084. // Tab switching logic with cookie storage
  1085. function switchTab(tabName) {
  1086. // Store the active tab in a cookie
  1087. setCookie('activeTab', tabName, 7); // Store for 7 days
  1088. // Deactivate all tab content
  1089. document.querySelectorAll('.tab-content').forEach(tab => {
  1090. tab.classList.remove('active');
  1091. });
  1092. // Activate the selected tab content
  1093. const activeTab = document.getElementById(`${tabName}-tab`);
  1094. if (activeTab) {
  1095. activeTab.classList.add('active');
  1096. } else {
  1097. console.error(`Error: Tab "${tabName}" not found.`);
  1098. }
  1099. // Deactivate all nav buttons
  1100. document.querySelectorAll('.bottom-nav .tab-button').forEach(button => {
  1101. button.classList.remove('active');
  1102. });
  1103. // Activate the selected nav button
  1104. const activeNavButton = document.getElementById(`nav-${tabName}`);
  1105. if (activeNavButton) {
  1106. activeNavButton.classList.add('active');
  1107. } else {
  1108. console.error(`Error: Nav button for "${tabName}" not found.`);
  1109. }
  1110. }
  1111. // Initialization
  1112. document.addEventListener('DOMContentLoaded', () => {
  1113. const activeTab = getCookie('activeTab') || 'patterns'; // Default to 'patterns' tab
  1114. switchTab(activeTab); // Load the active tab
  1115. checkSerialStatus(); // Check serial connection status
  1116. loadThetaRhoFiles(); // Load files on page load
  1117. loadAllPlaylists(); // Load all playlists on page load
  1118. loadSettingsFromCookies(); // Load saved settings
  1119. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1120. attachFullScreenListeners();
  1121. });