main.js 47 KB

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