sidepanel.js 17 KB

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