main.js 75 KB

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