sidepanel.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  94. if (row) {
  95. row.className = `step-row ${status}`;
  96. }
  97. updateButtonStates();
  98. updateProgressCounter();
  99. }
  100. function updateProgressCounter() {
  101. let completed = 0;
  102. document.querySelectorAll('.step-row').forEach(row => {
  103. if (row.classList.contains('completed')) completed++;
  104. });
  105. stepsProgress.textContent = `${completed} / 9`;
  106. }
  107. function updateButtonStates() {
  108. const statuses = {};
  109. document.querySelectorAll('.step-row').forEach(row => {
  110. const step = Number(row.dataset.step);
  111. if (row.classList.contains('completed')) statuses[step] = 'completed';
  112. else if (row.classList.contains('running')) statuses[step] = 'running';
  113. else if (row.classList.contains('failed')) statuses[step] = 'failed';
  114. else statuses[step] = 'pending';
  115. });
  116. const anyRunning = Object.values(statuses).some(s => s === 'running');
  117. for (let step = 1; step <= 9; step++) {
  118. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  119. if (!btn) continue;
  120. if (anyRunning) {
  121. btn.disabled = true;
  122. } else if (step === 1) {
  123. btn.disabled = false;
  124. } else {
  125. const prevStatus = statuses[step - 1];
  126. const currentStatus = statuses[step];
  127. btn.disabled = !(prevStatus === 'completed' || currentStatus === 'failed' || currentStatus === 'completed');
  128. }
  129. }
  130. }
  131. function updateStatusDisplay(state) {
  132. if (!state || !state.stepStatuses) return;
  133. statusBar.className = 'status-bar';
  134. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  135. if (running) {
  136. displayStatus.textContent = `Step ${running[0]} running...`;
  137. statusBar.classList.add('running');
  138. return;
  139. }
  140. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  141. if (failed) {
  142. displayStatus.textContent = `Step ${failed[0]} failed`;
  143. statusBar.classList.add('failed');
  144. return;
  145. }
  146. const lastCompleted = Object.entries(state.stepStatuses)
  147. .filter(([, s]) => s === 'completed')
  148. .map(([k]) => Number(k))
  149. .sort((a, b) => b - a)[0];
  150. if (lastCompleted === 9) {
  151. displayStatus.textContent = 'All steps completed!';
  152. statusBar.classList.add('completed');
  153. } else if (lastCompleted) {
  154. displayStatus.textContent = `Step ${lastCompleted} done`;
  155. } else {
  156. displayStatus.textContent = 'Ready';
  157. }
  158. }
  159. function appendLog(entry) {
  160. const time = new Date(entry.timestamp).toLocaleTimeString('en-US', { hour12: false });
  161. const levelLabel = entry.level.toUpperCase();
  162. const line = document.createElement('div');
  163. line.className = `log-line log-${entry.level}`;
  164. const stepMatch = entry.message.match(/Step (\d)/);
  165. const stepNum = stepMatch ? stepMatch[1] : null;
  166. let html = `<span class="log-time">${time}</span> `;
  167. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  168. if (stepNum) {
  169. html += `<span class="log-step-tag step-${stepNum}">S${stepNum}</span>`;
  170. }
  171. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  172. line.innerHTML = html;
  173. logArea.appendChild(line);
  174. logArea.scrollTop = logArea.scrollHeight;
  175. }
  176. function escapeHtml(text) {
  177. const div = document.createElement('div');
  178. div.textContent = text;
  179. return div.innerHTML;
  180. }
  181. // ============================================================
  182. // Button Handlers
  183. // ============================================================
  184. document.querySelectorAll('.step-btn').forEach(btn => {
  185. btn.addEventListener('click', async () => {
  186. const step = Number(btn.dataset.step);
  187. if (step === 3) {
  188. const email = inputEmail.value.trim();
  189. if (!email) {
  190. showToast('Please paste email address first', 'warn');
  191. return;
  192. }
  193. await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  194. } else {
  195. await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  196. }
  197. });
  198. });
  199. // Auto Run
  200. btnAutoRun.addEventListener('click', async () => {
  201. const totalRuns = parseInt(inputRunCount.value) || 1;
  202. btnAutoRun.disabled = true;
  203. inputRunCount.disabled = true;
  204. 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...';
  205. await chrome.runtime.sendMessage({ type: 'AUTO_RUN', source: 'sidepanel', payload: { totalRuns } });
  206. });
  207. btnAutoContinue.addEventListener('click', async () => {
  208. const email = inputEmail.value.trim();
  209. if (!email) {
  210. showToast('Please paste DuckDuckGo email first!', 'warn');
  211. return;
  212. }
  213. autoContinueBar.style.display = 'none';
  214. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  215. });
  216. // Reset
  217. btnReset.addEventListener('click', async () => {
  218. if (confirm('Reset all steps and data?')) {
  219. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  220. displayOauthUrl.textContent = 'Waiting...';
  221. displayOauthUrl.classList.remove('has-value');
  222. displayLocalhostUrl.textContent = 'Waiting...';
  223. displayLocalhostUrl.classList.remove('has-value');
  224. inputEmail.value = '';
  225. displayStatus.textContent = 'Ready';
  226. statusBar.className = 'status-bar';
  227. logArea.innerHTML = '';
  228. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  229. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  230. btnAutoRun.disabled = false;
  231. 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';
  232. autoContinueBar.style.display = 'none';
  233. updateButtonStates();
  234. updateProgressCounter();
  235. }
  236. });
  237. // Clear log
  238. btnClearLog.addEventListener('click', () => {
  239. logArea.innerHTML = '';
  240. });
  241. // Save settings on change
  242. inputEmail.addEventListener('change', async () => {
  243. const email = inputEmail.value.trim();
  244. if (email) {
  245. await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  246. }
  247. });
  248. inputVpsUrl.addEventListener('change', async () => {
  249. const vpsUrl = inputVpsUrl.value.trim();
  250. if (vpsUrl) {
  251. await chrome.runtime.sendMessage({ type: 'SAVE_SETTING', source: 'sidepanel', payload: { vpsUrl } });
  252. }
  253. });
  254. selectMailProvider.addEventListener('change', async () => {
  255. await chrome.runtime.sendMessage({
  256. type: 'SAVE_SETTING', source: 'sidepanel',
  257. payload: { mailProvider: selectMailProvider.value },
  258. });
  259. });
  260. // ============================================================
  261. // Listen for Background broadcasts
  262. // ============================================================
  263. chrome.runtime.onMessage.addListener((message) => {
  264. switch (message.type) {
  265. case 'LOG_ENTRY':
  266. appendLog(message.payload);
  267. if (message.payload.level === 'error') {
  268. showToast(message.payload.message, 'error');
  269. }
  270. break;
  271. case 'STEP_STATUS_CHANGED': {
  272. const { step, status } = message.payload;
  273. updateStepUI(step, status);
  274. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(updateStatusDisplay);
  275. if (status === 'completed') {
  276. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  277. if (state.oauthUrl) {
  278. displayOauthUrl.textContent = state.oauthUrl;
  279. displayOauthUrl.classList.add('has-value');
  280. }
  281. if (state.localhostUrl) {
  282. displayLocalhostUrl.textContent = state.localhostUrl;
  283. displayLocalhostUrl.classList.add('has-value');
  284. }
  285. });
  286. }
  287. break;
  288. }
  289. case 'AUTO_RUN_RESET': {
  290. // Full UI reset for next run
  291. displayOauthUrl.textContent = 'Waiting...';
  292. displayOauthUrl.classList.remove('has-value');
  293. displayLocalhostUrl.textContent = 'Waiting...';
  294. displayLocalhostUrl.classList.remove('has-value');
  295. inputEmail.value = '';
  296. displayStatus.textContent = 'Ready';
  297. statusBar.className = 'status-bar';
  298. logArea.innerHTML = '';
  299. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  300. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  301. updateProgressCounter();
  302. break;
  303. }
  304. case 'DATA_UPDATED': {
  305. if (message.payload.oauthUrl) {
  306. displayOauthUrl.textContent = message.payload.oauthUrl;
  307. displayOauthUrl.classList.add('has-value');
  308. }
  309. if (message.payload.localhostUrl) {
  310. displayLocalhostUrl.textContent = message.payload.localhostUrl;
  311. displayLocalhostUrl.classList.add('has-value');
  312. }
  313. break;
  314. }
  315. case 'AUTO_RUN_STATUS': {
  316. const { phase, currentRun, totalRuns } = message.payload;
  317. const runLabel = totalRuns > 1 ? ` (${currentRun}/${totalRuns})` : '';
  318. switch (phase) {
  319. case 'waiting_email':
  320. autoContinueBar.style.display = 'flex';
  321. btnAutoRun.innerHTML = `Paused${runLabel}`;
  322. break;
  323. case 'running':
  324. btnAutoRun.innerHTML = `Running${runLabel}`;
  325. break;
  326. case 'complete':
  327. btnAutoRun.disabled = false;
  328. inputRunCount.disabled = false;
  329. 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';
  330. autoContinueBar.style.display = 'none';
  331. break;
  332. case 'stopped':
  333. btnAutoRun.disabled = false;
  334. inputRunCount.disabled = false;
  335. 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';
  336. autoContinueBar.style.display = 'none';
  337. break;
  338. }
  339. break;
  340. }
  341. }
  342. });
  343. // ============================================================
  344. // Theme Toggle
  345. // ============================================================
  346. const btnTheme = document.getElementById('btn-theme');
  347. function setTheme(theme) {
  348. document.documentElement.setAttribute('data-theme', theme);
  349. localStorage.setItem('multipage-theme', theme);
  350. }
  351. function initTheme() {
  352. const saved = localStorage.getItem('multipage-theme');
  353. if (saved) {
  354. setTheme(saved);
  355. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  356. setTheme('dark');
  357. }
  358. }
  359. btnTheme.addEventListener('click', () => {
  360. const current = document.documentElement.getAttribute('data-theme');
  361. setTheme(current === 'dark' ? 'light' : 'dark');
  362. });
  363. // ============================================================
  364. // Init
  365. // ============================================================
  366. initTheme();
  367. restoreState().then(() => {
  368. updateButtonStates();
  369. });