settings.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  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. ]).then(([statusData, wledData, updateData, ports, patterns, clearPatterns]) => {
  156. // Update connection status
  157. setCachedConnectionStatus(statusData);
  158. updateConnectionUI(statusData);
  159. // Update WLED IP
  160. if (wledData.wled_ip) {
  161. document.getElementById('wledIpInput').value = wledData.wled_ip;
  162. setWledButtonState(true);
  163. } else {
  164. setWledButtonState(false);
  165. }
  166. // Update version display
  167. const currentVersionText = document.getElementById('currentVersionText');
  168. const latestVersionText = document.getElementById('latestVersionText');
  169. const updateButton = document.getElementById('updateSoftware');
  170. const updateIcon = document.getElementById('updateIcon');
  171. const updateText = document.getElementById('updateText');
  172. if (currentVersionText) {
  173. currentVersionText.textContent = updateData.current;
  174. }
  175. if (latestVersionText) {
  176. if (updateData.error) {
  177. latestVersionText.textContent = 'Error checking updates';
  178. latestVersionText.className = 'text-red-500 text-sm font-normal leading-normal';
  179. } else {
  180. latestVersionText.textContent = updateData.latest;
  181. latestVersionText.className = 'text-slate-500 text-sm font-normal leading-normal';
  182. }
  183. }
  184. // Update button state
  185. if (updateButton && updateIcon && updateText) {
  186. if (updateData.update_available) {
  187. updateButton.disabled = false;
  188. 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';
  189. updateIcon.textContent = 'download';
  190. updateText.textContent = 'Update';
  191. } else {
  192. updateButton.disabled = true;
  193. 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';
  194. updateIcon.textContent = 'check';
  195. updateText.textContent = 'Up to date';
  196. }
  197. }
  198. // Update port selection
  199. const portSelect = document.getElementById('portSelect');
  200. if (portSelect) {
  201. // Clear existing options except the first one
  202. while (portSelect.options.length > 1) {
  203. portSelect.remove(1);
  204. }
  205. // Add new options
  206. ports.forEach(port => {
  207. const option = document.createElement('option');
  208. option.value = port;
  209. option.textContent = port;
  210. portSelect.appendChild(option);
  211. });
  212. // If there's exactly one port available, select it
  213. if (ports.length === 1) {
  214. portSelect.value = ports[0];
  215. }
  216. }
  217. // Initialize autocomplete for clear patterns
  218. const clearFromInInput = document.getElementById('customClearFromInInput');
  219. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  220. if (clearFromInInput && clearFromOutInput && patterns && Array.isArray(patterns)) {
  221. // Store patterns globally for autocomplete
  222. window.availablePatterns = patterns;
  223. // Set current values if they exist
  224. if (clearPatterns && clearPatterns.custom_clear_from_in) {
  225. clearFromInInput.value = clearPatterns.custom_clear_from_in;
  226. }
  227. if (clearPatterns && clearPatterns.custom_clear_from_out) {
  228. clearFromOutInput.value = clearPatterns.custom_clear_from_out;
  229. }
  230. // Initialize autocomplete for both inputs
  231. initializeAutocomplete('customClearFromInInput', 'clearFromInSuggestions', 'clearFromInClear', patterns);
  232. initializeAutocomplete('customClearFromOutInput', 'clearFromOutSuggestions', 'clearFromOutClear', patterns);
  233. console.log('Autocomplete initialized with', patterns.length, 'patterns');
  234. }
  235. }).catch(error => {
  236. logMessage(`Error initializing settings page: ${error.message}`, LOG_TYPE.ERROR);
  237. });
  238. // Set up event listeners
  239. setupEventListeners();
  240. });
  241. // Setup event listeners
  242. function setupEventListeners() {
  243. // Save/Clear WLED configuration
  244. const saveWledConfig = document.getElementById('saveWledConfig');
  245. const wledIpInput = document.getElementById('wledIpInput');
  246. if (saveWledConfig && wledIpInput) {
  247. saveWledConfig.addEventListener('click', async () => {
  248. if (saveWledConfig.textContent.includes('Clear')) {
  249. // Clear WLED IP
  250. wledIpInput.value = '';
  251. try {
  252. const response = await fetch('/set_wled_ip', {
  253. method: 'POST',
  254. headers: { 'Content-Type': 'application/json' },
  255. body: JSON.stringify({ wled_ip: '' })
  256. });
  257. if (response.ok) {
  258. setWledButtonState(false);
  259. localStorage.removeItem('wled_ip');
  260. showStatusMessage('WLED IP cleared successfully', 'success');
  261. } else {
  262. throw new Error('Failed to clear WLED IP');
  263. }
  264. } catch (error) {
  265. showStatusMessage(`Failed to clear WLED IP: ${error.message}`, 'error');
  266. }
  267. } else {
  268. // Save WLED IP
  269. const wledIp = wledIpInput.value;
  270. try {
  271. const response = await fetch('/set_wled_ip', {
  272. method: 'POST',
  273. headers: { 'Content-Type': 'application/json' },
  274. body: JSON.stringify({ wled_ip: wledIp })
  275. });
  276. if (response.ok && wledIp) {
  277. setWledButtonState(true);
  278. localStorage.setItem('wled_ip', wledIp);
  279. showStatusMessage('WLED IP configured successfully', 'success');
  280. } else {
  281. setWledButtonState(false);
  282. throw new Error('Failed to save WLED configuration');
  283. }
  284. } catch (error) {
  285. showStatusMessage(`Failed to save WLED IP: ${error.message}`, 'error');
  286. }
  287. }
  288. });
  289. }
  290. // Update software
  291. const updateSoftware = document.getElementById('updateSoftware');
  292. if (updateSoftware) {
  293. updateSoftware.addEventListener('click', async () => {
  294. if (updateSoftware.disabled) {
  295. return;
  296. }
  297. try {
  298. const response = await fetch('/api/update', {
  299. method: 'POST'
  300. });
  301. const data = await response.json();
  302. if (data.success) {
  303. showStatusMessage('Software update started successfully', 'success');
  304. } else if (data.manual_update_url) {
  305. // Show modal with manual update instructions, but use wiki link
  306. const wikiData = {
  307. ...data,
  308. manual_update_url: 'https://github.com/tuanchris/dune-weaver/wiki/Updating-software'
  309. };
  310. showUpdateInstructionsModal(wikiData);
  311. } else {
  312. showStatusMessage(data.message || 'No updates available', 'info');
  313. }
  314. } catch (error) {
  315. logMessage(`Error updating software: ${error.message}`, LOG_TYPE.ERROR);
  316. showStatusMessage('Failed to check for updates', 'error');
  317. }
  318. });
  319. }
  320. // Connect button
  321. const connectButton = document.getElementById('connectButton');
  322. if (connectButton) {
  323. connectButton.addEventListener('click', async () => {
  324. const portSelect = document.getElementById('portSelect');
  325. if (!portSelect || !portSelect.value) {
  326. logMessage('Please select a port first', LOG_TYPE.WARNING);
  327. return;
  328. }
  329. try {
  330. const response = await fetch('/connect', {
  331. method: 'POST',
  332. headers: { 'Content-Type': 'application/json' },
  333. body: JSON.stringify({ port: portSelect.value })
  334. });
  335. if (response.ok) {
  336. logMessage('Connected successfully', LOG_TYPE.SUCCESS);
  337. await updateSerialStatus(true); // Force update after connecting
  338. } else {
  339. throw new Error('Failed to connect');
  340. }
  341. } catch (error) {
  342. logMessage(`Error connecting to device: ${error.message}`, LOG_TYPE.ERROR);
  343. }
  344. });
  345. }
  346. // Disconnect button
  347. const disconnectButton = document.getElementById('disconnectButton');
  348. if (disconnectButton) {
  349. disconnectButton.addEventListener('click', async () => {
  350. try {
  351. const response = await fetch('/disconnect', {
  352. method: 'POST'
  353. });
  354. if (response.ok) {
  355. logMessage('Device disconnected successfully', LOG_TYPE.SUCCESS);
  356. await updateSerialStatus(true); // Force update after disconnecting
  357. } else {
  358. throw new Error('Failed to disconnect device');
  359. }
  360. } catch (error) {
  361. logMessage(`Error disconnecting device: ${error.message}`, LOG_TYPE.ERROR);
  362. }
  363. });
  364. }
  365. // Save custom clear patterns button
  366. const saveClearPatterns = document.getElementById('saveClearPatterns');
  367. if (saveClearPatterns) {
  368. saveClearPatterns.addEventListener('click', async () => {
  369. const clearFromInInput = document.getElementById('customClearFromInInput');
  370. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  371. if (!clearFromInInput || !clearFromOutInput) {
  372. return;
  373. }
  374. // Validate that the entered patterns exist (if not empty)
  375. const inValue = clearFromInInput.value.trim();
  376. const outValue = clearFromOutInput.value.trim();
  377. if (inValue && window.availablePatterns && !window.availablePatterns.includes(inValue)) {
  378. showStatusMessage(`Pattern not found: ${inValue}`, 'error');
  379. return;
  380. }
  381. if (outValue && window.availablePatterns && !window.availablePatterns.includes(outValue)) {
  382. showStatusMessage(`Pattern not found: ${outValue}`, 'error');
  383. return;
  384. }
  385. try {
  386. const response = await fetch('/api/custom_clear_patterns', {
  387. method: 'POST',
  388. headers: { 'Content-Type': 'application/json' },
  389. body: JSON.stringify({
  390. custom_clear_from_in: inValue || null,
  391. custom_clear_from_out: outValue || null
  392. })
  393. });
  394. if (response.ok) {
  395. showStatusMessage('Clear patterns saved successfully', 'success');
  396. } else {
  397. const error = await response.json();
  398. throw new Error(error.detail || 'Failed to save clear patterns');
  399. }
  400. } catch (error) {
  401. showStatusMessage(`Failed to save clear patterns: ${error.message}`, 'error');
  402. }
  403. });
  404. }
  405. }
  406. // Button click handlers
  407. document.addEventListener('DOMContentLoaded', function() {
  408. // Home button
  409. const homeButton = document.getElementById('homeButton');
  410. if (homeButton) {
  411. homeButton.addEventListener('click', async () => {
  412. try {
  413. const response = await fetch('/send_home', {
  414. method: 'POST',
  415. headers: {
  416. 'Content-Type': 'application/json'
  417. }
  418. });
  419. const data = await response.json();
  420. if (data.success) {
  421. updateStatus('Moving to home position...');
  422. }
  423. } catch (error) {
  424. console.error('Error sending home command:', error);
  425. updateStatus('Error: Failed to move to home position');
  426. }
  427. });
  428. }
  429. // Stop button
  430. const stopButton = document.getElementById('stopButton');
  431. if (stopButton) {
  432. stopButton.addEventListener('click', async () => {
  433. try {
  434. const response = await fetch('/stop_execution', {
  435. method: 'POST',
  436. headers: {
  437. 'Content-Type': 'application/json'
  438. }
  439. });
  440. const data = await response.json();
  441. if (data.success) {
  442. updateStatus('Execution stopped');
  443. }
  444. } catch (error) {
  445. console.error('Error stopping execution:', error);
  446. updateStatus('Error: Failed to stop execution');
  447. }
  448. });
  449. }
  450. // Move to Center button
  451. const centerButton = document.getElementById('centerButton');
  452. if (centerButton) {
  453. centerButton.addEventListener('click', async () => {
  454. try {
  455. const response = await fetch('/move_to_center', {
  456. method: 'POST',
  457. headers: {
  458. 'Content-Type': 'application/json'
  459. }
  460. });
  461. const data = await response.json();
  462. if (data.success) {
  463. updateStatus('Moving to center position...');
  464. }
  465. } catch (error) {
  466. console.error('Error moving to center:', error);
  467. updateStatus('Error: Failed to move to center');
  468. }
  469. });
  470. }
  471. // Move to Perimeter button
  472. const perimeterButton = document.getElementById('perimeterButton');
  473. if (perimeterButton) {
  474. perimeterButton.addEventListener('click', async () => {
  475. try {
  476. const response = await fetch('/move_to_perimeter', {
  477. method: 'POST',
  478. headers: {
  479. 'Content-Type': 'application/json'
  480. }
  481. });
  482. const data = await response.json();
  483. if (data.success) {
  484. updateStatus('Moving to perimeter position...');
  485. }
  486. } catch (error) {
  487. console.error('Error moving to perimeter:', error);
  488. updateStatus('Error: Failed to move to perimeter');
  489. }
  490. });
  491. }
  492. });
  493. // Function to update status
  494. function updateStatus(message) {
  495. const statusElement = document.querySelector('.text-slate-800.text-base.font-medium.leading-normal');
  496. if (statusElement) {
  497. statusElement.textContent = message;
  498. // Reset status after 3 seconds if it's a temporary message
  499. if (message.includes('Moving') || message.includes('Execution')) {
  500. setTimeout(() => {
  501. statusElement.textContent = 'Status';
  502. }, 3000);
  503. }
  504. }
  505. }
  506. // Function to show status messages (using existing base.js showStatusMessage if available)
  507. function showStatusMessage(message, type) {
  508. if (typeof window.showStatusMessage === 'function') {
  509. window.showStatusMessage(message, type);
  510. } else {
  511. // Fallback to console logging
  512. console.log(`[${type}] ${message}`);
  513. }
  514. }
  515. // Function to show update instructions modal
  516. function showUpdateInstructionsModal(data) {
  517. // Create modal HTML
  518. const modal = document.createElement('div');
  519. modal.id = 'updateInstructionsModal';
  520. modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
  521. modal.innerHTML = `
  522. <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md">
  523. <div class="p-6">
  524. <div class="text-center mb-4">
  525. <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-2">Manual Update Required</h2>
  526. <p class="text-gray-600 dark:text-gray-400 text-sm">
  527. ${data.message}
  528. </p>
  529. </div>
  530. <div class="text-gray-700 dark:text-gray-300 text-sm mb-6">
  531. <p class="mb-3">${data.instructions}</p>
  532. </div>
  533. <div class="flex gap-3 justify-center">
  534. <button id="openGitHubRelease" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
  535. View Update Instructions
  536. </button>
  537. <button id="closeUpdateModal" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors">
  538. Close
  539. </button>
  540. </div>
  541. </div>
  542. </div>
  543. `;
  544. document.body.appendChild(modal);
  545. // Add event listeners
  546. const openGitHubButton = modal.querySelector('#openGitHubRelease');
  547. const closeButton = modal.querySelector('#closeUpdateModal');
  548. openGitHubButton.addEventListener('click', () => {
  549. window.open(data.manual_update_url, '_blank');
  550. document.body.removeChild(modal);
  551. });
  552. closeButton.addEventListener('click', () => {
  553. document.body.removeChild(modal);
  554. });
  555. // Close on outside click
  556. modal.addEventListener('click', (e) => {
  557. if (e.target === modal) {
  558. document.body.removeChild(modal);
  559. }
  560. });
  561. }
  562. // Autocomplete functionality
  563. function initializeAutocomplete(inputId, suggestionsId, clearButtonId, patterns) {
  564. const input = document.getElementById(inputId);
  565. const suggestionsDiv = document.getElementById(suggestionsId);
  566. const clearButton = document.getElementById(clearButtonId);
  567. let selectedIndex = -1;
  568. if (!input || !suggestionsDiv) return;
  569. // Function to update clear button visibility
  570. function updateClearButton() {
  571. if (clearButton) {
  572. if (input.value.trim()) {
  573. clearButton.classList.remove('hidden');
  574. } else {
  575. clearButton.classList.add('hidden');
  576. }
  577. }
  578. }
  579. // Format pattern name for display
  580. function formatPatternName(pattern) {
  581. return pattern.replace('.thr', '').replace(/_/g, ' ');
  582. }
  583. // Filter patterns based on input
  584. function filterPatterns(searchTerm) {
  585. if (!searchTerm) return patterns.slice(0, 20); // Show first 20 when empty
  586. const term = searchTerm.toLowerCase();
  587. return patterns.filter(pattern => {
  588. const name = pattern.toLowerCase();
  589. return name.includes(term);
  590. }).sort((a, b) => {
  591. // Prioritize patterns that start with the search term
  592. const aStarts = a.toLowerCase().startsWith(term);
  593. const bStarts = b.toLowerCase().startsWith(term);
  594. if (aStarts && !bStarts) return -1;
  595. if (!aStarts && bStarts) return 1;
  596. return a.localeCompare(b);
  597. }).slice(0, 20); // Limit to 20 results
  598. }
  599. // Highlight matching text
  600. function highlightMatch(text, searchTerm) {
  601. if (!searchTerm) return text;
  602. const regex = new RegExp(`(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
  603. return text.replace(regex, '<mark>$1</mark>');
  604. }
  605. // Show suggestions
  606. function showSuggestions(searchTerm) {
  607. const filtered = filterPatterns(searchTerm);
  608. if (filtered.length === 0 && searchTerm) {
  609. suggestionsDiv.innerHTML = '<div class="suggestion-item" style="cursor: default; color: #9ca3af;">No patterns found</div>';
  610. suggestionsDiv.classList.remove('hidden');
  611. return;
  612. }
  613. suggestionsDiv.innerHTML = filtered.map((pattern, index) => {
  614. const displayName = formatPatternName(pattern);
  615. const highlighted = highlightMatch(displayName, searchTerm);
  616. return `<div class="suggestion-item" data-value="${pattern}" data-index="${index}">${highlighted}</div>`;
  617. }).join('');
  618. suggestionsDiv.classList.remove('hidden');
  619. selectedIndex = -1;
  620. }
  621. // Hide suggestions
  622. function hideSuggestions() {
  623. setTimeout(() => {
  624. suggestionsDiv.classList.add('hidden');
  625. selectedIndex = -1;
  626. }, 200);
  627. }
  628. // Select suggestion
  629. function selectSuggestion(value) {
  630. input.value = value;
  631. hideSuggestions();
  632. updateClearButton();
  633. }
  634. // Handle keyboard navigation
  635. function handleKeyboard(e) {
  636. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  637. if (e.key === 'ArrowDown') {
  638. e.preventDefault();
  639. selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
  640. updateSelection(items);
  641. } else if (e.key === 'ArrowUp') {
  642. e.preventDefault();
  643. selectedIndex = Math.max(selectedIndex - 1, -1);
  644. updateSelection(items);
  645. } else if (e.key === 'Enter') {
  646. e.preventDefault();
  647. if (selectedIndex >= 0 && items[selectedIndex]) {
  648. selectSuggestion(items[selectedIndex].dataset.value);
  649. } else if (items.length === 1) {
  650. selectSuggestion(items[0].dataset.value);
  651. }
  652. } else if (e.key === 'Escape') {
  653. hideSuggestions();
  654. }
  655. }
  656. // Update visual selection
  657. function updateSelection(items) {
  658. items.forEach((item, index) => {
  659. if (index === selectedIndex) {
  660. item.classList.add('selected');
  661. item.scrollIntoView({ block: 'nearest' });
  662. } else {
  663. item.classList.remove('selected');
  664. }
  665. });
  666. }
  667. // Event listeners
  668. input.addEventListener('input', (e) => {
  669. const value = e.target.value.trim();
  670. updateClearButton();
  671. if (value.length > 0 || e.target === document.activeElement) {
  672. showSuggestions(value);
  673. } else {
  674. hideSuggestions();
  675. }
  676. });
  677. input.addEventListener('focus', () => {
  678. const value = input.value.trim();
  679. showSuggestions(value);
  680. });
  681. input.addEventListener('blur', hideSuggestions);
  682. input.addEventListener('keydown', handleKeyboard);
  683. // Click handler for suggestions
  684. suggestionsDiv.addEventListener('click', (e) => {
  685. const item = e.target.closest('.suggestion-item[data-value]');
  686. if (item) {
  687. selectSuggestion(item.dataset.value);
  688. }
  689. });
  690. // Mouse hover handler
  691. suggestionsDiv.addEventListener('mouseover', (e) => {
  692. const item = e.target.closest('.suggestion-item[data-value]');
  693. if (item) {
  694. selectedIndex = parseInt(item.dataset.index);
  695. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  696. updateSelection(items);
  697. }
  698. });
  699. // Clear button handler
  700. if (clearButton) {
  701. clearButton.addEventListener('click', () => {
  702. input.value = '';
  703. updateClearButton();
  704. hideSuggestions();
  705. input.focus();
  706. });
  707. }
  708. // Initialize clear button visibility
  709. updateClearButton();
  710. }