sidepanel.js 15 KB

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