sidepanel.js 13 KB

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