index.html 39 KB

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