main.js 49 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  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 clearSchedule() {
  556. document.getElementById("start_time").value = "";
  557. document.getElementById("end_time").value = "";
  558. }
  559. // Function to run the selected playlist with specified parameters
  560. async function runPlaylist() {
  561. const playlistName = document.getElementById('playlist_name_display').textContent;
  562. if (!playlistName) {
  563. logMessage("No playlist selected to run.");
  564. return;
  565. }
  566. const pauseTimeInput = document.getElementById('pause_time').value;
  567. const clearPatternSelect = document.getElementById('clear_pattern').value;
  568. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  569. const shuffle = document.getElementById('shuffle_playlist').checked;
  570. const startTimeInput = document.getElementById('start_time').value.trim();
  571. const endTimeInput = document.getElementById('end_time').value.trim();
  572. const pauseTime = parseFloat(pauseTimeInput);
  573. if (isNaN(pauseTime) || pauseTime < 0) {
  574. logMessage("Invalid pause time. Please enter a non-negative number.", LOG_TYPE.WARNING);
  575. return;
  576. }
  577. // Validate start and end time format and logic
  578. let startTime = startTimeInput || null;
  579. let endTime = endTimeInput || null;
  580. // Ensure that if one time is filled, the other must be as well
  581. if ((startTime && !endTime) || (!startTime && endTime)) {
  582. logMessage("Both start and end times must be provided together or left blank.", LOG_TYPE.WARNING);
  583. return;
  584. }
  585. // If both are provided, validate format and ensure start_time < end_time
  586. if (startTime && endTime) {
  587. try {
  588. const startDateTime = new Date(`1970-01-01T${startTime}:00`);
  589. const endDateTime = new Date(`1970-01-01T${endTime}:00`);
  590. if (isNaN(startDateTime.getTime()) || isNaN(endDateTime.getTime())) {
  591. logMessage("Invalid time format. Please use HH:MM format (e.g., 09:30).", LOG_TYPE.WARNING);
  592. return;
  593. }
  594. if (startDateTime >= endDateTime) {
  595. logMessage("Start time must be earlier than end time.", LOG_TYPE.WARNING);
  596. return;
  597. }
  598. } catch (error) {
  599. logMessage("Error parsing start or end time. Ensure correct HH:MM format.", LOG_TYPE.ERROR);
  600. return;
  601. }
  602. }
  603. logMessage(`Running playlist: ${playlistName} with pause_time=${pauseTime}, clear_pattern=${clearPatternSelect}, run_mode=${runMode}, shuffle=${shuffle}.`);
  604. try {
  605. const response = await fetch('/run_playlist', {
  606. method: 'POST',
  607. headers: { 'Content-Type': 'application/json' },
  608. body: JSON.stringify({
  609. playlist_name: playlistName,
  610. pause_time: pauseTime,
  611. clear_pattern: clearPatternSelect,
  612. run_mode: runMode,
  613. shuffle: shuffle,
  614. start_time: startTimeInput,
  615. end_time: endTimeInput
  616. })
  617. });
  618. const result = await response.json();
  619. if (result.success) {
  620. logMessage(`Playlist "${playlistName}" is now running.`, LOG_TYPE.SUCCESS);
  621. } else {
  622. logMessage(`Failed to run playlist "${playlistName}": ${result.error}`, LOG_TYPE.ERROR);
  623. }
  624. } catch (error) {
  625. logMessage(`Error running playlist "${playlistName}": ${error.message}`, LOG_TYPE.ERROR);
  626. }
  627. }
  628. // Track changes in the playlist
  629. let originalPlaylist = [];
  630. let isPlaylistChanged = false;
  631. // Load playlist and set the original state
  632. async function loadPlaylist(playlistName) {
  633. try {
  634. logMessage(`Loading playlist: ${playlistName}`);
  635. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  636. if (!response.ok) {
  637. throw new Error(`HTTP error! Status: ${response.status}`);
  638. }
  639. const data = await response.json();
  640. if (!data.name) {
  641. throw new Error('Playlist name is missing in the response.');
  642. }
  643. // Populate playlist items and set original state
  644. playlist = data.files || [];
  645. originalPlaylist = [...playlist]; // Clone the playlist as the original
  646. isPlaylistChanged = false; // Reset change tracking
  647. toggleSaveCancelButtons(false); // Hide the save and cancel buttons initially
  648. refreshPlaylistUI();
  649. logMessage(`Loaded playlist: "${playlistName}" with ${playlist.length} file(s).`);
  650. } catch (err) {
  651. logMessage(`Error loading playlist: ${err.message}`, LOG_TYPE.ERROR);
  652. console.error('Error details:', err);
  653. }
  654. }
  655. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  656. // PART B: Creating or Saving (Overwriting) a Playlist
  657. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  658. // Instead of separate create/modify functions, we’ll unify them:
  659. async function savePlaylist() {
  660. const name = document.getElementById('playlist_name_display').textContent
  661. if (!name) {
  662. logMessage("Please enter a playlist name.");
  663. return;
  664. }
  665. if (playlist.length === 0) {
  666. logMessage("No files in this playlist. Add files first.");
  667. return;
  668. }
  669. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  670. try {
  671. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  672. // Let's use /create_playlist to always overwrite or create anew.
  673. const response = await fetch('/create_playlist', {
  674. method: 'POST',
  675. headers: { 'Content-Type': 'application/json' },
  676. body: JSON.stringify({
  677. name: name,
  678. files: playlist
  679. })
  680. });
  681. const result = await response.json();
  682. if (result.success) {
  683. logMessage(`Playlist "${name}" with ${playlist.length} patterns saved`, LOG_TYPE.SUCCESS);
  684. // Reload the entire list of playlists to reflect changes
  685. // Check for changes and refresh the UI
  686. detectPlaylistChanges();
  687. refreshPlaylistUI();
  688. // Restore default action buttons
  689. toggleSaveCancelButtons(false);
  690. } else {
  691. logMessage(`Failed to save playlist: ${result.error}`, LOG_TYPE.ERROR);
  692. }
  693. } catch (err) {
  694. logMessage(`Error saving playlist: ${err}`);
  695. }
  696. }
  697. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  698. // PART C: Renaming and Deleting a playlist
  699. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  700. // Toggle the rename playlist input
  701. function populatePlaylistDropdown() {
  702. return fetch('/list_all_playlists')
  703. .then(response => response.json())
  704. .then(playlists => {
  705. const select = document.getElementById('select-playlist');
  706. select.innerHTML = ''; // Clear existing options
  707. // Retrieve the saved playlist from the cookie
  708. const savedPlaylist = getCookie('selected_playlist');
  709. playlists.forEach(playlist => {
  710. const option = document.createElement('option');
  711. option.value = playlist;
  712. option.textContent = playlist;
  713. // Mark the saved playlist as selected
  714. if (playlist === savedPlaylist) {
  715. option.selected = true;
  716. }
  717. select.appendChild(option);
  718. });
  719. // Attach the onchange event listener after populating the dropdown
  720. select.addEventListener('change', function () {
  721. const selectedPlaylist = this.value;
  722. setCookie('selected_playlist', selectedPlaylist, 7); // Save to cookie
  723. logMessage(`Selected playlist saved: ${selectedPlaylist}`);
  724. });
  725. logMessage('Playlist dropdown populated, event listener attached, and saved playlist restored.');
  726. })
  727. .catch(error => logMessage(`Error fetching playlists: ${error.message}`, LOG_TYPE.ERROR));
  728. }
  729. populatePlaylistDropdown().then(() => {
  730. loadSettingsFromCookies(); // Restore selected playlist after populating the dropdown
  731. });
  732. // Confirm and save the renamed playlist
  733. async function confirmAddPlaylist() {
  734. const playlistNameInput = document.getElementById('new_playlist_name');
  735. const playlistName = playlistNameInput.value.trim();
  736. if (!playlistName) {
  737. logMessage('Playlist name cannot be empty.', LOG_TYPE.ERROR);
  738. return;
  739. }
  740. try {
  741. logMessage(`Adding new playlist: "${playlistName}"...`);
  742. const response = await fetch('/create_playlist', {
  743. method: 'POST',
  744. headers: { 'Content-Type': 'application/json' },
  745. body: JSON.stringify({
  746. name: playlistName,
  747. files: [] // New playlist starts empty
  748. })
  749. });
  750. const result = await response.json();
  751. if (result.success) {
  752. logMessage(`Playlist "${playlistName}" created successfully.`, LOG_TYPE.SUCCESS);
  753. // Clear the input field
  754. playlistNameInput.value = '';
  755. // Refresh the playlist list
  756. loadAllPlaylists();
  757. // Hide the add playlist container
  758. toggleSecondaryButtons('add-playlist-container');
  759. } else {
  760. logMessage(`Failed to create playlist: ${result.error}`, LOG_TYPE.ERROR);
  761. }
  762. } catch (error) {
  763. logMessage(`Error creating playlist: ${error.message}`);
  764. }
  765. }
  766. async function confirmRenamePlaylist() {
  767. const newName = document.getElementById('playlist_name_input').value.trim();
  768. const currentName = document.getElementById('playlist_name_display').textContent;
  769. if (!newName) {
  770. logMessage("New playlist name cannot be empty.", LOG_TYPE.ERROR);
  771. return;
  772. }
  773. if (newName === currentName) {
  774. logMessage("New playlist name is the same as the current name. No changes made.", LOG_TYPE.WARNING);
  775. toggleSecondaryButtons('rename-playlist-container'); // Close the rename container
  776. return;
  777. }
  778. try {
  779. // Step 1: Create/Modify the playlist with the new name
  780. const createResponse = await fetch('/modify_playlist', {
  781. method: 'POST',
  782. headers: { 'Content-Type': 'application/json' },
  783. body: JSON.stringify({
  784. name: newName,
  785. files: playlist // Ensure `playlist` contains the current list of files
  786. })
  787. });
  788. const createResult = await createResponse.json();
  789. if (createResult.success) {
  790. logMessage(createResult.message, LOG_TYPE.SUCCESS);
  791. // Step 2: Delete the old playlist
  792. const deleteResponse = await fetch('/delete_playlist', {
  793. method: 'DELETE',
  794. headers: { 'Content-Type': 'application/json' },
  795. body: JSON.stringify({ name: currentName })
  796. });
  797. const deleteResult = await deleteResponse.json();
  798. if (deleteResult.success) {
  799. logMessage(deleteResult.message);
  800. // Update the UI with the new name
  801. document.getElementById('playlist_name_display').textContent = newName;
  802. // Refresh playlists list
  803. loadAllPlaylists();
  804. // Close the rename container and restore original action buttons
  805. toggleSecondaryButtons('rename-playlist-container');
  806. } else {
  807. logMessage(`Failed to delete old playlist: ${deleteResult.error}`, LOG_TYPE.ERROR);
  808. }
  809. } else {
  810. logMessage(`Failed to rename playlist: ${createResult.error}`, LOG_TYPE.ERROR);
  811. }
  812. } catch (error) {
  813. logMessage(`Error renaming playlist: ${error.message}`);
  814. }
  815. }
  816. // Delete the currently opened playlist
  817. async function deleteCurrentPlaylist() {
  818. const playlistName = document.getElementById('playlist_name_display').textContent;
  819. if (!confirm(`Are you sure you want to delete the playlist "${playlistName}"? This action cannot be undone.`)) {
  820. return;
  821. }
  822. try {
  823. const response = await fetch('/delete_playlist', {
  824. method: 'DELETE',
  825. headers: { 'Content-Type': 'application/json' },
  826. body: JSON.stringify({ name: playlistName })
  827. });
  828. const result = await response.json();
  829. if (result.success) {
  830. logMessage(`Playlist "${playlistName}" deleted.`, LOG_TYPE.INFO);
  831. closeStickySection('playlist-editor');
  832. loadAllPlaylists();
  833. } else {
  834. logMessage(`Failed to delete playlist: ${result.error}`, LOG_TYPE.ERROR);
  835. }
  836. } catch (error) {
  837. logMessage(`Error deleting playlist: ${error.message}`);
  838. }
  839. }
  840. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  841. // PART D: Local playlist array UI
  842. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  843. // Refresh the playlist UI and detect changes
  844. function refreshPlaylistUI() {
  845. const ul = document.getElementById('playlist_items');
  846. if (!ul) {
  847. logMessage('Error: Playlist container not found');
  848. return;
  849. }
  850. ul.innerHTML = ''; // Clear existing items
  851. if (playlist.length === 0) {
  852. // Add a placeholder if the playlist is empty
  853. const emptyLi = document.createElement('li');
  854. emptyLi.textContent = 'No items in the playlist.';
  855. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  856. ul.appendChild(emptyLi);
  857. return;
  858. }
  859. playlist.forEach((file, index) => {
  860. const li = document.createElement('li');
  861. // Add filename in a span
  862. const filenameSpan = document.createElement('span');
  863. filenameSpan.textContent = file;
  864. filenameSpan.classList.add('filename'); // Add a class for styling
  865. li.appendChild(filenameSpan);
  866. // Move Up button
  867. const moveUpBtn = document.createElement('button');
  868. moveUpBtn.textContent = '▲'; // Up arrow symbol
  869. moveUpBtn.classList.add('move-button');
  870. moveUpBtn.onclick = () => {
  871. if (index > 0) {
  872. const temp = playlist[index - 1];
  873. playlist[index - 1] = playlist[index];
  874. playlist[index] = temp;
  875. detectPlaylistChanges(); // Check for changes
  876. refreshPlaylistUI();
  877. }
  878. };
  879. li.appendChild(moveUpBtn);
  880. // Move Down button
  881. const moveDownBtn = document.createElement('button');
  882. moveDownBtn.textContent = '▼'; // Down arrow symbol
  883. moveDownBtn.classList.add('move-button');
  884. moveDownBtn.onclick = () => {
  885. if (index < playlist.length - 1) {
  886. const temp = playlist[index + 1];
  887. playlist[index + 1] = playlist[index];
  888. playlist[index] = temp;
  889. detectPlaylistChanges(); // Check for changes
  890. refreshPlaylistUI();
  891. }
  892. };
  893. li.appendChild(moveDownBtn);
  894. // Remove button
  895. const removeBtn = document.createElement('button');
  896. removeBtn.textContent = '✖';
  897. removeBtn.classList.add('remove-button');
  898. removeBtn.onclick = () => {
  899. playlist.splice(index, 1);
  900. detectPlaylistChanges(); // Check for changes
  901. refreshPlaylistUI();
  902. };
  903. li.appendChild(removeBtn);
  904. ul.appendChild(li);
  905. });
  906. }
  907. // Toggle the visibility of the save and cancel buttons
  908. function toggleSaveCancelButtons(show) {
  909. const actionButtons = document.querySelector('#playlist-editor .action-buttons');
  910. if (actionButtons) {
  911. // Show/hide all buttons except Save and Cancel
  912. actionButtons.querySelectorAll('button:not(.save-cancel)').forEach(button => {
  913. button.style.display = show ? 'none' : 'inline-block';
  914. });
  915. // Show/hide Save and Cancel buttons
  916. actionButtons.querySelectorAll('.save-cancel').forEach(button => {
  917. button.style.display = show ? 'inline-block' : 'none';
  918. });
  919. } else {
  920. logMessage('Error: Action buttons container not found.', LOG_TYPE.ERROR);
  921. }
  922. }
  923. // Detect changes in the playlist
  924. function detectPlaylistChanges() {
  925. isPlaylistChanged = JSON.stringify(originalPlaylist) !== JSON.stringify(playlist);
  926. toggleSaveCancelButtons(isPlaylistChanged);
  927. }
  928. // Toggle the "Add to Playlist" section
  929. function toggleSecondaryButtons(containerId, onShowCallback = null) {
  930. const container = document.getElementById(containerId);
  931. if (!container) {
  932. logMessage(`Error: Element with ID "${containerId}" not found`);
  933. return;
  934. }
  935. // Find the .action-buttons element preceding the container
  936. const previousActionButtons = container.previousElementSibling?.classList.contains('action-buttons')
  937. ? container.previousElementSibling
  938. : null;
  939. if (container.classList.contains('hidden')) {
  940. // Show the container
  941. container.classList.remove('hidden');
  942. // Hide the previous .action-buttons element
  943. if (previousActionButtons) {
  944. previousActionButtons.style.display = 'none';
  945. }
  946. // Optional callback for custom logic when showing the container
  947. if (onShowCallback) {
  948. onShowCallback();
  949. }
  950. } else {
  951. // Hide the container
  952. container.classList.add('hidden');
  953. // Restore the previous .action-buttons element
  954. if (previousActionButtons) {
  955. previousActionButtons.style.display = 'flex';
  956. }
  957. }
  958. }
  959. // Add the selected pattern to the selected playlist
  960. async function saveToPlaylist() {
  961. const playlist = document.getElementById('select-playlist').value;
  962. if (!playlist) {
  963. logMessage('No playlist selected.', LOG_TYPE.ERROR);
  964. return;
  965. }
  966. if (!selectedFile) {
  967. logMessage('No pattern selected to add.', LOG_TYPE.ERROR);
  968. return;
  969. }
  970. try {
  971. logMessage(`Adding pattern "${selectedFile}" to playlist "${playlist}"...`);
  972. const response = await fetch('/add_to_playlist', {
  973. method: 'POST',
  974. headers: { 'Content-Type': 'application/json' },
  975. body: JSON.stringify({ playlist_name: playlist, pattern: selectedFile })
  976. });
  977. const result = await response.json();
  978. if (result.success) {
  979. logMessage(`Pattern "${selectedFile}" successfully added to playlist "${playlist}".`, LOG_TYPE.SUCCESS);
  980. // Reset the UI state via toggleSecondaryButtons
  981. toggleSecondaryButtons('add-to-playlist-container', () => {
  982. const selectPlaylist = document.getElementById('select-playlist');
  983. selectPlaylist.value = ''; // Clear the selection
  984. });
  985. } else {
  986. logMessage(`Failed to add pattern to playlist: ${result.error}`, LOG_TYPE.ERROR);
  987. }
  988. } catch (error) {
  989. logMessage(`Error adding pattern to playlist: ${error.message}`);
  990. }
  991. }
  992. async function changeSpeed() {
  993. const speedInput = document.getElementById('speed_input');
  994. const speed = parseFloat(speedInput.value);
  995. if (isNaN(speed) || speed <= 0) {
  996. logMessage('Invalid speed. Please enter a positive number.');
  997. return;
  998. }
  999. logMessage(`Setting speed to: ${speed}...`);
  1000. const response = await fetch('/set_speed', {
  1001. method: 'POST',
  1002. headers: { 'Content-Type': 'application/json' },
  1003. body: JSON.stringify({ speed })
  1004. });
  1005. const result = await response.json();
  1006. if (result.success) {
  1007. document.getElementById('speed_status').textContent = `Current Speed: ${speed}`;
  1008. logMessage(`Speed set to: ${speed}`, LOG_TYPE.SUCCESS);
  1009. } else {
  1010. logMessage(`Failed to set speed: ${result.error}`, LOG_TYPE.ERROR);
  1011. }
  1012. }
  1013. // Function to close any sticky section
  1014. function closeStickySection(sectionId) {
  1015. const section = document.getElementById(sectionId);
  1016. if (section) {
  1017. section.classList.remove('visible');
  1018. section.classList.remove('fullscreen');
  1019. section.classList.add('hidden');
  1020. // Reset the fullscreen button text if it exists
  1021. const fullscreenButton = section.querySelector('.fullscreen-button');
  1022. if (fullscreenButton) {
  1023. fullscreenButton.textContent = '⛶'; // Reset to enter fullscreen icon/text
  1024. }
  1025. logMessage(`Closed section: ${sectionId}`);
  1026. if(sectionId === 'playlist-editor') {
  1027. document.querySelectorAll('#all_playlists .playlist-item').forEach(item => {
  1028. item.classList.remove('selected');
  1029. });
  1030. }
  1031. if(sectionId === 'pattern-preview-container') {
  1032. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1033. item.classList.remove('selected');
  1034. });
  1035. }
  1036. } else {
  1037. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1038. }
  1039. }
  1040. function attachFullScreenListeners() {
  1041. // Add event listener to all fullscreen buttons
  1042. document.querySelectorAll('.fullscreen-button').forEach(button => {
  1043. button.addEventListener('click', function () {
  1044. const stickySection = this.closest('.sticky'); // Find the closest sticky section
  1045. if (stickySection) {
  1046. stickySection.classList.toggle('fullscreen'); // Toggle fullscreen class
  1047. // Update button icon or text
  1048. if (stickySection.classList.contains('fullscreen')) {
  1049. this.textContent = '-'; // Exit fullscreen icon/text
  1050. } else {
  1051. this.textContent = '⛶'; // Enter fullscreen icon/text
  1052. }
  1053. } else {
  1054. console.error('Error: Fullscreen button is not inside a sticky section.');
  1055. }
  1056. });
  1057. });
  1058. }
  1059. // Utility function to manage cookies
  1060. function setCookie(name, value, days) {
  1061. const date = new Date();
  1062. date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  1063. document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
  1064. }
  1065. function getCookie(name) {
  1066. const nameEQ = `${name}=`;
  1067. const cookies = document.cookie.split(';');
  1068. for (let i = 0; i < cookies.length; i++) {
  1069. let cookie = cookies[i].trim();
  1070. if (cookie.startsWith(nameEQ)) {
  1071. return cookie.substring(nameEQ.length);
  1072. }
  1073. }
  1074. return null;
  1075. }
  1076. // Save settings to cookies
  1077. function saveSettingsToCookies() {
  1078. // Save the pause time
  1079. const pauseTime = document.getElementById('pause_time').value;
  1080. setCookie('pause_time', pauseTime, 7);
  1081. // Save the clear pattern
  1082. const clearPattern = document.getElementById('clear_pattern').value;
  1083. setCookie('clear_pattern', clearPattern, 7);
  1084. // Save the run mode
  1085. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  1086. setCookie('run_mode', runMode, 7);
  1087. // Save shuffle playlist checkbox state
  1088. const shufflePlaylist = document.getElementById('shuffle_playlist').checked;
  1089. setCookie('shuffle_playlist', shufflePlaylist, 7);
  1090. // Save pre-execution action
  1091. const preExecution = document.querySelector('input[name="pre_execution"]:checked').value;
  1092. setCookie('pre_execution', preExecution, 7);
  1093. logMessage('Settings saved.');
  1094. }
  1095. // Load settings from cookies
  1096. function loadSettingsFromCookies() {
  1097. // Load the pause time
  1098. const pauseTime = getCookie('pause_time');
  1099. if (pauseTime !== null) {
  1100. document.getElementById('pause_time').value = pauseTime;
  1101. }
  1102. // Load the clear pattern
  1103. const clearPattern = getCookie('clear_pattern');
  1104. if (clearPattern !== null) {
  1105. document.getElementById('clear_pattern').value = clearPattern;
  1106. }
  1107. // Load the run mode
  1108. const runMode = getCookie('run_mode');
  1109. if (runMode !== null) {
  1110. document.querySelector(`input[name="run_mode"][value="${runMode}"]`).checked = true;
  1111. }
  1112. // Load the shuffle playlist checkbox state
  1113. const shufflePlaylist = getCookie('shuffle_playlist');
  1114. if (shufflePlaylist !== null) {
  1115. document.getElementById('shuffle_playlist').checked = shufflePlaylist === 'true';
  1116. }
  1117. // Load the pre-execution action
  1118. const preExecution = getCookie('pre_execution');
  1119. if (preExecution !== null) {
  1120. document.querySelector(`input[name="pre_execution"][value="${preExecution}"]`).checked = true;
  1121. }
  1122. // Load the selected playlist
  1123. const selectedPlaylist = getCookie('selected_playlist');
  1124. if (selectedPlaylist !== null) {
  1125. const playlistDropdown = document.getElementById('select-playlist');
  1126. if (playlistDropdown && [...playlistDropdown.options].some(option => option.value === selectedPlaylist)) {
  1127. playlistDropdown.value = selectedPlaylist;
  1128. }
  1129. }
  1130. logMessage('Settings loaded from cookies.');
  1131. }
  1132. // Call this function to save settings when a value is changed
  1133. function attachSettingsSaveListeners() {
  1134. // Add event listeners to inputs
  1135. document.getElementById('pause_time').addEventListener('input', saveSettingsToCookies);
  1136. document.getElementById('clear_pattern').addEventListener('change', saveSettingsToCookies);
  1137. document.querySelectorAll('input[name="run_mode"]').forEach(input => {
  1138. input.addEventListener('change', saveSettingsToCookies);
  1139. });
  1140. document.getElementById('shuffle_playlist').addEventListener('change', saveSettingsToCookies);
  1141. document.querySelectorAll('input[name="pre_execution"]').forEach(input => {
  1142. input.addEventListener('change', saveSettingsToCookies);
  1143. });
  1144. }
  1145. // Tab switching logic with cookie storage
  1146. function switchTab(tabName) {
  1147. // Store the active tab in a cookie
  1148. setCookie('activeTab', tabName, 7); // Store for 7 days
  1149. // Deactivate all tab content
  1150. document.querySelectorAll('.tab-content').forEach(tab => {
  1151. tab.classList.remove('active');
  1152. });
  1153. // Activate the selected tab content
  1154. const activeTab = document.getElementById(`${tabName}-tab`);
  1155. if (activeTab) {
  1156. activeTab.classList.add('active');
  1157. } else {
  1158. console.error(`Error: Tab "${tabName}" not found.`);
  1159. }
  1160. // Deactivate all nav buttons
  1161. document.querySelectorAll('.bottom-nav .tab-button').forEach(button => {
  1162. button.classList.remove('active');
  1163. });
  1164. // Activate the selected nav button
  1165. const activeNavButton = document.getElementById(`nav-${tabName}`);
  1166. if (activeNavButton) {
  1167. activeNavButton.classList.add('active');
  1168. } else {
  1169. console.error(`Error: Nav button for "${tabName}" not found.`);
  1170. }
  1171. }
  1172. // Initialization
  1173. document.addEventListener('DOMContentLoaded', () => {
  1174. const activeTab = getCookie('activeTab') || 'patterns'; // Default to 'patterns' tab
  1175. switchTab(activeTab); // Load the active tab
  1176. checkSerialStatus(); // Check serial connection status
  1177. loadThetaRhoFiles(); // Load files on page load
  1178. loadAllPlaylists(); // Load all playlists on page load
  1179. loadSettingsFromCookies(); // Load saved settings
  1180. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1181. attachFullScreenListeners();
  1182. });