1
0

settings.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  242. if (clearPatternSpeedInput && clearSpeedData) {
  243. // Only set value if clear_pattern_speed is not null
  244. if (clearSpeedData.clear_pattern_speed !== null && clearSpeedData.clear_pattern_speed !== undefined) {
  245. clearPatternSpeedInput.value = clearSpeedData.clear_pattern_speed;
  246. if (effectiveClearSpeed) {
  247. effectiveClearSpeed.textContent = `Current: ${clearSpeedData.clear_pattern_speed} steps/min`;
  248. }
  249. } else {
  250. // Leave empty to show placeholder for default
  251. clearPatternSpeedInput.value = '';
  252. if (effectiveClearSpeed && clearSpeedData.effective_speed) {
  253. effectiveClearSpeed.textContent = `Using default pattern speed: ${clearSpeedData.effective_speed} steps/min`;
  254. }
  255. }
  256. }
  257. // Update app name
  258. const appNameInput = document.getElementById('appNameInput');
  259. if (appNameInput && appNameData.app_name) {
  260. appNameInput.value = appNameData.app_name;
  261. }
  262. }).catch(error => {
  263. logMessage(`Error initializing settings page: ${error.message}`, LOG_TYPE.ERROR);
  264. });
  265. // Set up event listeners
  266. setupEventListeners();
  267. });
  268. // Setup event listeners
  269. function setupEventListeners() {
  270. // Save App Name
  271. const saveAppNameButton = document.getElementById('saveAppName');
  272. const appNameInput = document.getElementById('appNameInput');
  273. if (saveAppNameButton && appNameInput) {
  274. saveAppNameButton.addEventListener('click', async () => {
  275. const appName = appNameInput.value.trim() || 'Dune Weaver';
  276. try {
  277. const response = await fetch('/api/app-name', {
  278. method: 'POST',
  279. headers: { 'Content-Type': 'application/json' },
  280. body: JSON.stringify({ app_name: appName })
  281. });
  282. if (response.ok) {
  283. const data = await response.json();
  284. showStatusMessage('Application name updated successfully. Refresh the page to see changes.', 'success');
  285. // Update the page title and header immediately
  286. document.title = `Settings - ${data.app_name}`;
  287. const headerTitle = document.querySelector('h1.text-gray-800');
  288. if (headerTitle) {
  289. // Update just the text content, preserving the connection status dot
  290. const textNode = headerTitle.childNodes[0];
  291. if (textNode && textNode.nodeType === Node.TEXT_NODE) {
  292. textNode.textContent = data.app_name;
  293. }
  294. }
  295. } else {
  296. throw new Error('Failed to save application name');
  297. }
  298. } catch (error) {
  299. showStatusMessage(`Failed to save application name: ${error.message}`, 'error');
  300. }
  301. });
  302. // Handle Enter key in app name input
  303. appNameInput.addEventListener('keypress', (e) => {
  304. if (e.key === 'Enter') {
  305. saveAppNameButton.click();
  306. }
  307. });
  308. }
  309. // Save/Clear WLED configuration
  310. const saveWledConfig = document.getElementById('saveWledConfig');
  311. const wledIpInput = document.getElementById('wledIpInput');
  312. if (saveWledConfig && wledIpInput) {
  313. saveWledConfig.addEventListener('click', async () => {
  314. if (saveWledConfig.textContent.includes('Clear')) {
  315. // Clear WLED IP
  316. wledIpInput.value = '';
  317. try {
  318. const response = await fetch('/set_wled_ip', {
  319. method: 'POST',
  320. headers: { 'Content-Type': 'application/json' },
  321. body: JSON.stringify({ wled_ip: '' })
  322. });
  323. if (response.ok) {
  324. setWledButtonState(false);
  325. localStorage.removeItem('wled_ip');
  326. showStatusMessage('WLED IP cleared successfully', 'success');
  327. } else {
  328. throw new Error('Failed to clear WLED IP');
  329. }
  330. } catch (error) {
  331. showStatusMessage(`Failed to clear WLED IP: ${error.message}`, 'error');
  332. }
  333. } else {
  334. // Save WLED IP
  335. const wledIp = wledIpInput.value;
  336. try {
  337. const response = await fetch('/set_wled_ip', {
  338. method: 'POST',
  339. headers: { 'Content-Type': 'application/json' },
  340. body: JSON.stringify({ wled_ip: wledIp })
  341. });
  342. if (response.ok && wledIp) {
  343. setWledButtonState(true);
  344. localStorage.setItem('wled_ip', wledIp);
  345. showStatusMessage('WLED IP configured successfully', 'success');
  346. } else {
  347. setWledButtonState(false);
  348. throw new Error('Failed to save WLED configuration');
  349. }
  350. } catch (error) {
  351. showStatusMessage(`Failed to save WLED IP: ${error.message}`, 'error');
  352. }
  353. }
  354. });
  355. }
  356. // Update software
  357. const updateSoftware = document.getElementById('updateSoftware');
  358. if (updateSoftware) {
  359. updateSoftware.addEventListener('click', async () => {
  360. if (updateSoftware.disabled) {
  361. return;
  362. }
  363. try {
  364. const response = await fetch('/api/update', {
  365. method: 'POST'
  366. });
  367. const data = await response.json();
  368. if (data.success) {
  369. showStatusMessage('Software update started successfully', 'success');
  370. } else if (data.manual_update_url) {
  371. // Show modal with manual update instructions, but use wiki link
  372. const wikiData = {
  373. ...data,
  374. manual_update_url: 'https://github.com/tuanchris/dune-weaver/wiki/Updating-software'
  375. };
  376. showUpdateInstructionsModal(wikiData);
  377. } else {
  378. showStatusMessage(data.message || 'No updates available', 'info');
  379. }
  380. } catch (error) {
  381. logMessage(`Error updating software: ${error.message}`, LOG_TYPE.ERROR);
  382. showStatusMessage('Failed to check for updates', 'error');
  383. }
  384. });
  385. }
  386. // Connect button
  387. const connectButton = document.getElementById('connectButton');
  388. if (connectButton) {
  389. connectButton.addEventListener('click', async () => {
  390. const portSelect = document.getElementById('portSelect');
  391. if (!portSelect || !portSelect.value) {
  392. logMessage('Please select a port first', LOG_TYPE.WARNING);
  393. return;
  394. }
  395. try {
  396. const response = await fetch('/connect', {
  397. method: 'POST',
  398. headers: { 'Content-Type': 'application/json' },
  399. body: JSON.stringify({ port: portSelect.value })
  400. });
  401. if (response.ok) {
  402. logMessage('Connected successfully', LOG_TYPE.SUCCESS);
  403. await updateSerialStatus(true); // Force update after connecting
  404. } else {
  405. throw new Error('Failed to connect');
  406. }
  407. } catch (error) {
  408. logMessage(`Error connecting to device: ${error.message}`, LOG_TYPE.ERROR);
  409. }
  410. });
  411. }
  412. // Disconnect button
  413. const disconnectButton = document.getElementById('disconnectButton');
  414. if (disconnectButton) {
  415. disconnectButton.addEventListener('click', async () => {
  416. try {
  417. const response = await fetch('/disconnect', {
  418. method: 'POST'
  419. });
  420. if (response.ok) {
  421. logMessage('Device disconnected successfully', LOG_TYPE.SUCCESS);
  422. await updateSerialStatus(true); // Force update after disconnecting
  423. } else {
  424. throw new Error('Failed to disconnect device');
  425. }
  426. } catch (error) {
  427. logMessage(`Error disconnecting device: ${error.message}`, LOG_TYPE.ERROR);
  428. }
  429. });
  430. }
  431. // Save custom clear patterns button
  432. const saveClearPatterns = document.getElementById('saveClearPatterns');
  433. if (saveClearPatterns) {
  434. saveClearPatterns.addEventListener('click', async () => {
  435. const clearFromInInput = document.getElementById('customClearFromInInput');
  436. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  437. if (!clearFromInInput || !clearFromOutInput) {
  438. return;
  439. }
  440. // Validate that the entered patterns exist (if not empty)
  441. const inValue = clearFromInInput.value.trim();
  442. const outValue = clearFromOutInput.value.trim();
  443. if (inValue && window.availablePatterns && !window.availablePatterns.includes(inValue)) {
  444. showStatusMessage(`Pattern not found: ${inValue}`, 'error');
  445. return;
  446. }
  447. if (outValue && window.availablePatterns && !window.availablePatterns.includes(outValue)) {
  448. showStatusMessage(`Pattern not found: ${outValue}`, 'error');
  449. return;
  450. }
  451. try {
  452. const response = await fetch('/api/custom_clear_patterns', {
  453. method: 'POST',
  454. headers: { 'Content-Type': 'application/json' },
  455. body: JSON.stringify({
  456. custom_clear_from_in: inValue || null,
  457. custom_clear_from_out: outValue || null
  458. })
  459. });
  460. if (response.ok) {
  461. showStatusMessage('Clear patterns saved successfully', 'success');
  462. } else {
  463. const error = await response.json();
  464. throw new Error(error.detail || 'Failed to save clear patterns');
  465. }
  466. } catch (error) {
  467. showStatusMessage(`Failed to save clear patterns: ${error.message}`, 'error');
  468. }
  469. });
  470. }
  471. // Save clear pattern speed button
  472. const saveClearSpeed = document.getElementById('saveClearSpeed');
  473. if (saveClearSpeed) {
  474. saveClearSpeed.addEventListener('click', async () => {
  475. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  476. if (!clearPatternSpeedInput) {
  477. return;
  478. }
  479. let speed;
  480. if (clearPatternSpeedInput.value === '' || clearPatternSpeedInput.value === null) {
  481. // Empty value means use default (None)
  482. speed = null;
  483. } else {
  484. speed = parseInt(clearPatternSpeedInput.value);
  485. // Validate speed only if it's not null
  486. if (isNaN(speed) || speed < 50 || speed > 2000) {
  487. showStatusMessage('Clear pattern speed must be between 50 and 2000, or leave empty for default', 'error');
  488. return;
  489. }
  490. }
  491. try {
  492. const response = await fetch('/api/clear_pattern_speed', {
  493. method: 'POST',
  494. headers: { 'Content-Type': 'application/json' },
  495. body: JSON.stringify({ clear_pattern_speed: speed })
  496. });
  497. if (response.ok) {
  498. const data = await response.json();
  499. if (speed === null) {
  500. showStatusMessage(`Clear pattern speed set to default (${data.effective_speed} steps/min)`, 'success');
  501. } else {
  502. showStatusMessage(`Clear pattern speed set to ${speed} steps/min`, 'success');
  503. }
  504. // Update the effective speed display
  505. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  506. if (effectiveClearSpeed) {
  507. if (speed === null) {
  508. effectiveClearSpeed.textContent = `Using default pattern speed: ${data.effective_speed} steps/min`;
  509. } else {
  510. effectiveClearSpeed.textContent = `Current: ${speed} steps/min`;
  511. }
  512. }
  513. } else {
  514. const error = await response.json();
  515. throw new Error(error.detail || 'Failed to save clear pattern speed');
  516. }
  517. } catch (error) {
  518. showStatusMessage(`Failed to save clear pattern speed: ${error.message}`, 'error');
  519. }
  520. });
  521. }
  522. }
  523. // Button click handlers
  524. document.addEventListener('DOMContentLoaded', function() {
  525. // Home button
  526. const homeButton = document.getElementById('homeButton');
  527. if (homeButton) {
  528. homeButton.addEventListener('click', async () => {
  529. try {
  530. const response = await fetch('/send_home', {
  531. method: 'POST',
  532. headers: {
  533. 'Content-Type': 'application/json'
  534. }
  535. });
  536. const data = await response.json();
  537. if (data.success) {
  538. updateStatus('Moving to home position...');
  539. }
  540. } catch (error) {
  541. console.error('Error sending home command:', error);
  542. updateStatus('Error: Failed to move to home position');
  543. }
  544. });
  545. }
  546. // Stop button
  547. const stopButton = document.getElementById('stopButton');
  548. if (stopButton) {
  549. stopButton.addEventListener('click', async () => {
  550. try {
  551. const response = await fetch('/stop_execution', {
  552. method: 'POST',
  553. headers: {
  554. 'Content-Type': 'application/json'
  555. }
  556. });
  557. const data = await response.json();
  558. if (data.success) {
  559. updateStatus('Execution stopped');
  560. }
  561. } catch (error) {
  562. console.error('Error stopping execution:', error);
  563. updateStatus('Error: Failed to stop execution');
  564. }
  565. });
  566. }
  567. // Move to Center button
  568. const centerButton = document.getElementById('centerButton');
  569. if (centerButton) {
  570. centerButton.addEventListener('click', async () => {
  571. try {
  572. const response = await fetch('/move_to_center', {
  573. method: 'POST',
  574. headers: {
  575. 'Content-Type': 'application/json'
  576. }
  577. });
  578. const data = await response.json();
  579. if (data.success) {
  580. updateStatus('Moving to center position...');
  581. }
  582. } catch (error) {
  583. console.error('Error moving to center:', error);
  584. updateStatus('Error: Failed to move to center');
  585. }
  586. });
  587. }
  588. // Move to Perimeter button
  589. const perimeterButton = document.getElementById('perimeterButton');
  590. if (perimeterButton) {
  591. perimeterButton.addEventListener('click', async () => {
  592. try {
  593. const response = await fetch('/move_to_perimeter', {
  594. method: 'POST',
  595. headers: {
  596. 'Content-Type': 'application/json'
  597. }
  598. });
  599. const data = await response.json();
  600. if (data.success) {
  601. updateStatus('Moving to perimeter position...');
  602. }
  603. } catch (error) {
  604. console.error('Error moving to perimeter:', error);
  605. updateStatus('Error: Failed to move to perimeter');
  606. }
  607. });
  608. }
  609. });
  610. // Function to update status
  611. function updateStatus(message) {
  612. const statusElement = document.querySelector('.text-slate-800.text-base.font-medium.leading-normal');
  613. if (statusElement) {
  614. statusElement.textContent = message;
  615. // Reset status after 3 seconds if it's a temporary message
  616. if (message.includes('Moving') || message.includes('Execution')) {
  617. setTimeout(() => {
  618. statusElement.textContent = 'Status';
  619. }, 3000);
  620. }
  621. }
  622. }
  623. // Function to show status messages (using existing base.js showStatusMessage if available)
  624. function showStatusMessage(message, type) {
  625. if (typeof window.showStatusMessage === 'function') {
  626. window.showStatusMessage(message, type);
  627. } else {
  628. // Fallback to console logging
  629. console.log(`[${type}] ${message}`);
  630. }
  631. }
  632. // Function to show update instructions modal
  633. function showUpdateInstructionsModal(data) {
  634. // Create modal HTML
  635. const modal = document.createElement('div');
  636. modal.id = 'updateInstructionsModal';
  637. modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
  638. modal.innerHTML = `
  639. <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md">
  640. <div class="p-6">
  641. <div class="text-center mb-4">
  642. <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-2">Manual Update Required</h2>
  643. <p class="text-gray-600 dark:text-gray-400 text-sm">
  644. ${data.message}
  645. </p>
  646. </div>
  647. <div class="text-gray-700 dark:text-gray-300 text-sm mb-6">
  648. <p class="mb-3">${data.instructions}</p>
  649. </div>
  650. <div class="flex gap-3 justify-center">
  651. <button id="openGitHubRelease" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
  652. View Update Instructions
  653. </button>
  654. <button id="closeUpdateModal" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors">
  655. Close
  656. </button>
  657. </div>
  658. </div>
  659. </div>
  660. `;
  661. document.body.appendChild(modal);
  662. // Add event listeners
  663. const openGitHubButton = modal.querySelector('#openGitHubRelease');
  664. const closeButton = modal.querySelector('#closeUpdateModal');
  665. openGitHubButton.addEventListener('click', () => {
  666. window.open(data.manual_update_url, '_blank');
  667. document.body.removeChild(modal);
  668. });
  669. closeButton.addEventListener('click', () => {
  670. document.body.removeChild(modal);
  671. });
  672. // Close on outside click
  673. modal.addEventListener('click', (e) => {
  674. if (e.target === modal) {
  675. document.body.removeChild(modal);
  676. }
  677. });
  678. }
  679. // Autocomplete functionality
  680. function initializeAutocomplete(inputId, suggestionsId, clearButtonId, patterns) {
  681. const input = document.getElementById(inputId);
  682. const suggestionsDiv = document.getElementById(suggestionsId);
  683. const clearButton = document.getElementById(clearButtonId);
  684. let selectedIndex = -1;
  685. if (!input || !suggestionsDiv) return;
  686. // Function to update clear button visibility
  687. function updateClearButton() {
  688. if (clearButton) {
  689. if (input.value.trim()) {
  690. clearButton.classList.remove('hidden');
  691. } else {
  692. clearButton.classList.add('hidden');
  693. }
  694. }
  695. }
  696. // Format pattern name for display
  697. function formatPatternName(pattern) {
  698. return pattern.replace('.thr', '').replace(/_/g, ' ');
  699. }
  700. // Filter patterns based on input
  701. function filterPatterns(searchTerm) {
  702. if (!searchTerm) return patterns.slice(0, 20); // Show first 20 when empty
  703. const term = searchTerm.toLowerCase();
  704. return patterns.filter(pattern => {
  705. const name = pattern.toLowerCase();
  706. return name.includes(term);
  707. }).sort((a, b) => {
  708. // Prioritize patterns that start with the search term
  709. const aStarts = a.toLowerCase().startsWith(term);
  710. const bStarts = b.toLowerCase().startsWith(term);
  711. if (aStarts && !bStarts) return -1;
  712. if (!aStarts && bStarts) return 1;
  713. return a.localeCompare(b);
  714. }).slice(0, 20); // Limit to 20 results
  715. }
  716. // Highlight matching text
  717. function highlightMatch(text, searchTerm) {
  718. if (!searchTerm) return text;
  719. const regex = new RegExp(`(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
  720. return text.replace(regex, '<mark>$1</mark>');
  721. }
  722. // Show suggestions
  723. function showSuggestions(searchTerm) {
  724. const filtered = filterPatterns(searchTerm);
  725. if (filtered.length === 0 && searchTerm) {
  726. suggestionsDiv.innerHTML = '<div class="suggestion-item" style="cursor: default; color: #9ca3af;">No patterns found</div>';
  727. suggestionsDiv.classList.remove('hidden');
  728. return;
  729. }
  730. suggestionsDiv.innerHTML = filtered.map((pattern, index) => {
  731. const displayName = formatPatternName(pattern);
  732. const highlighted = highlightMatch(displayName, searchTerm);
  733. return `<div class="suggestion-item" data-value="${pattern}" data-index="${index}">${highlighted}</div>`;
  734. }).join('');
  735. suggestionsDiv.classList.remove('hidden');
  736. selectedIndex = -1;
  737. }
  738. // Hide suggestions
  739. function hideSuggestions() {
  740. setTimeout(() => {
  741. suggestionsDiv.classList.add('hidden');
  742. selectedIndex = -1;
  743. }, 200);
  744. }
  745. // Select suggestion
  746. function selectSuggestion(value) {
  747. input.value = value;
  748. hideSuggestions();
  749. updateClearButton();
  750. }
  751. // Handle keyboard navigation
  752. function handleKeyboard(e) {
  753. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  754. if (e.key === 'ArrowDown') {
  755. e.preventDefault();
  756. selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
  757. updateSelection(items);
  758. } else if (e.key === 'ArrowUp') {
  759. e.preventDefault();
  760. selectedIndex = Math.max(selectedIndex - 1, -1);
  761. updateSelection(items);
  762. } else if (e.key === 'Enter') {
  763. e.preventDefault();
  764. if (selectedIndex >= 0 && items[selectedIndex]) {
  765. selectSuggestion(items[selectedIndex].dataset.value);
  766. } else if (items.length === 1) {
  767. selectSuggestion(items[0].dataset.value);
  768. }
  769. } else if (e.key === 'Escape') {
  770. hideSuggestions();
  771. }
  772. }
  773. // Update visual selection
  774. function updateSelection(items) {
  775. items.forEach((item, index) => {
  776. if (index === selectedIndex) {
  777. item.classList.add('selected');
  778. item.scrollIntoView({ block: 'nearest' });
  779. } else {
  780. item.classList.remove('selected');
  781. }
  782. });
  783. }
  784. // Event listeners
  785. input.addEventListener('input', (e) => {
  786. const value = e.target.value.trim();
  787. updateClearButton();
  788. if (value.length > 0 || e.target === document.activeElement) {
  789. showSuggestions(value);
  790. } else {
  791. hideSuggestions();
  792. }
  793. });
  794. input.addEventListener('focus', () => {
  795. const value = input.value.trim();
  796. showSuggestions(value);
  797. });
  798. input.addEventListener('blur', hideSuggestions);
  799. input.addEventListener('keydown', handleKeyboard);
  800. // Click handler for suggestions
  801. suggestionsDiv.addEventListener('click', (e) => {
  802. const item = e.target.closest('.suggestion-item[data-value]');
  803. if (item) {
  804. selectSuggestion(item.dataset.value);
  805. }
  806. });
  807. // Mouse hover handler
  808. suggestionsDiv.addEventListener('mouseover', (e) => {
  809. const item = e.target.closest('.suggestion-item[data-value]');
  810. if (item) {
  811. selectedIndex = parseInt(item.dataset.index);
  812. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  813. updateSelection(items);
  814. }
  815. });
  816. // Clear button handler
  817. if (clearButton) {
  818. clearButton.addEventListener('click', () => {
  819. input.value = '';
  820. updateClearButton();
  821. hideSuggestions();
  822. input.focus();
  823. });
  824. }
  825. // Initialize clear button visibility
  826. updateClearButton();
  827. }
  828. // auto_play Mode Functions
  829. async function initializeauto_playMode() {
  830. const auto_playToggle = document.getElementById('auto_playModeToggle');
  831. const auto_playSettings = document.getElementById('auto_playSettings');
  832. const auto_playPlaylistSelect = document.getElementById('auto_playPlaylistSelect');
  833. const auto_playRunModeSelect = document.getElementById('auto_playRunModeSelect');
  834. const auto_playPauseTimeInput = document.getElementById('auto_playPauseTimeInput');
  835. const auto_playClearPatternSelect = document.getElementById('auto_playClearPatternSelect');
  836. const auto_playShuffleToggle = document.getElementById('auto_playShuffleToggle');
  837. // Load current auto_play settings
  838. try {
  839. const response = await fetch('/api/auto_play-mode');
  840. const data = await response.json();
  841. auto_playToggle.checked = data.enabled;
  842. if (data.enabled) {
  843. auto_playSettings.style.display = 'block';
  844. }
  845. // Set current values
  846. auto_playRunModeSelect.value = data.run_mode || 'loop';
  847. auto_playPauseTimeInput.value = data.pause_time || 5.0;
  848. auto_playClearPatternSelect.value = data.clear_pattern || 'adaptive';
  849. auto_playShuffleToggle.checked = data.shuffle || false;
  850. // Load playlists for selection
  851. const playlistsResponse = await fetch('/list_all_playlists');
  852. const playlists = await playlistsResponse.json();
  853. // Clear and populate playlist select
  854. auto_playPlaylistSelect.innerHTML = '<option value="">Select a playlist...</option>';
  855. playlists.forEach(playlist => {
  856. const option = document.createElement('option');
  857. option.value = playlist;
  858. option.textContent = playlist;
  859. if (playlist === data.playlist) {
  860. option.selected = true;
  861. }
  862. auto_playPlaylistSelect.appendChild(option);
  863. });
  864. } catch (error) {
  865. logMessage(`Error loading auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  866. }
  867. // Function to save settings
  868. async function saveSettings() {
  869. try {
  870. const response = await fetch('/api/auto_play-mode', {
  871. method: 'POST',
  872. headers: { 'Content-Type': 'application/json' },
  873. body: JSON.stringify({
  874. enabled: auto_playToggle.checked,
  875. playlist: auto_playPlaylistSelect.value || null,
  876. run_mode: auto_playRunModeSelect.value,
  877. pause_time: parseFloat(auto_playPauseTimeInput.value) || 0,
  878. clear_pattern: auto_playClearPatternSelect.value,
  879. shuffle: auto_playShuffleToggle.checked
  880. })
  881. });
  882. if (!response.ok) {
  883. throw new Error('Failed to save settings');
  884. }
  885. } catch (error) {
  886. logMessage(`Error saving auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  887. }
  888. }
  889. // Toggle auto_play settings visibility and save
  890. auto_playToggle.addEventListener('change', async () => {
  891. auto_playSettings.style.display = auto_playToggle.checked ? 'block' : 'none';
  892. await saveSettings();
  893. });
  894. // Save when any setting changes
  895. auto_playPlaylistSelect.addEventListener('change', saveSettings);
  896. auto_playRunModeSelect.addEventListener('change', saveSettings);
  897. auto_playPauseTimeInput.addEventListener('change', saveSettings);
  898. auto_playPauseTimeInput.addEventListener('input', saveSettings); // Save as user types
  899. auto_playClearPatternSelect.addEventListener('change', saveSettings);
  900. auto_playShuffleToggle.addEventListener('change', saveSettings);
  901. }
  902. // Initialize auto_play mode when DOM is ready
  903. document.addEventListener('DOMContentLoaded', function() {
  904. initializeauto_playMode();
  905. });