main.js 62 KB

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