index.html 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Dune Weaver Controller</title>
  7. <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
  8. <link rel="stylesheet" href="../static/style.css">
  9. </head>
  10. <body>
  11. <h1>Dune Weaver Controller</h1>
  12. <div class="container">
  13. <!-- Left Column -->
  14. <div class="left-column">
  15. <div class="section">
  16. <h2>Serial Connection</h2>
  17. <div id="serial_status_container">Status: <span id="serial_status" class="status"> Not connected</span></div>
  18. <div id="serial_ports_container">
  19. <label for="serial_ports">Available Ports:</label>
  20. <select id="serial_ports"></select>
  21. <button onclick="connectSerial()">Connect</button>
  22. </div>
  23. <div id="serial_ports_buttons" class="button-group">
  24. <button onclick="disconnectSerial()">Disconnect</button>
  25. <button onclick="restartSerial()">Restart</button>
  26. </div>
  27. <p id="serial_status" class="status">Status: Not connected</p>
  28. </div>
  29. <div class="section">
  30. <h2>Quick Actions</h2>
  31. <div class="button-group">
  32. <button onclick="sendHomeCommand()">Home Device</button>
  33. <button onclick="moveToCenter()">Move to Center</button>
  34. <button onclick="moveToPerimeter()">Move to Perimeter</button>
  35. <button onclick="runClearIn()">Clear from In</button>
  36. <button onclick="runClearOut()">Clear from Out</button>
  37. <button onclick="runSideway()">Clear Sideway</button>
  38. <button onclick="stopExecution()" class="delete-button">Stop</button>
  39. </div>
  40. <div class="coordinate-input button-group">
  41. <label for="theta_input">θ:</label>
  42. <input type="number" id="theta_input" placeholder="Theta">
  43. <label for="rho_input">ρ:</label>
  44. <input type="number" id="rho_input" placeholder="Rho">
  45. <button class="small-button" onclick="sendCoordinate()">Send to coordinate</button>
  46. </div>
  47. </div>
  48. <div class="section">
  49. <h2>Preview</h2>
  50. <canvas id="patternPreviewCanvas" style="width: 100%;"></canvas>
  51. <p id="first_coordinate">First Coordinate: Not available</p>
  52. <p id="last_coordinate">Last Coordinate: Not available</p>
  53. </div>
  54. </div>
  55. <!-- Right Column -->
  56. <div class="right-column">
  57. <div class="section">
  58. <h2>Pattern Files</h2>
  59. <input type="text" id="search_pattern" placeholder="Search files..." oninput="searchPatternFiles()">
  60. <ul id="theta_rho_files"></ul>
  61. <div class="pre-execution-toggles">
  62. <h3>Pre-Execution Action</h3>
  63. <label>
  64. <input type="radio" name="pre_execution" value="clear_in" id="clear_in"> Clear from In
  65. </label>
  66. <label>
  67. <input type="radio" name="pre_execution" value="clear_out" id="clear_out"> Clear from Out
  68. </label>
  69. <label>
  70. <input type="radio" name="pre_execution" value="clear_sideway" id="clear_out"> Clear sideway
  71. </label>
  72. <label>
  73. <input type="radio" name="pre_execution" value="none" id="no_action" checked> None
  74. </label>
  75. </div>
  76. <div class="button-group">
  77. <button id="run_button" disabled>Run Selected File</button>
  78. <button onclick="stopExecution()" class="delete-button">Stop</button>
  79. </div>
  80. <div class="section modeSection single_run">
  81. <h2>Upload new files</h2>
  82. <div class="button-group">
  83. <input type="file" id="upload_file">
  84. <div class="button-group">
  85. <button onclick="uploadThetaRho()">Upload</button>
  86. <button id="delete_selected_button" class="delete-button" onclick="deleteSelectedFile()" disabled>Delete Selected File</button>
  87. </div>
  88. </div>
  89. </div>
  90. <div class="section modeSection create_playlist run_playlist" style="display: none;">
  91. <h2>Create Playlist</h2>
  92. <!-- A list showing the files that have been added to the playlist -->
  93. <ul id="playlist_items"></ul>
  94. <!-- Buttons to reorder files in the playlist -->
  95. <div class="button-group">
  96. <button onclick="movePlaylistItemUp()">Up</button>
  97. <button onclick="movePlaylistItemDown()">Down</button>
  98. <button onclick="removeFromPlaylist()" class="delete-button">Remove</button>
  99. </div>
  100. <div class="playlist-name-input">
  101. <label for="playlist_name">Playlist Name:</label>
  102. <input type="text" id="playlist_name" placeholder="Enter playlist name" />
  103. </div>
  104. <div class="button-group">
  105. <!-- Button to add the selected file (from #theta_rho_files) to the playlist -->
  106. <!-- Button to create/finalize the playlist -->
  107. <button onclick="savePlaylist()">Create Playlist</button>
  108. </div>
  109. </div>
  110. <div class="section modeSection create_playlist run_playlist" style="display: none;">
  111. <h2>Playlists</h2>
  112. <!-- Parameter Inputs -->
  113. <div class="playlist-parameters">
  114. <label for="pause_time">Pause Time (seconds):</label>
  115. <input type="number" id="pause_time" min="0" step="0.1" value="0">
  116. <label for="clear_pattern">Clear Pattern:</label>
  117. <select id="clear_pattern">
  118. <option value="none">None</option>
  119. <option value="clear_in">Clear from In</option>
  120. <option value="clear_out">Clear from Out</option>
  121. <option value="clear_sideway">Clear Sideway</option>
  122. <option value="random">Random</option>
  123. </select>
  124. <!-- New Parameters -->
  125. <div class="run-options">
  126. <label>Run Mode:</label>
  127. <label>
  128. <input type="radio" name="run_mode" value="single" checked> Single Run
  129. </label>
  130. <label>
  131. <input type="radio" name="run_mode" value="indefinite"> Indefinite Run
  132. </label>
  133. <label>
  134. <input type="checkbox" id="shuffle_playlist"> Shuffle Playlist
  135. </label>
  136. </div>
  137. </div>
  138. <!-- Playlists List -->
  139. <ul id="all_playlists"></ul>
  140. </div>
  141. </div>
  142. </div>
  143. </div>
  144. <div id="status_log">
  145. <h2>Status Log</h2>
  146. <!-- Messages will be appended here -->
  147. </div>
  148. <script>
  149. let selectedFile = null;
  150. function logMessage(message) {
  151. const log = document.getElementById('status_log');
  152. const entry = document.createElement('p');
  153. entry.textContent = message;
  154. log.appendChild(entry);
  155. log.scrollTop = log.scrollHeight; // Keep log scrolled to the bottom
  156. }
  157. async function selectFile(file, listItem) {
  158. selectedFile = file;
  159. // Highlight the selected file
  160. document.querySelectorAll('#theta_rho_files li').forEach(li => li.classList.remove('selected'));
  161. listItem.classList.add('selected');
  162. // Enable buttons
  163. document.getElementById('run_button').disabled = false;
  164. document.getElementById('delete_selected_button').disabled = false;
  165. logMessage(`Selected file: ${file}`);
  166. // Fetch and preview the selected file
  167. await previewPattern(file);
  168. }
  169. async function uploadThetaRho() {
  170. const fileInput = document.getElementById('upload_file');
  171. const file = fileInput.files[0];
  172. if (!file) {
  173. logMessage('No file selected for upload.');
  174. return;
  175. }
  176. logMessage(`Uploading file: ${file.name}...`);
  177. const formData = new FormData();
  178. formData.append('file', file);
  179. const response = await fetch('/upload_theta_rho', {
  180. method: 'POST',
  181. body: formData
  182. });
  183. const result = await response.json();
  184. if (result.success) {
  185. logMessage(`File uploaded successfully: ${file.name}`);
  186. await loadThetaRhoFiles();
  187. } else {
  188. logMessage(`Failed to upload file: ${file.name}`);
  189. }
  190. }
  191. async function deleteSelectedFile() {
  192. if (!selectedFile) {
  193. logMessage("No file selected for deletion.");
  194. return;
  195. }
  196. const userConfirmed = confirm(`Are you sure you want to delete the selected file "${selectedFile}"?`);
  197. if (!userConfirmed) return;
  198. logMessage(`Deleting file: ${selectedFile}...`);
  199. const response = await fetch('/delete_theta_rho_file', {
  200. method: 'POST',
  201. headers: { 'Content-Type': 'application/json' },
  202. body: JSON.stringify({ file_name: selectedFile }),
  203. });
  204. const result = await response.json();
  205. if (result.success) {
  206. const ul = document.getElementById('theta_rho_files');
  207. const selectedItem = Array.from(ul.children).find(li => li.classList.contains('selected'));
  208. if (selectedItem) selectedItem.remove();
  209. selectedFile = null;
  210. document.getElementById('run_button').disabled = true;
  211. document.getElementById('delete_selected_button').disabled = true;
  212. logMessage(`File deleted successfully: ${result.file_name}`);
  213. } else {
  214. logMessage(`Failed to delete file: ${selectedFile}`);
  215. }
  216. }
  217. async function runThetaRho() {
  218. if (!selectedFile) {
  219. logMessage("No file selected to run.");
  220. return;
  221. }
  222. // Get the selected pre-execution action
  223. const preExecutionAction = document.querySelector('input[name="pre_execution"]:checked').value;
  224. logMessage(`Running file: ${selectedFile} with pre-execution action: ${preExecutionAction}...`);
  225. const response = await fetch('/run_theta_rho', {
  226. method: 'POST',
  227. headers: { 'Content-Type': 'application/json' },
  228. body: JSON.stringify({ file_name: selectedFile, pre_execution: preExecutionAction })
  229. });
  230. const result = await response.json();
  231. if (result.success) {
  232. logMessage(`File running: ${selectedFile}`);
  233. } else {
  234. logMessage(`Failed to run file: ${selectedFile}`);
  235. }
  236. }
  237. async function stopExecution() {
  238. logMessage('Stopping execution...');
  239. const response = await fetch('/stop_execution', { method: 'POST' });
  240. const result = await response.json();
  241. if (result.success) {
  242. logMessage('Execution stopped.');
  243. } else {
  244. logMessage('Failed to stop execution.');
  245. }
  246. }
  247. async function loadSerialPorts() {
  248. const response = await fetch('/list_serial_ports');
  249. const ports = await response.json();
  250. const select = document.getElementById('serial_ports');
  251. select.innerHTML = '';
  252. ports.forEach(port => {
  253. const option = document.createElement('option');
  254. option.value = port;
  255. option.textContent = port;
  256. select.appendChild(option);
  257. });
  258. logMessage('Serial ports loaded.');
  259. }
  260. async function connectSerial() {
  261. const port = document.getElementById('serial_ports').value;
  262. const response = await fetch('/connect_serial', {
  263. method: 'POST',
  264. headers: { 'Content-Type': 'application/json' },
  265. body: JSON.stringify({ port })
  266. });
  267. const result = await response.json();
  268. if (result.success) {
  269. logMessage(`Connected to serial port: ${port}`);
  270. // Refresh the status
  271. await checkSerialStatus();
  272. } else {
  273. logMessage(`Error connecting to serial port: ${result.error}`);
  274. }
  275. }
  276. async function disconnectSerial() {
  277. const response = await fetch('/disconnect_serial', { method: 'POST' });
  278. const result = await response.json();
  279. if (result.success) {
  280. logMessage('Serial port disconnected.');
  281. // Refresh the status
  282. await checkSerialStatus();
  283. } else {
  284. logMessage(`Error disconnecting: ${result.error}`);
  285. }
  286. }
  287. async function restartSerial() {
  288. const port = document.getElementById('serial_ports').value;
  289. const response = await fetch('/restart_serial', {
  290. method: 'POST',
  291. headers: { 'Content-Type': 'application/json' },
  292. body: JSON.stringify({ port })
  293. });
  294. const result = await response.json();
  295. if (result.success) {
  296. document.getElementById('serial_status').textContent = `Restarted connection to ${port}`;
  297. logMessage('Serial connection restarted.');
  298. // No need to change visibility for restart
  299. } else {
  300. logMessage(`Error restarting serial connection: ${result.error}`);
  301. }
  302. }
  303. async function sendHomeCommand() {
  304. const response = await fetch('/send_home', { method: 'POST' });
  305. const result = await response.json();
  306. if (result.success) {
  307. logMessage('HOME command sent successfully.');
  308. } else {
  309. logMessage('Failed to send HOME command.');
  310. }
  311. }
  312. let allFiles = []; // Store all files for filtering
  313. async function loadThetaRhoFiles() {
  314. logMessage('Loading Theta-Rho files...');
  315. const response = await fetch('/list_theta_rho_files');
  316. let files = await response.json();
  317. // Filter only .thr files
  318. files = files.filter(file => file.endsWith('.thr'));
  319. // Separate files into categories
  320. const customPatternsFiles = files.filter(file => file.startsWith('custom_patterns/'));
  321. const otherFiles = files.filter(file => !file.startsWith('custom_patterns/'));
  322. // Sort the files
  323. const sortedFiles = [
  324. ...customPatternsFiles.sort(), // Custom patterns first
  325. ...otherFiles.sort() // Remaining files sorted alphabetically
  326. ];
  327. allFiles = sortedFiles; // Store the sorted list of files
  328. displayFiles(allFiles); // Display the sorted files
  329. logMessage('Theta-Rho files loaded successfully.');
  330. }
  331. function displayFiles(files) {
  332. const ul = document.getElementById('theta_rho_files');
  333. ul.innerHTML = ''; // Clear current list
  334. files.forEach(file => {
  335. const li = document.createElement('li');
  336. li.textContent = file;
  337. // Highlight the selected file when clicked
  338. li.onclick = () => selectFile(file, li);
  339. ul.appendChild(li);
  340. });
  341. }
  342. function searchPatternFiles() {
  343. const searchInput = document.getElementById('search_pattern').value.toLowerCase();
  344. const filteredFiles = allFiles.filter(file => file.toLowerCase().includes(searchInput));
  345. displayFiles(filteredFiles); // Display only matching files
  346. }
  347. async function moveToCenter() {
  348. logMessage('Moving to center...');
  349. const response = await fetch('/move_to_center', { method: 'POST' });
  350. const result = await response.json();
  351. if (result.success) {
  352. logMessage('Moved to center successfully.');
  353. } else {
  354. logMessage(`Failed to move to center: ${result.error}`);
  355. }
  356. }
  357. async function moveToPerimeter() {
  358. logMessage('Moving to perimeter...');
  359. const response = await fetch('/move_to_perimeter', { method: 'POST' });
  360. const result = await response.json();
  361. if (result.success) {
  362. logMessage('Moved to perimeter successfully.');
  363. } else {
  364. logMessage(`Failed to move to perimeter: ${result.error}`);
  365. }
  366. }
  367. async function sendCoordinate() {
  368. const theta = parseFloat(document.getElementById('theta_input').value);
  369. const rho = parseFloat(document.getElementById('rho_input').value);
  370. if (isNaN(theta) || isNaN(rho)) {
  371. logMessage('Invalid input: θ and ρ must be numbers.');
  372. return;
  373. }
  374. logMessage(`Sending coordinate: θ=${theta}, ρ=${rho}...`);
  375. const response = await fetch('/send_coordinate', {
  376. method: 'POST',
  377. headers: { 'Content-Type': 'application/json' },
  378. body: JSON.stringify({ theta, rho })
  379. });
  380. const result = await response.json();
  381. if (result.success) {
  382. logMessage(`Coordinate executed successfully: θ=${theta}, ρ=${rho}`);
  383. } else {
  384. logMessage(`Failed to execute coordinate: ${result.error}`);
  385. }
  386. }
  387. async function previewPattern(fileName) {
  388. logMessage(`Fetching data to preview file: ${fileName}...`);
  389. const response = await fetch('/preview_thr', {
  390. method: 'POST',
  391. headers: { 'Content-Type': 'application/json' },
  392. body: JSON.stringify({ file_name: fileName })
  393. });
  394. const result = await response.json();
  395. if (result.success) {
  396. const coordinates = result.coordinates;
  397. // Update coordinates display
  398. if (coordinates.length > 0) {
  399. const firstCoord = coordinates[0];
  400. const lastCoord = coordinates[coordinates.length - 1];
  401. document.getElementById('first_coordinate').textContent = `First Coordinate: θ=${firstCoord[0]}, ρ=${firstCoord[1]}`;
  402. document.getElementById('last_coordinate').textContent = `Last Coordinate: θ=${lastCoord[0]}, ρ=${lastCoord[1]}`;
  403. } else {
  404. document.getElementById('first_coordinate').textContent = 'First Coordinate: Not available';
  405. document.getElementById('last_coordinate').textContent = 'Last Coordinate: Not available';
  406. }
  407. renderPattern(coordinates);
  408. } else {
  409. logMessage(`Failed to fetch preview for file: ${result.error}`);
  410. // Clear the coordinate display on error
  411. document.getElementById('first_coordinate').textContent = 'First Coordinate: Not available';
  412. document.getElementById('last_coordinate').textContent = 'Last Coordinate: Not available';
  413. }
  414. }
  415. function renderPattern(coordinates) {
  416. const canvas = document.getElementById('patternPreviewCanvas');
  417. const ctx = canvas.getContext('2d');
  418. // Make canvas full screen
  419. canvas.width = window.innerWidth;
  420. canvas.height = window.innerHeight;
  421. // Clear the canvas
  422. ctx.clearRect(0, 0, canvas.width, canvas.height);
  423. // Convert polar to Cartesian and draw the pattern
  424. const centerX = canvas.width / 2;
  425. const centerY = canvas.height / 2;
  426. const maxRho = Math.max(...coordinates.map(coord => coord[1]));
  427. const scale = Math.min(canvas.width, canvas.height) / (2 * maxRho); // Scale to fit within the screen
  428. ctx.beginPath();
  429. coordinates.forEach(([theta, rho], index) => {
  430. const x = centerX + rho * Math.cos(theta) * scale;
  431. const y = centerY - rho * Math.sin(theta) * scale; // Invert y-axis for canvas
  432. if (index === 0) {
  433. ctx.moveTo(x, y);
  434. } else {
  435. ctx.lineTo(x, y);
  436. }
  437. });
  438. ctx.closePath();
  439. ctx.stroke();
  440. logMessage('Pattern preview rendered at full screen.');
  441. }
  442. function toggleDebugLog() {
  443. const statusLog = document.getElementById('status_log');
  444. const debugButton = document.getElementById('debug_button');
  445. if (statusLog.style.display === 'block') {
  446. statusLog.style.display = 'none';
  447. debugButton.textContent = 'Show Debug Log'; // Update the button label
  448. } else {
  449. statusLog.style.display = 'block';
  450. debugButton.textContent = 'Hide Debug Log'; // Update the button label
  451. statusLog.scrollIntoView({ behavior: 'smooth', block: 'start' }); // Smooth scrolling to the log
  452. }
  453. }
  454. async function checkSerialStatus() {
  455. const response = await fetch('/serial_status');
  456. const status = await response.json();
  457. const statusElement = document.getElementById('serial_status');
  458. const serialPortsContainer = document.getElementById('serial_ports_container');
  459. const connectButton = document.querySelector('button[onclick="connectSerial()"]');
  460. const disconnectButton = document.querySelector('button[onclick="disconnectSerial()"]');
  461. const restartButton = document.querySelector('button[onclick="restartSerial()"]');
  462. if (status.connected) {
  463. const port = status.port || 'Unknown'; // Fallback if port is undefined
  464. statusElement.textContent = `Connected to ${port}`;
  465. statusElement.classList.add('connected');
  466. statusElement.classList.remove('not-connected');
  467. logMessage(`Reconnected to serial port: ${port}`);
  468. // Hide Available Ports and show disconnect/restart buttons
  469. serialPortsContainer.style.display = 'none';
  470. connectButton.style.display = 'none';
  471. disconnectButton.style.display = 'inline-block';
  472. restartButton.style.display = 'inline-block';
  473. } else {
  474. statusElement.textContent = 'Not connected';
  475. statusElement.classList.add('not-connected');
  476. statusElement.classList.remove('connected');
  477. logMessage('No active serial connection.');
  478. // Show Available Ports and the connect button
  479. serialPortsContainer.style.display = 'block';
  480. connectButton.style.display = 'inline-block';
  481. disconnectButton.style.display = 'none';
  482. restartButton.style.display = 'none';
  483. // Attempt to auto-load available ports
  484. await loadSerialPorts();
  485. }
  486. }
  487. async function runFile(fileName) {
  488. const response = await fetch(`/run_theta_rho_file/${fileName}`, { method: 'POST' });
  489. const result = await response.json();
  490. if (result.success) {
  491. logMessage(`Running file: ${fileName}`);
  492. } else {
  493. logMessage(`Failed to run file: ${fileName}`);
  494. }
  495. }
  496. async function runClearIn() {
  497. await runFile('clear_from_in.thr');
  498. }
  499. async function runClearOut() {
  500. await runFile('clear_from_out.thr');
  501. }
  502. async function runSideway() {
  503. await runFile('clear_sideway.thr');
  504. }
  505. // Call this function on page load
  506. checkSerialStatus();
  507. // Initial load of serial ports and Theta-Rho files
  508. loadSerialPorts();
  509. loadThetaRhoFiles();
  510. document.getElementById('run_button').onclick = runThetaRho;
  511. document.querySelectorAll('.modeSelector').forEach((radio) => {
  512. radio.addEventListener('change', function () {
  513. // Hide all .modeSection first
  514. document.querySelectorAll('.modeSection').forEach((section) => {
  515. section.style.display = 'none';
  516. });
  517. // Figure out which mode was selected
  518. const selectedValue = this.value; // or document.querySelector('.modeSelector:checked').value
  519. // Show every element that has .modeSection AND the selected mode's class
  520. document
  521. .querySelectorAll(`.modeSection.${selectedValue}`)
  522. .forEach((elem) => {
  523. elem.style.display = 'block';
  524. });
  525. });
  526. });
  527. // Keep track of the files in the new playlist
  528. let playlist = [];
  529. // Currently selected item in the playlist
  530. let selectedPlaylistIndex = null;
  531. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  532. // PART A: Loading / listing playlists from the server
  533. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  534. async function loadAllPlaylists() {
  535. try {
  536. const response = await fetch('/list_all_playlists'); // GET
  537. const allPlaylists = await response.json(); // e.g. ["My Playlist", "Summer", ...]
  538. displayAllPlaylists(allPlaylists);
  539. } catch (err) {
  540. logMessage(`Error loading playlists: ${err}`);
  541. }
  542. }
  543. // Function to display all playlists with Load, Run, and Delete buttons
  544. function displayAllPlaylists(allPlaylists) {
  545. const ul = document.getElementById('all_playlists');
  546. ul.innerHTML = ''; // Clear current list
  547. allPlaylists.forEach((playlistName) => {
  548. const li = document.createElement('li');
  549. li.classList.add('playlist-item'); // For styling
  550. // Playlist Name
  551. const nameSpan = document.createElement('span');
  552. nameSpan.textContent = playlistName;
  553. li.appendChild(nameSpan);
  554. // "Load" button
  555. const loadBtn = document.createElement('button');
  556. loadBtn.textContent = 'Load';
  557. loadBtn.onclick = () => loadPlaylist(playlistName);
  558. loadBtn.classList.add('load-button'); // For styling
  559. li.appendChild(loadBtn);
  560. // "Run" button
  561. const runBtn = document.createElement('button');
  562. runBtn.textContent = 'Run';
  563. runBtn.onclick = () => runPlaylist(playlistName);
  564. runBtn.classList.add('run-button'); // For styling
  565. li.appendChild(runBtn);
  566. // "Delete" button
  567. const deleteBtn = document.createElement('button');
  568. deleteBtn.textContent = 'Delete';
  569. deleteBtn.onclick = () => deletePlaylist(playlistName);
  570. deleteBtn.classList.add('delete-button'); // For styling
  571. li.appendChild(deleteBtn);
  572. ul.appendChild(li);
  573. });
  574. }
  575. // Function to run the selected playlist with specified parameters
  576. async function runPlaylist(playlistName) {
  577. if (!playlistName) {
  578. logMessage("No playlist selected to run.");
  579. return;
  580. }
  581. // Get the parameters from the UI
  582. const pauseTimeInput = document.getElementById('pause_time').value;
  583. const clearPatternSelect = document.getElementById('clear_pattern').value;
  584. const runMode = document.querySelector('input[name="run_mode"]:checked').value;
  585. const shuffle = document.getElementById('shuffle_playlist').checked;
  586. // Validate pause time
  587. const pauseTime = parseFloat(pauseTimeInput);
  588. if (isNaN(pauseTime) || pauseTime < 0) {
  589. logMessage("Invalid pause time. Please enter a non-negative number.");
  590. return;
  591. }
  592. // Map clear_pattern select value to backend expected values
  593. let clearPattern = clearPatternSelect;
  594. if (clearPatternSelect === "none") {
  595. clearPattern = null;
  596. }
  597. logMessage(`Running playlist: ${playlistName} with pause_time=${pauseTime}, clear_pattern=${clearPattern || "None"}, run_mode=${runMode}, shuffle=${shuffle}`);
  598. try {
  599. const response = await fetch('/run_playlist', {
  600. method: 'POST',
  601. headers: { 'Content-Type': 'application/json' },
  602. body: JSON.stringify({
  603. playlist_name: playlistName,
  604. pause_time: pauseTime,
  605. clear_between_files: clearPattern !== null,
  606. clear_pattern: clearPattern,
  607. run_mode: runMode, // 'single' or 'indefinite'
  608. shuffle: shuffle // true or false
  609. })
  610. });
  611. const result = await response.json();
  612. if (result.success) {
  613. logMessage(`Playlist "${playlistName}" is now running.`);
  614. } else {
  615. logMessage(`Failed to run playlist "${playlistName}": ${result.error}`);
  616. }
  617. } catch (error) {
  618. logMessage(`Error running playlist "${playlistName}": ${error}`);
  619. }
  620. }
  621. async function loadPlaylist(playlistName) {
  622. // This fetches the named playlist from /get_playlist?name=...
  623. try {
  624. const response = await fetch(`/get_playlist?name=${encodeURIComponent(playlistName)}`);
  625. const data = await response.json(); // { "name": "XYZ", "files": [...] }
  626. if (data.error) {
  627. logMessage(`Error loading playlist "${playlistName}": ${data.error}`);
  628. return;
  629. }
  630. // Clear current local playlist; replace with loaded data
  631. playlist = data.files || [];
  632. selectedPlaylistIndex = null;
  633. document.getElementById('playlist_name').value = data.name; // Fill in the name field
  634. refreshPlaylistUI();
  635. logMessage(`Loaded playlist: ${data.name} with ${playlist.length} file(s).`);
  636. } catch (err) {
  637. logMessage(`Error loading playlist: ${err}`);
  638. }
  639. }
  640. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  641. // PART B: Creating or Saving (Overwriting) a Playlist
  642. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  643. // Instead of separate create/modify functions, we’ll unify them:
  644. async function savePlaylist() {
  645. const name = document.getElementById('playlist_name').value.trim();
  646. if (!name) {
  647. logMessage("Please enter a playlist name.");
  648. return;
  649. }
  650. if (playlist.length === 0) {
  651. logMessage("No files in this playlist. Add files first.");
  652. return;
  653. }
  654. logMessage(`Saving playlist "${name}" with ${playlist.length} file(s)...`);
  655. try {
  656. // We can use /create_playlist or /modify_playlist. They do roughly the same in our single-file approach.
  657. // Let's use /create_playlist to always overwrite or create anew.
  658. const response = await fetch('/create_playlist', {
  659. method: 'POST',
  660. headers: { 'Content-Type': 'application/json' },
  661. body: JSON.stringify({
  662. name: name,
  663. files: playlist
  664. })
  665. });
  666. const result = await response.json();
  667. if (result.success) {
  668. logMessage(result.message);
  669. // Reload the entire list of playlists to reflect changes
  670. loadAllPlaylists();
  671. } else {
  672. logMessage(`Failed to save playlist: ${result.error}`);
  673. }
  674. } catch (err) {
  675. logMessage(`Error saving playlist: ${err}`);
  676. }
  677. }
  678. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  679. // PART C: Deleting a playlist
  680. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  681. async function deletePlaylist(playlistName) {
  682. if (!confirm(`Delete playlist "${playlistName}"? This cannot be undone.`)) {
  683. return;
  684. }
  685. try {
  686. const response = await fetch('/delete_playlist', {
  687. method: 'DELETE',
  688. headers: { 'Content-Type': 'application/json' },
  689. body: JSON.stringify({ name: playlistName })
  690. });
  691. const result = await response.json();
  692. if (result.success) {
  693. logMessage(result.message);
  694. loadAllPlaylists(); // Refresh the UI
  695. } else {
  696. logMessage(`Failed to delete playlist: ${result.error}`);
  697. }
  698. } catch (err) {
  699. logMessage(`Error deleting playlist: ${err}`);
  700. }
  701. }
  702. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  703. // PART D: Local playlist array UI
  704. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  705. // Called when the user clicks "Add File to Playlist"
  706. function addToPlaylist() {
  707. if (!selectedFile) {
  708. logMessage("No file selected to add to the playlist.");
  709. return;
  710. }
  711. // Add the current selectedFile to the local array
  712. playlist.push(selectedFile);
  713. logMessage(`Added "${selectedFile}" to the playlist.`);
  714. refreshPlaylistUI();
  715. }
  716. function refreshPlaylistUI() {
  717. const ul = document.getElementById('playlist_items');
  718. ul.innerHTML = '';
  719. playlist.forEach((file, index) => {
  720. const li = document.createElement('li');
  721. li.textContent = file;
  722. // When you click on a file in the playlist, mark it as selected
  723. li.onclick = () => selectPlaylistItem(index);
  724. // Highlight the currently selected playlist item
  725. if (index === selectedPlaylistIndex) {
  726. li.classList.add('selected');
  727. }
  728. ul.appendChild(li);
  729. });
  730. }
  731. function selectPlaylistItem(index) {
  732. selectedPlaylistIndex = index;
  733. refreshPlaylistUI();
  734. logMessage(`Selected playlist file: ${playlist[index]}`);
  735. }
  736. function movePlaylistItemUp() {
  737. if (selectedPlaylistIndex === null || selectedPlaylistIndex <= 0) return;
  738. const temp = playlist[selectedPlaylistIndex - 1];
  739. playlist[selectedPlaylistIndex - 1] = playlist[selectedPlaylistIndex];
  740. playlist[selectedPlaylistIndex] = temp;
  741. selectedPlaylistIndex--;
  742. refreshPlaylistUI();
  743. }
  744. function movePlaylistItemDown() {
  745. if (selectedPlaylistIndex === null || selectedPlaylistIndex >= playlist.length - 1) return;
  746. const temp = playlist[selectedPlaylistIndex + 1];
  747. playlist[selectedPlaylistIndex + 1] = playlist[selectedPlaylistIndex];
  748. playlist[selectedPlaylistIndex] = temp;
  749. selectedPlaylistIndex++;
  750. refreshPlaylistUI();
  751. }
  752. function removeFromPlaylist() {
  753. if (selectedPlaylistIndex === null) {
  754. logMessage("No item selected in the playlist to remove.");
  755. return;
  756. }
  757. const removedFile = playlist[selectedPlaylistIndex];
  758. playlist.splice(selectedPlaylistIndex, 1);
  759. selectedPlaylistIndex = null;
  760. refreshPlaylistUI();
  761. logMessage(`Removed "${removedFile}" from the playlist.`);
  762. }
  763. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  764. // PART E: Page load initialization
  765. // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  766. // Make sure we load the existing playlists list on page load
  767. document.addEventListener('DOMContentLoaded', () => {
  768. loadAllPlaylists();
  769. });
  770. </script>
  771. </body>
  772. </html>