main.js 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110
  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. // Show the preview container
  130. const previewContainer = document.getElementById('pattern-preview-container');
  131. if (previewContainer) {
  132. previewContainer.classList.remove('hidden');
  133. previewContainer.classList.add('visible');
  134. }
  135. // Update the preview
  136. await previewPattern(file);
  137. // Populate the playlist dropdown after selecting a pattern
  138. await populatePlaylistDropdown();
  139. }
  140. // Fetch and display Theta-Rho files
  141. async function loadThetaRhoFiles() {
  142. try {
  143. logMessage('Loading Theta-Rho files...');
  144. const response = await fetch('/list_theta_rho_files');
  145. let files = await response.json();
  146. files = files.filter(file => file.endsWith('.thr'));
  147. // Sort files with custom_patterns on top and all alphabetically sorted
  148. const sortedFiles = files.sort((a, b) => {
  149. const isCustomA = a.startsWith('custom_patterns/');
  150. const isCustomB = b.startsWith('custom_patterns/');
  151. if (isCustomA && !isCustomB) return -1; // a comes first
  152. if (!isCustomA && isCustomB) return 1; // b comes first
  153. return a.localeCompare(b); // Alphabetical comparison
  154. });
  155. allFiles = sortedFiles; // Update global files
  156. displayFiles(sortedFiles); // Display sorted files
  157. logMessage('Theta-Rho files loaded and sorted successfully.');
  158. } catch (error) {
  159. logMessage(`Error loading Theta-Rho files: ${error.message}`, 'error');
  160. }
  161. }
  162. // Display files in the UI
  163. function displayFiles(files) {
  164. const ul = document.getElementById('theta_rho_files');
  165. if (!ul) {
  166. logMessage('Error: File list container not found');
  167. return;
  168. }
  169. ul.innerHTML = ''; // Clear existing list
  170. files.forEach(file => {
  171. const li = document.createElement('li');
  172. li.textContent = file;
  173. li.classList.add('file-item');
  174. // Attach file selection handler
  175. li.onclick = () => selectFile(file, li);
  176. ul.appendChild(li);
  177. });
  178. }
  179. // Filter files by search input
  180. function searchPatternFiles() {
  181. const searchInput = document.getElementById('search_pattern').value.toLowerCase();
  182. const filteredFiles = allFiles.filter(file => file.toLowerCase().includes(searchInput));
  183. displayFiles(filteredFiles);
  184. }
  185. // Upload a new Theta-Rho file
  186. async function uploadThetaRho() {
  187. const fileInput = document.getElementById('upload_file');
  188. const file = fileInput.files[0];
  189. if (!file) {
  190. logMessage('No file selected for upload.', LOG_TYPE.ERROR);
  191. return;
  192. }
  193. try {
  194. logMessage(`Uploading file: ${file.name}...`);
  195. const formData = new FormData();
  196. formData.append('file', file);
  197. const response = await fetch('/upload_theta_rho', {
  198. method: 'POST',
  199. body: formData
  200. });
  201. const result = await response.json();
  202. if (result.success) {
  203. logMessage(`File uploaded successfully: ${file.name}`, LOG_TYPE.SUCCESS);
  204. fileInput.value = '';
  205. await loadThetaRhoFiles();
  206. } else {
  207. logMessage(`Failed to upload file: ${file.name}`, LOG_TYPE.ERROR);
  208. }
  209. } catch (error) {
  210. logMessage(`Error uploading file: ${error.message}`);
  211. }
  212. }
  213. async function runThetaRho() {
  214. if (!selectedFile) {
  215. logMessage("No file selected to run.");
  216. return;
  217. }
  218. // Get the selected pre-execution action
  219. const preExecutionAction = document.getElementById('pre_execution').value;
  220. logMessage(`Running file: ${selectedFile} with pre-execution action: ${preExecutionAction}...`);
  221. try {
  222. const response = await fetch('/run_theta_rho', {
  223. method: 'POST',
  224. headers: { 'Content-Type': 'application/json' },
  225. body: JSON.stringify({
  226. file_name: selectedFile,
  227. pre_execution: preExecutionAction
  228. })
  229. });
  230. const result = await response.json();
  231. if (response.ok) {
  232. // Connect WebSocket when starting a pattern
  233. connectStatusWebSocket();
  234. // Show the currently playing UI immediately
  235. document.body.classList.add('playing');
  236. const currentlyPlayingFile = document.getElementById('currently-playing-file');
  237. if (currentlyPlayingFile) {
  238. currentlyPlayingFile.textContent = selectedFile.replace('./patterns/', '');
  239. }
  240. // Show initial preview
  241. updateCurrentlyPlayingPattern(selectedFile.replace('./patterns/', ''));
  242. logMessage(`Pattern running: ${selectedFile}`, LOG_TYPE.SUCCESS);
  243. } else {
  244. if (response.status === 409) {
  245. logMessage("Cannot start pattern: Another pattern is already running", LOG_TYPE.WARNING);
  246. } else {
  247. logMessage(`Failed to run file: ${result.detail || 'Unknown error'}`, LOG_TYPE.ERROR);
  248. }
  249. }
  250. } catch (error) {
  251. logMessage(`Error running pattern: ${error.message}`, LOG_TYPE.ERROR);
  252. }
  253. }
  254. async function stopExecution() {
  255. logMessage('Stopping execution...');
  256. const response = await fetch('/stop_execution', { method: 'POST' });
  257. const result = await response.json();
  258. if (result.success) {
  259. logMessage('Execution stopped.',LOG_TYPE.SUCCESS);
  260. } else {
  261. logMessage('Failed to stop execution.',LOG_TYPE.ERROR);
  262. }
  263. }
  264. let isPaused = false;
  265. function togglePausePlay() {
  266. const button = document.getElementById("pausePlayCurrent");
  267. if (isPaused) {
  268. // Resume execution
  269. fetch('/resume_execution', { method: 'POST' })
  270. .then(response => response.json())
  271. .then(data => {
  272. if (data.success) {
  273. isPaused = false;
  274. button.innerHTML = "<i class=\"fa-solid fa-pause\"></i>"; // Change to pause icon
  275. }
  276. })
  277. .catch(error => console.error("Error resuming execution:", error));
  278. } else {
  279. // Pause execution
  280. fetch('/pause_execution', { method: 'POST' })
  281. .then(response => response.json())
  282. .then(data => {
  283. if (data.success) {
  284. isPaused = true;
  285. button.innerHTML = "<i class=\"fa-solid fa-play\"></i>"; // Change to play icon
  286. }
  287. })
  288. .catch(error => console.error("Error pausing execution:", error));
  289. }
  290. }
  291. function removeCurrentPattern() {
  292. if (!selectedFile) {
  293. logMessage('No file selected to remove.', LOG_TYPE.ERROR);
  294. return;
  295. }
  296. if (!selectedFile.startsWith('custom_patterns/')) {
  297. logMessage('Only custom patterns can be removed.', LOG_TYPE.WARNING);
  298. return;
  299. }
  300. removeCustomPattern(selectedFile);
  301. }
  302. // Delete the selected file
  303. async function removeCustomPattern(fileName) {
  304. const userConfirmed = confirm(`Are you sure you want to delete the pattern "${fileName}"?`);
  305. if (!userConfirmed) return;
  306. try {
  307. logMessage(`Deleting pattern: ${fileName}...`);
  308. const response = await fetch('/delete_theta_rho_file', {
  309. method: 'POST',
  310. headers: { 'Content-Type': 'application/json' },
  311. body: JSON.stringify({ file_name: fileName })
  312. });
  313. const result = await response.json();
  314. if (result.success) {
  315. logMessage(`File deleted successfully: ${selectedFile}`, LOG_TYPE.SUCCESS);
  316. // Close the preview container
  317. const previewContainer = document.getElementById('pattern-preview-container');
  318. if (previewContainer) {
  319. previewContainer.classList.add('hidden');
  320. previewContainer.classList.remove('visible');
  321. }
  322. // Clear the selected file and refresh the file list
  323. selectedFile = null;
  324. await loadThetaRhoFiles(); // Refresh the file list
  325. } else {
  326. logMessage(`Failed to delete pattern "${fileName}": ${result.error}`, LOG_TYPE.ERROR);
  327. }
  328. } catch (error) {
  329. logMessage(`Error deleting pattern: ${error.message}`);
  330. }
  331. }
  332. // Preview a Theta-Rho file
  333. async function previewPattern(fileName, containerId = 'pattern-preview-container') {
  334. try {
  335. logMessage(`Fetching data to preview file: ${fileName}...`);
  336. const response = await fetch('/preview_thr', {
  337. method: 'POST',
  338. headers: { 'Content-Type': 'application/json' },
  339. body: JSON.stringify({ file_name: fileName })
  340. });
  341. if (!response.ok) {
  342. throw new Error(`HTTP error! status: ${response.status}`);
  343. }
  344. const data = await response.json();
  345. // Get the preview container
  346. const previewContainer = document.getElementById(containerId);
  347. if (!previewContainer) {
  348. logMessage(`Preview container not found: ${containerId}`, LOG_TYPE.ERROR);
  349. return;
  350. }
  351. // Get the pattern preview section
  352. const patternPreview = previewContainer.querySelector('#pattern-preview');
  353. if (!patternPreview) {
  354. logMessage('Pattern preview section not found', LOG_TYPE.ERROR);
  355. return;
  356. }
  357. // Clear existing content
  358. patternPreview.innerHTML = '';
  359. // Create SVG container
  360. const svgContainer = document.createElement('div');
  361. svgContainer.className = 'svg-container';
  362. svgContainer.innerHTML = data.svg;
  363. // Create coordinate display
  364. const coordDisplay = document.createElement('div');
  365. coordDisplay.className = 'coordinate-display';
  366. // Update coordinate text
  367. if (data.first_coordinate && data.last_coordinate) {
  368. coordDisplay.innerHTML = `
  369. <div>First Coordinate: θ=${data.first_coordinate[0].toFixed(2)}, ρ=${data.first_coordinate[1].toFixed(2)}</div>
  370. <div>Last Coordinate: θ=${data.last_coordinate[0].toFixed(2)}, ρ=${data.last_coordinate[1].toFixed(2)}</div>
  371. `;
  372. } else {
  373. coordDisplay.innerHTML = 'No coordinates available';
  374. }
  375. // Add elements to the preview
  376. patternPreview.appendChild(svgContainer);
  377. patternPreview.appendChild(coordDisplay);
  378. // Show the preview container
  379. previewContainer.classList.remove('hidden');
  380. previewContainer.classList.add('visible');
  381. } catch (error) {
  382. logMessage(`Error previewing pattern: ${error.message}`, LOG_TYPE.ERROR);
  383. }
  384. }
  385. // Function to update the currently playing pattern
  386. async function updateCurrentlyPlayingPattern(fileName) {
  387. try {
  388. const response = await fetch('/preview_thr', {
  389. method: 'POST',
  390. headers: { 'Content-Type': 'application/json' },
  391. body: JSON.stringify({ file_name: fileName })
  392. });
  393. if (!response.ok) {
  394. throw new Error(`HTTP error! status: ${response.status}`);
  395. }
  396. const data = await response.json();
  397. // Get the currently playing container
  398. const container = document.getElementById('currently-playing-container');
  399. if (!container) {
  400. logMessage('Currently playing container not found', LOG_TYPE.ERROR);
  401. return;
  402. }
  403. // Get the currently playing preview div
  404. const previewDiv = container.querySelector('#currently-playing-preview');
  405. if (!previewDiv) {
  406. logMessage('Currently playing preview div not found', LOG_TYPE.ERROR);
  407. return;
  408. }
  409. // Clear existing content
  410. previewDiv.innerHTML = '';
  411. // Create SVG container
  412. const svgContainer = document.createElement('div');
  413. svgContainer.className = 'svg-container';
  414. svgContainer.innerHTML = data.svg;
  415. // Add SVG to the preview div
  416. previewDiv.appendChild(svgContainer);
  417. } catch (error) {
  418. logMessage(`Error updating currently playing pattern: ${error.message}`, LOG_TYPE.ERROR);
  419. }
  420. }
  421. // Render the pattern on a canvas
  422. function renderPattern(coordinates, canvasId) {
  423. const canvas = document.getElementById(canvasId);
  424. if (!canvas) {
  425. logMessage(`Canvas element not found: ${canvasId}`, LOG_TYPE.ERROR);
  426. return;
  427. }
  428. if (!(canvas instanceof HTMLCanvasElement)) {
  429. logMessage(`Element with ID "${canvasId}" is not a canvas.`, LOG_TYPE.ERROR);
  430. return;
  431. }
  432. const ctx = canvas.getContext('2d');
  433. if (!ctx) {
  434. logMessage(`Could not get 2D context for canvas: ${canvasId}`, LOG_TYPE.ERROR);
  435. return;
  436. }
  437. // Account for device pixel ratio
  438. const dpr = window.devicePixelRatio || 1;
  439. const rect = canvas.getBoundingClientRect();
  440. canvas.width = rect.width * dpr; // Scale canvas width for high DPI
  441. canvas.height = rect.height * dpr; // Scale canvas height for high DPI
  442. ctx.scale(dpr, dpr); // Scale drawing context
  443. ctx.clearRect(0, 0, canvas.width, canvas.height);
  444. const centerX = rect.width / 2; // Use bounding client rect dimensions
  445. const centerY = rect.height / 2;
  446. const maxRho = Math.max(...coordinates.map(coord => coord[1]));
  447. const scale = Math.min(rect.width, rect.height) / (2 * maxRho); // Scale to fit
  448. ctx.beginPath();
  449. ctx.strokeStyle = 'white';
  450. coordinates.forEach(([theta, rho], index) => {
  451. const x = centerX + rho * Math.cos(theta) * scale;
  452. const y = centerY - rho * Math.sin(theta) * scale;
  453. if (index === 0) ctx.moveTo(x, y);
  454. else ctx.lineTo(x, y);
  455. });
  456. ctx.stroke();
  457. }
  458. async function moveToCenter() {
  459. logMessage('Moving to center...', LOG_TYPE.INFO);
  460. const response = await fetch('/move_to_center', { method: 'POST' });
  461. const result = await response.json();
  462. if (result.success) {
  463. logMessage('Moved to center successfully.', LOG_TYPE.SUCCESS);
  464. } else {
  465. logMessage(`Failed to move to center: ${result.error}`, LOG_TYPE.ERROR);
  466. }
  467. }
  468. async function moveToPerimeter() {
  469. logMessage('Moving to perimeter...', LOG_TYPE.INFO);
  470. const response = await fetch('/move_to_perimeter', { method: 'POST' });
  471. const result = await response.json();
  472. if (result.success) {
  473. logMessage('Moved to perimeter successfully.', LOG_TYPE.SUCCESS);
  474. } else {
  475. logMessage(`Failed to move to perimeter: ${result.error}`, LOG_TYPE.ERROR);
  476. }
  477. }
  478. async function sendCoordinate() {
  479. const theta = parseFloat(document.getElementById('theta_input').value);
  480. const rho = parseFloat(document.getElementById('rho_input').value);
  481. if (isNaN(theta) || isNaN(rho)) {
  482. logMessage('Invalid input: θ and ρ must be numbers.', LOG_TYPE.ERROR);
  483. return;
  484. }
  485. logMessage(`Sending coordinate: θ=${theta}, ρ=${rho}...`);
  486. const response = await fetch('/send_coordinate', {
  487. method: 'POST',
  488. headers: { 'Content-Type': 'application/json' },
  489. body: JSON.stringify({ theta, rho })
  490. });
  491. const result = await response.json();
  492. if (result.success) {
  493. logMessage(`Coordinate executed successfully: θ=${theta}, ρ=${rho}`, LOG_TYPE.SUCCESS);
  494. } else {
  495. logMessage(`Failed to execute coordinate: ${result.error}`, LOG_TYPE.ERROR);
  496. }
  497. }
  498. async function sendHomeCommand() {
  499. const response = await fetch('/send_home', { method: 'POST' });
  500. const result = await response.json();
  501. if (result.success) {
  502. logMessage('HOME command sent successfully.', LOG_TYPE.SUCCESS);
  503. } else {
  504. logMessage('Failed to send HOME command.', LOG_TYPE.ERROR);
  505. }
  506. }
  507. async function runClearIn() {
  508. logMessage('Running clear from center pattern...', LOG_TYPE.INFO);
  509. try {
  510. const response = await fetch('/run_theta_rho', {
  511. method: 'POST',
  512. headers: { 'Content-Type': 'application/json' },
  513. body: JSON.stringify({
  514. file_name: 'clear_from_in.thr',
  515. pre_execution: 'none'
  516. })
  517. });
  518. if (!response.ok) {
  519. if (response.status === 409) {
  520. logMessage('Cannot start pattern: Another pattern is already running', LOG_TYPE.WARNING);
  521. return;
  522. }
  523. throw new Error(`HTTP error! status: ${response.status}`);
  524. }
  525. const result = await response.json();
  526. if (result.success) {
  527. connectStatusWebSocket();
  528. document.body.classList.add('playing');
  529. logMessage('Clear from center pattern started', LOG_TYPE.SUCCESS);
  530. } else {
  531. logMessage('Failed to run clear pattern', LOG_TYPE.ERROR);
  532. }
  533. } catch (error) {
  534. logMessage(`Error running clear pattern: ${error}`, LOG_TYPE.ERROR);
  535. }
  536. }
  537. async function runClearOut() {
  538. logMessage('Running clear from perimeter pattern...', LOG_TYPE.INFO);
  539. try {
  540. const response = await fetch('/run_theta_rho', {
  541. method: 'POST',
  542. headers: { 'Content-Type': 'application/json' },
  543. body: JSON.stringify({
  544. file_name: 'clear_from_out.thr',
  545. pre_execution: 'none'
  546. })
  547. });
  548. if (!response.ok) {
  549. if (response.status === 409) {
  550. logMessage('Cannot start pattern: Another pattern is already running', LOG_TYPE.WARNING);
  551. return;
  552. }
  553. throw new Error(`HTTP error! status: ${response.status}`);
  554. }
  555. const result = await response.json();
  556. if (result.success) {
  557. connectStatusWebSocket();
  558. document.body.classList.add('playing');
  559. logMessage('Clear from perimeter pattern started', LOG_TYPE.SUCCESS);
  560. } else {
  561. logMessage('Failed to run clear pattern', LOG_TYPE.ERROR);
  562. }
  563. } catch (error) {
  564. logMessage(`Error running clear pattern: ${error}`, LOG_TYPE.ERROR);
  565. }
  566. }
  567. async function runClearSide() {
  568. logMessage('Running clear sideways pattern...', LOG_TYPE.INFO);
  569. try {
  570. const response = await fetch('/run_theta_rho', {
  571. method: 'POST',
  572. headers: { 'Content-Type': 'application/json' },
  573. body: JSON.stringify({
  574. file_name: 'clear_sideway.thr',
  575. pre_execution: 'none'
  576. })
  577. });
  578. if (!response.ok) {
  579. if (response.status === 409) {
  580. logMessage('Cannot start pattern: Another pattern is already running', LOG_TYPE.WARNING);
  581. return;
  582. }
  583. throw new Error(`HTTP error! status: ${response.status}`);
  584. }
  585. const result = await response.json();
  586. if (result.success) {
  587. connectStatusWebSocket();
  588. document.body.classList.add('playing');
  589. logMessage('Clear sideways pattern started', LOG_TYPE.SUCCESS);
  590. } else {
  591. logMessage('Failed to run clear pattern', LOG_TYPE.ERROR);
  592. }
  593. } catch (error) {
  594. logMessage(`Error running clear pattern: ${error}`, LOG_TYPE.ERROR);
  595. }
  596. }
  597. let scrollPosition = 0;
  598. function scrollSelection(direction) {
  599. const container = document.getElementById('clear_selection');
  600. const itemHeight = 50; // Adjust based on CSS height
  601. const maxScroll = container.children.length - 1;
  602. // Update scroll position
  603. scrollPosition += direction;
  604. scrollPosition = Math.max(0, Math.min(scrollPosition, maxScroll));
  605. // Update the transform to scroll items
  606. container.style.transform = `translateY(-${scrollPosition * itemHeight}px)`;
  607. setCookie('clear_action_index', scrollPosition, 365);
  608. }
  609. function executeClearAction(actionFunction) {
  610. // Save the new action to a cookie (optional)
  611. setCookie('clear_action', actionFunction, 365);
  612. if (actionFunction && typeof window[actionFunction] === 'function') {
  613. window[actionFunction](); // Execute the selected clear action
  614. } else {
  615. logMessage('No clear action selected or function not found.', LOG_TYPE.ERROR);
  616. }
  617. }
  618. async function runFile(fileName) {
  619. const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
  620. const result = await response.json();
  621. if (result.success) {
  622. logMessage(`Running file: ${fileName}`, LOG_TYPE.SUCCESS);
  623. } else {
  624. logMessage(`Failed to run file: ${fileName}`, LOG_TYPE.ERROR);
  625. }
  626. }
  627. // Connection Status
  628. async function checkSerialStatus() {
  629. const response = await fetch('/serial_status');
  630. const status = await response.json();
  631. const statusElement = document.getElementById('serial_status');
  632. const statusHeaderElement = document.getElementById('connection_status_header');
  633. const serialPortsContainer = document.getElementById('serial_ports_container');
  634. const selectElement = document.getElementById('serial_ports');
  635. const connectButton = document.querySelector('button[onclick="connectSerial()"]');
  636. const disconnectButton = document.querySelector('button[onclick="disconnectSerial()"]');
  637. const restartButton = document.querySelector('button[onclick="restartSerial()"]');
  638. if (status.connected) {
  639. const port = status.port || 'Unknown'; // Fallback if port is undefined
  640. statusElement.textContent = `Connected to ${port}`;
  641. statusElement.classList.add('connected');
  642. statusElement.classList.remove('not-connected');
  643. logMessage(`Connected to serial port: ${port}`);
  644. // Update header status
  645. statusHeaderElement.classList.add('connected');
  646. statusHeaderElement.classList.remove('not-connected');
  647. // Hide Available Ports and show disconnect/restart buttons
  648. serialPortsContainer.style.display = 'none';
  649. connectButton.style.display = 'none';
  650. disconnectButton.style.display = 'flex';
  651. restartButton.style.display = 'flex';
  652. // Preselect the connected port in the dropdown
  653. const newOption = document.createElement('option');
  654. newOption.value = port;
  655. newOption.textContent = port;
  656. selectElement.appendChild(newOption);
  657. selectElement.value = port;
  658. } else {
  659. statusElement.textContent = 'Not connected';
  660. statusElement.classList.add('not-connected');
  661. statusElement.classList.remove('connected');
  662. logMessage('No active connection.');
  663. // Update header status
  664. statusHeaderElement.classList.add('not-connected');
  665. statusHeaderElement.classList.remove('connected');
  666. // Show Available Ports and the connect button
  667. serialPortsContainer.style.display = 'block';
  668. connectButton.style.display = 'flex';
  669. disconnectButton.style.display = 'none';
  670. restartButton.style.display = 'none';
  671. // Attempt to auto-load available ports
  672. await loadSerialPorts();
  673. }
  674. }
  675. async function loadSerialPorts() {
  676. const response = await fetch('/list_serial_ports');
  677. const ports = await response.json();
  678. const select = document.getElementById('serial_ports');
  679. select.innerHTML = '';
  680. ports.forEach(port => {
  681. const option = document.createElement('option');
  682. option.value = port;
  683. option.textContent = port;
  684. select.appendChild(option);
  685. });
  686. logMessage('Serial ports loaded.');
  687. }
  688. async function connectSerial() {
  689. const port = document.getElementById('serial_ports').value;
  690. const response = await fetch('/connect', {
  691. method: 'POST',
  692. headers: { 'Content-Type': 'application/json' },
  693. body: JSON.stringify({ port })
  694. });
  695. const result = await response.json();
  696. if (result.success) {
  697. logMessage(`Connected to serial port: ${port}`, LOG_TYPE.SUCCESS);
  698. // Refresh the status
  699. await checkSerialStatus();
  700. } else {
  701. logMessage(`Error connecting to serial port: ${result.error}`, LOG_TYPE.ERROR);
  702. }
  703. }
  704. async function disconnectSerial() {
  705. const response = await fetch('/disconnect', { method: 'POST' });
  706. const result = await response.json();
  707. if (result.success) {
  708. logMessage('Serial port disconnected.', LOG_TYPE.SUCCESS);
  709. // Refresh the status
  710. await checkSerialStatus();
  711. } else {
  712. logMessage(`Error disconnecting: ${result.error}`, LOG_TYPE.ERROR);
  713. }
  714. }
  715. async function restartSerial() {
  716. const port = document.getElementById('serial_ports').value;
  717. const response = await fetch('/restart_connection', {
  718. method: 'POST',
  719. headers: { 'Content-Type': 'application/json' },
  720. body: JSON.stringify({ port })
  721. });
  722. const result = await response.json();
  723. if (result.success) {
  724. document.getElementById('serial_status').textContent = `Restarted connection to ${port}`;
  725. logMessage('Connection restarted.', LOG_TYPE.SUCCESS);
  726. // No need to change visibility for restart
  727. } else {
  728. logMessage(`Error restarting Connection: ${result.error}`, LOG_TYPE.ERROR);
  729. }
  730. }
  731. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  732. // Firmware / Software Updater
  733. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  734. async function checkForUpdates() {
  735. try {
  736. const response = await fetch('/check_software_update');
  737. const data = await response.json();
  738. // Handle updates available logic
  739. // if (data.updates_available) {
  740. // const updateButton = document.getElementById('update-software-btn');
  741. // const updateLinkElement = document.getElementById('update_link');
  742. // const tagLink = `https://github.com/tuanchris/dune-weaver/releases/tag/${data.latest_remote_tag}`;
  743. // updateButton.classList.remove('hidden'); // Show the button
  744. // logMessage("Software Update Available", LOG_TYPE.INFO, 'open-settings-button')
  745. // updateLinkElement.innerHTML = `<a href="${tagLink}" target="_blank">View Release Notes </a>`;
  746. // updateLinkElement.classList.remove('hidden'); // Show the link
  747. // }
  748. // Update current and latest version in the UI
  749. const currentVersionElem = document.getElementById('current_git_version');
  750. const latestVersionElem = document.getElementById('latest_git_version');
  751. currentVersionElem.textContent = `Current Version: ${data.latest_local_tag || 'Unknown'}`;
  752. latestVersionElem.textContent = data.updates_available
  753. ? `Latest Version: ${data.latest_remote_tag}`
  754. : 'You are up to date!';
  755. } catch (error) {
  756. console.error('Error checking for updates:', error);
  757. }
  758. }
  759. async function updateSoftware() {
  760. const updateButton = document.getElementById('update-software-btn');
  761. try {
  762. // Disable the button and update the text
  763. updateButton.disabled = true;
  764. updateButton.querySelector('span').textContent = 'Updating...';
  765. const response = await fetch('/update_software', { method: 'POST' });
  766. const data = await response.json();
  767. if (data.success) {
  768. logMessage('Software updated successfully!', LOG_TYPE.SUCCESS);
  769. window.location.reload(); // Reload the page after update
  770. } else {
  771. logMessage('Failed to update software: ' + data.error, LOG_TYPE.ERROR);
  772. }
  773. } catch (error) {
  774. console.error('Error updating software:', error);
  775. logMessage('Failed to update software', LOG_TYPE.ERROR);
  776. } finally {
  777. // Re-enable the button and reset the text
  778. updateButton.disabled = false;
  779. updateButton.textContent = 'Update Software'; // Adjust to the original text
  780. }
  781. }
  782. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  783. // PART A: Loading / listing playlists from the server
  784. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  785. async function loadAllPlaylists() {
  786. try {
  787. const response = await fetch('/list_all_playlists'); // GET
  788. const allPlaylists = await response.json(); // e.g. ["My Playlist", "Summer", ...]
  789. displayAllPlaylists(allPlaylists);
  790. } catch (err) {
  791. logMessage(`Error loading playlists: ${err}`, LOG_TYPE.ERROR);
  792. }
  793. }
  794. // Function to display all playlists with Load, Run, and Delete buttons
  795. function displayAllPlaylists(playlists) {
  796. const ul = document.getElementById('all_playlists');
  797. ul.innerHTML = ''; // Clear current list
  798. if (playlists.length === 0) {
  799. // Add a placeholder if the list is empty
  800. const emptyLi = document.createElement('li');
  801. emptyLi.textContent = "You don't have any playlists yet.";
  802. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  803. ul.appendChild(emptyLi);
  804. return;
  805. }
  806. playlists.forEach(playlistName => {
  807. const li = document.createElement('li');
  808. li.textContent = playlistName;
  809. li.classList.add('playlist-item'); // Add a class for styling
  810. // Attach click event to handle selection
  811. li.onclick = () => {
  812. // Remove 'selected' class from all items
  813. document.querySelectorAll('#all_playlists li').forEach(item => {
  814. item.classList.remove('selected');
  815. });
  816. // Add 'selected' class to the clicked item
  817. li.classList.add('selected');
  818. // Open the playlist editor for the selected playlist
  819. openPlaylistEditor(playlistName);
  820. };
  821. ul.appendChild(li);
  822. });
  823. }
  824. // Cancel changes and close the editor
  825. function cancelPlaylistChanges() {
  826. playlist = [...originalPlaylist]; // Revert to the original playlist
  827. isPlaylistChanged = false;
  828. toggleSaveCancelButtons(false); // Hide the save and cancel buttons
  829. refreshPlaylistUI(); // Refresh the UI with the original state
  830. closeStickySection('playlist-editor'); // Close the editor
  831. }
  832. // Open the playlist editor
  833. function openPlaylistEditor(playlistName) {
  834. logMessage(`Opening editor for playlist: ${playlistName}`);
  835. const editorSection = document.getElementById('playlist-editor');
  836. // Update the displayed playlist name
  837. document.getElementById('playlist_name_display').textContent = playlistName;
  838. // Store the current playlist name for renaming
  839. document.getElementById('playlist_name_input').value = playlistName;
  840. editorSection.classList.remove('hidden');
  841. editorSection.classList.add('visible');
  842. loadPlaylist(playlistName);
  843. }
  844. function clearSchedule() {
  845. document.getElementById("start_time").value = "";
  846. document.getElementById("end_time").value = "";
  847. document.getElementById('clear_time').style.display = 'none';
  848. setCookie('start_time', '', 365);
  849. setCookie('end_time', '', 365);
  850. }
  851. // Function to run the selected playlist with specified parameters
  852. async function runPlaylist() {
  853. const playlistName = document.getElementById('playlist_name_display').textContent;
  854. if (!playlistName) {
  855. logMessage('No playlist selected', 'error');
  856. return;
  857. }
  858. const pauseTime = parseFloat(document.getElementById('pause_time').value) || 0;
  859. const clearPattern = document.getElementById('clear_pattern').value;
  860. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  861. const shuffle = document.getElementById('shuffle_playlist').checked;
  862. try {
  863. const response = await fetch('/run_playlist', {
  864. method: 'POST',
  865. headers: {
  866. 'Content-Type': 'application/json',
  867. },
  868. body: JSON.stringify({
  869. playlist_name: playlistName,
  870. pause_time: pauseTime,
  871. clear_pattern: clearPattern,
  872. run_mode: runMode,
  873. shuffle: shuffle
  874. })
  875. });
  876. if (!response.ok) {
  877. if (response.status === 409) {
  878. logMessage('Another pattern is already running', 'warning');
  879. } else {
  880. const errorData = await response.json();
  881. logMessage(errorData.detail || 'Failed to run playlist', 'error');
  882. }
  883. return;
  884. }
  885. // Connect WebSocket when starting a playlist
  886. connectStatusWebSocket();
  887. logMessage(`Started playlist: ${playlistName}`, 'success');
  888. // Close the playlist editor container after successfully starting the playlist
  889. closeStickySection('playlist-editor');
  890. } catch (error) {
  891. logMessage('Error running playlist: ' + error, 'error');
  892. }
  893. }
  894. // Track changes in the playlist
  895. let originalPlaylist = [];
  896. let isPlaylistChanged = false;
  897. // Load playlist and set the original state
  898. async function loadPlaylist(playlistName) {
  899. try {
  900. logMessage(`Loading playlist: ${playlistName}`);
  901. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  902. const data = await response.json();
  903. if (!data.name) {
  904. throw new Error('Playlist name is missing in the response.');
  905. }
  906. // Populate playlist items and set original state
  907. playlist = data.files || [];
  908. originalPlaylist = [...playlist]; // Clone the playlist as the original
  909. isPlaylistChanged = false; // Reset change tracking
  910. toggleSaveCancelButtons(false); // Hide the save and cancel buttons initially
  911. refreshPlaylistUI();
  912. logMessage(`Loaded playlist: "${playlistName}" with ${playlist.length} file(s).`);
  913. } catch (err) {
  914. logMessage(`Error loading playlist: ${err.message}`, LOG_TYPE.ERROR);
  915. console.error('Error details:', err);
  916. }
  917. }
  918. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  919. // PART B: Creating or Saving (Overwriting) a Playlist
  920. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  921. // Instead of separate create/modify functions, we'll unify them:
  922. async function savePlaylist() {
  923. const name = document.getElementById('playlist_name_display').textContent
  924. if (!name) {
  925. logMessage("Please enter a playlist name.");
  926. return;
  927. }
  928. if (playlist.length === 0) {
  929. logMessage("No files in this playlist. Add files first.");
  930. return;
  931. }
  932. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  933. try {
  934. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  935. // Let's use /create_playlist to always overwrite or create anew.
  936. const response = await fetch('/create_playlist', {
  937. method: 'POST',
  938. headers: { 'Content-Type': 'application/json' },
  939. body: JSON.stringify({
  940. playlist_name: name,
  941. files: playlist
  942. })
  943. });
  944. const result = await response.json();
  945. if (result.success) {
  946. logMessage(`Playlist "${name}" with ${playlist.length} patterns saved`, LOG_TYPE.SUCCESS);
  947. // Reload the entire list of playlists to reflect changes
  948. // Check for changes and refresh the UI
  949. detectPlaylistChanges();
  950. refreshPlaylistUI();
  951. // Restore default action buttons
  952. toggleSaveCancelButtons(false);
  953. } else {
  954. logMessage(`Failed to save playlist: ${result.error}`, LOG_TYPE.ERROR);
  955. }
  956. } catch (err) {
  957. logMessage(`Error saving playlist: ${err}`);
  958. }
  959. }
  960. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  961. // PART C: Renaming and Deleting a playlist
  962. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  963. // Toggle the rename playlist input
  964. function populatePlaylistDropdown() {
  965. return fetch('/list_all_playlists')
  966. .then(response => response.json())
  967. .then(playlists => {
  968. const select = document.getElementById('select-playlist');
  969. select.innerHTML = ''; // Clear existing options
  970. // Retrieve the saved playlist from the cookie
  971. const savedPlaylist = getCookie('selected_playlist');
  972. // Check if there are playlists available
  973. if (playlists.length === 0) {
  974. // Add a placeholder option if no playlists are available
  975. const placeholderOption = document.createElement('option');
  976. placeholderOption.value = '';
  977. placeholderOption.textContent = 'No playlists available';
  978. placeholderOption.disabled = true; // Prevent selection
  979. placeholderOption.selected = true; // Set as default
  980. select.appendChild(placeholderOption);
  981. return;
  982. }
  983. playlists.forEach(playlist => {
  984. const option = document.createElement('option');
  985. option.value = playlist;
  986. option.textContent = playlist;
  987. // Mark the saved playlist as selected
  988. if (playlist === savedPlaylist) {
  989. option.selected = true;
  990. }
  991. select.appendChild(option);
  992. });
  993. // Attach the onchange event listener after populating the dropdown
  994. select.addEventListener('change', function () {
  995. const selectedPlaylist = this.value;
  996. setCookie('selected_playlist', selectedPlaylist, 365); // Save to cookie
  997. logMessage(`Selected playlist saved: ${selectedPlaylist}`);
  998. });
  999. logMessage('Playlist dropdown populated, event listener attached, and saved playlist restored.');
  1000. })
  1001. .catch(error => logMessage(`Error fetching playlists: ${error.message}`));
  1002. }
  1003. populatePlaylistDropdown().then(() => {
  1004. loadSettingsFromCookies(); // Restore selected playlist after populating the dropdown
  1005. });
  1006. // Confirm and save the renamed playlist
  1007. async function confirmAddPlaylist() {
  1008. const playlistNameInput = document.getElementById('new_playlist_name');
  1009. const playlistName = playlistNameInput.value.trim();
  1010. if (!playlistName) {
  1011. logMessage('Playlist name cannot be empty.', LOG_TYPE.ERROR);
  1012. return;
  1013. }
  1014. try {
  1015. logMessage(`Adding new playlist: "${playlistName}"...`);
  1016. const response = await fetch('/create_playlist', {
  1017. method: 'POST',
  1018. headers: { 'Content-Type': 'application/json' },
  1019. body: JSON.stringify({
  1020. playlist_name: playlistName,
  1021. files: [] // New playlist starts empty
  1022. })
  1023. });
  1024. const result = await response.json();
  1025. if (result.success) {
  1026. logMessage(`Playlist "${playlistName}" created successfully.`, LOG_TYPE.SUCCESS);
  1027. // Clear the input field
  1028. playlistNameInput.value = '';
  1029. // Refresh the playlist list
  1030. loadAllPlaylists();
  1031. populatePlaylistDropdown();
  1032. // Hide the add playlist container
  1033. toggleSecondaryButtons('add-playlist-container');
  1034. } else {
  1035. logMessage(`Failed to create playlist: ${result.error}`, LOG_TYPE.ERROR);
  1036. }
  1037. } catch (error) {
  1038. logMessage(`Error creating playlist: ${error.message}`);
  1039. }
  1040. }
  1041. async function confirmRenamePlaylist() {
  1042. const newName = document.getElementById('playlist_name_input').value.trim();
  1043. const currentName = document.getElementById('playlist_name_display').textContent;
  1044. if (!newName) {
  1045. logMessage("New playlist name cannot be empty.", LOG_TYPE.ERROR);
  1046. return;
  1047. }
  1048. if (newName === currentName) {
  1049. logMessage("New playlist name is the same as the current name. No changes made.", LOG_TYPE.WARNING);
  1050. toggleSecondaryButtons('rename-playlist-container'); // Close the rename container
  1051. return;
  1052. }
  1053. try {
  1054. // Step 1: Create/Modify the playlist with the new name
  1055. const createResponse = await fetch('/modify_playlist', {
  1056. method: 'POST',
  1057. headers: { 'Content-Type': 'application/json' },
  1058. body: JSON.stringify({
  1059. playlist_name: newName,
  1060. files: playlist // Ensure `playlist` contains the current list of files
  1061. })
  1062. });
  1063. const createResult = await createResponse.json();
  1064. if (createResult.success) {
  1065. logMessage(createResult.message, LOG_TYPE.SUCCESS);
  1066. // Step 2: Delete the old playlist
  1067. const deleteResponse = await fetch('/delete_playlist', {
  1068. method: 'DELETE',
  1069. headers: { 'Content-Type': 'application/json' },
  1070. body: JSON.stringify({ playlist_name: currentName })
  1071. });
  1072. const deleteResult = await deleteResponse.json();
  1073. if (deleteResult.success) {
  1074. logMessage(deleteResult.message);
  1075. // Update the UI with the new name
  1076. document.getElementById('playlist_name_display').textContent = newName;
  1077. // Refresh playlists list
  1078. loadAllPlaylists();
  1079. // Close the rename container and restore original action buttons
  1080. toggleSecondaryButtons('rename-playlist-container');
  1081. } else {
  1082. logMessage(`Failed to delete old playlist: ${deleteResult.error}`, LOG_TYPE.ERROR);
  1083. }
  1084. } else {
  1085. logMessage(`Failed to rename playlist: ${createResult.error}`, LOG_TYPE.ERROR);
  1086. }
  1087. } catch (error) {
  1088. logMessage(`Error renaming playlist: ${error.message}`);
  1089. }
  1090. }
  1091. // Delete the currently opened playlist
  1092. async function deleteCurrentPlaylist() {
  1093. const playlistName = document.getElementById('playlist_name_display').textContent;
  1094. if (!confirm(`Are you sure you want to delete the playlist "${playlistName}"? This action cannot be undone.`)) {
  1095. return;
  1096. }
  1097. try {
  1098. const response = await fetch('/delete_playlist', {
  1099. method: 'DELETE',
  1100. headers: { 'Content-Type': 'application/json' },
  1101. body: JSON.stringify({ playlist_name: playlistName })
  1102. });
  1103. const result = await response.json();
  1104. if (result.success) {
  1105. logMessage(`Playlist "${playlistName}" deleted.`, LOG_TYPE.INFO);
  1106. closeStickySection('playlist-editor');
  1107. loadAllPlaylists();
  1108. populatePlaylistDropdown();
  1109. } else {
  1110. logMessage(`Failed to delete playlist: ${result.error}`, LOG_TYPE.ERROR);
  1111. }
  1112. } catch (error) {
  1113. logMessage(`Error deleting playlist: ${error.message}`);
  1114. }
  1115. }
  1116. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1117. // PART D: Local playlist array UI
  1118. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1119. // Refresh the playlist UI and detect changes
  1120. function refreshPlaylistUI() {
  1121. const ul = document.getElementById('playlist_items');
  1122. if (!ul) {
  1123. logMessage('Error: Playlist container not found');
  1124. return;
  1125. }
  1126. ul.innerHTML = ''; // Clear existing items
  1127. if (playlist.length === 0) {
  1128. // Add a placeholder if the playlist is empty
  1129. const emptyLi = document.createElement('li');
  1130. emptyLi.textContent = 'No items in the playlist.';
  1131. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  1132. ul.appendChild(emptyLi);
  1133. return;
  1134. }
  1135. playlist.forEach((file, index) => {
  1136. const li = document.createElement('li');
  1137. // Add filename in a span
  1138. const filenameSpan = document.createElement('span');
  1139. filenameSpan.textContent = file;
  1140. filenameSpan.classList.add('filename'); // Add a class for styling
  1141. li.appendChild(filenameSpan);
  1142. // Move Up button
  1143. const moveUpBtn = document.createElement('button');
  1144. moveUpBtn.innerHTML = '<i class="fa-solid fa-turn-up"></i>'; // Up arrow symbol
  1145. moveUpBtn.classList.add('move-button');
  1146. moveUpBtn.onclick = () => {
  1147. if (index > 0) {
  1148. const temp = playlist[index - 1];
  1149. playlist[index - 1] = playlist[index];
  1150. playlist[index] = temp;
  1151. detectPlaylistChanges(); // Check for changes
  1152. refreshPlaylistUI();
  1153. }
  1154. };
  1155. li.appendChild(moveUpBtn);
  1156. // Move Down button
  1157. const moveDownBtn = document.createElement('button');
  1158. moveDownBtn.innerHTML = '<i class="fa-solid fa-turn-down"></i>'; // Down arrow symbol
  1159. moveDownBtn.classList.add('move-button');
  1160. moveDownBtn.onclick = () => {
  1161. if (index < playlist.length - 1) {
  1162. const temp = playlist[index + 1];
  1163. playlist[index + 1] = playlist[index];
  1164. playlist[index] = temp;
  1165. detectPlaylistChanges(); // Check for changes
  1166. refreshPlaylistUI();
  1167. }
  1168. };
  1169. li.appendChild(moveDownBtn);
  1170. // Remove button
  1171. const removeBtn = document.createElement('button');
  1172. removeBtn.innerHTML = '<i class="fa-solid fa-trash"></i>';
  1173. removeBtn.classList.add('remove-button');
  1174. removeBtn.onclick = () => {
  1175. playlist.splice(index, 1);
  1176. detectPlaylistChanges(); // Check for changes
  1177. refreshPlaylistUI();
  1178. };
  1179. li.appendChild(removeBtn);
  1180. ul.appendChild(li);
  1181. });
  1182. }
  1183. // Toggle the visibility of the save and cancel buttons
  1184. function toggleSaveCancelButtons(show) {
  1185. const actionButtons = document.querySelector('#playlist-editor .action-buttons');
  1186. if (actionButtons) {
  1187. // Show/hide all buttons except Save and Cancel
  1188. actionButtons.querySelectorAll('button:not(.save-cancel)').forEach(button => {
  1189. button.style.display = show ? 'none' : 'flex';
  1190. });
  1191. // Show/hide Save and Cancel buttons
  1192. actionButtons.querySelectorAll('.save-cancel').forEach(button => {
  1193. button.style.display = show ? 'flex' : 'none';
  1194. });
  1195. } else {
  1196. logMessage('Error: Action buttons container not found.', LOG_TYPE.ERROR);
  1197. }
  1198. }
  1199. // Detect changes in the playlist
  1200. function detectPlaylistChanges() {
  1201. isPlaylistChanged = JSON.stringify(originalPlaylist) !== JSON.stringify(playlist);
  1202. toggleSaveCancelButtons(isPlaylistChanged);
  1203. }
  1204. // Toggle the "Add to Playlist" section
  1205. function toggleSecondaryButtons(containerId, onShowCallback = null) {
  1206. const container = document.getElementById(containerId);
  1207. if (!container) {
  1208. logMessage(`Error: Element with ID "${containerId}" not found`);
  1209. return;
  1210. }
  1211. // Find the .action-buttons element preceding the container
  1212. const previousActionButtons = container.previousElementSibling?.classList.contains('action-buttons')
  1213. ? container.previousElementSibling
  1214. : null;
  1215. if (container.classList.contains('hidden')) {
  1216. // Show the container
  1217. container.classList.remove('hidden');
  1218. // Hide the previous .action-buttons element
  1219. if (previousActionButtons) {
  1220. previousActionButtons.style.display = 'none';
  1221. }
  1222. // Optional callback for custom logic when showing the container
  1223. if (onShowCallback) {
  1224. onShowCallback();
  1225. }
  1226. } else {
  1227. // Hide the container
  1228. container.classList.add('hidden');
  1229. // Restore the previous .action-buttons element
  1230. if (previousActionButtons) {
  1231. previousActionButtons.style.display = 'flex';
  1232. }
  1233. }
  1234. }
  1235. // Add the selected pattern to the selected playlist
  1236. async function saveToPlaylist() {
  1237. const playlist = document.getElementById('select-playlist').value;
  1238. if (!playlist) {
  1239. logMessage('No playlist selected.', LOG_TYPE.ERROR);
  1240. return;
  1241. }
  1242. if (!selectedFile) {
  1243. logMessage('No pattern selected to add.', LOG_TYPE.ERROR);
  1244. return;
  1245. }
  1246. try {
  1247. logMessage(`Adding pattern "${selectedFile}" to playlist "${playlist}"...`);
  1248. const response = await fetch('/add_to_playlist', {
  1249. method: 'POST',
  1250. headers: { 'Content-Type': 'application/json' },
  1251. body: JSON.stringify({ playlist_name: playlist, pattern: selectedFile })
  1252. });
  1253. const result = await response.json();
  1254. if (result.success) {
  1255. logMessage(`Pattern "${selectedFile}" successfully added to playlist "${playlist}".`, LOG_TYPE.SUCCESS);
  1256. // Reset the UI state via toggleSecondaryButtons
  1257. toggleSecondaryButtons('add-to-playlist-container', () => {
  1258. const selectPlaylist = document.getElementById('select-playlist');
  1259. selectPlaylist.value = ''; // Clear the selection
  1260. });
  1261. } else {
  1262. logMessage(`Failed to add pattern to playlist: ${result.error}`, LOG_TYPE.ERROR);
  1263. }
  1264. } catch (error) {
  1265. logMessage(`Error adding pattern to playlist: ${error.message}`);
  1266. }
  1267. }
  1268. async function changeSpeed() {
  1269. const speedInput = document.getElementById('speed_input');
  1270. const speed = parseFloat(speedInput.value);
  1271. if (isNaN(speed) || speed <= 0) {
  1272. logMessage('Invalid speed. Please enter a positive number.');
  1273. return;
  1274. }
  1275. logMessage(`Setting speed to: ${speed}...`);
  1276. const response = await fetch('/set_speed', {
  1277. method: 'POST',
  1278. headers: { 'Content-Type': 'application/json' },
  1279. body: JSON.stringify({ speed })
  1280. });
  1281. const result = await response.json();
  1282. if (result.success) {
  1283. document.getElementById('current_speed_display').textContent = `Current Speed: ${speed}`;
  1284. logMessage(`Speed set to: ${speed}`, LOG_TYPE.SUCCESS);
  1285. } else {
  1286. logMessage(`Failed to set speed: ${result.error}`, LOG_TYPE.ERROR);
  1287. }
  1288. }
  1289. // Function to close any sticky section
  1290. function closeStickySection(sectionId) {
  1291. const section = document.getElementById(sectionId);
  1292. if (section) {
  1293. section.classList.remove('visible');
  1294. section.classList.remove('fullscreen');
  1295. section.classList.add('hidden');
  1296. // Reset the fullscreen button text if it exists
  1297. const fullscreenButton = section.querySelector('.fullscreen-button');
  1298. if (fullscreenButton) {
  1299. fullscreenButton.innerHtml = '<i class="fa-solid fa-compress"></i>'; // Reset to enter fullscreen icon/text
  1300. }
  1301. logMessage(`Closed section: ${sectionId}`);
  1302. if(sectionId === 'playlist-editor') {
  1303. document.querySelectorAll('#all_playlists .playlist-item').forEach(item => {
  1304. item.classList.remove('selected');
  1305. });
  1306. }
  1307. if(sectionId === 'pattern-preview-container') {
  1308. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1309. item.classList.remove('selected');
  1310. });
  1311. }
  1312. } else {
  1313. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1314. }
  1315. }
  1316. // Function to open any sticky section
  1317. function openStickySection(sectionId) {
  1318. const section = document.getElementById(sectionId);
  1319. if (section) {
  1320. // Toggle the 'open' class
  1321. section.classList.toggle('open');
  1322. } else {
  1323. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1324. }
  1325. }
  1326. function attachFullScreenListeners() {
  1327. // Add event listener to all fullscreen buttons
  1328. document.querySelectorAll('.fullscreen-button').forEach(button => {
  1329. button.addEventListener('click', function () {
  1330. const stickySection = this.closest('.sticky'); // Find the closest sticky section
  1331. if (stickySection) {
  1332. // Close all other sections
  1333. document.querySelectorAll('.sticky:not(#currently-playing-container):not(#image-converter)').forEach(section => {
  1334. if (section !== stickySection) {
  1335. section.classList.remove('fullscreen');
  1336. section.classList.remove('visible');
  1337. section.classList.add('hidden');
  1338. // Reset the fullscreen button text for other sections
  1339. const otherFullscreenButton = section.querySelector('.fullscreen-button');
  1340. if (otherFullscreenButton) {
  1341. otherFullscreenButton.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1342. }
  1343. }
  1344. });
  1345. stickySection.classList.toggle('fullscreen'); // Toggle fullscreen class
  1346. // Update button icon or text
  1347. if (stickySection.classList.contains('fullscreen')) {
  1348. this.innerHTML = '<i class="fa-solid fa-compress"></i>'; // Exit fullscreen icon/text
  1349. } else {
  1350. this.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1351. }
  1352. } else {
  1353. console.error('Error: Fullscreen button is not inside a sticky section.');
  1354. }
  1355. });
  1356. });
  1357. }
  1358. let lastPreviewedFile = null; // Track the last previewed file
  1359. function formatSecondsToHMS(seconds) {
  1360. const hrs = Math.floor(seconds / 3600);
  1361. const mins = Math.floor((seconds % 3600) / 60);
  1362. const secs = Math.floor(seconds % 60);
  1363. return `${String(hrs).padStart(2, '0')}:${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
  1364. }
  1365. // Function to start or stop updates based on visibility
  1366. function toggleSettings() {
  1367. const settingsContainer = document.getElementById('settings-container');
  1368. if (settingsContainer) {
  1369. settingsContainer.classList.toggle('open');
  1370. }
  1371. }
  1372. // Utility function to manage cookies
  1373. function setCookie(name, value, days) {
  1374. const date = new Date();
  1375. date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  1376. document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
  1377. }
  1378. function getCookie(name) {
  1379. const nameEQ = `${name}=`;
  1380. const cookies = document.cookie.split(';');
  1381. for (let i = 0; i < cookies.length; i++) {
  1382. let cookie = cookies[i].trim();
  1383. if (cookie.startsWith(nameEQ)) {
  1384. return cookie.substring(nameEQ.length);
  1385. }
  1386. }
  1387. return null;
  1388. }
  1389. // Save settings to cookies
  1390. function saveSettingsToCookies() {
  1391. const pauseTime = document.getElementById('pause_time').value;
  1392. const clearPattern = document.getElementById('clear_pattern').value;
  1393. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  1394. const shuffle = document.getElementById('shuffle_playlist').checked;
  1395. const apiKey = document.getElementById('api-key').value;
  1396. setCookie('pause_time', pauseTime, 365);
  1397. setCookie('clear_pattern', clearPattern, 365);
  1398. setCookie('run_mode', runMode, 365);
  1399. setCookie('shuffle', shuffle, 365);
  1400. setCookie('api_key', apiKey, 365);
  1401. }
  1402. // Load settings from cookies
  1403. function loadSettingsFromCookies() {
  1404. const pauseTime = getCookie('pause_time');
  1405. if (pauseTime !== '') {
  1406. const pauseTimeElement = document.getElementById('pause_time');
  1407. if (pauseTimeElement) {
  1408. pauseTimeElement.value = pauseTime;
  1409. }
  1410. }
  1411. const clearPattern = getCookie('clear_pattern');
  1412. if (clearPattern !== '') {
  1413. const clearPatternElement = document.getElementById('clear_pattern');
  1414. if (clearPatternElement) {
  1415. clearPatternElement.value = clearPattern;
  1416. }
  1417. }
  1418. const runMode = getCookie('run_mode');
  1419. if (runMode !== '') {
  1420. const runModeElement = document.querySelector(`input[name="run_mode"][value="${runMode}"]`);
  1421. if (runModeElement) {
  1422. runModeElement.checked = true;
  1423. }
  1424. }
  1425. const shuffle = getCookie('shuffle');
  1426. if (shuffle !== '') {
  1427. const shuffleElement = document.getElementById('shuffle_playlist');
  1428. if (shuffleElement) {
  1429. shuffleElement.checked = shuffle === 'true';
  1430. }
  1431. }
  1432. const apiKey = getCookie('api_key');
  1433. if (apiKey !== '') {
  1434. const apiKeyElement = document.getElementById('api-key');
  1435. if (apiKeyElement) {
  1436. apiKeyElement.value = apiKey;
  1437. }
  1438. }
  1439. logMessage('Settings loaded from cookies.');
  1440. }
  1441. // Call this function to save settings when a value is changed
  1442. function attachSettingsSaveListeners() {
  1443. // Add event listeners to inputs
  1444. document.getElementById('pause_time').addEventListener('change', saveSettingsToCookies);
  1445. document.getElementById('clear_pattern').addEventListener('change', saveSettingsToCookies);
  1446. document.querySelectorAll('input[name="run_mode"]').forEach(input => {
  1447. input.addEventListener('change', saveSettingsToCookies);
  1448. });
  1449. document.getElementById('shuffle_playlist').addEventListener('change', saveSettingsToCookies);
  1450. document.getElementById('api-key').addEventListener('change', saveSettingsToCookies);
  1451. }
  1452. // Tab switching logic with cookie storage
  1453. function switchTab(tabName, tabGroup = 'main') {
  1454. // Store the active tab in a cookie (per tab group)
  1455. setCookie(`activeTab-${tabGroup}`, tabName, 365);
  1456. // Deactivate all tab content in the specific group
  1457. document.querySelectorAll(`.tab-content[data-group="${tabGroup}"]`).forEach(tab => {
  1458. tab.classList.remove('active');
  1459. });
  1460. // Activate the selected tab content
  1461. const activeTab = document.getElementById(`${tabName}-tab`);
  1462. if (activeTab) {
  1463. activeTab.classList.add('active');
  1464. } else {
  1465. console.error(`Error: Tab "${tabName}" not found.`);
  1466. }
  1467. // Deactivate all buttons in this group
  1468. document.querySelectorAll(`.tab-button[data-group="${tabGroup}"]`).forEach(button => {
  1469. button.classList.remove('active');
  1470. });
  1471. // Activate the selected nav button
  1472. const activeNavButton = document.getElementById(`nav-${tabName}`);
  1473. if (activeNavButton) {
  1474. activeNavButton.classList.add('active');
  1475. } else {
  1476. console.error(`Error: Nav button for "${tabName}" not found.`);
  1477. }
  1478. }
  1479. // Update the small UI segment to show the IP or hide it if none
  1480. function updateWledUI() {
  1481. const wledIp = localStorage.getItem('wled_ip');
  1482. const wledContainer = document.getElementById('wled-container');
  1483. const wledFrame = document.getElementById('wled-frame');
  1484. const wledStatus = document.getElementById('wled-status');
  1485. if (!wledIp) {
  1486. wledContainer.classList.add('hidden');
  1487. return;
  1488. }
  1489. // Show the container and load WLED UI
  1490. wledContainer.classList.remove('hidden');
  1491. wledFrame.src = `http://${wledIp}`;
  1492. }
  1493. // Save or clear the WLED IP, updating both the browser and backend
  1494. async function saveWledIp() {
  1495. const ipInput = document.getElementById('wled_ip');
  1496. const saveButton = document.querySelector('.wled-settings button.cta');
  1497. const currentIp = localStorage.getItem('wled_ip');
  1498. if (currentIp) {
  1499. // Clear the saved IP if one is already set
  1500. localStorage.removeItem('wled_ip');
  1501. ipInput.disabled = false;
  1502. ipInput.value = '';
  1503. saveButton.innerHTML = '<i class="fa-solid fa-save"></i><span>Save</span>';
  1504. logMessage('WLED IP cleared.', LOG_TYPE.INFO);
  1505. // Also clear the IP on the backend
  1506. try {
  1507. const response = await fetch('/set_wled_ip', {
  1508. method: 'POST',
  1509. headers: { 'Content-Type': 'application/json' },
  1510. body: JSON.stringify({ wled_ip: null })
  1511. });
  1512. const data = await response.json();
  1513. if (data.success) {
  1514. logMessage('Backend IP cleared successfully.', LOG_TYPE.INFO);
  1515. } else {
  1516. logMessage('Failed to clear backend IP.', LOG_TYPE.ERROR);
  1517. }
  1518. } catch (error) {
  1519. logMessage(`Error clearing backend IP: ${error.message}`, LOG_TYPE.ERROR);
  1520. }
  1521. } else {
  1522. // Validate and save the new IP
  1523. const ip = ipInput.value.trim();
  1524. if (!validateIp(ip)) {
  1525. logMessage('Invalid IP address format.', LOG_TYPE.ERROR);
  1526. return;
  1527. }
  1528. localStorage.setItem('wled_ip', ip);
  1529. ipInput.disabled = true;
  1530. saveButton.innerHTML = '<i class="fa-solid fa-xmark"></i><span>Clear</span>';
  1531. logMessage(`WLED IP saved: ${ip}`, LOG_TYPE.SUCCESS);
  1532. // Also save the IP to the backend
  1533. try {
  1534. const response = await fetch('/set_wled_ip', {
  1535. method: 'POST',
  1536. headers: { 'Content-Type': 'application/json' },
  1537. body: JSON.stringify({ wled_ip: ip })
  1538. });
  1539. const data = await response.json();
  1540. if (data.success) {
  1541. logMessage('Backend IP saved successfully.', LOG_TYPE.SUCCESS);
  1542. } else {
  1543. logMessage('Failed to save backend IP.', LOG_TYPE.ERROR);
  1544. }
  1545. } catch (error) {
  1546. logMessage(`Error saving backend IP: ${error.message}`, LOG_TYPE.ERROR);
  1547. }
  1548. }
  1549. updateWledUI(); // Refresh any UI elements that depend on the IP
  1550. }
  1551. // Load the WLED IP from localStorage; if not available, retrieve it from the backend
  1552. async function loadWledIp() {
  1553. const ipInput = document.getElementById('wled_ip');
  1554. const saveButton = document.querySelector('.wled-settings button.cta');
  1555. let savedIp = localStorage.getItem('wled_ip');
  1556. if (!savedIp) {
  1557. // Attempt to load from the backend if not found in localStorage
  1558. try {
  1559. const response = await fetch('/get_wled_ip');
  1560. const data = await response.json();
  1561. if (data.wled_ip) {
  1562. savedIp = data.wled_ip;
  1563. localStorage.setItem('wled_ip', savedIp);
  1564. }
  1565. } catch (error) {
  1566. logMessage(`Error fetching WLED IP from backend: ${error.message}`, LOG_TYPE.ERROR);
  1567. }
  1568. }
  1569. if (savedIp) {
  1570. ipInput.value = savedIp;
  1571. ipInput.disabled = true;
  1572. saveButton.innerHTML = '<i class="fa-solid fa-xmark"></i><span>Clear</span>';
  1573. } else {
  1574. ipInput.disabled = false;
  1575. saveButton.innerHTML = '<i class="fa-solid fa-save"></i><span>Save</span>';
  1576. }
  1577. updateWledUI(); // Update any dependent UI segments
  1578. }
  1579. function validateIp(ip) {
  1580. 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}$/;
  1581. return ipRegex.test(ip);
  1582. }
  1583. // Theme toggle functionality
  1584. const themeToggle = document.getElementById('theme-toggle');
  1585. const themeIcon = themeToggle.querySelector('i');
  1586. themeToggle.addEventListener('click', () => {
  1587. const root = document.documentElement;
  1588. const currentTheme = root.getAttribute('data-theme');
  1589. const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
  1590. root.setAttribute('data-theme', newTheme);
  1591. localStorage.setItem('theme', newTheme);
  1592. // Toggle the icon
  1593. themeIcon.className = newTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
  1594. });
  1595. // Set initial theme and icon based on saved theme
  1596. const savedTheme = localStorage.getItem('theme') || 'light';
  1597. document.documentElement.setAttribute('data-theme', savedTheme);
  1598. themeIcon.className = savedTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
  1599. // Add WebSocket connection for status updates
  1600. let statusSocket = null;
  1601. let reconnectAttempts = 0;
  1602. const MAX_RECONNECT_ATTEMPTS = 5;
  1603. let statusUpdateInterval = null;
  1604. let wsConnected = false;
  1605. function connectStatusWebSocket() {
  1606. // Don't create a new connection if one already exists
  1607. if (wsConnected) {
  1608. console.log('WebSocket already connected');
  1609. return;
  1610. }
  1611. // Close existing connection and clear interval if any
  1612. if (statusSocket) {
  1613. statusSocket.close();
  1614. }
  1615. if (statusUpdateInterval) {
  1616. clearInterval(statusUpdateInterval);
  1617. }
  1618. // Create WebSocket connection
  1619. const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
  1620. statusSocket = new WebSocket(`${protocol}//${window.location.host}/ws/status`);
  1621. statusSocket.onopen = () => {
  1622. console.log('Status WebSocket connected');
  1623. wsConnected = true;
  1624. reconnectAttempts = 0; // Reset reconnect attempts on successful connection
  1625. };
  1626. statusSocket.onmessage = (event) => {
  1627. try {
  1628. const message = JSON.parse(event.data);
  1629. if (message.type === 'status_update' && message.data) {
  1630. updateCurrentlyPlayingUI(message.data);
  1631. // Disconnect WebSocket if no pattern is running
  1632. if (!message.data.is_running) {
  1633. console.log('No pattern running, disconnecting WebSocket');
  1634. disconnectStatusWebSocket();
  1635. }
  1636. }
  1637. } catch (error) {
  1638. console.error('Error processing status update:', error);
  1639. console.error('Raw data that caused error:', event.data);
  1640. }
  1641. };
  1642. statusSocket.onclose = () => {
  1643. console.log('Status WebSocket disconnected');
  1644. wsConnected = false;
  1645. clearInterval(statusUpdateInterval);
  1646. // Only attempt to reconnect if we're supposed to be connected
  1647. if (reconnectAttempts < MAX_RECONNECT_ATTEMPTS && document.body.classList.contains('playing')) {
  1648. reconnectAttempts++;
  1649. const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);
  1650. console.log(`Reconnecting in ${delay/1000}s (Attempt ${reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`);
  1651. setTimeout(connectStatusWebSocket, delay);
  1652. }
  1653. };
  1654. statusSocket.onerror = (error) => {
  1655. console.error('WebSocket error:', error);
  1656. };
  1657. }
  1658. function disconnectStatusWebSocket() {
  1659. if (statusSocket && wsConnected) {
  1660. wsConnected = false;
  1661. statusSocket.close();
  1662. statusSocket = null;
  1663. reconnectAttempts = 0;
  1664. }
  1665. }
  1666. // Replace the polling mechanism with WebSocket
  1667. document.addEventListener('DOMContentLoaded', () => {
  1668. const activeMainTab = getCookie('activeTab-main') || 'patterns';
  1669. switchTab(activeMainTab, 'main');
  1670. const activeImageConverterTab = getCookie('activeTab-image-converter') || 'dot';
  1671. switchTab(activeImageConverterTab, 'image-converter');
  1672. checkSerialStatus(); // Check connection status
  1673. loadThetaRhoFiles(); // Load files on page load
  1674. loadAllPlaylists(); // Load all playlists on page load
  1675. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1676. attachFullScreenListeners();
  1677. loadWledIp();
  1678. updateWledUI();
  1679. // Initialize WebSocket connection for status updates
  1680. connectStatusWebSocket();
  1681. // Handle visibility change
  1682. document.addEventListener('visibilitychange', () => {
  1683. if (document.visibilityState === 'visible' && statusSocket && statusSocket.readyState !== WebSocket.OPEN) {
  1684. connectStatusWebSocket();
  1685. }
  1686. });
  1687. checkForUpdates();
  1688. });
  1689. // Track the last time we had a file playing
  1690. let lastPlayingTime = 0;
  1691. const HIDE_DELAY = 5000; // 1 second delay before hiding
  1692. // Update the updateCurrentlyPlayingUI function to handle WebSocket updates
  1693. // Track the last played file to detect when a new pattern starts
  1694. let lastPlayedFile = null;
  1695. function updateCurrentlyPlayingUI(status) {
  1696. // Get all required DOM elements once
  1697. const container = document.getElementById('currently-playing-container');
  1698. const fileNameElement = document.getElementById('currently-playing-file');
  1699. const progressBar = document.getElementById('play_progress');
  1700. const progressText = document.getElementById('play_progress_text');
  1701. const pausePlayButton = document.getElementById('pausePlayCurrent');
  1702. const speedDisplay = document.getElementById('current_speed_display');
  1703. // Check if all required elements exist
  1704. if (!container || !fileNameElement || !progressBar || !progressText) {
  1705. console.log('Required DOM elements not found:', {
  1706. container: !!container,
  1707. fileNameElement: !!fileNameElement,
  1708. progressBar: !!progressBar,
  1709. progressText: !!progressText
  1710. });
  1711. setTimeout(() => updateCurrentlyPlayingUI(status), 100);
  1712. return;
  1713. }
  1714. // Update container visibility based on status
  1715. if (status.current_file && status.is_running) {
  1716. document.body.classList.add('playing');
  1717. container.style.display = 'flex';
  1718. } else {
  1719. document.body.classList.remove('playing');
  1720. container.style.display = 'none';
  1721. }
  1722. // Update file name display
  1723. if (status.current_file) {
  1724. const fileName = status.current_file.replace('./patterns/', '');
  1725. fileNameElement.textContent = fileName;
  1726. } else {
  1727. fileNameElement.textContent = 'No pattern playing';
  1728. }
  1729. // Update next file display
  1730. const nextFileElement = document.getElementById('next-file');
  1731. if (nextFileElement) {
  1732. if (status.playlist && status.playlist.next_file) {
  1733. const nextFileName = status.playlist.next_file.replace('./patterns/', '');
  1734. nextFileElement.textContent = `(Next: ${nextFileName})`;
  1735. nextFileElement.style.display = 'block';
  1736. } else {
  1737. nextFileElement.style.display = 'none';
  1738. }
  1739. }
  1740. // Update speed display if it exists
  1741. if (speedDisplay && status.speed) {
  1742. speedDisplay.textContent = `Current Speed: ${status.speed}`;
  1743. }
  1744. // Update pattern preview if it's a new pattern
  1745. if (status.current_file && lastPlayedFile !== status.current_file) {
  1746. lastPlayedFile = status.current_file;
  1747. const cleanFileName = status.current_file.replace('./patterns/', '');
  1748. updateCurrentlyPlayingPattern(cleanFileName);
  1749. }
  1750. // Update progress information
  1751. if (status.progress) {
  1752. const { percentage, remaining_time, elapsed_time } = status.progress;
  1753. const formattedPercentage = percentage.toFixed(1);
  1754. const remainingText = remaining_time === null ? 'calculating...' : formatSecondsToHMS(remaining_time);
  1755. const elapsedText = formatSecondsToHMS(elapsed_time);
  1756. progressBar.value = formattedPercentage;
  1757. progressText.textContent = `${formattedPercentage}% (Elapsed: ${elapsedText} | Remaining: ${remainingText})`;
  1758. } else {
  1759. progressBar.value = 0;
  1760. progressText.textContent = '0%';
  1761. }
  1762. // Update pause/play button if it exists
  1763. if (pausePlayButton) {
  1764. pausePlayButton.innerHTML = status.is_paused ?
  1765. '<i class="fa-solid fa-play"></i>' :
  1766. '<i class="fa-solid fa-pause"></i>';
  1767. }
  1768. // Update playlist UI if the function exists
  1769. if (typeof updatePlaylistUI === 'function') {
  1770. updatePlaylistUI(status);
  1771. }
  1772. // Update skip button visibility based on playlist status
  1773. updateSkipButtonVisibility(status);
  1774. }
  1775. // Add these functions to handle the skip button
  1776. function updateSkipButtonVisibility(status) {
  1777. const skipButton = document.getElementById('skipCurrent');
  1778. if (skipButton) {
  1779. // Check if a playlist is playing using the correct status properties
  1780. console.log('status', status);
  1781. const isPlaylistPlaying = status && status.playlist && status.playlist.next_file;
  1782. if (isPlaylistPlaying) {
  1783. skipButton.classList.remove('hidden');
  1784. } else {
  1785. skipButton.classList.add('hidden');
  1786. }
  1787. }
  1788. }
  1789. async function skipPattern() {
  1790. try {
  1791. const response = await fetch('/skip_pattern', {
  1792. method: 'POST',
  1793. });
  1794. const data = await response.json();
  1795. if (data.success) {
  1796. logMessage('Skipping to next pattern', LOG_TYPE.INFO);
  1797. } else {
  1798. logMessage(data.message, LOG_TYPE.ERROR);
  1799. }
  1800. } catch (error) {
  1801. logMessage('Error skipping pattern', 'error');
  1802. }
  1803. }