main.js 67 KB

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