settings.js 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335
  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. // Check if elements exist
  920. if (!stillSandsToggle || !stillSandsSettings || !addTimeSlotButton || !saveStillSandsButton || !timeSlotsContainer) {
  921. logMessage('Still Sands elements not found, skipping initialization', LOG_TYPE.WARNING);
  922. logMessage(`Found elements: toggle=${!!stillSandsToggle}, settings=${!!stillSandsSettings}, addBtn=${!!addTimeSlotButton}, saveBtn=${!!saveStillSandsButton}, container=${!!timeSlotsContainer}`, LOG_TYPE.WARNING);
  923. return;
  924. }
  925. logMessage('All Still Sands elements found successfully', LOG_TYPE.INFO);
  926. // Track time slots
  927. let timeSlots = [];
  928. let slotIdCounter = 0;
  929. // Load current Still Sands settings from initial data
  930. try {
  931. // Use the data loaded during page initialization, fallback to API if not available
  932. let data;
  933. if (window.initialStillSandsData) {
  934. data = window.initialStillSandsData;
  935. // Clear the global variable after use
  936. delete window.initialStillSandsData;
  937. } else {
  938. // Fallback to API call if initial data not available
  939. const response = await fetch('/api/scheduled-pause');
  940. data = await response.json();
  941. }
  942. stillSandsToggle.checked = data.enabled || false;
  943. if (data.enabled) {
  944. stillSandsSettings.style.display = 'block';
  945. }
  946. // Load existing time slots
  947. timeSlots = data.time_slots || [];
  948. renderTimeSlots();
  949. } catch (error) {
  950. logMessage(`Error loading Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  951. // Initialize with empty settings if load fails
  952. timeSlots = [];
  953. renderTimeSlots();
  954. }
  955. // Function to validate time format (HH:MM)
  956. function isValidTime(timeString) {
  957. const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
  958. return timeRegex.test(timeString);
  959. }
  960. // Function to create a new time slot element
  961. function createTimeSlotElement(slot) {
  962. const slotDiv = document.createElement('div');
  963. slotDiv.className = 'time-slot-item';
  964. slotDiv.dataset.slotId = slot.id;
  965. slotDiv.innerHTML = `
  966. <div class="flex items-center gap-3">
  967. <div class="flex-1 grid grid-cols-1 md:grid-cols-2 gap-3">
  968. <div class="flex flex-col gap-1">
  969. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Start Time</label>
  970. <input
  971. type="time"
  972. 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"
  973. value="${slot.start_time || ''}"
  974. required
  975. />
  976. </div>
  977. <div class="flex flex-col gap-1">
  978. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">End Time</label>
  979. <input
  980. type="time"
  981. 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"
  982. value="${slot.end_time || ''}"
  983. required
  984. />
  985. </div>
  986. </div>
  987. <div class="flex flex-col gap-1">
  988. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium">Days</label>
  989. <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">
  990. <option value="daily" ${slot.days === 'daily' ? 'selected' : ''}>Daily</option>
  991. <option value="weekdays" ${slot.days === 'weekdays' ? 'selected' : ''}>Weekdays</option>
  992. <option value="weekends" ${slot.days === 'weekends' ? 'selected' : ''}>Weekends</option>
  993. <option value="custom" ${slot.days === 'custom' ? 'selected' : ''}>Custom</option>
  994. </select>
  995. </div>
  996. <button
  997. type="button"
  998. 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"
  999. title="Remove time slot"
  1000. >
  1001. <span class="material-icons text-base">delete</span>
  1002. </button>
  1003. </div>
  1004. <div class="custom-days-container mt-2" style="display: ${slot.days === 'custom' ? 'block' : 'none'};">
  1005. <label class="text-slate-700 dark:text-slate-300 text-xs font-medium mb-1 block">Select Days</label>
  1006. <div class="flex flex-wrap gap-2">
  1007. ${['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'].map(day => `
  1008. <label class="flex items-center gap-1 text-xs">
  1009. <input
  1010. type="checkbox"
  1011. name="custom-days-${slot.id}"
  1012. value="${day}"
  1013. ${slot.custom_days && slot.custom_days.includes(day) ? 'checked' : ''}
  1014. class="rounded border-slate-300 text-sky-600 focus:ring-sky-500"
  1015. />
  1016. <span class="text-slate-700 dark:text-slate-300 capitalize">${day.substring(0, 3)}</span>
  1017. </label>
  1018. `).join('')}
  1019. </div>
  1020. </div>
  1021. `;
  1022. // Add event listeners for this slot
  1023. const startTimeInput = slotDiv.querySelector('.start-time');
  1024. const endTimeInput = slotDiv.querySelector('.end-time');
  1025. const daysSelect = slotDiv.querySelector('.days-select');
  1026. const customDaysContainer = slotDiv.querySelector('.custom-days-container');
  1027. const removeButton = slotDiv.querySelector('.remove-slot-btn');
  1028. // Show/hide custom days based on selection
  1029. daysSelect.addEventListener('change', () => {
  1030. customDaysContainer.style.display = daysSelect.value === 'custom' ? 'block' : 'none';
  1031. updateTimeSlot(slot.id);
  1032. });
  1033. // Update slot data when inputs change
  1034. startTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1035. endTimeInput.addEventListener('change', () => updateTimeSlot(slot.id));
  1036. // Handle custom day checkboxes
  1037. customDaysContainer.addEventListener('change', () => updateTimeSlot(slot.id));
  1038. // Remove slot button
  1039. removeButton.addEventListener('click', () => {
  1040. removeTimeSlot(slot.id);
  1041. });
  1042. return slotDiv;
  1043. }
  1044. // Function to render all time slots
  1045. function renderTimeSlots() {
  1046. timeSlotsContainer.innerHTML = '';
  1047. if (timeSlots.length === 0) {
  1048. timeSlotsContainer.innerHTML = `
  1049. <div class="text-center py-8 text-slate-500 dark:text-slate-400">
  1050. <span class="material-icons text-4xl mb-2 block">schedule</span>
  1051. <p>No time slots configured</p>
  1052. <p class="text-xs mt-1">Click "Add Time Slot" to create a pause schedule</p>
  1053. </div>
  1054. `;
  1055. return;
  1056. }
  1057. timeSlots.forEach(slot => {
  1058. const slotElement = createTimeSlotElement(slot);
  1059. timeSlotsContainer.appendChild(slotElement);
  1060. });
  1061. }
  1062. // Function to add a new time slot
  1063. function addTimeSlot() {
  1064. const newSlot = {
  1065. id: ++slotIdCounter,
  1066. start_time: '22:00',
  1067. end_time: '08:00',
  1068. days: 'daily',
  1069. custom_days: []
  1070. };
  1071. timeSlots.push(newSlot);
  1072. renderTimeSlots();
  1073. }
  1074. // Function to remove a time slot
  1075. function removeTimeSlot(slotId) {
  1076. timeSlots = timeSlots.filter(slot => slot.id !== slotId);
  1077. renderTimeSlots();
  1078. }
  1079. // Function to update a time slot's data
  1080. function updateTimeSlot(slotId) {
  1081. const slotElement = timeSlotsContainer.querySelector(`[data-slot-id="${slotId}"]`);
  1082. if (!slotElement) return;
  1083. const slot = timeSlots.find(s => s.id === slotId);
  1084. if (!slot) return;
  1085. // Update slot data from inputs
  1086. slot.start_time = slotElement.querySelector('.start-time').value;
  1087. slot.end_time = slotElement.querySelector('.end-time').value;
  1088. slot.days = slotElement.querySelector('.days-select').value;
  1089. // Update custom days if applicable
  1090. if (slot.days === 'custom') {
  1091. const checkedDays = Array.from(slotElement.querySelectorAll(`input[name="custom-days-${slotId}"]:checked`))
  1092. .map(cb => cb.value);
  1093. slot.custom_days = checkedDays;
  1094. } else {
  1095. slot.custom_days = [];
  1096. }
  1097. }
  1098. // Function to validate all time slots
  1099. function validateTimeSlots() {
  1100. const errors = [];
  1101. timeSlots.forEach((slot, index) => {
  1102. if (!slot.start_time || !isValidTime(slot.start_time)) {
  1103. errors.push(`Time slot ${index + 1}: Invalid start time`);
  1104. }
  1105. if (!slot.end_time || !isValidTime(slot.end_time)) {
  1106. errors.push(`Time slot ${index + 1}: Invalid end time`);
  1107. }
  1108. if (slot.days === 'custom' && (!slot.custom_days || slot.custom_days.length === 0)) {
  1109. errors.push(`Time slot ${index + 1}: Please select at least one day for custom schedule`);
  1110. }
  1111. });
  1112. return errors;
  1113. }
  1114. // Function to save settings
  1115. async function saveStillSandsSettings() {
  1116. // Update all slots from current form values
  1117. timeSlots.forEach(slot => updateTimeSlot(slot.id));
  1118. // Validate time slots
  1119. const validationErrors = validateTimeSlots();
  1120. if (validationErrors.length > 0) {
  1121. showStatusMessage(`Validation errors: ${validationErrors.join(', ')}`, 'error');
  1122. return;
  1123. }
  1124. try {
  1125. const response = await fetch('/api/scheduled-pause', {
  1126. method: 'POST',
  1127. headers: { 'Content-Type': 'application/json' },
  1128. body: JSON.stringify({
  1129. enabled: stillSandsToggle.checked,
  1130. time_slots: timeSlots.map(slot => ({
  1131. start_time: slot.start_time,
  1132. end_time: slot.end_time,
  1133. days: slot.days,
  1134. custom_days: slot.custom_days
  1135. }))
  1136. })
  1137. });
  1138. if (!response.ok) {
  1139. const errorData = await response.json();
  1140. throw new Error(errorData.detail || 'Failed to save Still Sands settings');
  1141. }
  1142. showStatusMessage('Still Sands settings saved successfully', 'success');
  1143. } catch (error) {
  1144. logMessage(`Error saving Still Sands settings: ${error.message}`, LOG_TYPE.ERROR);
  1145. showStatusMessage(`Failed to save settings: ${error.message}`, 'error');
  1146. }
  1147. }
  1148. // Initialize slot ID counter
  1149. if (timeSlots.length > 0) {
  1150. slotIdCounter = Math.max(...timeSlots.map(slot => slot.id || 0));
  1151. }
  1152. // Assign IDs to existing slots if they don't have them
  1153. timeSlots.forEach(slot => {
  1154. if (!slot.id) {
  1155. slot.id = ++slotIdCounter;
  1156. }
  1157. });
  1158. // Event listeners
  1159. stillSandsToggle.addEventListener('change', async () => {
  1160. logMessage(`Still Sands toggle changed: ${stillSandsToggle.checked}`, LOG_TYPE.INFO);
  1161. stillSandsSettings.style.display = stillSandsToggle.checked ? 'block' : 'none';
  1162. logMessage(`Settings display set to: ${stillSandsSettings.style.display}`, LOG_TYPE.INFO);
  1163. // Auto-save when toggle changes
  1164. try {
  1165. await saveStillSandsSettings();
  1166. const statusText = stillSandsToggle.checked ? 'enabled' : 'disabled';
  1167. showStatusMessage(`Still Sands ${statusText} successfully`, 'success');
  1168. } catch (error) {
  1169. logMessage(`Error saving Still Sands toggle: ${error.message}`, LOG_TYPE.ERROR);
  1170. showStatusMessage(`Failed to save Still Sands setting: ${error.message}`, 'error');
  1171. }
  1172. });
  1173. addTimeSlotButton.addEventListener('click', addTimeSlot);
  1174. saveStillSandsButton.addEventListener('click', saveStillSandsSettings);
  1175. }