main.js 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832
  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(`Reconnected 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. } else {
  634. logMessage("Could not fetch firmware info.", LOG_TYPE.WARNING);
  635. logMessage(data.error, LOG_TYPE.DEBUG);
  636. }
  637. } catch (error) {
  638. logMessage("Could not fetch firmware info.", LOG_TYPE.WARNING);
  639. logMessage(error.message, LOG_TYPE.DEBUG);
  640. } finally {
  641. // Re-enable the button after fetching
  642. checkButton.disabled = false;
  643. checkButton.textContent = "Check for Updates";
  644. }
  645. }
  646. function setMotorType() {
  647. const selectElement = document.getElementById("manual_motor_type");
  648. const selectedMotorType = selectElement.value;
  649. if (!selectedMotorType) {
  650. logMessage("Please select a motor type before proceeding.", LOG_TYPE.WARNING);
  651. return;
  652. }
  653. const motorSelectionDiv = document.getElementById("motor_selection");
  654. motorSelectionDiv.style.display = "none";
  655. // Call fetchFirmwareInfo with the selected motor type
  656. fetchFirmwareInfo(selectedMotorType);
  657. }
  658. async function updateFirmware() {
  659. const button = document.getElementById("update_firmware_button");
  660. const motorTypeDropdown = document.getElementById("manual_motor_type");
  661. const motorType = motorTypeDropdown ? motorTypeDropdown.value : null;
  662. if (!motorType) {
  663. logMessage("Motor type is not set. Please select a motor type.", LOG_TYPE.WARNING);
  664. return;
  665. }
  666. button.disabled = true;
  667. button.textContent = "Updating...";
  668. try {
  669. logMessage("Firmware update started...", LOG_TYPE.INFO);
  670. const response = await fetch("/flash_firmware", {
  671. method: "POST",
  672. headers: { "Content-Type": "application/json" },
  673. body: JSON.stringify({ motorType }),
  674. });
  675. const data = await response.json();
  676. if (data.success) {
  677. logMessage("Firmware updated successfully!", LOG_TYPE.SUCCESS);
  678. // Refresh the firmware info to update current version
  679. logMessage("Refreshing firmware info...");
  680. await fetchFirmwareInfo();
  681. // Display "You're up to date" message if versions match
  682. const newVersionElement = document.getElementById("new_firmware_version");
  683. const currentVersionElement = document.getElementById("current_firmware_version");
  684. currentVersionElement.textContent = newVersionElement.innerHTML
  685. newVersionElement.textContent = "You are up to date!";
  686. const motorSelectionDiv = document.getElementById("motor_selection");
  687. motorSelectionDiv.style.display = "none";
  688. } else {
  689. logMessage(`Firmware update failed: ${data.error}`, LOG_TYPE.ERROR);
  690. }
  691. } catch (error) {
  692. logMessage(`Error during firmware update: ${error.message}`, LOG_TYPE.ERROR);
  693. } finally {
  694. button.disabled = false; // Re-enable button
  695. button.textContent = "Update Firmware";
  696. }
  697. }
  698. async function checkForUpdates() {
  699. try {
  700. const response = await fetch('/check_software_update');
  701. const data = await response.json();
  702. // Handle updates available logic
  703. if (data.updates_available) {
  704. const updateButton = document.getElementById('update-software-btn');
  705. const updateLinkElement = document.getElementById('update_link');
  706. const tagLink = `https://github.com/tuanchris/dune-weaver/releases/tag/${data.latest_remote_tag}`;
  707. updateButton.classList.remove('hidden'); // Show the button
  708. logMessage("Software Update Available", LOG_TYPE.INFO, 'open-settings-button')
  709. updateLinkElement.innerHTML = `<a href="${tagLink}" target="_blank">View Release Notes </a>`;
  710. updateLinkElement.classList.remove('hidden'); // Show the link
  711. }
  712. // Update current and latest version in the UI
  713. const currentVersionElem = document.getElementById('current_git_version');
  714. const latestVersionElem = document.getElementById('latest_git_version');
  715. currentVersionElem.textContent = `Current Version: ${data.latest_local_tag || 'Unknown'}`;
  716. latestVersionElem.textContent = data.updates_available
  717. ? `Latest Version: ${data.latest_remote_tag}`
  718. : 'You are up to date!';
  719. } catch (error) {
  720. console.error('Error checking for updates:', error);
  721. }
  722. }
  723. async function updateSoftware() {
  724. const updateButton = document.getElementById('update-software-btn');
  725. try {
  726. // Disable the button and update the text
  727. updateButton.disabled = true;
  728. updateButton.querySelector('span').textContent = 'Updating...';
  729. const response = await fetch('/update_software', { method: 'POST' });
  730. const data = await response.json();
  731. if (data.success) {
  732. logMessage('Software updated successfully!', LOG_TYPE.SUCCESS);
  733. window.location.reload(); // Reload the page after update
  734. } else {
  735. logMessage('Failed to update software: ' + data.error, LOG_TYPE.ERROR);
  736. }
  737. } catch (error) {
  738. console.error('Error updating software:', error);
  739. logMessage('Failed to update software', LOG_TYPE.ERROR);
  740. } finally {
  741. // Re-enable the button and reset the text
  742. updateButton.disabled = false;
  743. updateButton.textContent = 'Update Software'; // Adjust to the original text
  744. }
  745. }
  746. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  747. // PART A: Loading / listing playlists from the server
  748. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  749. async function loadAllPlaylists() {
  750. try {
  751. const response = await fetch('/list_all_playlists'); // GET
  752. const allPlaylists = await response.json(); // e.g. ["My Playlist", "Summer", ...]
  753. displayAllPlaylists(allPlaylists);
  754. } catch (err) {
  755. logMessage(`Error loading playlists: ${err}`, LOG_TYPE.ERROR);
  756. }
  757. }
  758. // Function to display all playlists with Load, Run, and Delete buttons
  759. function displayAllPlaylists(playlists) {
  760. const ul = document.getElementById('all_playlists');
  761. ul.innerHTML = ''; // Clear current list
  762. if (playlists.length === 0) {
  763. // Add a placeholder if the list is empty
  764. const emptyLi = document.createElement('li');
  765. emptyLi.textContent = "You don't have any playlists yet.";
  766. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  767. ul.appendChild(emptyLi);
  768. return;
  769. }
  770. playlists.forEach(playlistName => {
  771. const li = document.createElement('li');
  772. li.textContent = playlistName;
  773. li.classList.add('playlist-item'); // Add a class for styling
  774. // Attach click event to handle selection
  775. li.onclick = () => {
  776. // Remove 'selected' class from all items
  777. document.querySelectorAll('#all_playlists li').forEach(item => {
  778. item.classList.remove('selected');
  779. });
  780. // Add 'selected' class to the clicked item
  781. li.classList.add('selected');
  782. // Open the playlist editor for the selected playlist
  783. openPlaylistEditor(playlistName);
  784. };
  785. ul.appendChild(li);
  786. });
  787. }
  788. // Cancel changes and close the editor
  789. function cancelPlaylistChanges() {
  790. playlist = [...originalPlaylist]; // Revert to the original playlist
  791. isPlaylistChanged = false;
  792. toggleSaveCancelButtons(false); // Hide the save and cancel buttons
  793. refreshPlaylistUI(); // Refresh the UI with the original state
  794. closeStickySection('playlist-editor'); // Close the editor
  795. }
  796. // Open the playlist editor
  797. function openPlaylistEditor(playlistName) {
  798. logMessage(`Opening editor for playlist: ${playlistName}`);
  799. const editorSection = document.getElementById('playlist-editor');
  800. // Update the displayed playlist name
  801. document.getElementById('playlist_name_display').textContent = playlistName;
  802. // Store the current playlist name for renaming
  803. document.getElementById('playlist_name_input').value = playlistName;
  804. editorSection.classList.remove('hidden');
  805. editorSection.classList.add('visible');
  806. loadPlaylist(playlistName);
  807. }
  808. function clearSchedule() {
  809. document.getElementById("start_time").value = "";
  810. document.getElementById("end_time").value = "";
  811. document.getElementById('clear_time').style.display = 'none';
  812. setCookie('start_time', '', 365);
  813. setCookie('end_time', '', 365);
  814. }
  815. // Function to run the selected playlist with specified parameters
  816. async function runPlaylist() {
  817. const playlistName = document.getElementById('playlist_name_display').textContent;
  818. if (!playlistName) {
  819. logMessage("No playlist selected to run.");
  820. return;
  821. }
  822. const pauseTimeInput = document.getElementById('pause_time').value;
  823. const clearPatternSelect = document.getElementById('clear_pattern').value;
  824. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  825. const shuffle = document.getElementById('shuffle_playlist').checked;
  826. const startTimeInput = document.getElementById('start_time').value.trim();
  827. const endTimeInput = document.getElementById('end_time').value.trim();
  828. const pauseTime = parseFloat(pauseTimeInput);
  829. if (isNaN(pauseTime) || pauseTime < 0) {
  830. logMessage("Invalid pause time. Please enter a non-negative number.", LOG_TYPE.WARNING);
  831. return;
  832. }
  833. // Validate start and end time format and logic
  834. let startTime = startTimeInput || null;
  835. let endTime = endTimeInput || null;
  836. // Ensure that if one time is filled, the other must be as well
  837. if ((startTime && !endTime) || (!startTime && endTime)) {
  838. logMessage("Both start and end times must be provided together or left blank.", LOG_TYPE.WARNING);
  839. return;
  840. }
  841. // If both are provided, validate format and ensure start_time < end_time
  842. if (startTime && endTime) {
  843. try {
  844. const startDateTime = new Date(`1970-01-01T${startTime}:00`);
  845. const endDateTime = new Date(`1970-01-01T${endTime}:00`);
  846. if (isNaN(startDateTime.getTime()) || isNaN(endDateTime.getTime())) {
  847. logMessage("Invalid time format. Please use HH:MM format (e.g., 09:30).", LOG_TYPE.WARNING);
  848. return;
  849. }
  850. if (startDateTime >= endDateTime) {
  851. logMessage("Start time must be earlier than end time.", LOG_TYPE.WARNING);
  852. return;
  853. }
  854. } catch (error) {
  855. logMessage("Error parsing start or end time. Ensure correct HH:MM format.", LOG_TYPE.ERROR);
  856. return;
  857. }
  858. }
  859. logMessage(`Running playlist: ${playlistName} with pause_time=${pauseTime}, clear_pattern=${clearPatternSelect}, run_mode=${runMode}, shuffle=${shuffle}.`);
  860. try {
  861. const response = await fetch('/run_playlist', {
  862. method: 'POST',
  863. headers: { 'Content-Type': 'application/json' },
  864. body: JSON.stringify({
  865. playlist_name: playlistName,
  866. pause_time: pauseTime,
  867. clear_pattern: clearPatternSelect,
  868. run_mode: runMode,
  869. shuffle: shuffle,
  870. start_time: startTimeInput,
  871. end_time: endTimeInput
  872. })
  873. });
  874. const result = await response.json();
  875. if (result.success) {
  876. logMessage(`Playlist "${playlistName}" is now running.`, LOG_TYPE.SUCCESS);
  877. } else {
  878. logMessage(`Failed to run playlist "${playlistName}": ${result.error}`, LOG_TYPE.ERROR);
  879. }
  880. } catch (error) {
  881. logMessage(`Error running playlist "${playlistName}": ${error.message}`, LOG_TYPE.ERROR);
  882. }
  883. }
  884. // Track changes in the playlist
  885. let originalPlaylist = [];
  886. let isPlaylistChanged = false;
  887. // Load playlist and set the original state
  888. async function loadPlaylist(playlistName) {
  889. try {
  890. logMessage(`Loading playlist: ${playlistName}`);
  891. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  892. const data = await response.json();
  893. if (!data.name) {
  894. throw new Error('Playlist name is missing in the response.');
  895. }
  896. // Populate playlist items and set original state
  897. playlist = data.files || [];
  898. originalPlaylist = [...playlist]; // Clone the playlist as the original
  899. isPlaylistChanged = false; // Reset change tracking
  900. toggleSaveCancelButtons(false); // Hide the save and cancel buttons initially
  901. refreshPlaylistUI();
  902. logMessage(`Loaded playlist: "${playlistName}" with ${playlist.length} file(s).`);
  903. } catch (err) {
  904. logMessage(`Error loading playlist: ${err.message}`, LOG_TYPE.ERROR);
  905. console.error('Error details:', err);
  906. }
  907. }
  908. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  909. // PART B: Creating or Saving (Overwriting) a Playlist
  910. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  911. // Instead of separate create/modify functions, we’ll unify them:
  912. async function savePlaylist() {
  913. const name = document.getElementById('playlist_name_display').textContent
  914. if (!name) {
  915. logMessage("Please enter a playlist name.");
  916. return;
  917. }
  918. if (playlist.length === 0) {
  919. logMessage("No files in this playlist. Add files first.");
  920. return;
  921. }
  922. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  923. try {
  924. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  925. // Let's use /create_playlist to always overwrite or create anew.
  926. const response = await fetch('/create_playlist', {
  927. method: 'POST',
  928. headers: { 'Content-Type': 'application/json' },
  929. body: JSON.stringify({
  930. name: name,
  931. files: playlist
  932. })
  933. });
  934. const result = await response.json();
  935. if (result.success) {
  936. logMessage(`Playlist "${name}" with ${playlist.length} patterns saved`, LOG_TYPE.SUCCESS);
  937. // Reload the entire list of playlists to reflect changes
  938. // Check for changes and refresh the UI
  939. detectPlaylistChanges();
  940. refreshPlaylistUI();
  941. // Restore default action buttons
  942. toggleSaveCancelButtons(false);
  943. } else {
  944. logMessage(`Failed to save playlist: ${result.error}`, LOG_TYPE.ERROR);
  945. }
  946. } catch (err) {
  947. logMessage(`Error saving playlist: ${err}`);
  948. }
  949. }
  950. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  951. // PART C: Renaming and Deleting a playlist
  952. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  953. // Toggle the rename playlist input
  954. function populatePlaylistDropdown() {
  955. return fetch('/list_all_playlists')
  956. .then(response => response.json())
  957. .then(playlists => {
  958. const select = document.getElementById('select-playlist');
  959. select.innerHTML = ''; // Clear existing options
  960. // Retrieve the saved playlist from the cookie
  961. const savedPlaylist = getCookie('selected_playlist');
  962. // Check if there are playlists available
  963. if (playlists.length === 0) {
  964. // Add a placeholder option if no playlists are available
  965. const placeholderOption = document.createElement('option');
  966. placeholderOption.value = '';
  967. placeholderOption.textContent = 'No playlists available';
  968. placeholderOption.disabled = true; // Prevent selection
  969. placeholderOption.selected = true; // Set as default
  970. select.appendChild(placeholderOption);
  971. return;
  972. }
  973. playlists.forEach(playlist => {
  974. const option = document.createElement('option');
  975. option.value = playlist;
  976. option.textContent = playlist;
  977. // Mark the saved playlist as selected
  978. if (playlist === savedPlaylist) {
  979. option.selected = true;
  980. }
  981. select.appendChild(option);
  982. });
  983. // Attach the onchange event listener after populating the dropdown
  984. select.addEventListener('change', function () {
  985. const selectedPlaylist = this.value;
  986. setCookie('selected_playlist', selectedPlaylist, 365); // Save to cookie
  987. logMessage(`Selected playlist saved: ${selectedPlaylist}`);
  988. });
  989. logMessage('Playlist dropdown populated, event listener attached, and saved playlist restored.');
  990. })
  991. .catch(error => logMessage(`Error fetching playlists: ${error.message}`));
  992. }
  993. populatePlaylistDropdown().then(() => {
  994. loadSettingsFromCookies(); // Restore selected playlist after populating the dropdown
  995. });
  996. // Confirm and save the renamed playlist
  997. async function confirmAddPlaylist() {
  998. const playlistNameInput = document.getElementById('new_playlist_name');
  999. const playlistName = playlistNameInput.value.trim();
  1000. if (!playlistName) {
  1001. logMessage('Playlist name cannot be empty.', LOG_TYPE.ERROR);
  1002. return;
  1003. }
  1004. try {
  1005. logMessage(`Adding new playlist: "${playlistName}"...`);
  1006. const response = await fetch('/create_playlist', {
  1007. method: 'POST',
  1008. headers: { 'Content-Type': 'application/json' },
  1009. body: JSON.stringify({
  1010. name: playlistName,
  1011. files: [] // New playlist starts empty
  1012. })
  1013. });
  1014. const result = await response.json();
  1015. if (result.success) {
  1016. logMessage(`Playlist "${playlistName}" created successfully.`, LOG_TYPE.SUCCESS);
  1017. // Clear the input field
  1018. playlistNameInput.value = '';
  1019. // Refresh the playlist list
  1020. loadAllPlaylists();
  1021. populatePlaylistDropdown();
  1022. // Hide the add playlist container
  1023. toggleSecondaryButtons('add-playlist-container');
  1024. } else {
  1025. logMessage(`Failed to create playlist: ${result.error}`, LOG_TYPE.ERROR);
  1026. }
  1027. } catch (error) {
  1028. logMessage(`Error creating playlist: ${error.message}`);
  1029. }
  1030. }
  1031. async function confirmRenamePlaylist() {
  1032. const newName = document.getElementById('playlist_name_input').value.trim();
  1033. const currentName = document.getElementById('playlist_name_display').textContent;
  1034. if (!newName) {
  1035. logMessage("New playlist name cannot be empty.", LOG_TYPE.ERROR);
  1036. return;
  1037. }
  1038. if (newName === currentName) {
  1039. logMessage("New playlist name is the same as the current name. No changes made.", LOG_TYPE.WARNING);
  1040. toggleSecondaryButtons('rename-playlist-container'); // Close the rename container
  1041. return;
  1042. }
  1043. try {
  1044. // Step 1: Create/Modify the playlist with the new name
  1045. const createResponse = await fetch('/modify_playlist', {
  1046. method: 'POST',
  1047. headers: { 'Content-Type': 'application/json' },
  1048. body: JSON.stringify({
  1049. name: newName,
  1050. files: playlist // Ensure `playlist` contains the current list of files
  1051. })
  1052. });
  1053. const createResult = await createResponse.json();
  1054. if (createResult.success) {
  1055. logMessage(createResult.message, LOG_TYPE.SUCCESS);
  1056. // Step 2: Delete the old playlist
  1057. const deleteResponse = await fetch('/delete_playlist', {
  1058. method: 'DELETE',
  1059. headers: { 'Content-Type': 'application/json' },
  1060. body: JSON.stringify({ name: currentName })
  1061. });
  1062. const deleteResult = await deleteResponse.json();
  1063. if (deleteResult.success) {
  1064. logMessage(deleteResult.message);
  1065. // Update the UI with the new name
  1066. document.getElementById('playlist_name_display').textContent = newName;
  1067. // Refresh playlists list
  1068. loadAllPlaylists();
  1069. // Close the rename container and restore original action buttons
  1070. toggleSecondaryButtons('rename-playlist-container');
  1071. } else {
  1072. logMessage(`Failed to delete old playlist: ${deleteResult.error}`, LOG_TYPE.ERROR);
  1073. }
  1074. } else {
  1075. logMessage(`Failed to rename playlist: ${createResult.error}`, LOG_TYPE.ERROR);
  1076. }
  1077. } catch (error) {
  1078. logMessage(`Error renaming playlist: ${error.message}`);
  1079. }
  1080. }
  1081. // Delete the currently opened playlist
  1082. async function deleteCurrentPlaylist() {
  1083. const playlistName = document.getElementById('playlist_name_display').textContent;
  1084. if (!confirm(`Are you sure you want to delete the playlist "${playlistName}"? This action cannot be undone.`)) {
  1085. return;
  1086. }
  1087. try {
  1088. const response = await fetch('/delete_playlist', {
  1089. method: 'DELETE',
  1090. headers: { 'Content-Type': 'application/json' },
  1091. body: JSON.stringify({ name: playlistName })
  1092. });
  1093. const result = await response.json();
  1094. if (result.success) {
  1095. logMessage(`Playlist "${playlistName}" deleted.`, LOG_TYPE.INFO);
  1096. closeStickySection('playlist-editor');
  1097. loadAllPlaylists();
  1098. populatePlaylistDropdown();
  1099. } else {
  1100. logMessage(`Failed to delete playlist: ${result.error}`, LOG_TYPE.ERROR);
  1101. }
  1102. } catch (error) {
  1103. logMessage(`Error deleting playlist: ${error.message}`);
  1104. }
  1105. }
  1106. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1107. // PART D: Local playlist array UI
  1108. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1109. // Refresh the playlist UI and detect changes
  1110. function refreshPlaylistUI() {
  1111. const ul = document.getElementById('playlist_items');
  1112. if (!ul) {
  1113. logMessage('Error: Playlist container not found');
  1114. return;
  1115. }
  1116. ul.innerHTML = ''; // Clear existing items
  1117. if (playlist.length === 0) {
  1118. // Add a placeholder if the playlist is empty
  1119. const emptyLi = document.createElement('li');
  1120. emptyLi.textContent = 'No items in the playlist.';
  1121. emptyLi.classList.add('empty-placeholder'); // Optional: Add a class for styling
  1122. ul.appendChild(emptyLi);
  1123. return;
  1124. }
  1125. playlist.forEach((file, index) => {
  1126. const li = document.createElement('li');
  1127. // Add filename in a span
  1128. const filenameSpan = document.createElement('span');
  1129. filenameSpan.textContent = file;
  1130. filenameSpan.classList.add('filename'); // Add a class for styling
  1131. li.appendChild(filenameSpan);
  1132. // Move Up button
  1133. const moveUpBtn = document.createElement('button');
  1134. moveUpBtn.innerHTML = '<i class="fa-solid fa-turn-up"></i>'; // Up arrow symbol
  1135. moveUpBtn.classList.add('move-button');
  1136. moveUpBtn.onclick = () => {
  1137. if (index > 0) {
  1138. const temp = playlist[index - 1];
  1139. playlist[index - 1] = playlist[index];
  1140. playlist[index] = temp;
  1141. detectPlaylistChanges(); // Check for changes
  1142. refreshPlaylistUI();
  1143. }
  1144. };
  1145. li.appendChild(moveUpBtn);
  1146. // Move Down button
  1147. const moveDownBtn = document.createElement('button');
  1148. moveDownBtn.innerHTML = '<i class="fa-solid fa-turn-down"></i>'; // Down arrow symbol
  1149. moveDownBtn.classList.add('move-button');
  1150. moveDownBtn.onclick = () => {
  1151. if (index < playlist.length - 1) {
  1152. const temp = playlist[index + 1];
  1153. playlist[index + 1] = playlist[index];
  1154. playlist[index] = temp;
  1155. detectPlaylistChanges(); // Check for changes
  1156. refreshPlaylistUI();
  1157. }
  1158. };
  1159. li.appendChild(moveDownBtn);
  1160. // Remove button
  1161. const removeBtn = document.createElement('button');
  1162. removeBtn.innerHTML = '<i class="fa-solid fa-trash"></i>';
  1163. removeBtn.classList.add('remove-button');
  1164. removeBtn.onclick = () => {
  1165. playlist.splice(index, 1);
  1166. detectPlaylistChanges(); // Check for changes
  1167. refreshPlaylistUI();
  1168. };
  1169. li.appendChild(removeBtn);
  1170. ul.appendChild(li);
  1171. });
  1172. }
  1173. // Toggle the visibility of the save and cancel buttons
  1174. function toggleSaveCancelButtons(show) {
  1175. const actionButtons = document.querySelector('#playlist-editor .action-buttons');
  1176. if (actionButtons) {
  1177. // Show/hide all buttons except Save and Cancel
  1178. actionButtons.querySelectorAll('button:not(.save-cancel)').forEach(button => {
  1179. button.style.display = show ? 'none' : 'flex';
  1180. });
  1181. // Show/hide Save and Cancel buttons
  1182. actionButtons.querySelectorAll('.save-cancel').forEach(button => {
  1183. button.style.display = show ? 'flex' : 'none';
  1184. });
  1185. } else {
  1186. logMessage('Error: Action buttons container not found.', LOG_TYPE.ERROR);
  1187. }
  1188. }
  1189. // Detect changes in the playlist
  1190. function detectPlaylistChanges() {
  1191. isPlaylistChanged = JSON.stringify(originalPlaylist) !== JSON.stringify(playlist);
  1192. toggleSaveCancelButtons(isPlaylistChanged);
  1193. }
  1194. // Toggle the "Add to Playlist" section
  1195. function toggleSecondaryButtons(containerId, onShowCallback = null) {
  1196. const container = document.getElementById(containerId);
  1197. if (!container) {
  1198. logMessage(`Error: Element with ID "${containerId}" not found`);
  1199. return;
  1200. }
  1201. // Find the .action-buttons element preceding the container
  1202. const previousActionButtons = container.previousElementSibling?.classList.contains('action-buttons')
  1203. ? container.previousElementSibling
  1204. : null;
  1205. if (container.classList.contains('hidden')) {
  1206. // Show the container
  1207. container.classList.remove('hidden');
  1208. // Hide the previous .action-buttons element
  1209. if (previousActionButtons) {
  1210. previousActionButtons.style.display = 'none';
  1211. }
  1212. // Optional callback for custom logic when showing the container
  1213. if (onShowCallback) {
  1214. onShowCallback();
  1215. }
  1216. } else {
  1217. // Hide the container
  1218. container.classList.add('hidden');
  1219. // Restore the previous .action-buttons element
  1220. if (previousActionButtons) {
  1221. previousActionButtons.style.display = 'flex';
  1222. }
  1223. }
  1224. }
  1225. // Add the selected pattern to the selected playlist
  1226. async function saveToPlaylist() {
  1227. const playlist = document.getElementById('select-playlist').value;
  1228. if (!playlist) {
  1229. logMessage('No playlist selected.', LOG_TYPE.ERROR);
  1230. return;
  1231. }
  1232. if (!selectedFile) {
  1233. logMessage('No pattern selected to add.', LOG_TYPE.ERROR);
  1234. return;
  1235. }
  1236. try {
  1237. logMessage(`Adding pattern "${selectedFile}" to playlist "${playlist}"...`);
  1238. const response = await fetch('/add_to_playlist', {
  1239. method: 'POST',
  1240. headers: { 'Content-Type': 'application/json' },
  1241. body: JSON.stringify({ playlist_name: playlist, pattern: selectedFile })
  1242. });
  1243. const result = await response.json();
  1244. if (result.success) {
  1245. logMessage(`Pattern "${selectedFile}" successfully added to playlist "${playlist}".`, LOG_TYPE.SUCCESS);
  1246. // Reset the UI state via toggleSecondaryButtons
  1247. toggleSecondaryButtons('add-to-playlist-container', () => {
  1248. const selectPlaylist = document.getElementById('select-playlist');
  1249. selectPlaylist.value = ''; // Clear the selection
  1250. });
  1251. } else {
  1252. logMessage(`Failed to add pattern to playlist: ${result.error}`, LOG_TYPE.ERROR);
  1253. }
  1254. } catch (error) {
  1255. logMessage(`Error adding pattern to playlist: ${error.message}`);
  1256. }
  1257. }
  1258. async function changeSpeed() {
  1259. const speedInput = document.getElementById('speed_input');
  1260. const speed = parseFloat(speedInput.value);
  1261. if (isNaN(speed) || speed <= 0) {
  1262. logMessage('Invalid speed. Please enter a positive number.');
  1263. return;
  1264. }
  1265. logMessage(`Setting speed to: ${speed}...`);
  1266. const response = await fetch('/set_speed', {
  1267. method: 'POST',
  1268. headers: { 'Content-Type': 'application/json' },
  1269. body: JSON.stringify({ speed })
  1270. });
  1271. const result = await response.json();
  1272. if (result.success) {
  1273. document.getElementById('speed_status').textContent = `Current Speed: ${speed}`;
  1274. logMessage(`Speed set to: ${speed}`, LOG_TYPE.SUCCESS);
  1275. } else {
  1276. logMessage(`Failed to set speed: ${result.error}`, LOG_TYPE.ERROR);
  1277. }
  1278. }
  1279. // Function to close any sticky section
  1280. function closeStickySection(sectionId) {
  1281. const section = document.getElementById(sectionId);
  1282. if (section) {
  1283. section.classList.remove('visible');
  1284. section.classList.remove('fullscreen');
  1285. section.classList.add('hidden');
  1286. // Reset the fullscreen button text if it exists
  1287. const fullscreenButton = section.querySelector('.fullscreen-button');
  1288. if (fullscreenButton) {
  1289. fullscreenButton.innerHtml = '<i class="fa-solid fa-compress"></i>'; // Reset to enter fullscreen icon/text
  1290. }
  1291. logMessage(`Closed section: ${sectionId}`);
  1292. if(sectionId === 'playlist-editor') {
  1293. document.querySelectorAll('#all_playlists .playlist-item').forEach(item => {
  1294. item.classList.remove('selected');
  1295. });
  1296. }
  1297. if(sectionId === 'pattern-preview-container') {
  1298. document.querySelectorAll('#theta_rho_files .file-item').forEach(item => {
  1299. item.classList.remove('selected');
  1300. });
  1301. }
  1302. } else {
  1303. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1304. }
  1305. }
  1306. // Function to open any sticky section
  1307. function openStickySection(sectionId) {
  1308. const section = document.getElementById(sectionId);
  1309. if (section) {
  1310. // Toggle the 'open' class
  1311. section.classList.toggle('open');
  1312. } else {
  1313. logMessage(`Error: Section with ID "${sectionId}" not found`);
  1314. }
  1315. }
  1316. function attachFullScreenListeners() {
  1317. // Add event listener to all fullscreen buttons
  1318. document.querySelectorAll('.fullscreen-button').forEach(button => {
  1319. button.addEventListener('click', function () {
  1320. const stickySection = this.closest('.sticky'); // Find the closest sticky section
  1321. if (stickySection) {
  1322. // Close all other sections
  1323. document.querySelectorAll('.sticky:not(#currently-playing-container)').forEach(section => {
  1324. if (section !== stickySection) {
  1325. section.classList.remove('fullscreen');
  1326. section.classList.remove('visible');
  1327. section.classList.add('hidden');
  1328. // Reset the fullscreen button text for other sections
  1329. const otherFullscreenButton = section.querySelector('.fullscreen-button');
  1330. if (otherFullscreenButton) {
  1331. otherFullscreenButton.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1332. }
  1333. }
  1334. });
  1335. stickySection.classList.toggle('fullscreen'); // Toggle fullscreen class
  1336. // Update button icon or text
  1337. if (stickySection.classList.contains('fullscreen')) {
  1338. this.innerHTML = '<i class="fa-solid fa-compress"></i>'; // Exit fullscreen icon/text
  1339. } else {
  1340. this.innerHTML = '<i class="fa-solid fa-expand"></i>'; // Enter fullscreen icon/text
  1341. }
  1342. } else {
  1343. console.error('Error: Fullscreen button is not inside a sticky section.');
  1344. }
  1345. });
  1346. });
  1347. }
  1348. let lastPreviewedFile = null; // Track the last previewed file
  1349. let updateInterval = null;
  1350. async function updateCurrentlyPlaying() {
  1351. try {
  1352. if (!document.hasFocus()) return; // Stop execution if the page is not visible
  1353. const response = await fetch('/status');
  1354. const data = await response.json();
  1355. const currentlyPlayingSection = document.getElementById('currently-playing-container');
  1356. if (!currentlyPlayingSection) {
  1357. logMessage('Currently Playing section not found.', LOG_TYPE.ERROR);
  1358. return;
  1359. }
  1360. if (data.current_playing_file && !data.stop_requested) {
  1361. const { current_playing_file, execution_progress, pause_requested } = data;
  1362. // Strip './patterns/' prefix from the file name
  1363. const fileName = current_playing_file.replace('./patterns/', '');
  1364. if (!document.body.classList.contains('playing')) {
  1365. closeStickySection('pattern-preview-container')
  1366. }
  1367. // Show "Currently Playing" section
  1368. document.body.classList.add('playing');
  1369. // Update pattern preview only if the file is different
  1370. if (current_playing_file !== lastPreviewedFile) {
  1371. previewPattern(fileName, 'currently-playing-container');
  1372. lastPreviewedFile = current_playing_file;
  1373. }
  1374. // Update the filename display
  1375. const fileNameDisplay = document.getElementById('currently-playing-file');
  1376. if (fileNameDisplay) fileNameDisplay.textContent = fileName;
  1377. // Update progress bar
  1378. const progressBar = document.getElementById('play_progress');
  1379. const progressText = document.getElementById('play_progress_text');
  1380. if (execution_progress) {
  1381. const progressPercentage = (execution_progress[0] / execution_progress[1]) * 100;
  1382. progressBar.value = progressPercentage;
  1383. progressText.textContent = `${Math.round(progressPercentage)}%`;
  1384. } else {
  1385. progressBar.value = 0;
  1386. progressText.textContent = '0%';
  1387. }
  1388. // Update play/pause button
  1389. const pausePlayButton = document.getElementById('pausePlayCurrent');
  1390. if (pausePlayButton) pausePlayButton.innerHTML = pause_requested ? '<i class="fa-solid fa-play"></i>' : '<i class="fa-solid fa-pause"></i>';
  1391. } else {
  1392. document.body.classList.remove('playing');
  1393. }
  1394. } catch (error) {
  1395. logMessage(`Error updating "Currently Playing" section: ${error.message}`);
  1396. }
  1397. }
  1398. // Function to start or stop updates based on visibility
  1399. function handleVisibilityChange() {
  1400. if (document.hasFocus()) {
  1401. // User is active, start updating
  1402. if (!updateInterval) {
  1403. updateCurrentlyPlaying(); // Run immediately
  1404. updateInterval = setInterval(updateCurrentlyPlaying, 5000); // Update every 5s
  1405. }
  1406. } else {
  1407. // User is inactive, stop updating
  1408. clearInterval(updateInterval);
  1409. updateInterval = null;
  1410. }
  1411. }
  1412. function toggleSettings() {
  1413. const settingsContainer = document.getElementById('settings-container');
  1414. if (settingsContainer) {
  1415. settingsContainer.classList.toggle('open');
  1416. }
  1417. }
  1418. // Utility function to manage cookies
  1419. function setCookie(name, value, days) {
  1420. const date = new Date();
  1421. date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  1422. document.cookie = `${name}=${value};expires=${date.toUTCString()};path=/`;
  1423. }
  1424. function getCookie(name) {
  1425. const nameEQ = `${name}=`;
  1426. const cookies = document.cookie.split(';');
  1427. for (let i = 0; i < cookies.length; i++) {
  1428. let cookie = cookies[i].trim();
  1429. if (cookie.startsWith(nameEQ)) {
  1430. return cookie.substring(nameEQ.length);
  1431. }
  1432. }
  1433. return null;
  1434. }
  1435. // Save settings to cookies
  1436. function saveSettingsToCookies() {
  1437. // Save the pause time
  1438. const pauseTime = document.getElementById('pause_time').value;
  1439. setCookie('pause_time', pauseTime, 365);
  1440. // Save the clear pattern
  1441. const clearPattern = document.getElementById('clear_pattern').value;
  1442. setCookie('clear_pattern', clearPattern, 365);
  1443. // Save the run mode
  1444. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  1445. setCookie('run_mode', runMode, 365);
  1446. // Save shuffle playlist checkbox state
  1447. const shufflePlaylist = document.getElementById('shuffle_playlist').checked;
  1448. setCookie('shuffle_playlist', shufflePlaylist, 365);
  1449. // Save pre-execution action
  1450. const preExecution = document.getElementById('pre_execution').value;
  1451. setCookie('pre_execution', preExecution, 365);
  1452. // Save start and end times
  1453. const startTime = document.getElementById('start_time').value;
  1454. const endTime = document.getElementById('end_time').value;
  1455. setCookie('start_time', startTime, 365);
  1456. setCookie('end_time', endTime, 365);
  1457. logMessage('Settings saved.');
  1458. }
  1459. // Load settings from cookies
  1460. function loadSettingsFromCookies() {
  1461. // Load the pause time
  1462. const pauseTime = getCookie('pause_time');
  1463. if (pauseTime !== null) {
  1464. document.getElementById('pause_time').value = pauseTime;
  1465. }
  1466. // Load the clear pattern
  1467. const clearPattern = getCookie('clear_pattern');
  1468. if (clearPattern !== null) {
  1469. document.getElementById('clear_pattern').value = clearPattern;
  1470. }
  1471. // Load the run mode
  1472. const runMode = getCookie('run_mode');
  1473. if (runMode !== null) {
  1474. document.querySelector(`input[name="run_mode"][value="${runMode}"]`).checked = true;
  1475. }
  1476. // Load the shuffle playlist checkbox state
  1477. const shufflePlaylist = getCookie('shuffle_playlist');
  1478. if (shufflePlaylist !== null) {
  1479. document.getElementById('shuffle_playlist').checked = shufflePlaylist === 'true';
  1480. }
  1481. // Load the pre-execution action
  1482. const preExecution = getCookie('pre_execution');
  1483. if (preExecution !== null) {
  1484. document.getElementById('pre_execution').value = preExecution;
  1485. }
  1486. // Load start and end times
  1487. const startTime = getCookie('start_time');
  1488. if (startTime !== null) {
  1489. document.getElementById('start_time').value = startTime;
  1490. }
  1491. const endTime = getCookie('end_time');
  1492. if (endTime !== null) {
  1493. document.getElementById('end_time').value = endTime;
  1494. }
  1495. if (startTime && endTime ) {
  1496. document.getElementById('clear_time').style.display = 'block';
  1497. }
  1498. logMessage('Settings loaded from cookies.');
  1499. }
  1500. // Call this function to save settings when a value is changed
  1501. function attachSettingsSaveListeners() {
  1502. // Add event listeners to inputs
  1503. document.getElementById('pause_time').addEventListener('input', saveSettingsToCookies);
  1504. document.getElementById('clear_pattern').addEventListener('change', saveSettingsToCookies);
  1505. document.querySelectorAll('input[name="run_mode"]').forEach(input => {
  1506. input.addEventListener('change', saveSettingsToCookies);
  1507. });
  1508. document.getElementById('shuffle_playlist').addEventListener('change', saveSettingsToCookies);
  1509. document.getElementById('pre_execution').addEventListener('change', saveSettingsToCookies);
  1510. document.getElementById('start_time').addEventListener('change', saveSettingsToCookies);
  1511. document.getElementById('end_time').addEventListener('change', saveSettingsToCookies);
  1512. }
  1513. // Tab switching logic with cookie storage
  1514. function switchTab(tabName) {
  1515. // Store the active tab in a cookie
  1516. setCookie('activeTab', tabName, 365); // Store for 7 days
  1517. // Deactivate all tab content
  1518. document.querySelectorAll('.tab-content').forEach(tab => {
  1519. tab.classList.remove('active');
  1520. });
  1521. // Activate the selected tab content
  1522. const activeTab = document.getElementById(`${tabName}-tab`);
  1523. if (activeTab) {
  1524. activeTab.classList.add('active');
  1525. } else {
  1526. console.error(`Error: Tab "${tabName}" not found.`);
  1527. }
  1528. // Deactivate all nav buttons
  1529. document.querySelectorAll('.bottom-nav .tab-button').forEach(button => {
  1530. button.classList.remove('active');
  1531. });
  1532. // Activate the selected nav button
  1533. const activeNavButton = document.getElementById(`nav-${tabName}`);
  1534. if (activeNavButton) {
  1535. activeNavButton.classList.add('active');
  1536. } else {
  1537. console.error(`Error: Nav button for "${tabName}" not found.`);
  1538. }
  1539. }
  1540. document.addEventListener("visibilitychange", handleVisibilityChange);
  1541. // Initialization
  1542. document.addEventListener('DOMContentLoaded', () => {
  1543. const activeTab = getCookie('activeTab') || 'patterns'; // Default to 'patterns' tab
  1544. switchTab(activeTab); // Load the active tab
  1545. checkSerialStatus(); // Check serial connection status
  1546. loadThetaRhoFiles(); // Load files on page load
  1547. loadAllPlaylists(); // Load all playlists on page load
  1548. attachSettingsSaveListeners(); // Attach event listeners to save changes
  1549. attachFullScreenListeners();
  1550. fetchFirmwareInfo();
  1551. checkForUpdates();
  1552. // Periodically check for currently playing status
  1553. if (document.hasFocus()) {
  1554. updateInterval = setInterval(updateCurrentlyPlaying, 5000);
  1555. }
  1556. });