sidepanel.js 12 KB

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