main.js 64 KB

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