sidepanel.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595
  1. // sidepanel/sidepanel.js — Side Panel logic
  2. const STATUS_ICONS = {
  3. pending: '',
  4. running: '',
  5. completed: '\u2713', // ✓
  6. failed: '\u2717', // ✗
  7. stopped: '\u25A0', // ■
  8. };
  9. const logArea = document.getElementById('log-area');
  10. const displayOauthUrl = document.getElementById('display-oauth-url');
  11. const displayLocalhostUrl = document.getElementById('display-localhost-url');
  12. const displayStatus = document.getElementById('display-status');
  13. const statusBar = document.getElementById('status-bar');
  14. const inputEmail = document.getElementById('input-email');
  15. const inputPassword = document.getElementById('input-password');
  16. const btnFetchEmail = document.getElementById('btn-fetch-email');
  17. const btnTogglePassword = document.getElementById('btn-toggle-password');
  18. const btnStop = document.getElementById('btn-stop');
  19. const btnReset = document.getElementById('btn-reset');
  20. const stepsProgress = document.getElementById('steps-progress');
  21. const btnAutoRun = document.getElementById('btn-auto-run');
  22. const btnAutoContinue = document.getElementById('btn-auto-continue');
  23. const autoContinueBar = document.getElementById('auto-continue-bar');
  24. const btnClearLog = document.getElementById('btn-clear-log');
  25. const inputVpsUrl = document.getElementById('input-vps-url');
  26. const selectMailProvider = document.getElementById('select-mail-provider');
  27. const rowTempApiUrl = document.getElementById('row-temp-api-url');
  28. const inputTempApiUrl = document.getElementById('input-temp-api-url');
  29. const rowInbucketHost = document.getElementById('row-inbucket-host');
  30. const inputInbucketHost = document.getElementById('input-inbucket-host');
  31. const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox');
  32. const inputInbucketMailbox = document.getElementById('input-inbucket-mailbox');
  33. const inputDuckToken = document.getElementById('input-duck-token');
  34. const inputRunCount = document.getElementById('input-run-count');
  35. // ============================================================
  36. // Toast Notifications
  37. // ============================================================
  38. const toastContainer = document.getElementById('toast-container');
  39. const TOAST_ICONS = {
  40. error: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>',
  41. warn: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
  42. success: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
  43. info: '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>',
  44. };
  45. function showToast(message, type = 'error', duration = 4000) {
  46. const toast = document.createElement('div');
  47. toast.className = `toast toast-${type}`;
  48. toast.innerHTML = `${TOAST_ICONS[type] || ''}<span class="toast-msg">${escapeHtml(message)}</span><button class="toast-close">&times;</button>`;
  49. toast.querySelector('.toast-close').addEventListener('click', () => dismissToast(toast));
  50. toastContainer.appendChild(toast);
  51. if (duration > 0) {
  52. setTimeout(() => dismissToast(toast), duration);
  53. }
  54. }
  55. function dismissToast(toast) {
  56. if (!toast.parentNode) return;
  57. toast.classList.add('toast-exit');
  58. toast.addEventListener('animationend', () => toast.remove());
  59. }
  60. // ============================================================
  61. // State Restore on load
  62. // ============================================================
  63. async function restoreState() {
  64. try {
  65. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  66. if (state.oauthUrl) {
  67. displayOauthUrl.textContent = state.oauthUrl;
  68. displayOauthUrl.classList.add('has-value');
  69. }
  70. if (state.localhostUrl) {
  71. displayLocalhostUrl.textContent = state.localhostUrl;
  72. displayLocalhostUrl.classList.add('has-value');
  73. }
  74. if (state.email) {
  75. inputEmail.value = state.email;
  76. }
  77. syncPasswordField(state);
  78. if (state.vpsUrl) {
  79. inputVpsUrl.value = state.vpsUrl;
  80. }
  81. if (state.mailProvider) {
  82. selectMailProvider.value = state.mailProvider;
  83. }
  84. if (state.tempApiUrl) {
  85. inputTempApiUrl.value = state.tempApiUrl;
  86. }
  87. if (state.duckToken) {
  88. inputDuckToken.value = state.duckToken;
  89. }
  90. if (state.inbucketHost) {
  91. inputInbucketHost.value = state.inbucketHost;
  92. }
  93. if (state.inbucketMailbox) {
  94. inputInbucketMailbox.value = state.inbucketMailbox;
  95. }
  96. if (state.stepStatuses) {
  97. for (const [step, status] of Object.entries(state.stepStatuses)) {
  98. updateStepUI(Number(step), status);
  99. }
  100. }
  101. if (state.logs) {
  102. for (const entry of state.logs) {
  103. appendLog(entry);
  104. }
  105. }
  106. updateStatusDisplay(state);
  107. updateProgressCounter();
  108. updateMailProviderUI();
  109. // Sync temp API URL from UI to state (handles browser autocomplete / form restore)
  110. const currentTempApiUrl = inputTempApiUrl.value.trim();
  111. if (currentTempApiUrl && currentTempApiUrl !== (state.tempApiUrl || '')) {
  112. await chrome.runtime.sendMessage({
  113. type: 'SAVE_SETTING',
  114. source: 'sidepanel',
  115. payload: { tempApiUrl: currentTempApiUrl },
  116. });
  117. }
  118. } catch (err) {
  119. console.error('Failed to restore state:', err);
  120. }
  121. }
  122. function syncPasswordField(state) {
  123. inputPassword.value = state.customPassword || state.password || '';
  124. }
  125. function updateMailProviderUI() {
  126. const val = selectMailProvider.value;
  127. rowTempApiUrl.style.display = val === 'temp-api' ? '' : 'none';
  128. rowInbucketHost.style.display = val === 'inbucket' ? '' : 'none';
  129. rowInbucketMailbox.style.display = val === 'inbucket' ? '' : 'none';
  130. }
  131. // ============================================================
  132. // UI Updates
  133. // ============================================================
  134. function updateStepUI(step, status) {
  135. const statusEl = document.querySelector(`.step-status[data-step="${step}"]`);
  136. const row = document.querySelector(`.step-row[data-step="${step}"]`);
  137. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  138. if (row) {
  139. row.className = `step-row ${status}`;
  140. }
  141. updateButtonStates();
  142. updateProgressCounter();
  143. }
  144. function updateProgressCounter() {
  145. let completed = 0;
  146. document.querySelectorAll('.step-row').forEach(row => {
  147. if (row.classList.contains('completed')) completed++;
  148. });
  149. stepsProgress.textContent = `${completed} / 9`;
  150. }
  151. function updateButtonStates() {
  152. const statuses = {};
  153. document.querySelectorAll('.step-row').forEach(row => {
  154. const step = Number(row.dataset.step);
  155. if (row.classList.contains('completed')) statuses[step] = 'completed';
  156. else if (row.classList.contains('running')) statuses[step] = 'running';
  157. else if (row.classList.contains('failed')) statuses[step] = 'failed';
  158. else if (row.classList.contains('stopped')) statuses[step] = 'stopped';
  159. else statuses[step] = 'pending';
  160. });
  161. const anyRunning = Object.values(statuses).some(s => s === 'running');
  162. for (let step = 1; step <= 9; step++) {
  163. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  164. if (!btn) continue;
  165. if (anyRunning) {
  166. btn.disabled = true;
  167. } else if (step === 1) {
  168. btn.disabled = false;
  169. } else {
  170. const prevStatus = statuses[step - 1];
  171. const currentStatus = statuses[step];
  172. btn.disabled = !(prevStatus === 'completed' || currentStatus === 'failed' || currentStatus === 'completed' || currentStatus === 'stopped');
  173. }
  174. }
  175. updateStopButtonState(anyRunning || autoContinueBar.style.display !== 'none');
  176. }
  177. function updateStopButtonState(active) {
  178. btnStop.disabled = !active;
  179. }
  180. function updateStatusDisplay(state) {
  181. if (!state || !state.stepStatuses) return;
  182. statusBar.className = 'status-bar';
  183. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  184. if (running) {
  185. displayStatus.textContent = `Step ${running[0]} running...`;
  186. statusBar.classList.add('running');
  187. return;
  188. }
  189. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  190. if (failed) {
  191. displayStatus.textContent = `Step ${failed[0]} failed`;
  192. statusBar.classList.add('failed');
  193. return;
  194. }
  195. const stopped = Object.entries(state.stepStatuses).find(([, s]) => s === 'stopped');
  196. if (stopped) {
  197. displayStatus.textContent = `Step ${stopped[0]} stopped`;
  198. statusBar.classList.add('stopped');
  199. return;
  200. }
  201. const lastCompleted = Object.entries(state.stepStatuses)
  202. .filter(([, s]) => s === 'completed')
  203. .map(([k]) => Number(k))
  204. .sort((a, b) => b - a)[0];
  205. if (lastCompleted === 9) {
  206. displayStatus.textContent = 'All steps completed!';
  207. statusBar.classList.add('completed');
  208. } else if (lastCompleted) {
  209. displayStatus.textContent = `Step ${lastCompleted} done`;
  210. } else {
  211. displayStatus.textContent = 'Ready';
  212. }
  213. }
  214. function appendLog(entry) {
  215. const time = new Date(entry.timestamp).toLocaleTimeString('en-US', { hour12: false });
  216. const levelLabel = entry.level.toUpperCase();
  217. const line = document.createElement('div');
  218. line.className = `log-line log-${entry.level}`;
  219. const stepMatch = entry.message.match(/Step (\d)/);
  220. const stepNum = stepMatch ? stepMatch[1] : null;
  221. let html = `<span class="log-time">${time}</span> `;
  222. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  223. if (stepNum) {
  224. html += `<span class="log-step-tag step-${stepNum}">S${stepNum}</span>`;
  225. }
  226. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  227. line.innerHTML = html;
  228. logArea.appendChild(line);
  229. logArea.scrollTop = logArea.scrollHeight;
  230. }
  231. function escapeHtml(text) {
  232. const div = document.createElement('div');
  233. div.textContent = text;
  234. return div.innerHTML;
  235. }
  236. async function fetchDuckEmail() {
  237. const defaultLabel = 'Auto';
  238. btnFetchEmail.disabled = true;
  239. btnFetchEmail.textContent = '...';
  240. try {
  241. const response = await chrome.runtime.sendMessage({
  242. type: 'FETCH_DUCK_EMAIL',
  243. source: 'sidepanel',
  244. payload: { generateNew: true },
  245. });
  246. if (response?.error) {
  247. throw new Error(response.error);
  248. }
  249. if (!response?.email) {
  250. throw new Error('Duck email was not returned.');
  251. }
  252. inputEmail.value = response.email;
  253. showToast(`Fetched ${response.email}`, 'success', 2500);
  254. return response.email;
  255. } catch (err) {
  256. showToast(`Auto fetch failed: ${err.message}`, 'error');
  257. throw err;
  258. } finally {
  259. btnFetchEmail.disabled = false;
  260. btnFetchEmail.textContent = defaultLabel;
  261. }
  262. }
  263. function syncPasswordToggleLabel() {
  264. btnTogglePassword.textContent = inputPassword.type === 'password' ? 'Show' : 'Hide';
  265. }
  266. // ============================================================
  267. // Button Handlers
  268. // ============================================================
  269. document.querySelectorAll('.step-btn').forEach(btn => {
  270. btn.addEventListener('click', async () => {
  271. const step = Number(btn.dataset.step);
  272. if (step === 3) {
  273. const email = inputEmail.value.trim();
  274. if (!email) {
  275. showToast('Please paste email address or use Auto first', 'warn');
  276. return;
  277. }
  278. await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  279. } else {
  280. await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  281. }
  282. });
  283. });
  284. btnFetchEmail.addEventListener('click', async () => {
  285. await fetchDuckEmail().catch(() => {});
  286. });
  287. btnTogglePassword.addEventListener('click', () => {
  288. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  289. syncPasswordToggleLabel();
  290. });
  291. btnStop.addEventListener('click', async () => {
  292. btnStop.disabled = true;
  293. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  294. showToast('Stopping current flow...', 'warn', 2000);
  295. });
  296. // Auto Run
  297. btnAutoRun.addEventListener('click', async () => {
  298. const totalRuns = parseInt(inputRunCount.value) || 1;
  299. btnAutoRun.disabled = true;
  300. inputRunCount.disabled = true;
  301. btnAutoRun.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></svg> Running...';
  302. await chrome.runtime.sendMessage({ type: 'AUTO_RUN', source: 'sidepanel', payload: { totalRuns } });
  303. });
  304. btnAutoContinue.addEventListener('click', async () => {
  305. const email = inputEmail.value.trim();
  306. if (!email) {
  307. showToast('Please fetch or paste DuckDuckGo email first!', 'warn');
  308. return;
  309. }
  310. autoContinueBar.style.display = 'none';
  311. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  312. });
  313. // Reset
  314. btnReset.addEventListener('click', async () => {
  315. if (confirm('Reset all steps and data?')) {
  316. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  317. displayOauthUrl.textContent = 'Waiting...';
  318. displayOauthUrl.classList.remove('has-value');
  319. displayLocalhostUrl.textContent = 'Waiting...';
  320. displayLocalhostUrl.classList.remove('has-value');
  321. inputEmail.value = '';
  322. displayStatus.textContent = 'Ready';
  323. statusBar.className = 'status-bar';
  324. logArea.innerHTML = '';
  325. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  326. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  327. btnAutoRun.disabled = false;
  328. inputRunCount.disabled = false;
  329. btnAutoRun.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg> Auto';
  330. autoContinueBar.style.display = 'none';
  331. updateStopButtonState(false);
  332. updateButtonStates();
  333. updateProgressCounter();
  334. }
  335. });
  336. // Clear log
  337. btnClearLog.addEventListener('click', () => {
  338. logArea.innerHTML = '';
  339. });
  340. // Save settings on change
  341. inputEmail.addEventListener('change', async () => {
  342. const email = inputEmail.value.trim();
  343. if (email) {
  344. await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  345. }
  346. });
  347. inputVpsUrl.addEventListener('change', async () => {
  348. const vpsUrl = inputVpsUrl.value.trim();
  349. if (vpsUrl) {
  350. await chrome.runtime.sendMessage({ type: 'SAVE_SETTING', source: 'sidepanel', payload: { vpsUrl } });
  351. }
  352. });
  353. inputPassword.addEventListener('change', async () => {
  354. await chrome.runtime.sendMessage({
  355. type: 'SAVE_SETTING',
  356. source: 'sidepanel',
  357. payload: { customPassword: inputPassword.value },
  358. });
  359. });
  360. selectMailProvider.addEventListener('change', async () => {
  361. updateMailProviderUI();
  362. await chrome.runtime.sendMessage({
  363. type: 'SAVE_SETTING', source: 'sidepanel',
  364. payload: { mailProvider: selectMailProvider.value },
  365. });
  366. });
  367. inputInbucketMailbox.addEventListener('change', async () => {
  368. await chrome.runtime.sendMessage({
  369. type: 'SAVE_SETTING',
  370. source: 'sidepanel',
  371. payload: { inbucketMailbox: inputInbucketMailbox.value.trim() },
  372. });
  373. });
  374. // Save on both 'change' (blur) and 'input' (immediate, e.g. paste)
  375. for (const evt of ['change', 'input']) {
  376. inputTempApiUrl.addEventListener(evt, async () => {
  377. await chrome.runtime.sendMessage({
  378. type: 'SAVE_SETTING',
  379. source: 'sidepanel',
  380. payload: { tempApiUrl: inputTempApiUrl.value.trim() },
  381. });
  382. });
  383. inputDuckToken.addEventListener(evt, async () => {
  384. await chrome.runtime.sendMessage({
  385. type: 'SAVE_SETTING',
  386. source: 'sidepanel',
  387. payload: { duckToken: inputDuckToken.value.trim() },
  388. });
  389. });
  390. }
  391. inputInbucketHost.addEventListener('change', async () => {
  392. await chrome.runtime.sendMessage({
  393. type: 'SAVE_SETTING',
  394. source: 'sidepanel',
  395. payload: { inbucketHost: inputInbucketHost.value.trim() },
  396. });
  397. });
  398. // ============================================================
  399. // Listen for Background broadcasts
  400. // ============================================================
  401. chrome.runtime.onMessage.addListener((message) => {
  402. switch (message.type) {
  403. case 'LOG_ENTRY':
  404. appendLog(message.payload);
  405. if (message.payload.level === 'error') {
  406. showToast(message.payload.message, 'error');
  407. }
  408. break;
  409. case 'STEP_STATUS_CHANGED': {
  410. const { step, status } = message.payload;
  411. updateStepUI(step, status);
  412. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(updateStatusDisplay);
  413. if (status === 'completed') {
  414. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  415. syncPasswordField(state);
  416. if (state.oauthUrl) {
  417. displayOauthUrl.textContent = state.oauthUrl;
  418. displayOauthUrl.classList.add('has-value');
  419. }
  420. if (state.localhostUrl) {
  421. displayLocalhostUrl.textContent = state.localhostUrl;
  422. displayLocalhostUrl.classList.add('has-value');
  423. }
  424. });
  425. }
  426. break;
  427. }
  428. case 'AUTO_RUN_RESET': {
  429. // Full UI reset for next run
  430. displayOauthUrl.textContent = 'Waiting...';
  431. displayOauthUrl.classList.remove('has-value');
  432. displayLocalhostUrl.textContent = 'Waiting...';
  433. displayLocalhostUrl.classList.remove('has-value');
  434. inputEmail.value = '';
  435. displayStatus.textContent = 'Ready';
  436. statusBar.className = 'status-bar';
  437. logArea.innerHTML = '';
  438. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  439. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  440. updateStopButtonState(false);
  441. updateProgressCounter();
  442. break;
  443. }
  444. case 'DATA_UPDATED': {
  445. if (message.payload.email) {
  446. inputEmail.value = message.payload.email;
  447. }
  448. if (message.payload.password !== undefined) {
  449. inputPassword.value = message.payload.password || '';
  450. }
  451. if (message.payload.oauthUrl) {
  452. displayOauthUrl.textContent = message.payload.oauthUrl;
  453. displayOauthUrl.classList.add('has-value');
  454. }
  455. if (message.payload.localhostUrl) {
  456. displayLocalhostUrl.textContent = message.payload.localhostUrl;
  457. displayLocalhostUrl.classList.add('has-value');
  458. }
  459. break;
  460. }
  461. case 'AUTO_RUN_STATUS': {
  462. const { phase, currentRun, totalRuns, successCount } = message.payload;
  463. const successLabel = successCount > 0 ? ` ok:${successCount}` : '';
  464. switch (phase) {
  465. case 'waiting_email':
  466. autoContinueBar.style.display = 'flex';
  467. btnAutoRun.innerHTML = `Paused${successLabel}`;
  468. updateStopButtonState(true);
  469. break;
  470. case 'running':
  471. btnAutoRun.innerHTML = `Running${successLabel}`;
  472. updateStopButtonState(true);
  473. break;
  474. case 'complete':
  475. btnAutoRun.disabled = false;
  476. inputRunCount.disabled = false;
  477. btnAutoRun.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg> Auto';
  478. autoContinueBar.style.display = 'none';
  479. updateStopButtonState(false);
  480. break;
  481. case 'stopped':
  482. btnAutoRun.disabled = false;
  483. inputRunCount.disabled = false;
  484. btnAutoRun.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><polygon points="5 3 19 12 5 21 5 3"/></svg> Auto';
  485. autoContinueBar.style.display = 'none';
  486. updateStopButtonState(false);
  487. break;
  488. }
  489. break;
  490. }
  491. }
  492. });
  493. // ============================================================
  494. // Theme Toggle
  495. // ============================================================
  496. const btnTheme = document.getElementById('btn-theme');
  497. function setTheme(theme) {
  498. document.documentElement.setAttribute('data-theme', theme);
  499. localStorage.setItem('multipage-theme', theme);
  500. }
  501. function initTheme() {
  502. const saved = localStorage.getItem('multipage-theme');
  503. if (saved) {
  504. setTheme(saved);
  505. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  506. setTheme('dark');
  507. }
  508. }
  509. btnTheme.addEventListener('click', () => {
  510. const current = document.documentElement.getAttribute('data-theme');
  511. setTheme(current === 'dark' ? 'light' : 'dark');
  512. });
  513. // ============================================================
  514. // Init
  515. // ============================================================
  516. initTheme();
  517. restoreState().then(() => {
  518. syncPasswordToggleLabel();
  519. updateButtonStates();
  520. });