sidepanel.js 19 KB

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