settings.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  1. // Constants for log message types
  2. const LOG_TYPE = {
  3. SUCCESS: 'success',
  4. WARNING: 'warning',
  5. ERROR: 'error',
  6. INFO: 'info',
  7. DEBUG: 'debug'
  8. };
  9. // Constants for cache
  10. const CACHE_KEYS = {
  11. CONNECTION_STATUS: 'connection_status',
  12. LAST_UPDATE: 'last_status_update'
  13. };
  14. const CACHE_DURATION = 5000; // 5 seconds cache duration
  15. // Function to log messages
  16. function logMessage(message, type = LOG_TYPE.DEBUG) {
  17. console.log(`[${type}] ${message}`);
  18. }
  19. // Function to get cached connection status
  20. function getCachedConnectionStatus() {
  21. const cachedData = localStorage.getItem(CACHE_KEYS.CONNECTION_STATUS);
  22. const lastUpdate = localStorage.getItem(CACHE_KEYS.LAST_UPDATE);
  23. if (cachedData && lastUpdate) {
  24. const now = Date.now();
  25. const cacheAge = now - parseInt(lastUpdate);
  26. if (cacheAge < CACHE_DURATION) {
  27. return JSON.parse(cachedData);
  28. }
  29. }
  30. return null;
  31. }
  32. // Function to set cached connection status
  33. function setCachedConnectionStatus(data) {
  34. localStorage.setItem(CACHE_KEYS.CONNECTION_STATUS, JSON.stringify(data));
  35. localStorage.setItem(CACHE_KEYS.LAST_UPDATE, Date.now().toString());
  36. }
  37. // Function to update serial connection status
  38. async function updateSerialStatus(forceUpdate = false) {
  39. try {
  40. // Check cache first unless force update is requested
  41. if (!forceUpdate) {
  42. const cachedData = getCachedConnectionStatus();
  43. if (cachedData) {
  44. updateConnectionUI(cachedData);
  45. return;
  46. }
  47. }
  48. const response = await fetch('/serial_status');
  49. if (response.ok) {
  50. const data = await response.json();
  51. setCachedConnectionStatus(data);
  52. updateConnectionUI(data);
  53. }
  54. } catch (error) {
  55. logMessage(`Error checking serial status: ${error.message}`, LOG_TYPE.ERROR);
  56. }
  57. }
  58. // Function to update UI based on connection status
  59. function updateConnectionUI(data) {
  60. const statusElement = document.getElementById('serialStatus');
  61. const iconElement = document.querySelector('.material-icons.text-3xl');
  62. const disconnectButton = document.getElementById('disconnectButton');
  63. const portSelectionDiv = document.getElementById('portSelectionDiv');
  64. if (statusElement && iconElement) {
  65. if (data.connected) {
  66. statusElement.textContent = `Connected to ${data.port || 'unknown port'}`;
  67. statusElement.className = 'text-green-500 text-sm font-medium leading-normal';
  68. iconElement.textContent = 'usb';
  69. if (disconnectButton) {
  70. disconnectButton.hidden = false;
  71. }
  72. if (portSelectionDiv) {
  73. portSelectionDiv.hidden = true;
  74. }
  75. } else {
  76. statusElement.textContent = 'Disconnected';
  77. statusElement.className = 'text-red-500 text-sm font-medium leading-normal';
  78. iconElement.textContent = 'usb_off';
  79. if (disconnectButton) {
  80. disconnectButton.hidden = true;
  81. }
  82. if (portSelectionDiv) {
  83. portSelectionDiv.hidden = false;
  84. }
  85. }
  86. }
  87. }
  88. // Function to update available serial ports
  89. async function updateSerialPorts() {
  90. try {
  91. const response = await fetch('/list_serial_ports');
  92. if (response.ok) {
  93. const ports = await response.json();
  94. const portsElement = document.getElementById('availablePorts');
  95. const portSelect = document.getElementById('portSelect');
  96. if (portsElement) {
  97. portsElement.textContent = ports.length > 0 ? ports.join(', ') : 'No ports available';
  98. }
  99. if (portSelect) {
  100. // Clear existing options except the first one
  101. while (portSelect.options.length > 1) {
  102. portSelect.remove(1);
  103. }
  104. // Add new options
  105. ports.forEach(port => {
  106. const option = document.createElement('option');
  107. option.value = port;
  108. option.textContent = port;
  109. portSelect.appendChild(option);
  110. });
  111. // If there's exactly one port available, select and connect to it
  112. if (ports.length === 1) {
  113. portSelect.value = ports[0];
  114. // Trigger connect button click
  115. const connectButton = document.getElementById('connectButton');
  116. if (connectButton) {
  117. connectButton.click();
  118. }
  119. }
  120. }
  121. }
  122. } catch (error) {
  123. logMessage(`Error fetching serial ports: ${error.message}`, LOG_TYPE.ERROR);
  124. }
  125. }
  126. function setWledButtonState(isSet) {
  127. const saveWledConfig = document.getElementById('saveWledConfig');
  128. if (!saveWledConfig) return;
  129. if (isSet) {
  130. saveWledConfig.className = 'flex items-center justify-center gap-2 min-w-[100px] max-w-[480px] cursor-pointer rounded-lg h-10 px-4 bg-red-600 hover:bg-red-700 text-white text-sm font-medium leading-normal tracking-[0.015em] transition-colors';
  131. saveWledConfig.innerHTML = '<span class="material-icons text-lg">close</span><span class="truncate">Clear WLED IP</span>';
  132. } else {
  133. saveWledConfig.className = 'flex items-center justify-center gap-2 min-w-[100px] max-w-[480px] cursor-pointer rounded-lg h-10 px-4 bg-sky-600 hover:bg-sky-700 text-white text-sm font-medium leading-normal tracking-[0.015em] transition-colors';
  134. saveWledConfig.innerHTML = '<span class="material-icons text-lg">save</span><span class="truncate">Save Configuration</span>';
  135. }
  136. }
  137. // Initialize settings page
  138. document.addEventListener('DOMContentLoaded', async () => {
  139. // Initialize UI with default disconnected state
  140. updateConnectionUI({ connected: false });
  141. // Load all data asynchronously
  142. Promise.all([
  143. // Check connection status
  144. fetch('/serial_status').then(response => response.json()).catch(() => ({ connected: false })),
  145. // Load current WLED IP
  146. fetch('/get_wled_ip').then(response => response.json()).catch(() => ({ wled_ip: null })),
  147. // Load current version and check for updates
  148. fetch('/api/version').then(response => response.json()).catch(() => ({ current: '1.0.0', latest: '1.0.0', update_available: false })),
  149. // Load available serial ports
  150. fetch('/list_serial_ports').then(response => response.json()).catch(() => []),
  151. // Load available pattern files for clear pattern selection
  152. fetch('/list_theta_rho_files').then(response => response.json()).catch(() => []),
  153. // Load current custom clear patterns
  154. fetch('/api/custom_clear_patterns').then(response => response.json()).catch(() => ({ custom_clear_from_in: null, custom_clear_from_out: null })),
  155. // Load current clear pattern speed
  156. fetch('/api/clear_pattern_speed').then(response => response.json()).catch(() => ({ clear_pattern_speed: 200 })),
  157. // Load current app name
  158. fetch('/api/app-name').then(response => response.json()).catch(() => ({ app_name: 'Dune Weaver' }))
  159. ]).then(([statusData, wledData, updateData, ports, patterns, clearPatterns, clearSpeedData, appNameData]) => {
  160. // Update connection status
  161. setCachedConnectionStatus(statusData);
  162. updateConnectionUI(statusData);
  163. // Update WLED IP
  164. if (wledData.wled_ip) {
  165. document.getElementById('wledIpInput').value = wledData.wled_ip;
  166. setWledButtonState(true);
  167. } else {
  168. setWledButtonState(false);
  169. }
  170. // Update version display
  171. const currentVersionText = document.getElementById('currentVersionText');
  172. const latestVersionText = document.getElementById('latestVersionText');
  173. const updateButton = document.getElementById('updateSoftware');
  174. const updateIcon = document.getElementById('updateIcon');
  175. const updateText = document.getElementById('updateText');
  176. if (currentVersionText) {
  177. currentVersionText.textContent = updateData.current;
  178. }
  179. if (latestVersionText) {
  180. if (updateData.error) {
  181. latestVersionText.textContent = 'Error checking updates';
  182. latestVersionText.className = 'text-red-500 text-sm font-normal leading-normal';
  183. } else {
  184. latestVersionText.textContent = updateData.latest;
  185. latestVersionText.className = 'text-slate-500 text-sm font-normal leading-normal';
  186. }
  187. }
  188. // Update button state
  189. if (updateButton && updateIcon && updateText) {
  190. if (updateData.update_available) {
  191. updateButton.disabled = false;
  192. updateButton.className = 'flex items-center justify-center gap-1.5 min-w-[84px] cursor-pointer rounded-lg h-9 px-3 bg-emerald-500 hover:bg-emerald-600 text-white text-xs font-medium leading-normal tracking-[0.015em] transition-colors';
  193. updateIcon.textContent = 'download';
  194. updateText.textContent = 'Update';
  195. } else {
  196. updateButton.disabled = true;
  197. updateButton.className = 'flex items-center justify-center gap-1.5 min-w-[84px] cursor-pointer rounded-lg h-9 px-3 bg-gray-400 text-white text-xs font-medium leading-normal tracking-[0.015em] transition-colors disabled:opacity-50 disabled:cursor-not-allowed';
  198. updateIcon.textContent = 'check';
  199. updateText.textContent = 'Up to date';
  200. }
  201. }
  202. // Update port selection
  203. const portSelect = document.getElementById('portSelect');
  204. if (portSelect) {
  205. // Clear existing options except the first one
  206. while (portSelect.options.length > 1) {
  207. portSelect.remove(1);
  208. }
  209. // Add new options
  210. ports.forEach(port => {
  211. const option = document.createElement('option');
  212. option.value = port;
  213. option.textContent = port;
  214. portSelect.appendChild(option);
  215. });
  216. // If there's exactly one port available, select it
  217. if (ports.length === 1) {
  218. portSelect.value = ports[0];
  219. }
  220. }
  221. // Initialize autocomplete for clear patterns
  222. const clearFromInInput = document.getElementById('customClearFromInInput');
  223. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  224. if (clearFromInInput && clearFromOutInput && patterns && Array.isArray(patterns)) {
  225. // Store patterns globally for autocomplete
  226. window.availablePatterns = patterns;
  227. // Set current values if they exist
  228. if (clearPatterns && clearPatterns.custom_clear_from_in) {
  229. clearFromInInput.value = clearPatterns.custom_clear_from_in;
  230. }
  231. if (clearPatterns && clearPatterns.custom_clear_from_out) {
  232. clearFromOutInput.value = clearPatterns.custom_clear_from_out;
  233. }
  234. // Initialize autocomplete for both inputs
  235. initializeAutocomplete('customClearFromInInput', 'clearFromInSuggestions', 'clearFromInClear', patterns);
  236. initializeAutocomplete('customClearFromOutInput', 'clearFromOutSuggestions', 'clearFromOutClear', patterns);
  237. console.log('Autocomplete initialized with', patterns.length, 'patterns');
  238. }
  239. // Set clear pattern speed
  240. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  241. if (clearPatternSpeedInput && clearSpeedData && clearSpeedData.clear_pattern_speed) {
  242. clearPatternSpeedInput.value = clearSpeedData.clear_pattern_speed;
  243. }
  244. // Update app name
  245. const appNameInput = document.getElementById('appNameInput');
  246. if (appNameInput && appNameData.app_name) {
  247. appNameInput.value = appNameData.app_name;
  248. }
  249. }).catch(error => {
  250. logMessage(`Error initializing settings page: ${error.message}`, LOG_TYPE.ERROR);
  251. });
  252. // Set up event listeners
  253. setupEventListeners();
  254. });
  255. // Setup event listeners
  256. function setupEventListeners() {
  257. // Save App Name
  258. const saveAppNameButton = document.getElementById('saveAppName');
  259. const appNameInput = document.getElementById('appNameInput');
  260. if (saveAppNameButton && appNameInput) {
  261. saveAppNameButton.addEventListener('click', async () => {
  262. const appName = appNameInput.value.trim() || 'Dune Weaver';
  263. try {
  264. const response = await fetch('/api/app-name', {
  265. method: 'POST',
  266. headers: { 'Content-Type': 'application/json' },
  267. body: JSON.stringify({ app_name: appName })
  268. });
  269. if (response.ok) {
  270. const data = await response.json();
  271. showStatusMessage('Application name updated successfully. Refresh the page to see changes.', 'success');
  272. // Update the page title and header immediately
  273. document.title = `Settings - ${data.app_name}`;
  274. const headerTitle = document.querySelector('h1.text-gray-800');
  275. if (headerTitle) {
  276. // Update just the text content, preserving the connection status dot
  277. const textNode = headerTitle.childNodes[0];
  278. if (textNode && textNode.nodeType === Node.TEXT_NODE) {
  279. textNode.textContent = data.app_name;
  280. }
  281. }
  282. } else {
  283. throw new Error('Failed to save application name');
  284. }
  285. } catch (error) {
  286. showStatusMessage(`Failed to save application name: ${error.message}`, 'error');
  287. }
  288. });
  289. // Handle Enter key in app name input
  290. appNameInput.addEventListener('keypress', (e) => {
  291. if (e.key === 'Enter') {
  292. saveAppNameButton.click();
  293. }
  294. });
  295. }
  296. // Save/Clear WLED configuration
  297. const saveWledConfig = document.getElementById('saveWledConfig');
  298. const wledIpInput = document.getElementById('wledIpInput');
  299. if (saveWledConfig && wledIpInput) {
  300. saveWledConfig.addEventListener('click', async () => {
  301. if (saveWledConfig.textContent.includes('Clear')) {
  302. // Clear WLED IP
  303. wledIpInput.value = '';
  304. try {
  305. const response = await fetch('/set_wled_ip', {
  306. method: 'POST',
  307. headers: { 'Content-Type': 'application/json' },
  308. body: JSON.stringify({ wled_ip: '' })
  309. });
  310. if (response.ok) {
  311. setWledButtonState(false);
  312. localStorage.removeItem('wled_ip');
  313. showStatusMessage('WLED IP cleared successfully', 'success');
  314. } else {
  315. throw new Error('Failed to clear WLED IP');
  316. }
  317. } catch (error) {
  318. showStatusMessage(`Failed to clear WLED IP: ${error.message}`, 'error');
  319. }
  320. } else {
  321. // Save WLED IP
  322. const wledIp = wledIpInput.value;
  323. try {
  324. const response = await fetch('/set_wled_ip', {
  325. method: 'POST',
  326. headers: { 'Content-Type': 'application/json' },
  327. body: JSON.stringify({ wled_ip: wledIp })
  328. });
  329. if (response.ok && wledIp) {
  330. setWledButtonState(true);
  331. localStorage.setItem('wled_ip', wledIp);
  332. showStatusMessage('WLED IP configured successfully', 'success');
  333. } else {
  334. setWledButtonState(false);
  335. throw new Error('Failed to save WLED configuration');
  336. }
  337. } catch (error) {
  338. showStatusMessage(`Failed to save WLED IP: ${error.message}`, 'error');
  339. }
  340. }
  341. });
  342. }
  343. // Update software
  344. const updateSoftware = document.getElementById('updateSoftware');
  345. if (updateSoftware) {
  346. updateSoftware.addEventListener('click', async () => {
  347. if (updateSoftware.disabled) {
  348. return;
  349. }
  350. try {
  351. const response = await fetch('/api/update', {
  352. method: 'POST'
  353. });
  354. const data = await response.json();
  355. if (data.success) {
  356. showStatusMessage('Software update started successfully', 'success');
  357. } else if (data.manual_update_url) {
  358. // Show modal with manual update instructions, but use wiki link
  359. const wikiData = {
  360. ...data,
  361. manual_update_url: 'https://github.com/tuanchris/dune-weaver/wiki/Updating-software'
  362. };
  363. showUpdateInstructionsModal(wikiData);
  364. } else {
  365. showStatusMessage(data.message || 'No updates available', 'info');
  366. }
  367. } catch (error) {
  368. logMessage(`Error updating software: ${error.message}`, LOG_TYPE.ERROR);
  369. showStatusMessage('Failed to check for updates', 'error');
  370. }
  371. });
  372. }
  373. // Connect button
  374. const connectButton = document.getElementById('connectButton');
  375. if (connectButton) {
  376. connectButton.addEventListener('click', async () => {
  377. const portSelect = document.getElementById('portSelect');
  378. if (!portSelect || !portSelect.value) {
  379. logMessage('Please select a port first', LOG_TYPE.WARNING);
  380. return;
  381. }
  382. try {
  383. const response = await fetch('/connect', {
  384. method: 'POST',
  385. headers: { 'Content-Type': 'application/json' },
  386. body: JSON.stringify({ port: portSelect.value })
  387. });
  388. if (response.ok) {
  389. logMessage('Connected successfully', LOG_TYPE.SUCCESS);
  390. await updateSerialStatus(true); // Force update after connecting
  391. } else {
  392. throw new Error('Failed to connect');
  393. }
  394. } catch (error) {
  395. logMessage(`Error connecting to device: ${error.message}`, LOG_TYPE.ERROR);
  396. }
  397. });
  398. }
  399. // Disconnect button
  400. const disconnectButton = document.getElementById('disconnectButton');
  401. if (disconnectButton) {
  402. disconnectButton.addEventListener('click', async () => {
  403. try {
  404. const response = await fetch('/disconnect', {
  405. method: 'POST'
  406. });
  407. if (response.ok) {
  408. logMessage('Device disconnected successfully', LOG_TYPE.SUCCESS);
  409. await updateSerialStatus(true); // Force update after disconnecting
  410. } else {
  411. throw new Error('Failed to disconnect device');
  412. }
  413. } catch (error) {
  414. logMessage(`Error disconnecting device: ${error.message}`, LOG_TYPE.ERROR);
  415. }
  416. });
  417. }
  418. // Save custom clear patterns button
  419. const saveClearPatterns = document.getElementById('saveClearPatterns');
  420. if (saveClearPatterns) {
  421. saveClearPatterns.addEventListener('click', async () => {
  422. const clearFromInInput = document.getElementById('customClearFromInInput');
  423. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  424. if (!clearFromInInput || !clearFromOutInput) {
  425. return;
  426. }
  427. // Validate that the entered patterns exist (if not empty)
  428. const inValue = clearFromInInput.value.trim();
  429. const outValue = clearFromOutInput.value.trim();
  430. if (inValue && window.availablePatterns && !window.availablePatterns.includes(inValue)) {
  431. showStatusMessage(`Pattern not found: ${inValue}`, 'error');
  432. return;
  433. }
  434. if (outValue && window.availablePatterns && !window.availablePatterns.includes(outValue)) {
  435. showStatusMessage(`Pattern not found: ${outValue}`, 'error');
  436. return;
  437. }
  438. try {
  439. const response = await fetch('/api/custom_clear_patterns', {
  440. method: 'POST',
  441. headers: { 'Content-Type': 'application/json' },
  442. body: JSON.stringify({
  443. custom_clear_from_in: inValue || null,
  444. custom_clear_from_out: outValue || null
  445. })
  446. });
  447. if (response.ok) {
  448. showStatusMessage('Clear patterns saved successfully', 'success');
  449. } else {
  450. const error = await response.json();
  451. throw new Error(error.detail || 'Failed to save clear patterns');
  452. }
  453. } catch (error) {
  454. showStatusMessage(`Failed to save clear patterns: ${error.message}`, 'error');
  455. }
  456. });
  457. }
  458. // Save clear pattern speed button
  459. const saveClearSpeed = document.getElementById('saveClearSpeed');
  460. if (saveClearSpeed) {
  461. saveClearSpeed.addEventListener('click', async () => {
  462. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  463. if (!clearPatternSpeedInput) {
  464. return;
  465. }
  466. const speed = parseInt(clearPatternSpeedInput.value);
  467. // Validate speed
  468. if (isNaN(speed) || speed < 50 || speed > 2000) {
  469. showStatusMessage('Clear pattern speed must be between 50 and 2000', 'error');
  470. return;
  471. }
  472. try {
  473. const response = await fetch('/api/clear_pattern_speed', {
  474. method: 'POST',
  475. headers: { 'Content-Type': 'application/json' },
  476. body: JSON.stringify({ clear_pattern_speed: speed })
  477. });
  478. if (response.ok) {
  479. showStatusMessage('Clear pattern speed saved successfully', 'success');
  480. } else {
  481. const error = await response.json();
  482. throw new Error(error.detail || 'Failed to save clear pattern speed');
  483. }
  484. } catch (error) {
  485. showStatusMessage(`Failed to save clear pattern speed: ${error.message}`, 'error');
  486. }
  487. });
  488. }
  489. }
  490. // Button click handlers
  491. document.addEventListener('DOMContentLoaded', function() {
  492. // Home button
  493. const homeButton = document.getElementById('homeButton');
  494. if (homeButton) {
  495. homeButton.addEventListener('click', async () => {
  496. try {
  497. const response = await fetch('/send_home', {
  498. method: 'POST',
  499. headers: {
  500. 'Content-Type': 'application/json'
  501. }
  502. });
  503. const data = await response.json();
  504. if (data.success) {
  505. updateStatus('Moving to home position...');
  506. }
  507. } catch (error) {
  508. console.error('Error sending home command:', error);
  509. updateStatus('Error: Failed to move to home position');
  510. }
  511. });
  512. }
  513. // Stop button
  514. const stopButton = document.getElementById('stopButton');
  515. if (stopButton) {
  516. stopButton.addEventListener('click', async () => {
  517. try {
  518. const response = await fetch('/stop_execution', {
  519. method: 'POST',
  520. headers: {
  521. 'Content-Type': 'application/json'
  522. }
  523. });
  524. const data = await response.json();
  525. if (data.success) {
  526. updateStatus('Execution stopped');
  527. }
  528. } catch (error) {
  529. console.error('Error stopping execution:', error);
  530. updateStatus('Error: Failed to stop execution');
  531. }
  532. });
  533. }
  534. // Move to Center button
  535. const centerButton = document.getElementById('centerButton');
  536. if (centerButton) {
  537. centerButton.addEventListener('click', async () => {
  538. try {
  539. const response = await fetch('/move_to_center', {
  540. method: 'POST',
  541. headers: {
  542. 'Content-Type': 'application/json'
  543. }
  544. });
  545. const data = await response.json();
  546. if (data.success) {
  547. updateStatus('Moving to center position...');
  548. }
  549. } catch (error) {
  550. console.error('Error moving to center:', error);
  551. updateStatus('Error: Failed to move to center');
  552. }
  553. });
  554. }
  555. // Move to Perimeter button
  556. const perimeterButton = document.getElementById('perimeterButton');
  557. if (perimeterButton) {
  558. perimeterButton.addEventListener('click', async () => {
  559. try {
  560. const response = await fetch('/move_to_perimeter', {
  561. method: 'POST',
  562. headers: {
  563. 'Content-Type': 'application/json'
  564. }
  565. });
  566. const data = await response.json();
  567. if (data.success) {
  568. updateStatus('Moving to perimeter position...');
  569. }
  570. } catch (error) {
  571. console.error('Error moving to perimeter:', error);
  572. updateStatus('Error: Failed to move to perimeter');
  573. }
  574. });
  575. }
  576. });
  577. // Function to update status
  578. function updateStatus(message) {
  579. const statusElement = document.querySelector('.text-slate-800.text-base.font-medium.leading-normal');
  580. if (statusElement) {
  581. statusElement.textContent = message;
  582. // Reset status after 3 seconds if it's a temporary message
  583. if (message.includes('Moving') || message.includes('Execution')) {
  584. setTimeout(() => {
  585. statusElement.textContent = 'Status';
  586. }, 3000);
  587. }
  588. }
  589. }
  590. // Function to show status messages (using existing base.js showStatusMessage if available)
  591. function showStatusMessage(message, type) {
  592. if (typeof window.showStatusMessage === 'function') {
  593. window.showStatusMessage(message, type);
  594. } else {
  595. // Fallback to console logging
  596. console.log(`[${type}] ${message}`);
  597. }
  598. }
  599. // Function to show update instructions modal
  600. function showUpdateInstructionsModal(data) {
  601. // Create modal HTML
  602. const modal = document.createElement('div');
  603. modal.id = 'updateInstructionsModal';
  604. modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
  605. modal.innerHTML = `
  606. <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md">
  607. <div class="p-6">
  608. <div class="text-center mb-4">
  609. <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-2">Manual Update Required</h2>
  610. <p class="text-gray-600 dark:text-gray-400 text-sm">
  611. ${data.message}
  612. </p>
  613. </div>
  614. <div class="text-gray-700 dark:text-gray-300 text-sm mb-6">
  615. <p class="mb-3">${data.instructions}</p>
  616. </div>
  617. <div class="flex gap-3 justify-center">
  618. <button id="openGitHubRelease" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
  619. View Update Instructions
  620. </button>
  621. <button id="closeUpdateModal" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors">
  622. Close
  623. </button>
  624. </div>
  625. </div>
  626. </div>
  627. `;
  628. document.body.appendChild(modal);
  629. // Add event listeners
  630. const openGitHubButton = modal.querySelector('#openGitHubRelease');
  631. const closeButton = modal.querySelector('#closeUpdateModal');
  632. openGitHubButton.addEventListener('click', () => {
  633. window.open(data.manual_update_url, '_blank');
  634. document.body.removeChild(modal);
  635. });
  636. closeButton.addEventListener('click', () => {
  637. document.body.removeChild(modal);
  638. });
  639. // Close on outside click
  640. modal.addEventListener('click', (e) => {
  641. if (e.target === modal) {
  642. document.body.removeChild(modal);
  643. }
  644. });
  645. }
  646. // Autocomplete functionality
  647. function initializeAutocomplete(inputId, suggestionsId, clearButtonId, patterns) {
  648. const input = document.getElementById(inputId);
  649. const suggestionsDiv = document.getElementById(suggestionsId);
  650. const clearButton = document.getElementById(clearButtonId);
  651. let selectedIndex = -1;
  652. if (!input || !suggestionsDiv) return;
  653. // Function to update clear button visibility
  654. function updateClearButton() {
  655. if (clearButton) {
  656. if (input.value.trim()) {
  657. clearButton.classList.remove('hidden');
  658. } else {
  659. clearButton.classList.add('hidden');
  660. }
  661. }
  662. }
  663. // Format pattern name for display
  664. function formatPatternName(pattern) {
  665. return pattern.replace('.thr', '').replace(/_/g, ' ');
  666. }
  667. // Filter patterns based on input
  668. function filterPatterns(searchTerm) {
  669. if (!searchTerm) return patterns.slice(0, 20); // Show first 20 when empty
  670. const term = searchTerm.toLowerCase();
  671. return patterns.filter(pattern => {
  672. const name = pattern.toLowerCase();
  673. return name.includes(term);
  674. }).sort((a, b) => {
  675. // Prioritize patterns that start with the search term
  676. const aStarts = a.toLowerCase().startsWith(term);
  677. const bStarts = b.toLowerCase().startsWith(term);
  678. if (aStarts && !bStarts) return -1;
  679. if (!aStarts && bStarts) return 1;
  680. return a.localeCompare(b);
  681. }).slice(0, 20); // Limit to 20 results
  682. }
  683. // Highlight matching text
  684. function highlightMatch(text, searchTerm) {
  685. if (!searchTerm) return text;
  686. const regex = new RegExp(`(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
  687. return text.replace(regex, '<mark>$1</mark>');
  688. }
  689. // Show suggestions
  690. function showSuggestions(searchTerm) {
  691. const filtered = filterPatterns(searchTerm);
  692. if (filtered.length === 0 && searchTerm) {
  693. suggestionsDiv.innerHTML = '<div class="suggestion-item" style="cursor: default; color: #9ca3af;">No patterns found</div>';
  694. suggestionsDiv.classList.remove('hidden');
  695. return;
  696. }
  697. suggestionsDiv.innerHTML = filtered.map((pattern, index) => {
  698. const displayName = formatPatternName(pattern);
  699. const highlighted = highlightMatch(displayName, searchTerm);
  700. return `<div class="suggestion-item" data-value="${pattern}" data-index="${index}">${highlighted}</div>`;
  701. }).join('');
  702. suggestionsDiv.classList.remove('hidden');
  703. selectedIndex = -1;
  704. }
  705. // Hide suggestions
  706. function hideSuggestions() {
  707. setTimeout(() => {
  708. suggestionsDiv.classList.add('hidden');
  709. selectedIndex = -1;
  710. }, 200);
  711. }
  712. // Select suggestion
  713. function selectSuggestion(value) {
  714. input.value = value;
  715. hideSuggestions();
  716. updateClearButton();
  717. }
  718. // Handle keyboard navigation
  719. function handleKeyboard(e) {
  720. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  721. if (e.key === 'ArrowDown') {
  722. e.preventDefault();
  723. selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
  724. updateSelection(items);
  725. } else if (e.key === 'ArrowUp') {
  726. e.preventDefault();
  727. selectedIndex = Math.max(selectedIndex - 1, -1);
  728. updateSelection(items);
  729. } else if (e.key === 'Enter') {
  730. e.preventDefault();
  731. if (selectedIndex >= 0 && items[selectedIndex]) {
  732. selectSuggestion(items[selectedIndex].dataset.value);
  733. } else if (items.length === 1) {
  734. selectSuggestion(items[0].dataset.value);
  735. }
  736. } else if (e.key === 'Escape') {
  737. hideSuggestions();
  738. }
  739. }
  740. // Update visual selection
  741. function updateSelection(items) {
  742. items.forEach((item, index) => {
  743. if (index === selectedIndex) {
  744. item.classList.add('selected');
  745. item.scrollIntoView({ block: 'nearest' });
  746. } else {
  747. item.classList.remove('selected');
  748. }
  749. });
  750. }
  751. // Event listeners
  752. input.addEventListener('input', (e) => {
  753. const value = e.target.value.trim();
  754. updateClearButton();
  755. if (value.length > 0 || e.target === document.activeElement) {
  756. showSuggestions(value);
  757. } else {
  758. hideSuggestions();
  759. }
  760. });
  761. input.addEventListener('focus', () => {
  762. const value = input.value.trim();
  763. showSuggestions(value);
  764. });
  765. input.addEventListener('blur', hideSuggestions);
  766. input.addEventListener('keydown', handleKeyboard);
  767. // Click handler for suggestions
  768. suggestionsDiv.addEventListener('click', (e) => {
  769. const item = e.target.closest('.suggestion-item[data-value]');
  770. if (item) {
  771. selectSuggestion(item.dataset.value);
  772. }
  773. });
  774. // Mouse hover handler
  775. suggestionsDiv.addEventListener('mouseover', (e) => {
  776. const item = e.target.closest('.suggestion-item[data-value]');
  777. if (item) {
  778. selectedIndex = parseInt(item.dataset.index);
  779. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  780. updateSelection(items);
  781. }
  782. });
  783. // Clear button handler
  784. if (clearButton) {
  785. clearButton.addEventListener('click', () => {
  786. input.value = '';
  787. updateClearButton();
  788. hideSuggestions();
  789. input.focus();
  790. });
  791. }
  792. // Initialize clear button visibility
  793. updateClearButton();
  794. }