main.js 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854
  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. // Save or clear the WLED IP, updating both the browser and backend
  1453. async function saveWledIp() {
  1454. const ipInput = document.getElementById('wled_ip');
  1455. const saveButton = document.querySelector('.wled-settings button.cta');
  1456. const currentIp = localStorage.getItem('wled_ip');
  1457. if (currentIp) {
  1458. // Clear the saved IP if one is already set
  1459. localStorage.removeItem('wled_ip');
  1460. ipInput.disabled = false;
  1461. ipInput.value = '';
  1462. saveButton.innerHTML = '<i class="fa-solid fa-save"></i><span>Save</span>';
  1463. logMessage('WLED IP cleared.', LOG_TYPE.INFO);
  1464. // Also clear the IP on the backend
  1465. try {
  1466. const response = await fetch('/set_wled_ip', {
  1467. method: 'POST',
  1468. headers: { 'Content-Type': 'application/json' },
  1469. body: JSON.stringify({ wled_ip: null })
  1470. });
  1471. const data = await response.json();
  1472. if (data.success) {
  1473. logMessage('Backend IP cleared successfully.', LOG_TYPE.INFO);
  1474. } else {
  1475. logMessage('Failed to clear backend IP.', LOG_TYPE.ERROR);
  1476. }
  1477. } catch (error) {
  1478. logMessage(`Error clearing backend IP: ${error.message}`, LOG_TYPE.ERROR);
  1479. }
  1480. } else {
  1481. // Validate and save the new IP
  1482. const ip = ipInput.value.trim();
  1483. if (!validateIp(ip)) {
  1484. logMessage('Invalid IP address format.', LOG_TYPE.ERROR);
  1485. return;
  1486. }
  1487. localStorage.setItem('wled_ip', ip);
  1488. ipInput.disabled = true;
  1489. saveButton.innerHTML = '<i class="fa-solid fa-xmark"></i><span>Clear</span>';
  1490. logMessage(`WLED IP saved: ${ip}`, LOG_TYPE.SUCCESS);
  1491. // Also save the IP to the backend
  1492. try {
  1493. const response = await fetch('/set_wled_ip', {
  1494. method: 'POST',
  1495. headers: { 'Content-Type': 'application/json' },
  1496. body: JSON.stringify({ wled_ip: ip })
  1497. });
  1498. const data = await response.json();
  1499. if (data.success) {
  1500. logMessage('Backend IP saved successfully.', LOG_TYPE.SUCCESS);
  1501. } else {
  1502. logMessage('Failed to save backend IP.', LOG_TYPE.ERROR);
  1503. }
  1504. } catch (error) {
  1505. logMessage(`Error saving backend IP: ${error.message}`, LOG_TYPE.ERROR);
  1506. }
  1507. }
  1508. updateWledUI(); // Refresh any UI elements that depend on the IP
  1509. }
  1510. // Load the WLED IP from localStorage; if not available, retrieve it from the backend
  1511. async function loadWledIp() {
  1512. const ipInput = document.getElementById('wled_ip');
  1513. const saveButton = document.querySelector('.wled-settings button.cta');
  1514. let savedIp = localStorage.getItem('wled_ip');
  1515. if (!savedIp) {
  1516. // Attempt to load from the backend if not found in localStorage
  1517. try {
  1518. const response = await fetch('/get_wled_ip');
  1519. const data = await response.json();
  1520. if (data.wled_ip) {
  1521. savedIp = data.wled_ip;
  1522. localStorage.setItem('wled_ip', savedIp);
  1523. }
  1524. } catch (error) {
  1525. logMessage(`Error fetching WLED IP from backend: ${error.message}`, LOG_TYPE.ERROR);
  1526. }
  1527. }
  1528. if (savedIp) {
  1529. ipInput.value = savedIp;
  1530. ipInput.disabled = true;
  1531. saveButton.innerHTML = '<i class="fa-solid fa-xmark"></i><span>Clear</span>';
  1532. } else {
  1533. ipInput.disabled = false;
  1534. saveButton.innerHTML = '<i class="fa-solid fa-save"></i><span>Save</span>';
  1535. }
  1536. updateWledUI(); // Update any dependent UI segments
  1537. }
  1538. function validateIp(ip) {
  1539. 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}$/;
  1540. return ipRegex.test(ip);
  1541. }
  1542. // Theme toggle functionality
  1543. const themeToggle = document.getElementById('theme-toggle');
  1544. const themeIcon = themeToggle.querySelector('i');
  1545. themeToggle.addEventListener('click', () => {
  1546. const root = document.documentElement;
  1547. const currentTheme = root.getAttribute('data-theme');
  1548. const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
  1549. root.setAttribute('data-theme', newTheme);
  1550. localStorage.setItem('theme', newTheme);
  1551. // Toggle the icon
  1552. themeIcon.className = newTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
  1553. });
  1554. // Set initial theme and icon based on saved theme
  1555. const savedTheme = localStorage.getItem('theme') || 'light';
  1556. document.documentElement.setAttribute('data-theme', savedTheme);
  1557. themeIcon.className = savedTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
  1558. document.addEventListener("visibilitychange", handleVisibilityChange);
  1559. // Initialization
  1560. document.addEventListener('DOMContentLoaded', () => {
  1561. const activeTab = getCookie('activeTab') || 'patterns'; // Default to 'patterns' tab
  1562. switchTab(activeTab); // Load the active tab
  1563. checkSerialStatus(); // Check connection status
  1564. loadThetaRhoFiles(); // Load files on page load
  1565. loadAllPlaylists(); // Load all playlists on page load
  1566. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1567. attachFullScreenListeners();
  1568. loadWledIp();
  1569. updateWledUI();
  1570. // Periodically check for currently playing status
  1571. if (document.hasFocus()) {
  1572. updateInterval = setInterval(updateCurrentlyPlaying, 3000);
  1573. }
  1574. checkForUpdates();
  1575. });