1
0

settings.js 56 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367
  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. getCachedPatternFiles().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. // Load Still Sands settings
  160. fetch('/api/scheduled-pause').then(response => response.json()).catch(() => ({ enabled: false, time_slots: [] }))
  161. ]).then(([statusData, wledData, updateData, ports, patterns, clearPatterns, clearSpeedData, appNameData, scheduledPauseData]) => {
  162. // Update connection status
  163. setCachedConnectionStatus(statusData);
  164. updateConnectionUI(statusData);
  165. // Update WLED IP
  166. if (wledData.wled_ip) {
  167. document.getElementById('wledIpInput').value = wledData.wled_ip;
  168. setWledButtonState(true);
  169. } else {
  170. setWledButtonState(false);
  171. }
  172. // Update version display
  173. const currentVersionText = document.getElementById('currentVersionText');
  174. const latestVersionText = document.getElementById('latestVersionText');
  175. const updateButton = document.getElementById('updateSoftware');
  176. const updateIcon = document.getElementById('updateIcon');
  177. const updateText = document.getElementById('updateText');
  178. if (currentVersionText) {
  179. currentVersionText.textContent = updateData.current;
  180. }
  181. if (latestVersionText) {
  182. if (updateData.error) {
  183. latestVersionText.textContent = 'Error checking updates';
  184. latestVersionText.className = 'text-red-500 text-sm font-normal leading-normal';
  185. } else {
  186. latestVersionText.textContent = updateData.latest;
  187. latestVersionText.className = 'text-slate-500 text-sm font-normal leading-normal';
  188. }
  189. }
  190. // Update button state
  191. if (updateButton && updateIcon && updateText) {
  192. if (updateData.update_available) {
  193. updateButton.disabled = false;
  194. 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';
  195. updateIcon.textContent = 'download';
  196. updateText.textContent = 'Update';
  197. } else {
  198. updateButton.disabled = true;
  199. 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';
  200. updateIcon.textContent = 'check';
  201. updateText.textContent = 'Up to date';
  202. }
  203. }
  204. // Update port selection
  205. const portSelect = document.getElementById('portSelect');
  206. if (portSelect) {
  207. // Clear existing options except the first one
  208. while (portSelect.options.length > 1) {
  209. portSelect.remove(1);
  210. }
  211. // Add new options
  212. ports.forEach(port => {
  213. const option = document.createElement('option');
  214. option.value = port;
  215. option.textContent = port;
  216. portSelect.appendChild(option);
  217. });
  218. // If there's exactly one port available, select it
  219. if (ports.length === 1) {
  220. portSelect.value = ports[0];
  221. }
  222. }
  223. // Initialize autocomplete for clear patterns
  224. const clearFromInInput = document.getElementById('customClearFromInInput');
  225. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  226. if (clearFromInInput && clearFromOutInput && patterns && Array.isArray(patterns)) {
  227. // Store patterns globally for autocomplete
  228. window.availablePatterns = patterns;
  229. // Set current values if they exist
  230. if (clearPatterns && clearPatterns.custom_clear_from_in) {
  231. clearFromInInput.value = clearPatterns.custom_clear_from_in;
  232. }
  233. if (clearPatterns && clearPatterns.custom_clear_from_out) {
  234. clearFromOutInput.value = clearPatterns.custom_clear_from_out;
  235. }
  236. // Initialize autocomplete for both inputs
  237. initializeAutocomplete('customClearFromInInput', 'clearFromInSuggestions', 'clearFromInClear', patterns);
  238. initializeAutocomplete('customClearFromOutInput', 'clearFromOutSuggestions', 'clearFromOutClear', patterns);
  239. console.log('Autocomplete initialized with', patterns.length, 'patterns');
  240. }
  241. // Set clear pattern speed
  242. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  243. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  244. if (clearPatternSpeedInput && clearSpeedData) {
  245. // Only set value if clear_pattern_speed is not null
  246. if (clearSpeedData.clear_pattern_speed !== null && clearSpeedData.clear_pattern_speed !== undefined) {
  247. clearPatternSpeedInput.value = clearSpeedData.clear_pattern_speed;
  248. if (effectiveClearSpeed) {
  249. effectiveClearSpeed.textContent = `Current: ${clearSpeedData.clear_pattern_speed} steps/min`;
  250. }
  251. } else {
  252. // Leave empty to show placeholder for default
  253. clearPatternSpeedInput.value = '';
  254. if (effectiveClearSpeed && clearSpeedData.effective_speed) {
  255. effectiveClearSpeed.textContent = `Using default pattern speed: ${clearSpeedData.effective_speed} steps/min`;
  256. }
  257. }
  258. }
  259. // Update app name
  260. const appNameInput = document.getElementById('appNameInput');
  261. if (appNameInput && appNameData.app_name) {
  262. appNameInput.value = appNameData.app_name;
  263. }
  264. // Store Still Sands data for later initialization
  265. window.initialStillSandsData = scheduledPauseData;
  266. }).catch(error => {
  267. logMessage(`Error initializing settings page: ${error.message}`, LOG_TYPE.ERROR);
  268. });
  269. // Set up event listeners
  270. setupEventListeners();
  271. });
  272. // Setup event listeners
  273. function setupEventListeners() {
  274. // Save App Name
  275. const saveAppNameButton = document.getElementById('saveAppName');
  276. const appNameInput = document.getElementById('appNameInput');
  277. if (saveAppNameButton && appNameInput) {
  278. saveAppNameButton.addEventListener('click', async () => {
  279. const appName = appNameInput.value.trim() || 'Dune Weaver';
  280. try {
  281. const response = await fetch('/api/app-name', {
  282. method: 'POST',
  283. headers: { 'Content-Type': 'application/json' },
  284. body: JSON.stringify({ app_name: appName })
  285. });
  286. if (response.ok) {
  287. const data = await response.json();
  288. showStatusMessage('Application name updated successfully. Refresh the page to see changes.', 'success');
  289. // Update the page title and header immediately
  290. document.title = `Settings - ${data.app_name}`;
  291. const headerTitle = document.querySelector('h1.text-gray-800');
  292. if (headerTitle) {
  293. // Update just the text content, preserving the connection status dot
  294. const textNode = headerTitle.childNodes[0];
  295. if (textNode && textNode.nodeType === Node.TEXT_NODE) {
  296. textNode.textContent = data.app_name;
  297. }
  298. }
  299. } else {
  300. throw new Error('Failed to save application name');
  301. }
  302. } catch (error) {
  303. showStatusMessage(`Failed to save application name: ${error.message}`, 'error');
  304. }
  305. });
  306. // Handle Enter key in app name input
  307. appNameInput.addEventListener('keypress', (e) => {
  308. if (e.key === 'Enter') {
  309. saveAppNameButton.click();
  310. }
  311. });
  312. }
  313. // Save/Clear WLED configuration
  314. const saveWledConfig = document.getElementById('saveWledConfig');
  315. const wledIpInput = document.getElementById('wledIpInput');
  316. if (saveWledConfig && wledIpInput) {
  317. saveWledConfig.addEventListener('click', async () => {
  318. if (saveWledConfig.textContent.includes('Clear')) {
  319. // Clear WLED IP
  320. wledIpInput.value = '';
  321. try {
  322. const response = await fetch('/set_wled_ip', {
  323. method: 'POST',
  324. headers: { 'Content-Type': 'application/json' },
  325. body: JSON.stringify({ wled_ip: '' })
  326. });
  327. if (response.ok) {
  328. setWledButtonState(false);
  329. localStorage.removeItem('wled_ip');
  330. showStatusMessage('WLED IP cleared successfully', 'success');
  331. } else {
  332. throw new Error('Failed to clear WLED IP');
  333. }
  334. } catch (error) {
  335. showStatusMessage(`Failed to clear WLED IP: ${error.message}`, 'error');
  336. }
  337. } else {
  338. // Save WLED IP
  339. const wledIp = wledIpInput.value;
  340. try {
  341. const response = await fetch('/set_wled_ip', {
  342. method: 'POST',
  343. headers: { 'Content-Type': 'application/json' },
  344. body: JSON.stringify({ wled_ip: wledIp })
  345. });
  346. if (response.ok && wledIp) {
  347. setWledButtonState(true);
  348. localStorage.setItem('wled_ip', wledIp);
  349. showStatusMessage('WLED IP configured successfully', 'success');
  350. } else {
  351. setWledButtonState(false);
  352. throw new Error('Failed to save WLED configuration');
  353. }
  354. } catch (error) {
  355. showStatusMessage(`Failed to save WLED IP: ${error.message}`, 'error');
  356. }
  357. }
  358. });
  359. }
  360. // Update software
  361. const updateSoftware = document.getElementById('updateSoftware');
  362. if (updateSoftware) {
  363. updateSoftware.addEventListener('click', async () => {
  364. if (updateSoftware.disabled) {
  365. return;
  366. }
  367. try {
  368. const response = await fetch('/api/update', {
  369. method: 'POST'
  370. });
  371. const data = await response.json();
  372. if (data.success) {
  373. showStatusMessage('Software update started successfully', 'success');
  374. } else if (data.manual_update_url) {
  375. // Show modal with manual update instructions, but use wiki link
  376. const wikiData = {
  377. ...data,
  378. manual_update_url: 'https://github.com/tuanchris/dune-weaver/wiki/Updating-software'
  379. };
  380. showUpdateInstructionsModal(wikiData);
  381. } else {
  382. showStatusMessage(data.message || 'No updates available', 'info');
  383. }
  384. } catch (error) {
  385. logMessage(`Error updating software: ${error.message}`, LOG_TYPE.ERROR);
  386. showStatusMessage('Failed to check for updates', 'error');
  387. }
  388. });
  389. }
  390. // Connect button
  391. const connectButton = document.getElementById('connectButton');
  392. if (connectButton) {
  393. connectButton.addEventListener('click', async () => {
  394. const portSelect = document.getElementById('portSelect');
  395. if (!portSelect || !portSelect.value) {
  396. logMessage('Please select a port first', LOG_TYPE.WARNING);
  397. return;
  398. }
  399. try {
  400. const response = await fetch('/connect', {
  401. method: 'POST',
  402. headers: { 'Content-Type': 'application/json' },
  403. body: JSON.stringify({ port: portSelect.value })
  404. });
  405. if (response.ok) {
  406. logMessage('Connected successfully', LOG_TYPE.SUCCESS);
  407. await updateSerialStatus(true); // Force update after connecting
  408. } else {
  409. throw new Error('Failed to connect');
  410. }
  411. } catch (error) {
  412. logMessage(`Error connecting to device: ${error.message}`, LOG_TYPE.ERROR);
  413. }
  414. });
  415. }
  416. // Disconnect button
  417. const disconnectButton = document.getElementById('disconnectButton');
  418. if (disconnectButton) {
  419. disconnectButton.addEventListener('click', async () => {
  420. try {
  421. const response = await fetch('/disconnect', {
  422. method: 'POST'
  423. });
  424. if (response.ok) {
  425. logMessage('Device disconnected successfully', LOG_TYPE.SUCCESS);
  426. await updateSerialStatus(true); // Force update after disconnecting
  427. } else {
  428. throw new Error('Failed to disconnect device');
  429. }
  430. } catch (error) {
  431. logMessage(`Error disconnecting device: ${error.message}`, LOG_TYPE.ERROR);
  432. }
  433. });
  434. }
  435. // Save custom clear patterns button
  436. const saveClearPatterns = document.getElementById('saveClearPatterns');
  437. if (saveClearPatterns) {
  438. saveClearPatterns.addEventListener('click', async () => {
  439. const clearFromInInput = document.getElementById('customClearFromInInput');
  440. const clearFromOutInput = document.getElementById('customClearFromOutInput');
  441. if (!clearFromInInput || !clearFromOutInput) {
  442. return;
  443. }
  444. // Validate that the entered patterns exist (if not empty)
  445. const inValue = clearFromInInput.value.trim();
  446. const outValue = clearFromOutInput.value.trim();
  447. if (inValue && window.availablePatterns && !window.availablePatterns.includes(inValue)) {
  448. showStatusMessage(`Pattern not found: ${inValue}`, 'error');
  449. return;
  450. }
  451. if (outValue && window.availablePatterns && !window.availablePatterns.includes(outValue)) {
  452. showStatusMessage(`Pattern not found: ${outValue}`, 'error');
  453. return;
  454. }
  455. try {
  456. const response = await fetch('/api/custom_clear_patterns', {
  457. method: 'POST',
  458. headers: { 'Content-Type': 'application/json' },
  459. body: JSON.stringify({
  460. custom_clear_from_in: inValue || null,
  461. custom_clear_from_out: outValue || null
  462. })
  463. });
  464. if (response.ok) {
  465. showStatusMessage('Clear patterns saved successfully', 'success');
  466. } else {
  467. const error = await response.json();
  468. throw new Error(error.detail || 'Failed to save clear patterns');
  469. }
  470. } catch (error) {
  471. showStatusMessage(`Failed to save clear patterns: ${error.message}`, 'error');
  472. }
  473. });
  474. }
  475. // Save clear pattern speed button
  476. const saveClearSpeed = document.getElementById('saveClearSpeed');
  477. if (saveClearSpeed) {
  478. saveClearSpeed.addEventListener('click', async () => {
  479. const clearPatternSpeedInput = document.getElementById('clearPatternSpeedInput');
  480. if (!clearPatternSpeedInput) {
  481. return;
  482. }
  483. let speed;
  484. if (clearPatternSpeedInput.value === '' || clearPatternSpeedInput.value === null) {
  485. // Empty value means use default (None)
  486. speed = null;
  487. } else {
  488. speed = parseInt(clearPatternSpeedInput.value);
  489. // Validate speed only if it's not null
  490. if (isNaN(speed) || speed < 50 || speed > 2000) {
  491. showStatusMessage('Clear pattern speed must be between 50 and 2000, or leave empty for default', 'error');
  492. return;
  493. }
  494. }
  495. try {
  496. const response = await fetch('/api/clear_pattern_speed', {
  497. method: 'POST',
  498. headers: { 'Content-Type': 'application/json' },
  499. body: JSON.stringify({ clear_pattern_speed: speed })
  500. });
  501. if (response.ok) {
  502. const data = await response.json();
  503. if (speed === null) {
  504. showStatusMessage(`Clear pattern speed set to default (${data.effective_speed} steps/min)`, 'success');
  505. } else {
  506. showStatusMessage(`Clear pattern speed set to ${speed} steps/min`, 'success');
  507. }
  508. // Update the effective speed display
  509. const effectiveClearSpeed = document.getElementById('effectiveClearSpeed');
  510. if (effectiveClearSpeed) {
  511. if (speed === null) {
  512. effectiveClearSpeed.textContent = `Using default pattern speed: ${data.effective_speed} steps/min`;
  513. } else {
  514. effectiveClearSpeed.textContent = `Current: ${speed} steps/min`;
  515. }
  516. }
  517. } else {
  518. const error = await response.json();
  519. throw new Error(error.detail || 'Failed to save clear pattern speed');
  520. }
  521. } catch (error) {
  522. showStatusMessage(`Failed to save clear pattern speed: ${error.message}`, 'error');
  523. }
  524. });
  525. }
  526. }
  527. // Button click handlers
  528. document.addEventListener('DOMContentLoaded', function() {
  529. // Home button
  530. const homeButton = document.getElementById('homeButton');
  531. if (homeButton) {
  532. homeButton.addEventListener('click', async () => {
  533. try {
  534. const response = await fetch('/send_home', {
  535. method: 'POST',
  536. headers: {
  537. 'Content-Type': 'application/json'
  538. }
  539. });
  540. const data = await response.json();
  541. if (data.success) {
  542. updateStatus('Moving to home position...');
  543. }
  544. } catch (error) {
  545. console.error('Error sending home command:', error);
  546. updateStatus('Error: Failed to move to home position');
  547. }
  548. });
  549. }
  550. // Stop button
  551. const stopButton = document.getElementById('stopButton');
  552. if (stopButton) {
  553. stopButton.addEventListener('click', async () => {
  554. try {
  555. const response = await fetch('/stop_execution', {
  556. method: 'POST',
  557. headers: {
  558. 'Content-Type': 'application/json'
  559. }
  560. });
  561. const data = await response.json();
  562. if (data.success) {
  563. updateStatus('Execution stopped');
  564. }
  565. } catch (error) {
  566. console.error('Error stopping execution:', error);
  567. updateStatus('Error: Failed to stop execution');
  568. }
  569. });
  570. }
  571. // Move to Center button
  572. const centerButton = document.getElementById('centerButton');
  573. if (centerButton) {
  574. centerButton.addEventListener('click', async () => {
  575. try {
  576. const response = await fetch('/move_to_center', {
  577. method: 'POST',
  578. headers: {
  579. 'Content-Type': 'application/json'
  580. }
  581. });
  582. const data = await response.json();
  583. if (data.success) {
  584. updateStatus('Moving to center position...');
  585. }
  586. } catch (error) {
  587. console.error('Error moving to center:', error);
  588. updateStatus('Error: Failed to move to center');
  589. }
  590. });
  591. }
  592. // Move to Perimeter button
  593. const perimeterButton = document.getElementById('perimeterButton');
  594. if (perimeterButton) {
  595. perimeterButton.addEventListener('click', async () => {
  596. try {
  597. const response = await fetch('/move_to_perimeter', {
  598. method: 'POST',
  599. headers: {
  600. 'Content-Type': 'application/json'
  601. }
  602. });
  603. const data = await response.json();
  604. if (data.success) {
  605. updateStatus('Moving to perimeter position...');
  606. }
  607. } catch (error) {
  608. console.error('Error moving to perimeter:', error);
  609. updateStatus('Error: Failed to move to perimeter');
  610. }
  611. });
  612. }
  613. });
  614. // Function to update status
  615. function updateStatus(message) {
  616. const statusElement = document.querySelector('.text-slate-800.text-base.font-medium.leading-normal');
  617. if (statusElement) {
  618. statusElement.textContent = message;
  619. // Reset status after 3 seconds if it's a temporary message
  620. if (message.includes('Moving') || message.includes('Execution')) {
  621. setTimeout(() => {
  622. statusElement.textContent = 'Status';
  623. }, 3000);
  624. }
  625. }
  626. }
  627. // Function to show status messages (using existing base.js showStatusMessage if available)
  628. function showStatusMessage(message, type) {
  629. if (typeof window.showStatusMessage === 'function') {
  630. window.showStatusMessage(message, type);
  631. } else {
  632. // Fallback to console logging
  633. console.log(`[${type}] ${message}`);
  634. }
  635. }
  636. // Function to show update instructions modal
  637. function showUpdateInstructionsModal(data) {
  638. // Create modal HTML
  639. const modal = document.createElement('div');
  640. modal.id = 'updateInstructionsModal';
  641. modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4';
  642. modal.innerHTML = `
  643. <div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-md">
  644. <div class="p-6">
  645. <div class="text-center mb-4">
  646. <h2 class="text-xl font-semibold text-gray-800 dark:text-gray-200 mb-2">Manual Update Required</h2>
  647. <p class="text-gray-600 dark:text-gray-400 text-sm">
  648. ${data.message}
  649. </p>
  650. </div>
  651. <div class="text-gray-700 dark:text-gray-300 text-sm mb-6">
  652. <p class="mb-3">${data.instructions}</p>
  653. </div>
  654. <div class="flex gap-3 justify-center">
  655. <button id="openGitHubRelease" class="px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition-colors">
  656. View Update Instructions
  657. </button>
  658. <button id="closeUpdateModal" class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition-colors">
  659. Close
  660. </button>
  661. </div>
  662. </div>
  663. </div>
  664. `;
  665. document.body.appendChild(modal);
  666. // Add event listeners
  667. const openGitHubButton = modal.querySelector('#openGitHubRelease');
  668. const closeButton = modal.querySelector('#closeUpdateModal');
  669. openGitHubButton.addEventListener('click', () => {
  670. window.open(data.manual_update_url, '_blank');
  671. document.body.removeChild(modal);
  672. });
  673. closeButton.addEventListener('click', () => {
  674. document.body.removeChild(modal);
  675. });
  676. // Close on outside click
  677. modal.addEventListener('click', (e) => {
  678. if (e.target === modal) {
  679. document.body.removeChild(modal);
  680. }
  681. });
  682. }
  683. // Autocomplete functionality
  684. function initializeAutocomplete(inputId, suggestionsId, clearButtonId, patterns) {
  685. const input = document.getElementById(inputId);
  686. const suggestionsDiv = document.getElementById(suggestionsId);
  687. const clearButton = document.getElementById(clearButtonId);
  688. let selectedIndex = -1;
  689. if (!input || !suggestionsDiv) return;
  690. // Function to update clear button visibility
  691. function updateClearButton() {
  692. if (clearButton) {
  693. if (input.value.trim()) {
  694. clearButton.classList.remove('hidden');
  695. } else {
  696. clearButton.classList.add('hidden');
  697. }
  698. }
  699. }
  700. // Format pattern name for display
  701. function formatPatternName(pattern) {
  702. return pattern.replace('.thr', '').replace(/_/g, ' ');
  703. }
  704. // Filter patterns based on input
  705. function filterPatterns(searchTerm) {
  706. if (!searchTerm) return patterns.slice(0, 20); // Show first 20 when empty
  707. const term = searchTerm.toLowerCase();
  708. return patterns.filter(pattern => {
  709. const name = pattern.toLowerCase();
  710. return name.includes(term);
  711. }).sort((a, b) => {
  712. // Prioritize patterns that start with the search term
  713. const aStarts = a.toLowerCase().startsWith(term);
  714. const bStarts = b.toLowerCase().startsWith(term);
  715. if (aStarts && !bStarts) return -1;
  716. if (!aStarts && bStarts) return 1;
  717. return a.localeCompare(b);
  718. }).slice(0, 20); // Limit to 20 results
  719. }
  720. // Highlight matching text
  721. function highlightMatch(text, searchTerm) {
  722. if (!searchTerm) return text;
  723. const regex = new RegExp(`(${searchTerm.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
  724. return text.replace(regex, '<mark>$1</mark>');
  725. }
  726. // Show suggestions
  727. function showSuggestions(searchTerm) {
  728. const filtered = filterPatterns(searchTerm);
  729. if (filtered.length === 0 && searchTerm) {
  730. suggestionsDiv.innerHTML = '<div class="suggestion-item" style="cursor: default; color: #9ca3af;">No patterns found</div>';
  731. suggestionsDiv.classList.remove('hidden');
  732. return;
  733. }
  734. suggestionsDiv.innerHTML = filtered.map((pattern, index) => {
  735. const displayName = formatPatternName(pattern);
  736. const highlighted = highlightMatch(displayName, searchTerm);
  737. return `<div class="suggestion-item" data-value="${pattern}" data-index="${index}">${highlighted}</div>`;
  738. }).join('');
  739. suggestionsDiv.classList.remove('hidden');
  740. selectedIndex = -1;
  741. }
  742. // Hide suggestions
  743. function hideSuggestions() {
  744. setTimeout(() => {
  745. suggestionsDiv.classList.add('hidden');
  746. selectedIndex = -1;
  747. }, 200);
  748. }
  749. // Select suggestion
  750. function selectSuggestion(value) {
  751. input.value = value;
  752. hideSuggestions();
  753. updateClearButton();
  754. }
  755. // Handle keyboard navigation
  756. function handleKeyboard(e) {
  757. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  758. if (e.key === 'ArrowDown') {
  759. e.preventDefault();
  760. selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
  761. updateSelection(items);
  762. } else if (e.key === 'ArrowUp') {
  763. e.preventDefault();
  764. selectedIndex = Math.max(selectedIndex - 1, -1);
  765. updateSelection(items);
  766. } else if (e.key === 'Enter') {
  767. e.preventDefault();
  768. if (selectedIndex >= 0 && items[selectedIndex]) {
  769. selectSuggestion(items[selectedIndex].dataset.value);
  770. } else if (items.length === 1) {
  771. selectSuggestion(items[0].dataset.value);
  772. }
  773. } else if (e.key === 'Escape') {
  774. hideSuggestions();
  775. }
  776. }
  777. // Update visual selection
  778. function updateSelection(items) {
  779. items.forEach((item, index) => {
  780. if (index === selectedIndex) {
  781. item.classList.add('selected');
  782. item.scrollIntoView({ block: 'nearest' });
  783. } else {
  784. item.classList.remove('selected');
  785. }
  786. });
  787. }
  788. // Event listeners
  789. input.addEventListener('input', (e) => {
  790. const value = e.target.value.trim();
  791. updateClearButton();
  792. if (value.length > 0 || e.target === document.activeElement) {
  793. showSuggestions(value);
  794. } else {
  795. hideSuggestions();
  796. }
  797. });
  798. input.addEventListener('focus', () => {
  799. const value = input.value.trim();
  800. showSuggestions(value);
  801. });
  802. input.addEventListener('blur', hideSuggestions);
  803. input.addEventListener('keydown', handleKeyboard);
  804. // Click handler for suggestions
  805. suggestionsDiv.addEventListener('click', (e) => {
  806. const item = e.target.closest('.suggestion-item[data-value]');
  807. if (item) {
  808. selectSuggestion(item.dataset.value);
  809. }
  810. });
  811. // Mouse hover handler
  812. suggestionsDiv.addEventListener('mouseover', (e) => {
  813. const item = e.target.closest('.suggestion-item[data-value]');
  814. if (item) {
  815. selectedIndex = parseInt(item.dataset.index);
  816. const items = suggestionsDiv.querySelectorAll('.suggestion-item[data-value]');
  817. updateSelection(items);
  818. }
  819. });
  820. // Clear button handler
  821. if (clearButton) {
  822. clearButton.addEventListener('click', () => {
  823. input.value = '';
  824. updateClearButton();
  825. hideSuggestions();
  826. input.focus();
  827. });
  828. }
  829. // Initialize clear button visibility
  830. updateClearButton();
  831. }
  832. // auto_play Mode Functions
  833. async function initializeauto_playMode() {
  834. const auto_playToggle = document.getElementById('auto_playModeToggle');
  835. const auto_playSettings = document.getElementById('auto_playSettings');
  836. const auto_playPlaylistSelect = document.getElementById('auto_playPlaylistSelect');
  837. const auto_playRunModeSelect = document.getElementById('auto_playRunModeSelect');
  838. const auto_playPauseTimeInput = document.getElementById('auto_playPauseTimeInput');
  839. const auto_playClearPatternSelect = document.getElementById('auto_playClearPatternSelect');
  840. const auto_playShuffleToggle = document.getElementById('auto_playShuffleToggle');
  841. // Load current auto_play settings
  842. try {
  843. const response = await fetch('/api/auto_play-mode');
  844. const data = await response.json();
  845. auto_playToggle.checked = data.enabled;
  846. if (data.enabled) {
  847. auto_playSettings.style.display = 'block';
  848. }
  849. // Set current values
  850. auto_playRunModeSelect.value = data.run_mode || 'loop';
  851. auto_playPauseTimeInput.value = data.pause_time || 5.0;
  852. auto_playClearPatternSelect.value = data.clear_pattern || 'adaptive';
  853. auto_playShuffleToggle.checked = data.shuffle || false;
  854. // Load playlists for selection
  855. const playlistsResponse = await fetch('/list_all_playlists');
  856. const playlists = await playlistsResponse.json();
  857. // Clear and populate playlist select
  858. auto_playPlaylistSelect.innerHTML = '<option value="">Select a playlist...</option>';
  859. playlists.forEach(playlist => {
  860. const option = document.createElement('option');
  861. option.value = playlist;
  862. option.textContent = playlist;
  863. if (playlist === data.playlist) {
  864. option.selected = true;
  865. }
  866. auto_playPlaylistSelect.appendChild(option);
  867. });
  868. } catch (error) {
  869. logMessage(`Error loading auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  870. }
  871. // Function to save settings
  872. async function saveSettings() {
  873. try {
  874. const response = await fetch('/api/auto_play-mode', {
  875. method: 'POST',
  876. headers: { 'Content-Type': 'application/json' },
  877. body: JSON.stringify({
  878. enabled: auto_playToggle.checked,
  879. playlist: auto_playPlaylistSelect.value || null,
  880. run_mode: auto_playRunModeSelect.value,
  881. pause_time: parseFloat(auto_playPauseTimeInput.value) || 0,
  882. clear_pattern: auto_playClearPatternSelect.value,
  883. shuffle: auto_playShuffleToggle.checked
  884. })
  885. });
  886. if (!response.ok) {
  887. throw new Error('Failed to save settings');
  888. }
  889. } catch (error) {
  890. logMessage(`Error saving auto_play settings: ${error.message}`, LOG_TYPE.ERROR);
  891. }
  892. }
  893. // Toggle auto_play settings visibility and save
  894. auto_playToggle.addEventListener('change', async () => {
  895. auto_playSettings.style.display = auto_playToggle.checked ? 'block' : 'none';
  896. await saveSettings();
  897. });
  898. // Save when any setting changes
  899. auto_playPlaylistSelect.addEventListener('change', saveSettings);
  900. auto_playRunModeSelect.addEventListener('change', saveSettings);
  901. auto_playPauseTimeInput.addEventListener('change', saveSettings);
  902. auto_playPauseTimeInput.addEventListener('input', saveSettings); // Save as user types
  903. auto_playClearPatternSelect.addEventListener('change', saveSettings);
  904. auto_playShuffleToggle.addEventListener('change', saveSettings);
  905. }
  906. // Initialize auto_play mode when DOM is ready
  907. document.addEventListener('DOMContentLoaded', function() {
  908. initializeauto_playMode();
  909. initializeStillSandsMode();
  910. });
  911. // Still Sands Mode Functions
  912. async function initializeStillSandsMode() {
  913. logMessage('Initializing Still Sands mode', LOG_TYPE.INFO);
  914. const stillSandsToggle = document.getElementById('scheduledPauseToggle');
  915. const stillSandsSettings = document.getElementById('scheduledPauseSettings');
  916. const addTimeSlotButton = document.getElementById('addTimeSlotButton');
  917. const saveStillSandsButton = document.getElementById('savePauseSettings');
  918. const timeSlotsContainer = document.getElementById('timeSlotsContainer');
  919. const wledControlToggle = document.getElementById('stillSandsWledControl');
  920. // Check if elements exist
  921. if (!stillSandsToggle || !stillSandsSettings || !addTimeSlotButton || !saveStillSandsButton || !timeSlotsContainer) {
  922. logMessage('Still Sands elements not found, skipping initialization', LOG_TYPE.WARNING);
  923. logMessage(`Found elements: toggle=${!!stillSandsToggle}, settings=${!!stillSandsSettings}, addBtn=${!!addTimeSlotButton}, saveBtn=${!!saveStillSandsButton}, container=${!!timeSlotsContainer}`, LOG_TYPE.WARNING);
  924. return;
  925. }
  926. logMessage('All Still Sands elements found successfully', LOG_TYPE.INFO);
  927. // Track time slots
  928. let timeSlots = [];
  929. let slotIdCounter = 0;
  930. // Load current Still Sands settings from initial data
  931. try {
  932. // Use the data loaded during page initialization, fallback to API if not available
  933. let data;
  934. if (window.initialStillSandsData) {
  935. data = window.initialStillSandsData;
  936. // Clear the global variable after use
  937. delete window.initialStillSandsData;
  938. } else {
  939. // Fallback to API call if initial data not available
  940. const response = await fetch('/api/scheduled-pause');
  941. data = await response.json();
  942. }
  943. stillSandsToggle.checked = data.enabled || false;
  944. if (data.enabled) {
  945. stillSandsSettings.style.display = 'block';
  946. }
  947. // Load WLED control setting
  948. if (wledControlToggle) {
  949. wledControlToggle.checked = data.control_wled || false;
  950. }
  951. // Load existing time slots
  952. timeSlots = data.time_slots || [];
  953. // Assign IDs to loaded slots BEFORE rendering
  954. if (timeSlots.length > 0) {
  955. slotIdCounter = 0;
  956. timeSlots.forEach(slot => {
  957. slot.id = ++slotIdCounter;
  958. });
  959. }
  960. renderTimeSlots();
  961. } catch (error) {
  962. logMessage(`Error loading Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  963. // Initialize with empty settings if load fails
  964. timeSlots = [];
  965. renderTimeSlots();
  966. }
  967. // Function to validate time format (HH:MM)
  968. function isValidTime(timeString) {
  969. const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
  970. return timeRegex.test(timeString);
  971. }
  972. // Function to create a new time slot element
  973. function createTimeSlotElement(slot) {
  974. const slotDiv = document.createElement('div');
  975. slotDiv.className = 'time-slot-item';
  976. slotDiv.dataset.slotId = slot.id;
  977. slotDiv.innerHTML = `
  978. <div class="flex items-center gap-3">
  979. <div class="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
  980. <div class="flex flex-col gap-1">
  981. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Start Time</label>
  982. <input
  983. type="time"
  984. class="start-time form-input resize-none overflow-hidden rounded-lg text-slate-900 focus:outline-0 focus:ring-2 focus:ring-sky-500 border border-slate-300 bg-white focus:border-sky-500 h-9 px-3 text-sm font-normal leading-normal transition-colors"
  985. value="${slot.start_time || ''}"
  986. required
  987. />
  988. </div>
  989. <div class="flex flex-col gap-1">
  990. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">End Time</label>
  991. <input
  992. type="time"
  993. class="end-time form-input resize-none overflow-hidden rounded-lg text-slate-900 focus:outline-0 focus:ring-2 focus:ring-sky-500 border border-slate-300 bg-white focus:border-sky-500 h-9 px-3 text-sm font-normal leading-normal transition-colors"
  994. value="${slot.end_time || ''}"
  995. required
  996. />
  997. </div>
  998. </div>
  999. <div class="flex flex-col gap-1">
  1000. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Days</label>
  1001. <select class="days-select form-select resize-none overflow-hidden rounded-lg text-slate-900 focus:outline-0 focus:ring-2 focus:ring-sky-500 border border-slate-300 bg-white focus:border-sky-500 h-9 px-3 text-sm font-normal transition-colors">
  1002. <option value="daily" ${slot.days === 'daily' ? 'selected' : ''}>Daily</option>
  1003. <option value="weekdays" ${slot.days === 'weekdays' ? 'selected' : ''}>Weekdays</option>
  1004. <option value="weekends" ${slot.days === 'weekends' ? 'selected' : ''}>Weekends</option>
  1005. <option value="custom" ${slot.days === 'custom' ? 'selected' : ''}>Custom</option>
  1006. </select>
  1007. </div>
  1008. <button
  1009. type="button"
  1010. class="remove-slot-btn flex items-center justify-center w-9 h-9 text-red-600 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-lg transition-colors"
  1011. title="Remove time slot"
  1012. >
  1013. <span class="material-icons text-base">delete</span>
  1014. </button>
  1015. </div>
  1016. <div class="custom-days-container mt-2" style="display: ${slot.days === 'custom' ? 'block' : 'none'};">
  1017. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium mb-1 block">Select Days</label>
  1018. <div class="flex flex-wrap gap-2">
  1019. ${['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'].map(day => `
  1020. <label class="flex items-center gap-1 text-xs">
  1021. <input
  1022. type="checkbox"
  1023. name="custom-days-${slot.id}"
  1024. value="${day}"
  1025. ${slot.custom_days && slot.custom_days.includes(day) ? 'checked' : ''}
  1026. class="rounded border-slate-300 text-sky-600 focus:ring-sky-500"
  1027. />
  1028. <span class="text-slate-700 dark:text-slate-300 capitalize">${day.substring(0, 3)}</span>
  1029. </label>
  1030. `).join('')}
  1031. </div>
  1032. </div>
  1033. `;
  1034. // Add event listeners for this slot
  1035. const startTimeInput = slotDiv.querySelector('.start-time');
  1036. const endTimeInput = slotDiv.querySelector('.end-time');
  1037. const daysSelect = slotDiv.querySelector('.days-select');
  1038. const customDaysContainer = slotDiv.querySelector('.custom-days-container');
  1039. const removeButton = slotDiv.querySelector('.remove-slot-btn');
  1040. // Show/hide custom days based on selection
  1041. daysSelect.addEventListener('change', () => {
  1042. customDaysContainer.style.display = daysSelect.value === 'custom' ? 'block' : 'none';
  1043. updateTimeSlot(slot.id);
  1044. });
  1045. // Update slot data when inputs change
  1046. startTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1047. endTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1048. // Handle custom day checkboxes
  1049. customDaysContainer.addEventListener('change', () => updateTimeSlot(slot.id));
  1050. // Remove slot button
  1051. removeButton.addEventListener('click', () => {
  1052. removeTimeSlot(slot.id);
  1053. });
  1054. return slotDiv;
  1055. }
  1056. // Function to render all time slots
  1057. function renderTimeSlots() {
  1058. timeSlotsContainer.innerHTML = '';
  1059. if (timeSlots.length === 0) {
  1060. timeSlotsContainer.innerHTML = `
  1061. <div class="text-center py-8 text-slate-500 dark:text-slate-400">
  1062. <span class="material-icons text-4xl mb-2 block">schedule</span>
  1063. <p>No time slots configured</p>
  1064. <p class="text-xs mt-1">Click "Add Time Slot" to create a pause schedule</p>
  1065. </div>
  1066. `;
  1067. return;
  1068. }
  1069. timeSlots.forEach(slot => {
  1070. const slotElement = createTimeSlotElement(slot);
  1071. timeSlotsContainer.appendChild(slotElement);
  1072. });
  1073. }
  1074. // Function to add a new time slot
  1075. function addTimeSlot() {
  1076. const newSlot = {
  1077. id: ++slotIdCounter,
  1078. start_time: '22:00',
  1079. end_time: '08:00',
  1080. days: 'daily',
  1081. custom_days: []
  1082. };
  1083. timeSlots.push(newSlot);
  1084. renderTimeSlots();
  1085. }
  1086. // Function to remove a time slot
  1087. function removeTimeSlot(slotId) {
  1088. timeSlots = timeSlots.filter(slot => slot.id !== slotId);
  1089. renderTimeSlots();
  1090. }
  1091. // Function to update a time slot's data
  1092. function updateTimeSlot(slotId) {
  1093. const slotElement = timeSlotsContainer.querySelector(`[data-slot-id="${slotId}"]`);
  1094. if (!slotElement) return;
  1095. const slot = timeSlots.find(s => s.id === slotId);
  1096. if (!slot) return;
  1097. // Update slot data from inputs
  1098. slot.start_time = slotElement.querySelector('.start-time').value;
  1099. slot.end_time = slotElement.querySelector('.end-time').value;
  1100. slot.days = slotElement.querySelector('.days-select').value;
  1101. // Update custom days if applicable
  1102. if (slot.days === 'custom') {
  1103. const checkedDays = Array.from(slotElement.querySelectorAll(`input[name="custom-days-${slotId}"]:checked`))
  1104. .map(cb => cb.value);
  1105. slot.custom_days = checkedDays;
  1106. } else {
  1107. slot.custom_days = [];
  1108. }
  1109. }
  1110. // Function to validate all time slots
  1111. function validateTimeSlots() {
  1112. const errors = [];
  1113. timeSlots.forEach((slot, index) => {
  1114. if (!slot.start_time || !isValidTime(slot.start_time)) {
  1115. errors.push(`Time slot ${index + 1}: Invalid start time`);
  1116. }
  1117. if (!slot.end_time || !isValidTime(slot.end_time)) {
  1118. errors.push(`Time slot ${index + 1}: Invalid end time`);
  1119. }
  1120. if (slot.days === 'custom' && (!slot.custom_days || slot.custom_days.length === 0)) {
  1121. errors.push(`Time slot ${index + 1}: Please select at least one day for custom schedule`);
  1122. }
  1123. });
  1124. return errors;
  1125. }
  1126. // Function to save settings
  1127. async function saveStillSandsSettings() {
  1128. // Update all slots from current form values
  1129. timeSlots.forEach(slot => updateTimeSlot(slot.id));
  1130. // Validate time slots
  1131. const validationErrors = validateTimeSlots();
  1132. if (validationErrors.length > 0) {
  1133. showStatusMessage(`Validation errors: ${validationErrors.join(', ')}`, 'error');
  1134. return;
  1135. }
  1136. // Update button UI to show loading state
  1137. const originalButtonHTML = saveStillSandsButton.innerHTML;
  1138. saveStillSandsButton.disabled = true;
  1139. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg animate-spin">refresh</span><span class="truncate">Saving...</span>';
  1140. try {
  1141. const response = await fetch('/api/scheduled-pause', {
  1142. method: 'POST',
  1143. headers: { 'Content-Type': 'application/json' },
  1144. body: JSON.stringify({
  1145. enabled: stillSandsToggle.checked,
  1146. control_wled: wledControlToggle ? wledControlToggle.checked : false,
  1147. time_slots: timeSlots.map(slot => ({
  1148. start_time: slot.start_time,
  1149. end_time: slot.end_time,
  1150. days: slot.days,
  1151. custom_days: slot.custom_days
  1152. }))
  1153. })
  1154. });
  1155. if (!response.ok) {
  1156. const errorData = await response.json();
  1157. throw new Error(errorData.detail || 'Failed to save Still Sands settings');
  1158. }
  1159. // Show success state temporarily
  1160. saveStillSandsButton.innerHTML = '<span class="material-icons text-lg">check</span><span class="truncate">Saved!</span>';
  1161. showStatusMessage('Still Sands settings saved successfully', 'success');
  1162. // Restore button after 2 seconds
  1163. setTimeout(() => {
  1164. saveStillSandsButton.innerHTML = originalButtonHTML;
  1165. saveStillSandsButton.disabled = false;
  1166. }, 2000);
  1167. } catch (error) {
  1168. logMessage(`Error saving Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1169. showStatusMessage(`Failed to save settings: ${error.message}`, 'error');
  1170. // Restore button immediately on error
  1171. saveStillSandsButton.innerHTML = originalButtonHTML;
  1172. saveStillSandsButton.disabled = false;
  1173. }
  1174. }
  1175. // Note: Slot IDs are now assigned during initialization above, before first render
  1176. // Event listeners
  1177. stillSandsToggle.addEventListener('change', async () => {
  1178. logMessage(`Still Sands toggle changed: ${stillSandsToggle.checked}`, LOG_TYPE.INFO);
  1179. stillSandsSettings.style.display = stillSandsToggle.checked ? 'block' : 'none';
  1180. logMessage(`Settings display set to: ${stillSandsSettings.style.display}`, LOG_TYPE.INFO);
  1181. // Auto-save when toggle changes
  1182. try {
  1183. await saveStillSandsSettings();
  1184. const statusText = stillSandsToggle.checked ? 'enabled' : 'disabled';
  1185. showStatusMessage(`Still Sands ${statusText} successfully`, 'success');
  1186. } catch (error) {
  1187. logMessage(`Error saving Still Sands toggle: ${error.message}`, LOG_TYPE.ERROR);
  1188. showStatusMessage(`Failed to save Still Sands setting: ${error.message}`, 'error');
  1189. }
  1190. });
  1191. addTimeSlotButton.addEventListener('click', addTimeSlot);
  1192. saveStillSandsButton.addEventListener('click', saveStillSandsSettings);
  1193. // Add listener for WLED control toggle
  1194. if (wledControlToggle) {
  1195. wledControlToggle.addEventListener('change', async () => {
  1196. logMessage(`WLED control toggle changed: ${wledControlToggle.checked}`, LOG_TYPE.INFO);
  1197. // Auto-save when WLED control changes
  1198. await saveStillSandsSettings();
  1199. });
  1200. }
  1201. }