sidepanel.js 19 KB

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