index.html 38 KB

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