main.js 76 KB

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