main.js 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  1. // Global variables
  2. let selectedFile = null;
  3. let playlist = [];
  4. let selectedPlaylistIndex = null;
  5. let allFiles = [];
  6. // Define constants for log message types
  7. const LOG_TYPE = {
  8. SUCCESS: 'success',
  9. WARNING: 'warning',
  10. ERROR: 'error',
  11. INFO: 'info',
  12. DEBUG: 'debug'
  13. };
  14. // Enhanced logMessage with notification system
  15. function logMessage(message, type = LOG_TYPE.DEBUG, clickTargetId = null) {
  16. const log = document.getElementById('status_log');
  17. const header = document.querySelector('header');
  18. if (!header) {
  19. console.error('Error: <header> element not found');
  20. return;
  21. }
  22. // Debug messages only go to the status log
  23. if (type === LOG_TYPE.DEBUG) {
  24. if (!log) {
  25. console.error('Error: #status_log element not found');
  26. return;
  27. }
  28. const entry = document.createElement('p');
  29. entry.textContent = message;
  30. log.appendChild(entry);
  31. log.scrollTop = log.scrollHeight; // Scroll to the bottom of the log
  32. return;
  33. }
  34. // Clear any existing notifications
  35. const existingNotification = header.querySelector('.notification');
  36. if (existingNotification) {
  37. existingNotification.remove();
  38. }
  39. // Create a notification for other message types
  40. const notification = document.createElement('div');
  41. notification.className = `notification ${type}`;
  42. notification.textContent = message;
  43. // Add a close button
  44. const closeButton = document.createElement('button');
  45. closeButton.innerHTML = '<i class="fa-solid fa-xmark"></i>';
  46. closeButton.className = 'close-button no-bg';
  47. closeButton.onclick = (e) => {
  48. e.stopPropagation(); // Prevent triggering the clickTarget when the close button is clicked
  49. notification.classList.remove('show');
  50. setTimeout(() => notification.remove(), 250); // Match transition duration
  51. };
  52. notification.appendChild(closeButton);
  53. // Attach click event to the notification if a clickTargetId is provided
  54. if (clickTargetId) {
  55. notification.onclick = () => {
  56. const target = document.getElementById(clickTargetId);
  57. if (target) {
  58. // Find the closest <main> parent
  59. const parentMain = target.closest('main');
  60. if (parentMain) {
  61. // Remove 'active' class from all <main> elements
  62. document.querySelectorAll('main').forEach((main) => {
  63. main.classList.remove('active');
  64. });
  65. // Add 'active' class to the parent <main>
  66. parentMain.classList.add('active');
  67. target.click();
  68. // Update tab buttons based on the parent <main> ID
  69. const parentId = parentMain.id; // e.g., "patterns-tab"
  70. const tabId = `nav-${parentId.replace('-tab', '')}`; // e.g., "nav-patterns"
  71. document.querySelectorAll('.tab-button').forEach((button) => {
  72. button.classList.remove('active');
  73. });
  74. const tabButton = document.getElementById(tabId);
  75. if (tabButton) {
  76. tabButton.classList.add('active');
  77. }
  78. }
  79. }
  80. };
  81. }
  82. // Append the notification to the header
  83. header.appendChild(notification);
  84. // Trigger the transition
  85. requestAnimationFrame(() => {
  86. notification.classList.add('show');
  87. });
  88. // Auto-remove the notification after 5 seconds
  89. setTimeout(() => {
  90. if (notification.parentNode) {
  91. notification.classList.remove('show');
  92. setTimeout(() => notification.remove(), 250); // Match transition duration
  93. }
  94. }, 5000);
  95. // Also log the message to the status log if available
  96. if (log) {
  97. const entry = document.createElement('p');
  98. entry.textContent = message;
  99. log.appendChild(entry);
  100. log.scrollTop = log.scrollHeight; // Scroll to the bottom of the log
  101. }
  102. }
  103. function toggleDebugLog() {
  104. const statusLog = document.getElementById('status_log');
  105. const debugButton = document.getElementById('debug_button');
  106. if (statusLog.style.display === 'block') {
  107. statusLog.style.display = 'none';
  108. debugButton.classList.remove('active');
  109. } else {
  110. statusLog.style.display = 'block';
  111. debugButton.classList.add( 'active');
  112. statusLog.scrollIntoView({ behavior: 'smooth', block: 'start' }); // Smooth scrolling to the log
  113. }
  114. }
  115. // File selection logic
  116. async function selectFile(file, listItem) {
  117. selectedFile = file;
  118. // Highlight the selected file
  119. document.querySelectorAll('#theta_rho_files li').forEach(li => li.classList.remove('selected'));
  120. listItem.classList.add('selected');
  121. // Update the Remove button visibility
  122. const removeButton = document.querySelector('#pattern-preview-container .remove-button');
  123. if (file.startsWith('custom_patterns/')) {
  124. removeButton.classList.remove('hidden');
  125. } else {
  126. removeButton.classList.add('hidden');
  127. }
  128. logMessage(`Selected file: ${file}`);
  129. await previewPattern(file);
  130. // Populate the playlist dropdown after selecting a pattern
  131. await populatePlaylistDropdown();
  132. }
  133. // Fetch and display Theta-Rho files
  134. async function loadThetaRhoFiles() {
  135. try {
  136. logMessage('Loading Theta-Rho files...');
  137. const response = await fetch('/list_theta_rho_files');
  138. let files = await response.json();
  139. files = files.filter(file => file.endsWith('.thr'));
  140. // Sort files with custom_patterns on top and all alphabetically sorted
  141. const sortedFiles = files.sort((a, b) => {
  142. const isCustomA = a.startsWith('custom_patterns/');
  143. const isCustomB = b.startsWith('custom_patterns/');
  144. if (isCustomA && !isCustomB) return -1; // a comes first
  145. if (!isCustomA && isCustomB) return 1; // b comes first
  146. return a.localeCompare(b); // Alphabetical comparison
  147. });
  148. allFiles = sortedFiles; // Update global files
  149. displayFiles(sortedFiles); // Display sorted files
  150. logMessage('Theta-Rho files loaded and sorted successfully.');
  151. } catch (error) {
  152. logMessage(`Error loading Theta-Rho files: ${error.message}`, 'error');
  153. }
  154. }
  155. // Display files in the UI
  156. function displayFiles(files) {
  157. const ul = document.getElementById('theta_rho_files');
  158. if (!ul) {
  159. logMessage('Error: File list container not found');
  160. return;
  161. }
  162. ul.innerHTML = ''; // Clear existing list
  163. files.forEach(file => {
  164. const li = document.createElement('li');
  165. li.textContent = file;
  166. li.classList.add('file-item');
  167. // Attach file selection handler
  168. li.onclick = () => selectFile(file, li);
  169. ul.appendChild(li);
  170. });
  171. }
  172. // Filter files by search input
  173. function searchPatternFiles() {
  174. const searchInput = document.getElementById('search_pattern').value.toLowerCase();
  175. const filteredFiles = allFiles.filter(file => file.toLowerCase().includes(searchInput));
  176. displayFiles(filteredFiles);
  177. }
  178. // Upload a new Theta-Rho file
  179. async function uploadThetaRho() {
  180. const fileInput = document.getElementById('upload_file');
  181. const file = fileInput.files[0];
  182. if (!file) {
  183. logMessage('No file selected for upload.', LOG_TYPE.ERROR);
  184. return;
  185. }
  186. try {
  187. logMessage(`Uploading file: ${file.name}...`);
  188. const formData = new FormData();
  189. formData.append('file', file);
  190. const response = await fetch('/upload_theta_rho', {
  191. method: 'POST',
  192. body: formData
  193. });
  194. const result = await response.json();
  195. if (result.success) {
  196. logMessage(`File uploaded successfully: ${file.name}`, LOG_TYPE.SUCCESS);
  197. fileInput.value = '';
  198. await loadThetaRhoFiles();
  199. } else {
  200. logMessage(`Failed to upload file: ${file.name}`, LOG_TYPE.ERROR);
  201. }
  202. } catch (error) {
  203. logMessage(`Error uploading file: ${error.message}`);
  204. }
  205. }
  206. async function runThetaRho() {
  207. if (!selectedFile) {
  208. logMessage("No file selected to run.");
  209. return;
  210. }
  211. // Get the selected pre-execution action
  212. const preExecutionAction = document.getElementById('pre_execution').value;
  213. logMessage(`Running file: ${selectedFile} with pre-execution action: ${preExecutionAction}...`);
  214. const response = await fetch('/run_theta_rho', {
  215. method: 'POST',
  216. headers: { 'Content-Type': 'application/json' },
  217. body: JSON.stringify({ file_name: selectedFile, pre_execution: preExecutionAction })
  218. });
  219. const result = await response.json();
  220. if (result.success) {
  221. logMessage(`Pattern running: ${selectedFile}`, LOG_TYPE.SUCCESS);
  222. updateCurrentlyPlaying();
  223. } else {
  224. logMessage(`Failed to run file: ${selectedFile}`,LOG_TYPE.ERROR);
  225. }
  226. }
  227. async function stopExecution() {
  228. logMessage('Stopping execution...');
  229. const response = await fetch('/stop_execution', { method: 'POST' });
  230. const result = await response.json();
  231. if (result.success) {
  232. logMessage('Execution stopped.',LOG_TYPE.SUCCESS);
  233. } else {
  234. logMessage('Failed to stop execution.',LOG_TYPE.ERROR);
  235. }
  236. }
  237. let isPaused = false;
  238. function togglePausePlay() {
  239. const button = document.getElementById("pausePlayCurrent");
  240. if (isPaused) {
  241. // Resume execution
  242. fetch('/resume_execution', { method: 'POST' })
  243. .then(response => response.json())
  244. .then(data => {
  245. if (data.success) {
  246. isPaused = false;
  247. button.innerHTML = "<i class=\"fa-solid fa-pause\"></i>"; // Change to pause icon
  248. }
  249. })
  250. .catch(error => console.error("Error resuming execution:", error));
  251. } else {
  252. // Pause execution
  253. fetch('/pause_execution', { method: 'POST' })
  254. .then(response => response.json())
  255. .then(data => {
  256. if (data.success) {
  257. isPaused = true;
  258. button.innerHTML = "<i class=\"fa-solid fa-play\"></i>"; // Change to play icon
  259. }
  260. })
  261. .catch(error => console.error("Error pausing execution:", error));
  262. }
  263. }
  264. function removeCurrentPattern() {
  265. if (!selectedFile) {
  266. logMessage('No file selected to remove.', LOG_TYPE.ERROR);
  267. return;
  268. }
  269. if (!selectedFile.startsWith('custom_patterns/')) {
  270. logMessage('Only custom patterns can be removed.', LOG_TYPE.WARNING);
  271. return;
  272. }
  273. removeCustomPattern(selectedFile);
  274. }
  275. // Delete the selected file
  276. async function removeCustomPattern(fileName) {
  277. const userConfirmed = confirm(`Are you sure you want to delete the pattern "${fileName}"?`);
  278. if (!userConfirmed) return;
  279. try {
  280. logMessage(`Deleting pattern: ${fileName}...`);
  281. const response = await fetch('/delete_theta_rho_file', {
  282. method: 'POST',
  283. headers: { 'Content-Type': 'application/json' },
  284. body: JSON.stringify({ file_name: fileName })
  285. });
  286. const result = await response.json();
  287. if (result.success) {
  288. logMessage(`File deleted successfully: ${selectedFile}`, LOG_TYPE.SUCCESS);
  289. // Close the preview container
  290. const previewContainer = document.getElementById('pattern-preview-container');
  291. if (previewContainer) {
  292. previewContainer.classList.add('hidden');
  293. previewContainer.classList.remove('visible');
  294. }
  295. // Clear the selected file and refresh the file list
  296. selectedFile = null;
  297. await loadThetaRhoFiles(); // Refresh the file list
  298. } else {
  299. logMessage(`Failed to delete pattern "${fileName}": ${result.error}`, LOG_TYPE.ERROR);
  300. }
  301. } catch (error) {
  302. logMessage(`Error deleting pattern: ${error.message}`);
  303. }
  304. }
  305. // Preview a Theta-Rho file
  306. async function previewPattern(fileName, containerId = 'pattern-preview-container') {
  307. try {
  308. logMessage(`Fetching data to preview file: ${fileName}...`);
  309. const response = await fetch('/preview_thr', {
  310. method: 'POST',
  311. headers: { 'Content-Type': 'application/json' },
  312. body: JSON.stringify({ file_name: fileName })
  313. });
  314. const result = await response.json();
  315. if (result.success) {
  316. const coordinates = result.coordinates;
  317. // Render the pattern in the specified container
  318. const canvasId = containerId === 'currently-playing-container'
  319. ? 'currentlyPlayingCanvas'
  320. : 'patternPreviewCanvas';
  321. renderPattern(coordinates, canvasId);
  322. // Update coordinate display
  323. const firstCoordElement = document.getElementById('first_coordinate');
  324. const lastCoordElement = document.getElementById('last_coordinate');
  325. if (firstCoordElement) {
  326. const firstCoord = coordinates[0];
  327. firstCoordElement.textContent = `First Coordinate: θ=${firstCoord[0]}, ρ=${firstCoord[1]}`;
  328. } else {
  329. logMessage('First coordinate element not found.', LOG_TYPE.WARNING);
  330. }
  331. if (lastCoordElement) {
  332. const lastCoord = coordinates[coordinates.length - 1];
  333. lastCoordElement.textContent = `Last Coordinate: θ=${lastCoord[0]}, ρ=${lastCoord[1]}`;
  334. } else {
  335. logMessage('Last coordinate element not found.', LOG_TYPE.WARNING);
  336. }
  337. // Show the preview container
  338. const previewContainer = document.getElementById(containerId);
  339. if (previewContainer) {
  340. previewContainer.classList.remove('hidden');
  341. previewContainer.classList.add('visible');
  342. } else {
  343. logMessage(`Preview container not found: ${containerId}`, LOG_TYPE.ERROR);
  344. }
  345. } else {
  346. logMessage(`Failed to fetch preview for file: ${fileName}`, LOG_TYPE.WARNING);
  347. }
  348. } catch (error) {
  349. logMessage(`Error previewing pattern: ${error.message}`, LOG_TYPE.ERROR);
  350. }
  351. }
  352. // Render the pattern on a canvas
  353. function renderPattern(coordinates, canvasId) {
  354. const canvas = document.getElementById(canvasId);
  355. if (!canvas) {
  356. logMessage(`Canvas element not found: ${canvasId}`, LOG_TYPE.ERROR);
  357. return;
  358. }
  359. if (!(canvas instanceof HTMLCanvasElement)) {
  360. logMessage(`Element with ID "${canvasId}" is not a canvas.`, LOG_TYPE.ERROR);
  361. return;
  362. }
  363. const ctx = canvas.getContext('2d');
  364. if (!ctx) {
  365. logMessage(`Could not get 2D context for canvas: ${canvasId}`, LOG_TYPE.ERROR);
  366. return;
  367. }
  368. // Account for device pixel ratio
  369. const dpr = window.devicePixelRatio || 1;
  370. const rect = canvas.getBoundingClientRect();
  371. canvas.width = rect.width * dpr; // Scale canvas width for high DPI
  372. canvas.height = rect.height * dpr; // Scale canvas height for high DPI
  373. ctx.scale(dpr, dpr); // Scale drawing context
  374. ctx.clearRect(0, 0, canvas.width, canvas.height);
  375. const centerX = rect.width / 2; // Use bounding client rect dimensions
  376. const centerY = rect.height / 2;
  377. const maxRho = Math.max(...coordinates.map(coord => coord[1]));
  378. const scale = Math.min(rect.width, rect.height) / (2 * maxRho); // Scale to fit
  379. ctx.beginPath();
  380. ctx.strokeStyle = 'white';
  381. coordinates.forEach(([theta, rho], index) => {
  382. const x = centerX + rho * Math.cos(theta) * scale;
  383. const y = centerY - rho * Math.sin(theta) * scale;
  384. if (index === 0) ctx.moveTo(x, y);
  385. else ctx.lineTo(x, y);
  386. });
  387. ctx.stroke();
  388. }
  389. async function moveToCenter() {
  390. logMessage('Moving to center...', LOG_TYPE.INFO);
  391. const response = await fetch('/move_to_center', { method: 'POST' });
  392. const result = await response.json();
  393. if (result.success) {
  394. logMessage('Moved to center successfully.', LOG_TYPE.SUCCESS);
  395. } else {
  396. logMessage(`Failed to move to center: ${result.error}`, LOG_TYPE.ERROR);
  397. }
  398. }
  399. async function moveToPerimeter() {
  400. logMessage('Moving to perimeter...', LOG_TYPE.INFO);
  401. const response = await fetch('/move_to_perimeter', { method: 'POST' });
  402. const result = await response.json();
  403. if (result.success) {
  404. logMessage('Moved to perimeter successfully.', LOG_TYPE.SUCCESS);
  405. } else {
  406. logMessage(`Failed to move to perimeter: ${result.error}`, LOG_TYPE.ERROR);
  407. }
  408. }
  409. async function sendCoordinate() {
  410. const theta = parseFloat(document.getElementById('theta_input').value);
  411. const rho = parseFloat(document.getElementById('rho_input').value);
  412. if (isNaN(theta) || isNaN(rho)) {
  413. logMessage('Invalid input: θ and ρ must be numbers.', LOG_TYPE.ERROR);
  414. return;
  415. }
  416. logMessage(`Sending coordinate: θ=${theta}, ρ=${rho}...`);
  417. const response = await fetch('/send_coordinate', {
  418. method: 'POST',
  419. headers: { 'Content-Type': 'application/json' },
  420. body: JSON.stringify({ theta, rho })
  421. });
  422. const result = await response.json();
  423. if (result.success) {
  424. logMessage(`Coordinate executed successfully: θ=${theta}, ρ=${rho}`, LOG_TYPE.SUCCESS);
  425. } else {
  426. logMessage(`Failed to execute coordinate: ${result.error}`, LOG_TYPE.ERROR);
  427. }
  428. }
  429. async function sendHomeCommand() {
  430. const response = await fetch('/send_home', { method: 'POST' });
  431. const result = await response.json();
  432. if (result.success) {
  433. logMessage('HOME command sent successfully.', LOG_TYPE.SUCCESS);
  434. } else {
  435. logMessage('Failed to send HOME command.', LOG_TYPE.ERROR);
  436. }
  437. }
  438. async function runClearIn() {
  439. await runFile('clear_from_in.thr');
  440. }
  441. async function runClearOut() {
  442. await runFile('clear_from_out.thr');
  443. }
  444. async function runClearSide() {
  445. await runFile('clear_sideway.thr');
  446. }
  447. let scrollPosition = 0;
  448. function scrollSelection(direction) {
  449. const container = document.getElementById('clear_selection');
  450. const itemHeight = 50; // Adjust based on CSS height
  451. const maxScroll = container.children.length - 1;
  452. // Update scroll position
  453. scrollPosition += direction;
  454. scrollPosition = Math.max(0, Math.min(scrollPosition, maxScroll));
  455. // Update the transform to scroll items
  456. container.style.transform = `translateY(-${scrollPosition * itemHeight}px)`;
  457. setCookie('clear_action_index', scrollPosition, 365);
  458. }
  459. function executeClearAction(actionFunction) {
  460. // Save the new action to a cookie (optional)
  461. setCookie('clear_action', actionFunction, 365);
  462. if (actionFunction && typeof window[actionFunction] === 'function') {
  463. window[actionFunction](); // Execute the selected clear action
  464. } else {
  465. logMessage('No clear action selected or function not found.', LOG_TYPE.ERROR);
  466. }
  467. }
  468. async function runFile(fileName) {
  469. const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
  470. const result = await response.json();
  471. if (result.success) {
  472. logMessage(`Running file: ${fileName}`, LOG_TYPE.SUCCESS);
  473. } else {
  474. logMessage(`Failed to run file: ${fileName}`, LOG_TYPE.ERROR);
  475. }
  476. }
  477. // Connection Status
  478. async function checkSerialStatus() {
  479. const response = await fetch('/serial_status');
  480. const status = await response.json();
  481. const statusElement = document.getElementById('serial_status');
  482. const statusHeaderElement = document.getElementById('serial_status_header');
  483. const serialPortsContainer = document.getElementById('serial_ports_container');
  484. const selectElement = document.getElementById('serial_ports');
  485. const connectButton = document.querySelector('button[onclick="connectSerial()"]');
  486. const disconnectButton = document.querySelector('button[onclick="disconnectSerial()"]');
  487. const restartButton = document.querySelector('button[onclick="restartSerial()"]');
  488. if (status.connected) {
  489. const port = status.port || 'Unknown'; // Fallback if port is undefined
  490. statusElement.textContent = `Connected to ${port}`;
  491. statusElement.classList.add('connected');
  492. statusElement.classList.remove('not-connected');
  493. logMessage(`Connected to serial port: ${port}`);
  494. // Update header status
  495. statusHeaderElement.classList.add('connected');
  496. statusHeaderElement.classList.remove('not-connected');
  497. // Hide Available Ports and show disconnect/restart buttons
  498. serialPortsContainer.style.display = 'none';
  499. connectButton.style.display = 'none';
  500. disconnectButton.style.display = 'flex';
  501. restartButton.style.display = 'flex';
  502. // Preselect the connected port in the dropdown
  503. const newOption = document.createElement('option');
  504. newOption.value = port;
  505. newOption.textContent = port;
  506. selectElement.appendChild(newOption);
  507. selectElement.value = port;
  508. } else {
  509. statusElement.textContent = 'Not connected';
  510. statusElement.classList.add('not-connected');
  511. statusElement.classList.remove('connected');
  512. logMessage('No active connection.');
  513. // Update header status
  514. statusHeaderElement.classList.add('not-connected');
  515. statusHeaderElement.classList.remove('connected');
  516. // Show Available Ports and the connect button
  517. serialPortsContainer.style.display = 'block';
  518. connectButton.style.display = 'flex';
  519. disconnectButton.style.display = 'none';
  520. restartButton.style.display = 'none';
  521. // Attempt to auto-load available ports
  522. await loadSerialPorts();
  523. }
  524. }
  525. async function loadSerialPorts() {
  526. const response = await fetch('/list_serial_ports');
  527. const ports = await response.json();
  528. const select = document.getElementById('serial_ports');
  529. select.innerHTML = '';
  530. ports.forEach(port => {
  531. const option = document.createElement('option');
  532. option.value = port;
  533. option.textContent = port;
  534. select.appendChild(option);
  535. });
  536. logMessage('Serial ports loaded.');
  537. }
  538. async function connectSerial() {
  539. const port = document.getElementById('serial_ports').value;
  540. const response = await fetch('/connect', {
  541. method: 'POST',
  542. headers: { 'Content-Type': 'application/json' },
  543. body: JSON.stringify({ port })
  544. });
  545. const result = await response.json();
  546. if (result.success) {
  547. logMessage(`Connected to serial port: ${port}`, LOG_TYPE.SUCCESS);
  548. // Refresh the status
  549. await checkSerialStatus();
  550. } else {
  551. logMessage(`Error connecting to serial port: ${result.error}`, LOG_TYPE.ERROR);
  552. }
  553. }
  554. async function disconnectSerial() {
  555. const response = await fetch('/disconnect', { method: 'POST' });
  556. const result = await response.json();
  557. if (result.success) {
  558. logMessage('Serial port disconnected.', LOG_TYPE.SUCCESS);
  559. // Refresh the status
  560. await checkSerialStatus();
  561. } else {
  562. logMessage(`Error disconnecting: ${result.error}`, LOG_TYPE.ERROR);
  563. }
  564. }
  565. async function restartSerial() {
  566. const port = document.getElementById('serial_ports').value;
  567. const response = await fetch('/restart_connection', {
  568. method: 'POST',
  569. headers: { 'Content-Type': 'application/json' },
  570. body: JSON.stringify({ port })
  571. });
  572. const result = await response.json();
  573. if (result.success) {
  574. document.getElementById('serial_status').textContent = `Restarted connection to ${port}`;
  575. logMessage('Connection restarted.', LOG_TYPE.SUCCESS);
  576. // No need to change visibility for restart
  577. } else {
  578. logMessage(`Error restarting Connection: ${result.error}`, LOG_TYPE.ERROR);
  579. }
  580. }
  581. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  582. // Firmware / Software Updater
  583. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  584. async function checkForUpdates() {
  585. try {
  586. const response = await fetch('/check_software_update');
  587. const data = await response.json();
  588. // Handle updates available logic
  589. if (data.updates_available) {
  590. const updateButton = document.getElementById('update-software-btn');
  591. const updateLinkElement = document.getElementById('update_link');
  592. const tagLink = `https://github.com/tuanchris/dune-weaver/releases/tag/${data.latest_remote_tag}`;
  593. updateButton.classList.remove('hidden'); // Show the button
  594. logMessage("Software Update Available", LOG_TYPE.INFO, 'open-settings-button')
  595. updateLinkElement.innerHTML = `<a href="${tagLink}" target="_blank">View Release Notes </a>`;
  596. updateLinkElement.classList.remove('hidden'); // Show the link
  597. }
  598. // Update current and latest version in the UI
  599. const currentVersionElem = document.getElementById('current_git_version');
  600. const latestVersionElem = document.getElementById('latest_git_version');
  601. currentVersionElem.textContent = `Current Version: ${data.latest_local_tag || 'Unknown'}`;
  602. latestVersionElem.textContent = data.updates_available
  603. ? `Latest Version: ${data.latest_remote_tag}`
  604. : 'You are up to date!';
  605. } catch (error) {
  606. console.error('Error checking for updates:', error);
  607. }
  608. }
  609. async function updateSoftware() {
  610. const updateButton = document.getElementById('update-software-btn');
  611. try {
  612. // Disable the button and update the text
  613. updateButton.disabled = true;
  614. updateButton.querySelector('span').textContent = 'Updating...';
  615. const response = await fetch('/update_software', { method: 'POST' });
  616. const data = await response.json();
  617. if (data.success) {
  618. logMessage('Software updated successfully!', LOG_TYPE.SUCCESS);
  619. window.location.reload(); // Reload the page after update
  620. } else {
  621. logMessage('Failed to update software: ' + data.error, LOG_TYPE.ERROR);
  622. }
  623. } catch (error) {
  624. console.error('Error updating software:', error);
  625. logMessage('Failed to update software', LOG_TYPE.ERROR);
  626. } finally {
  627. // Re-enable the button and reset the text
  628. updateButton.disabled = false;
  629. updateButton.textContent = 'Update Software'; // Adjust to the original text
  630. }
  631. }
  632. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  633. // PART A: Loading / listing playlists from the server
  634. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  635. async function loadAllPlaylists() {
  636. try {
  637. const response = await fetch('/list_all_playlists'); // GET
  638. const allPlaylists = await response.json(); // e.g. ["My Playlist", "Summer", ...]
  639. displayAllPlaylists(allPlaylists);
  640. } catch (err) {
  641. logMessage(`Error loading playlists: ${err}`, LOG_TYPE.ERROR);
  642. }
  643. }
  644. // Function to display all playlists with Load, Run, and Delete buttons
  645. function displayAllPlaylists(playlists) {
  646. const ul = document.getElementById('all_playlists');
  647. ul.innerHTML = ''; // Clear current list
  648. if (playlists.length === 0) {
  649. // Add a placeholder if the list is empty
  650. const emptyLi = document.createElement('li');
  651. emptyLi.textContent = "You don't have any playlists yet.";
  652. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  653. ul.appendChild(emptyLi);
  654. return;
  655. }
  656. playlists.forEach(playlistName => {
  657. const li = document.createElement('li');
  658. li.textContent = playlistName;
  659. li.classList.add('playlist-item'); // Add a class for styling
  660. // Attach click event to handle selection
  661. li.onclick = () => {
  662. // Remove 'selected' class from all items
  663. document.querySelectorAll('#all_playlists li').forEach(item => {
  664. item.classList.remove('selected');
  665. });
  666. // Add 'selected' class to the clicked item
  667. li.classList.add('selected');
  668. // Open the playlist editor for the selected playlist
  669. openPlaylistEditor(playlistName);
  670. };
  671. ul.appendChild(li);
  672. });
  673. }
  674. // Cancel changes and close the editor
  675. function cancelPlaylistChanges() {
  676. playlist = [...originalPlaylist]; // Revert to the original playlist
  677. isPlaylistChanged = false;
  678. toggleSaveCancelButtons(false); // Hide the save and cancel buttons
  679. refreshPlaylistUI(); // Refresh the UI with the original state
  680. closeStickySection('playlist-editor'); // Close the editor
  681. }
  682. // Open the playlist editor
  683. function openPlaylistEditor(playlistName) {
  684. logMessage(`Opening editor for playlist: ${playlistName}`);
  685. const editorSection = document.getElementById('playlist-editor');
  686. // Update the displayed playlist name
  687. document.getElementById('playlist_name_display').textContent = playlistName;
  688. // Store the current playlist name for renaming
  689. document.getElementById('playlist_name_input').value = playlistName;
  690. editorSection.classList.remove('hidden');
  691. editorSection.classList.add('visible');
  692. loadPlaylist(playlistName);
  693. }
  694. function clearSchedule() {
  695. document.getElementById("start_time").value = "";
  696. document.getElementById("end_time").value = "";
  697. document.getElementById('clear_time').style.display = 'none';
  698. setCookie('start_time', '', 365);
  699. setCookie('end_time', '', 365);
  700. }
  701. // Function to run the selected playlist with specified parameters
  702. async function runPlaylist() {
  703. const playlistName = document.getElementById('playlist_name_display').textContent;
  704. if (!playlistName) {
  705. logMessage("No playlist selected to run.");
  706. return;
  707. }
  708. const pauseTimeInput = document.getElementById('pause_time').value;
  709. const clearPatternSelect = document.getElementById('clear_pattern').value;
  710. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  711. const shuffle = document.getElementById('shuffle_playlist').checked;
  712. const startTimeInput = document.getElementById('start_time').value.trim();
  713. const endTimeInput = document.getElementById('end_time').value.trim();
  714. const pauseTime = parseFloat(pauseTimeInput);
  715. if (isNaN(pauseTime) || pauseTime < 0) {
  716. logMessage("Invalid pause time. Please enter a non-negative number.", LOG_TYPE.WARNING);
  717. return;
  718. }
  719. // Validate start and end time format and logic
  720. let startTime = startTimeInput || null;
  721. let endTime = endTimeInput || null;
  722. // Ensure that if one time is filled, the other must be as well
  723. if ((startTime && !endTime) || (!startTime && endTime)) {
  724. logMessage("Both start and end times must be provided together or left blank.", LOG_TYPE.WARNING);
  725. return;
  726. }
  727. // If both are provided, validate format and ensure start_time < end_time
  728. if (startTime && endTime) {
  729. try {
  730. const startDateTime = new Date(`1970-01-01T${startTime}:00`);
  731. const endDateTime = new Date(`1970-01-01T${endTime}:00`);
  732. if (isNaN(startDateTime.getTime()) || isNaN(endDateTime.getTime())) {
  733. logMessage("Invalid time format. Please use HH:MM format (e.g., 09:30).", LOG_TYPE.WARNING);
  734. return;
  735. }
  736. if (startDateTime >= endDateTime) {
  737. logMessage("Start time must be earlier than end time.", LOG_TYPE.WARNING);
  738. return;
  739. }
  740. } catch (error) {
  741. logMessage("Error parsing start or end time. Ensure correct HH:MM format.", LOG_TYPE.ERROR);
  742. return;
  743. }
  744. }
  745. logMessage(`Running playlist: ${playlistName} with pause_time=${pauseTime}, clear_pattern=${clearPatternSelect}, run_mode=${runMode}, shuffle=${shuffle}.`);
  746. try {
  747. const response = await fetch('/run_playlist', {
  748. method: 'POST',
  749. headers: { 'Content-Type': 'application/json' },
  750. body: JSON.stringify({
  751. playlist_name: playlistName,
  752. pause_time: pauseTime,
  753. clear_pattern: clearPatternSelect,
  754. run_mode: runMode,
  755. shuffle: shuffle,
  756. start_time: startTimeInput,
  757. end_time: endTimeInput
  758. })
  759. });
  760. const result = await response.json();
  761. if (result.success) {
  762. logMessage(`Playlist "${playlistName}" is now running.`, LOG_TYPE.SUCCESS);
  763. updateCurrentlyPlaying();
  764. } else {
  765. logMessage(`Failed to run playlist "${playlistName}": ${result.error}`, LOG_TYPE.ERROR);
  766. }
  767. } catch (error) {
  768. logMessage(`Error running playlist "${playlistName}": ${error.message}`, LOG_TYPE.ERROR);
  769. }
  770. }
  771. // Track changes in the playlist
  772. let originalPlaylist = [];
  773. let isPlaylistChanged = false;
  774. // Load playlist and set the original state
  775. async function loadPlaylist(playlistName) {
  776. try {
  777. logMessage(`Loading playlist: ${playlistName}`);
  778. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  779. const data = await response.json();
  780. if (!data.name) {
  781. throw new Error('Playlist name is missing in the response.');
  782. }
  783. // Populate playlist items and set original state
  784. playlist = data.files || [];
  785. originalPlaylist = [...playlist]; // Clone the playlist as the original
  786. isPlaylistChanged = false; // Reset change tracking
  787. toggleSaveCancelButtons(false); // Hide the save and cancel buttons initially
  788. refreshPlaylistUI();
  789. logMessage(`Loaded playlist: "${playlistName}" with ${playlist.length} file(s).`);
  790. } catch (err) {
  791. logMessage(`Error loading playlist: ${err.message}`, LOG_TYPE.ERROR);
  792. console.error('Error details:', err);
  793. }
  794. }
  795. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  796. // PART B: Creating or Saving (Overwriting) a Playlist
  797. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  798. // Instead of separate create/modify functions, we’ll unify them:
  799. async function savePlaylist() {
  800. const name = document.getElementById('playlist_name_display').textContent
  801. if (!name) {
  802. logMessage("Please enter a playlist name.");
  803. return;
  804. }
  805. if (playlist.length === 0) {
  806. logMessage("No files in this playlist. Add files first.");
  807. return;
  808. }
  809. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  810. try {
  811. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  812. // Let's use /create_playlist to always overwrite or create anew.
  813. const response = await fetch('/create_playlist', {
  814. method: 'POST',
  815. headers: { 'Content-Type': 'application/json' },
  816. body: JSON.stringify({
  817. name: name,
  818. files: playlist
  819. })
  820. });
  821. const result = await response.json();
  822. if (result.success) {
  823. logMessage(`Playlist "${name}" with ${playlist.length} patterns saved`, LOG_TYPE.SUCCESS);
  824. // Reload the entire list of playlists to reflect changes
  825. // Check for changes and refresh the UI
  826. detectPlaylistChanges();
  827. refreshPlaylistUI();
  828. // Restore default action buttons
  829. toggleSaveCancelButtons(false);
  830. } else {
  831. logMessage(`Failed to save playlist: ${result.error}`, LOG_TYPE.ERROR);
  832. }
  833. } catch (err) {
  834. logMessage(`Error saving playlist: ${err}`);
  835. }
  836. }
  837. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  838. // PART C: Renaming and Deleting a playlist
  839. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  840. // Toggle the rename playlist input
  841. function populatePlaylistDropdown() {
  842. return fetch('/list_all_playlists')
  843. .then(response => response.json())
  844. .then(playlists => {
  845. const select = document.getElementById('select-playlist');
  846. select.innerHTML = ''; // Clear existing options
  847. // Retrieve the saved playlist from the cookie
  848. const savedPlaylist = getCookie('selected_playlist');
  849. // Check if there are playlists available
  850. if (playlists.length === 0) {
  851. // Add a placeholder option if no playlists are available
  852. const placeholderOption = document.createElement('option');
  853. placeholderOption.value = '';
  854. placeholderOption.textContent = 'No playlists available';
  855. placeholderOption.disabled = true; // Prevent selection
  856. placeholderOption.selected = true; // Set as default
  857. select.appendChild(placeholderOption);
  858. return;
  859. }
  860. playlists.forEach(playlist => {
  861. const option = document.createElement('option');
  862. option.value = playlist;
  863. option.textContent = playlist;
  864. // Mark the saved playlist as selected
  865. if (playlist === savedPlaylist) {
  866. option.selected = true;
  867. }
  868. select.appendChild(option);
  869. });
  870. // Attach the onchange event listener after populating the dropdown
  871. select.addEventListener('change', function () {
  872. const selectedPlaylist = this.value;
  873. setCookie('selected_playlist', selectedPlaylist, 365); // Save to cookie
  874. logMessage(`Selected playlist saved: ${selectedPlaylist}`);
  875. });
  876. logMessage('Playlist dropdown populated, event listener attached, and saved playlist restored.');
  877. })
  878. .catch(error => logMessage(`Error fetching playlists: ${error.message}`));
  879. }
  880. populatePlaylistDropdown().then(() => {
  881. loadSettingsFromCookies(); // Restore selected playlist after populating the dropdown
  882. });
  883. // Confirm and save the renamed playlist
  884. async function confirmAddPlaylist() {
  885. const playlistNameInput = document.getElementById('new_playlist_name');
  886. const playlistName = playlistNameInput.value.trim();
  887. if (!playlistName) {
  888. logMessage('Playlist name cannot be empty.', LOG_TYPE.ERROR);
  889. return;
  890. }
  891. try {
  892. logMessage(`Adding new playlist: "${playlistName}"...`);
  893. const response = await fetch('/create_playlist', {
  894. method: 'POST',
  895. headers: { 'Content-Type': 'application/json' },
  896. body: JSON.stringify({
  897. name: playlistName,
  898. files: [] // New playlist starts empty
  899. })
  900. });
  901. const result = await response.json();
  902. if (result.success) {
  903. logMessage(`Playlist "${playlistName}" created successfully.`, LOG_TYPE.SUCCESS);
  904. // Clear the input field
  905. playlistNameInput.value = '';
  906. // Refresh the playlist list
  907. loadAllPlaylists();
  908. populatePlaylistDropdown();
  909. // Hide the add playlist container
  910. toggleSecondaryButtons('add-playlist-container');
  911. } else {
  912. logMessage(`Failed to create playlist: ${result.error}`, LOG_TYPE.ERROR);
  913. }
  914. } catch (error) {
  915. logMessage(`Error creating playlist: ${error.message}`);
  916. }
  917. }
  918. async function confirmRenamePlaylist() {
  919. const newName = document.getElementById('playlist_name_input').value.trim();
  920. const currentName = document.getElementById('playlist_name_display').textContent;
  921. if (!newName) {
  922. logMessage("New playlist name cannot be empty.", LOG_TYPE.ERROR);
  923. return;
  924. }
  925. if (newName === currentName) {
  926. logMessage("New playlist name is the same as the current name. No changes made.", LOG_TYPE.WARNING);
  927. toggleSecondaryButtons('rename-playlist-container'); // Close the rename container
  928. return;
  929. }
  930. try {
  931. // Step 1: Create/Modify the playlist with the new name
  932. const createResponse = await fetch('/modify_playlist', {
  933. method: 'POST',
  934. headers: { 'Content-Type': 'application/json' },
  935. body: JSON.stringify({
  936. name: newName,
  937. files: playlist // Ensure `playlist` contains the current list of files
  938. })
  939. });
  940. const createResult = await createResponse.json();
  941. if (createResult.success) {
  942. logMessage(createResult.message, LOG_TYPE.SUCCESS);
  943. // Step 2: Delete the old playlist
  944. const deleteResponse = await fetch('/delete_playlist', {
  945. method: 'DELETE',
  946. headers: { 'Content-Type': 'application/json' },
  947. body: JSON.stringify({ name: currentName })
  948. });
  949. const deleteResult = await deleteResponse.json();
  950. if (deleteResult.success) {
  951. logMessage(deleteResult.message);
  952. // Update the UI with the new name
  953. document.getElementById('playlist_name_display').textContent = newName;
  954. // Refresh playlists list
  955. loadAllPlaylists();
  956. // Close the rename container and restore original action buttons
  957. toggleSecondaryButtons('rename-playlist-container');
  958. } else {
  959. logMessage(`Failed to delete old playlist: ${deleteResult.error}`, LOG_TYPE.ERROR);
  960. }
  961. } else {
  962. logMessage(`Failed to rename playlist: ${createResult.error}`, LOG_TYPE.ERROR);
  963. }
  964. } catch (error) {
  965. logMessage(`Error renaming playlist: ${error.message}`);
  966. }
  967. }
  968. // Delete the currently opened playlist
  969. async function deleteCurrentPlaylist() {
  970. const playlistName = document.getElementById('playlist_name_display').textContent;
  971. if (!confirm(`Are you sure you want to delete the playlist "${playlistName}"? This action cannot be undone.`)) {
  972. return;
  973. }
  974. try {
  975. const response = await fetch('/delete_playlist', {
  976. method: 'DELETE',
  977. headers: { 'Content-Type': 'application/json' },
  978. body: JSON.stringify({ name: playlistName })
  979. });
  980. const result = await response.json();
  981. if (result.success) {
  982. logMessage(`Playlist "${playlistName}" deleted.`, LOG_TYPE.INFO);
  983. closeStickySection('playlist-editor');
  984. loadAllPlaylists();
  985. populatePlaylistDropdown();
  986. } else {
  987. logMessage(`Failed to delete playlist: ${result.error}`, LOG_TYPE.ERROR);
  988. }
  989. } catch (error) {
  990. logMessage(`Error deleting playlist: ${error.message}`);
  991. }
  992. }
  993. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  994. // PART D: Local playlist array UI
  995. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  996. // Refresh the playlist UI and detect changes
  997. function refreshPlaylistUI() {
  998. const ul = document.getElementById('playlist_items');
  999. if (!ul) {
  1000. logMessage('Error: Playlist container not found');
  1001. return;
  1002. }
  1003. ul.innerHTML = ''; // Clear existing items
  1004. if (playlist.length === 0) {
  1005. // Add a placeholder if the playlist is empty
  1006. const emptyLi = document.createElement('li');
  1007. emptyLi.textContent = 'No items in the playlist.';
  1008. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  1009. ul.appendChild(emptyLi);
  1010. return;
  1011. }
  1012. playlist.forEach((file, index) => {
  1013. const li = document.createElement('li');
  1014. // Add filename in a span
  1015. const filenameSpan = document.createElement('span');
  1016. filenameSpan.textContent = file;
  1017. filenameSpan.classList.add('filename'); // Add a class for styling
  1018. li.appendChild(filenameSpan);
  1019. // Move Up button
  1020. const moveUpBtn = document.createElement('button');
  1021. moveUpBtn.innerHTML = '<i class="fa-solid fa-turn-up"></i>'; // Up arrow symbol
  1022. moveUpBtn.classList.add('move-button');
  1023. moveUpBtn.onclick = () => {
  1024. if (index > 0) {
  1025. const temp = playlist[index - 1];
  1026. playlist[index - 1] = playlist[index];
  1027. playlist[index] = temp;
  1028. detectPlaylistChanges(); // Check for changes
  1029. refreshPlaylistUI();
  1030. }
  1031. };
  1032. li.appendChild(moveUpBtn);
  1033. // Move Down button
  1034. const moveDownBtn = document.createElement('button');
  1035. moveDownBtn.innerHTML = '<i class="fa-solid fa-turn-down"></i>'; // Down arrow symbol
  1036. moveDownBtn.classList.add('move-button');
  1037. moveDownBtn.onclick = () => {
  1038. if (index < playlist.length - 1) {
  1039. const temp = playlist[index + 1];
  1040. playlist[index + 1] = playlist[index];
  1041. playlist[index] = temp;
  1042. detectPlaylistChanges(); // Check for changes
  1043. refreshPlaylistUI();
  1044. }
  1045. };
  1046. li.appendChild(moveDownBtn);
  1047. // Remove button
  1048. const removeBtn = document.createElement('button');
  1049. removeBtn.innerHTML = '<i class="fa-solid fa-trash"></i>';
  1050. removeBtn.classList.add('remove-button');
  1051. removeBtn.onclick = () => {
  1052. playlist.splice(index, 1);
  1053. detectPlaylistChanges(); // Check for changes
  1054. refreshPlaylistUI();
  1055. };
  1056. li.appendChild(removeBtn);
  1057. ul.appendChild(li);
  1058. });
  1059. }
  1060. // Toggle the visibility of the save and cancel buttons
  1061. function toggleSaveCancelButtons(show) {
  1062. const actionButtons = document.querySelector('#playlist-editor .action-buttons');
  1063. if (actionButtons) {
  1064. // Show/hide all buttons except Save and Cancel
  1065. actionButtons.querySelectorAll('button:not(.save-cancel)').forEach(button => {
  1066. button.style.display = show ? 'none' : 'flex';
  1067. });
  1068. // Show/hide Save and Cancel buttons
  1069. actionButtons.querySelectorAll('.save-cancel').forEach(button => {
  1070. button.style.display = show ? 'flex' : 'none';
  1071. });
  1072. } else {
  1073. logMessage('Error: Action buttons container not found.', LOG_TYPE.ERROR);
  1074. }
  1075. }
  1076. // Detect changes in the playlist
  1077. function detectPlaylistChanges() {
  1078. isPlaylistChanged = JSON.stringify(originalPlaylist) !== JSON.stringify(playlist);
  1079. toggleSaveCancelButtons(isPlaylistChanged);
  1080. }
  1081. // Toggle the "Add to Playlist" section
  1082. function toggleSecondaryButtons(containerId, onShowCallback = null) {
  1083. const container = document.getElementById(containerId);
  1084. if (!container) {
  1085. logMessage(`Error: Element with ID "${containerId}" not found`);
  1086. return;
  1087. }
  1088. // Find the .action-buttons element preceding the container
  1089. const previousActionButtons = container.previousElementSibling?.classList.contains('action-buttons')
  1090. ? container.previousElementSibling
  1091. : null;
  1092. if (container.classList.contains('hidden')) {
  1093. // Show the container
  1094. container.classList.remove('hidden');
  1095. // Hide the previous .action-buttons element
  1096. if (previousActionButtons) {
  1097. previousActionButtons.style.display = 'none';
  1098. }
  1099. // Optional callback for custom logic when showing the container
  1100. if (onShowCallback) {
  1101. onShowCallback();
  1102. }
  1103. } else {
  1104. // Hide the container
  1105. container.classList.add('hidden');
  1106. // Restore the previous .action-buttons element
  1107. if (previousActionButtons) {
  1108. previousActionButtons.style.display = 'flex';
  1109. }
  1110. }
  1111. }
  1112. // Add the selected pattern to the selected playlist
  1113. async function saveToPlaylist() {
  1114. const playlist = document.getElementById('select-playlist').value;
  1115. if (!playlist) {
  1116. logMessage('No playlist selected.', LOG_TYPE.ERROR);
  1117. return;
  1118. }
  1119. if (!selectedFile) {
  1120. logMessage('No pattern selected to add.', LOG_TYPE.ERROR);
  1121. return;
  1122. }
  1123. try {
  1124. logMessage(`Adding pattern "${selectedFile}" to playlist "${playlist}"...`);
  1125. const response = await fetch('/add_to_playlist', {
  1126. method: 'POST',
  1127. headers: { 'Content-Type': 'application/json' },
  1128. body: JSON.stringify({ playlist_name: playlist, pattern: selectedFile })
  1129. });
  1130. const result = await response.json();
  1131. if (result.success) {
  1132. logMessage(`Pattern "${selectedFile}" successfully added to playlist "${playlist}".`, LOG_TYPE.SUCCESS);
  1133. // Reset the UI state via toggleSecondaryButtons
  1134. toggleSecondaryButtons('add-to-playlist-container', () => {
  1135. const selectPlaylist = document.getElementById('select-playlist');
  1136. selectPlaylist.value = ''; // Clear the selection
  1137. });
  1138. } else {
  1139. logMessage(`Failed to add pattern to playlist: ${result.error}`, LOG_TYPE.ERROR);
  1140. }
  1141. } catch (error) {
  1142. logMessage(`Error adding pattern to playlist: ${error.message}`);
  1143. }
  1144. }
  1145. async function changeSpeed() {
  1146. const speedInput = document.getElementById('speed_input');
  1147. const speed = parseFloat(speedInput.value);
  1148. if (isNaN(speed) || speed <= 0) {
  1149. logMessage('Invalid speed. Please enter a positive number.');
  1150. return;
  1151. }
  1152. logMessage(`Setting speed to: ${speed}...`);
  1153. const response = await fetch('/set_speed', {
  1154. method: 'POST',
  1155. headers: { 'Content-Type': 'application/json' },
  1156. body: JSON.stringify({ speed })
  1157. });
  1158. const result = await response.json();
  1159. if (result.success) {
  1160. document.getElementById('speed_status').textContent = `Current Speed: ${speed}`;
  1161. logMessage(`Speed set to: ${speed}`, LOG_TYPE.SUCCESS);
  1162. } else {
  1163. logMessage(`Failed to set speed: ${result.error}`, LOG_TYPE.ERROR);
  1164. }
  1165. }
  1166. // Function to close any sticky section
  1167. function closeStickySection(sectionId) {
  1168. const section = document.getElementById(sectionId);
  1169. if (section) {
  1170. section.classList.remove('visible');
  1171. section.classList.remove('fullscreen');
  1172. section.classList.add('hidden');
  1173. // Reset the fullscreen button text if it exists
  1174. const fullscreenButton = section.querySelector('.fullscreen-button');
  1175. if (fullscreenButton) {
  1176. fullscreenButton.innerHtml = '<i class="fa-solid fa-compress"></i>'; // Reset to enter fullscreen icon/text
  1177. }
  1178. logMessage(`Closed section: ${sectionId}`);
  1179. if(sectionId === 'playlist-editor') {
  1180. document.querySelectorAll('#all_playlists .playlist-item').forEach(item => {
  1181. item.classList.remove('selected');
  1182. });
  1183. }
  1184. if(sectionId === 'pattern-preview-container') {
  1185. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1186. item.classList.remove('selected');
  1187. });
  1188. }
  1189. } else {
  1190. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1191. }
  1192. }
  1193. // Function to open any sticky section
  1194. function openStickySection(sectionId) {
  1195. const section = document.getElementById(sectionId);
  1196. if (section) {
  1197. // Toggle the 'open' class
  1198. section.classList.toggle('open');
  1199. } else {
  1200. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1201. }
  1202. }
  1203. function attachFullScreenListeners() {
  1204. // Add event listener to all fullscreen buttons
  1205. document.querySelectorAll('.fullscreen-button').forEach(button => {
  1206. button.addEventListener('click', function () {
  1207. const stickySection = this.closest('.sticky'); // Find the closest sticky section
  1208. if (stickySection) {
  1209. // Close all other sections
  1210. document.querySelectorAll('.sticky:not(#currently-playing-container)').forEach(section => {
  1211. if (section !== stickySection) {
  1212. section.classList.remove('fullscreen');
  1213. section.classList.remove('visible');
  1214. section.classList.add('hidden');
  1215. // Reset the fullscreen button text for other sections
  1216. const otherFullscreenButton = section.querySelector('.fullscreen-button');
  1217. if (otherFullscreenButton) {
  1218. otherFullscreenButton.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1219. }
  1220. }
  1221. });
  1222. stickySection.classList.toggle('fullscreen'); // Toggle fullscreen class
  1223. // Update button icon or text
  1224. if (stickySection.classList.contains('fullscreen')) {
  1225. this.innerHTML = '<i class="fa-solid fa-compress"></i>'; // Exit fullscreen icon/text
  1226. } else {
  1227. this.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1228. }
  1229. } else {
  1230. console.error('Error: Fullscreen button is not inside a sticky section.');
  1231. }
  1232. });
  1233. });
  1234. }
  1235. let lastPreviewedFile = null; // Track the last previewed file
  1236. let updateInterval = null;
  1237. async function updateCurrentlyPlaying() {
  1238. try {
  1239. if (!document.hasFocus()) return; // Stop execution if the page is not visible
  1240. const response = await fetch('/status');
  1241. const data = await response.json();
  1242. const currentlyPlayingSection = document.getElementById('currently-playing-container');
  1243. if (!currentlyPlayingSection) {
  1244. logMessage('Currently Playing section not found.', LOG_TYPE.ERROR);
  1245. return;
  1246. }
  1247. const currentSpeedElem = document.getElementById('current_speed_display');
  1248. if (data.current_speed !== undefined) {
  1249. currentSpeedElem.textContent = `Current Speed: ${data.current_speed}`;
  1250. } else {
  1251. currentSpeedElem.textContent = 'Current Speed: N/A';
  1252. }
  1253. if (data.current_playing_file && !data.stop_requested) {
  1254. const { current_playing_file, execution_progress, pause_requested } = data;
  1255. // Strip './patterns/' prefix from the file name
  1256. const fileName = current_playing_file.replace('./patterns/', '');
  1257. if (!document.body.classList.contains('playing')) {
  1258. closeStickySection('pattern-preview-container')
  1259. }
  1260. // Show "Currently Playing" section
  1261. document.body.classList.add('playing');
  1262. // Update pattern preview only if the file is different
  1263. if (current_playing_file !== lastPreviewedFile) {
  1264. previewPattern(fileName, 'currently-playing-container');
  1265. lastPreviewedFile = current_playing_file;
  1266. }
  1267. // Update the filename display
  1268. const fileNameDisplay = document.getElementById('currently-playing-file');
  1269. if (fileNameDisplay) fileNameDisplay.textContent = fileName;
  1270. // Update progress bar
  1271. const progressBar = document.getElementById('play_progress');
  1272. const progressText = document.getElementById('play_progress_text');
  1273. if (execution_progress) {
  1274. const progressPercentage = (execution_progress[0] / execution_progress[1]) * 100;
  1275. progressBar.value = progressPercentage;
  1276. progressText.textContent = `${Math.round(progressPercentage)}% (Elapsed: ${formatSecondsToHMS(execution_progress[3])} | Remaining: ${formatSecondsToHMS(execution_progress[2])})`;
  1277. } else {
  1278. progressBar.value = 0;
  1279. progressText.textContent = '0%';
  1280. }
  1281. // Update play/pause button
  1282. const pausePlayButton = document.getElementById('pausePlayCurrent');
  1283. if (pausePlayButton) pausePlayButton.innerHTML = pause_requested ? '<i class="fa-solid fa-play"></i>' : '<i class="fa-solid fa-pause"></i>';
  1284. } else {
  1285. document.body.classList.remove('playing');
  1286. }
  1287. } catch (error) {
  1288. logMessage(`Error updating "Currently Playing" section: ${error.message}`);
  1289. }
  1290. }
  1291. function formatSecondsToHMS(seconds) {
  1292. const hrs = Math.floor(seconds / 3600);
  1293. const mins = Math.floor((seconds % 3600) / 60);
  1294. const secs = Math.floor(seconds % 60);
  1295. return `${String(hrs).padStart(2, '0')}:${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  1296. }
  1297. // Function to start or stop updates based on visibility
  1298. function handleVisibilityChange() {
  1299. if (document.hasFocus()) {
  1300. // User is active, start updating
  1301. if (!updateInterval) {
  1302. updateCurrentlyPlaying(); // Run immediately
  1303. updateInterval = setInterval(updateCurrentlyPlaying, 5000); // Update every 5s
  1304. }
  1305. } else {
  1306. // User is inactive, stop updating
  1307. clearInterval(updateInterval);
  1308. updateInterval = null;
  1309. }
  1310. }
  1311. function toggleSettings() {
  1312. const settingsContainer = document.getElementById('settings-container');
  1313. if (settingsContainer) {
  1314. settingsContainer.classList.toggle('open');
  1315. }
  1316. }
  1317. // Utility function to manage cookies
  1318. function setCookie(name, value, days) {
  1319. const date = new Date();
  1320. date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  1321. document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
  1322. }
  1323. function getCookie(name) {
  1324. const nameEQ = `${name}=`;
  1325. const cookies = document.cookie.split(';');
  1326. for (let i = 0; i < cookies.length; i++) {
  1327. let cookie = cookies[i].trim();
  1328. if (cookie.startsWith(nameEQ)) {
  1329. return cookie.substring(nameEQ.length);
  1330. }
  1331. }
  1332. return null;
  1333. }
  1334. // Save settings to cookies
  1335. function saveSettingsToCookies() {
  1336. // Save the pause time
  1337. const pauseTime = document.getElementById('pause_time').value;
  1338. setCookie('pause_time', pauseTime, 365);
  1339. // Save the clear pattern
  1340. const clearPattern = document.getElementById('clear_pattern').value;
  1341. setCookie('clear_pattern', clearPattern, 365);
  1342. // Save the run mode
  1343. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  1344. setCookie('run_mode', runMode, 365);
  1345. // Save shuffle playlist checkbox state
  1346. const shufflePlaylist = document.getElementById('shuffle_playlist').checked;
  1347. setCookie('shuffle_playlist', shufflePlaylist, 365);
  1348. // Save pre-execution action
  1349. const preExecution = document.getElementById('pre_execution').value;
  1350. setCookie('pre_execution', preExecution, 365);
  1351. // Save start and end times
  1352. const startTime = document.getElementById('start_time').value;
  1353. const endTime = document.getElementById('end_time').value;
  1354. setCookie('start_time', startTime, 365);
  1355. setCookie('end_time', endTime, 365);
  1356. logMessage('Settings saved.');
  1357. }
  1358. // Load settings from cookies
  1359. function loadSettingsFromCookies() {
  1360. // Load the pause time
  1361. const pauseTime = getCookie('pause_time');
  1362. if (pauseTime !== null) {
  1363. document.getElementById('pause_time').value = pauseTime;
  1364. }
  1365. // Load the clear pattern
  1366. const clearPattern = getCookie('clear_pattern');
  1367. if (clearPattern !== null) {
  1368. document.getElementById('clear_pattern').value = clearPattern;
  1369. }
  1370. // Load the run mode
  1371. const runMode = getCookie('run_mode');
  1372. if (runMode !== null) {
  1373. document.querySelector(`input[name="run_mode"][value="${runMode}"]`).checked = true;
  1374. }
  1375. // Load the shuffle playlist checkbox state
  1376. const shufflePlaylist = getCookie('shuffle_playlist');
  1377. if (shufflePlaylist !== null) {
  1378. document.getElementById('shuffle_playlist').checked = shufflePlaylist === 'true';
  1379. }
  1380. // Load the pre-execution action
  1381. const preExecution = getCookie('pre_execution');
  1382. if (preExecution !== null) {
  1383. document.getElementById('pre_execution').value = preExecution;
  1384. }
  1385. // Load start and end times
  1386. const startTime = getCookie('start_time');
  1387. if (startTime !== null) {
  1388. document.getElementById('start_time').value = startTime;
  1389. }
  1390. const endTime = getCookie('end_time');
  1391. if (endTime !== null) {
  1392. document.getElementById('end_time').value = endTime;
  1393. }
  1394. if (startTime && endTime ) {
  1395. document.getElementById('clear_time').style.display = 'block';
  1396. }
  1397. logMessage('Settings loaded from cookies.');
  1398. }
  1399. // Call this function to save settings when a value is changed
  1400. function attachSettingsSaveListeners() {
  1401. // Add event listeners to inputs
  1402. document.getElementById('pause_time').addEventListener('input', saveSettingsToCookies);
  1403. document.getElementById('clear_pattern').addEventListener('change', saveSettingsToCookies);
  1404. document.querySelectorAll('input[name="run_mode"]').forEach(input => {
  1405. input.addEventListener('change', saveSettingsToCookies);
  1406. });
  1407. document.getElementById('shuffle_playlist').addEventListener('change', saveSettingsToCookies);
  1408. document.getElementById('pre_execution').addEventListener('change', saveSettingsToCookies);
  1409. document.getElementById('start_time').addEventListener('change', saveSettingsToCookies);
  1410. document.getElementById('end_time').addEventListener('change', saveSettingsToCookies);
  1411. }
  1412. // Tab switching logic with cookie storage
  1413. function switchTab(tabName) {
  1414. // Store the active tab in a cookie
  1415. setCookie('activeTab', tabName, 365); // Store for 7 days
  1416. // Deactivate all tab content
  1417. document.querySelectorAll('.tab-content').forEach(tab => {
  1418. tab.classList.remove('active');
  1419. });
  1420. // Activate the selected tab content
  1421. const activeTab = document.getElementById(`${tabName}-tab`);
  1422. if (activeTab) {
  1423. activeTab.classList.add('active');
  1424. } else {
  1425. console.error(`Error: Tab "${tabName}" not found.`);
  1426. }
  1427. // Deactivate all nav buttons
  1428. document.querySelectorAll('.bottom-nav .tab-button').forEach(button => {
  1429. button.classList.remove('active');
  1430. });
  1431. // Activate the selected nav button
  1432. const activeNavButton = document.getElementById(`nav-${tabName}`);
  1433. if (activeNavButton) {
  1434. activeNavButton.classList.add('active');
  1435. } else {
  1436. console.error(`Error: Nav button for "${tabName}" not found.`);
  1437. }
  1438. }
  1439. document.addEventListener("visibilitychange", handleVisibilityChange);
  1440. // Initialization
  1441. document.addEventListener('DOMContentLoaded', () => {
  1442. const activeTab = getCookie('activeTab') || 'patterns'; // Default to 'patterns' tab
  1443. switchTab(activeTab); // Load the active tab
  1444. checkSerialStatus(); // Check connection status
  1445. loadThetaRhoFiles(); // Load files on page load
  1446. loadAllPlaylists(); // Load all playlists on page load
  1447. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1448. attachFullScreenListeners();
  1449. // Periodically check for currently playing status
  1450. if (document.hasFocus()) {
  1451. updateInterval = setInterval(updateCurrentlyPlaying, 5000);
  1452. }
  1453. checkForUpdates();
  1454. });