sidepanel.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  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. manual_completed: '跳',
  9. skipped: '跳',
  10. };
  11. const logArea = document.getElementById('log-area');
  12. const displayOauthUrl = document.getElementById('display-oauth-url');
  13. const displayLocalhostUrl = document.getElementById('display-localhost-url');
  14. const displayStatus = document.getElementById('display-status');
  15. const statusBar = document.getElementById('status-bar');
  16. const inputEmail = document.getElementById('input-email');
  17. const inputPassword = document.getElementById('input-password');
  18. const btnToggleVpsUrl = document.getElementById('btn-toggle-vps-url');
  19. const btnFetchEmail = document.getElementById('btn-fetch-email');
  20. const btnTogglePassword = document.getElementById('btn-toggle-password');
  21. const btnSaveSettings = document.getElementById('btn-save-settings');
  22. const btnStop = document.getElementById('btn-stop');
  23. const btnReset = document.getElementById('btn-reset');
  24. const stepsProgress = document.getElementById('steps-progress');
  25. const btnAutoRun = document.getElementById('btn-auto-run');
  26. const btnAutoContinue = document.getElementById('btn-auto-continue');
  27. const autoContinueBar = document.getElementById('auto-continue-bar');
  28. const btnClearLog = document.getElementById('btn-clear-log');
  29. const inputVpsUrl = document.getElementById('input-vps-url');
  30. const inputVpsPassword = document.getElementById('input-vps-password');
  31. const selectMailProvider = document.getElementById('select-mail-provider');
  32. const rowInbucketHost = document.getElementById('row-inbucket-host');
  33. const inputInbucketHost = document.getElementById('input-inbucket-host');
  34. const rowInbucketMailbox = document.getElementById('row-inbucket-mailbox');
  35. const inputInbucketMailbox = document.getElementById('input-inbucket-mailbox');
  36. const inputRunCount = document.getElementById('input-run-count');
  37. const inputAutoSkipFailures = document.getElementById('input-auto-skip-failures');
  38. const autoStartModal = document.getElementById('auto-start-modal');
  39. const autoStartTitle = autoStartModal?.querySelector('.modal-title');
  40. const autoStartMessage = document.getElementById('auto-start-message');
  41. const btnAutoStartClose = document.getElementById('btn-auto-start-close');
  42. const btnAutoStartCancel = document.getElementById('btn-auto-start-cancel');
  43. const btnAutoStartRestart = document.getElementById('btn-auto-start-restart');
  44. const btnAutoStartContinue = document.getElementById('btn-auto-start-continue');
  45. const STEP_DEFAULT_STATUSES = {
  46. 1: 'pending',
  47. 2: 'pending',
  48. 3: 'pending',
  49. 4: 'pending',
  50. 5: 'pending',
  51. 6: 'pending',
  52. 7: 'pending',
  53. 8: 'pending',
  54. 9: 'pending',
  55. };
  56. const SKIPPABLE_STEPS = new Set([1, 2, 3, 4, 5, 6, 7, 8, 9]);
  57. let latestState = null;
  58. let currentAutoRun = {
  59. autoRunning: false,
  60. phase: 'idle',
  61. currentRun: 0,
  62. totalRuns: 1,
  63. attemptRun: 0,
  64. };
  65. let settingsDirty = false;
  66. let settingsSaveInFlight = false;
  67. let settingsAutoSaveTimer = null;
  68. let modalChoiceResolver = null;
  69. let currentModalActions = [];
  70. const EYE_OPEN_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-7 11-7 11 7 11 7-4 7-11 7S1 12 1 12z"/><circle cx="12" cy="12" r="3"/></svg>';
  71. const EYE_CLOSED_ICON = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.94 10.94 0 0 1 12 19C5 19 1 12 1 12a21.77 21.77 0 0 1 5.06-6.94"/><path d="M9.9 4.24A10.94 10.94 0 0 1 12 5c7 0 11 7 11 7a21.86 21.86 0 0 1-2.16 3.19"/><path d="M1 1l22 22"/><path d="M14.12 14.12a3 3 0 1 1-4.24-4.24"/></svg>';
  72. // ============================================================
  73. // Toast Notifications
  74. // ============================================================
  75. const toastContainer = document.getElementById('toast-container');
  76. const TOAST_ICONS = {
  77. 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>',
  78. 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>',
  79. 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>',
  80. 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>',
  81. };
  82. const LOG_LEVEL_LABELS = {
  83. info: '信息',
  84. ok: '成功',
  85. warn: '警告',
  86. error: '错误',
  87. };
  88. function showToast(message, type = 'error', duration = 4000) {
  89. const toast = document.createElement('div');
  90. toast.className = `toast toast-${type}`;
  91. toast.innerHTML = `${TOAST_ICONS[type] || ''}<span class="toast-msg">${escapeHtml(message)}</span><button class="toast-close">&times;</button>`;
  92. toast.querySelector('.toast-close').addEventListener('click', () => dismissToast(toast));
  93. toastContainer.appendChild(toast);
  94. if (duration > 0) {
  95. setTimeout(() => dismissToast(toast), duration);
  96. }
  97. }
  98. function dismissToast(toast) {
  99. if (!toast.parentNode) return;
  100. toast.classList.add('toast-exit');
  101. toast.addEventListener('animationend', () => toast.remove());
  102. }
  103. function resetActionModalButtons() {
  104. const buttons = [btnAutoStartCancel, btnAutoStartRestart, btnAutoStartContinue];
  105. buttons.forEach((button) => {
  106. if (!button) return;
  107. button.hidden = true;
  108. button.disabled = false;
  109. button.onclick = null;
  110. });
  111. currentModalActions = [];
  112. }
  113. function configureActionModalButton(button, action) {
  114. if (!button) return;
  115. if (!action) {
  116. button.hidden = true;
  117. button.onclick = null;
  118. return;
  119. }
  120. button.hidden = false;
  121. button.disabled = false;
  122. button.textContent = action.label;
  123. button.className = `btn ${action.variant || 'btn-outline'} btn-sm`;
  124. button.onclick = () => resolveModalChoice(action.id);
  125. }
  126. function resolveModalChoice(choice) {
  127. if (modalChoiceResolver) {
  128. modalChoiceResolver(choice);
  129. modalChoiceResolver = null;
  130. }
  131. resetActionModalButtons();
  132. if (autoStartModal) {
  133. autoStartModal.hidden = true;
  134. }
  135. }
  136. function openActionModal({ title, message, actions }) {
  137. if (!autoStartModal) {
  138. return Promise.resolve(null);
  139. }
  140. if (modalChoiceResolver) {
  141. resolveModalChoice(null);
  142. }
  143. autoStartTitle.textContent = title;
  144. autoStartMessage.textContent = message;
  145. currentModalActions = actions || [];
  146. configureActionModalButton(btnAutoStartCancel, currentModalActions[0]);
  147. configureActionModalButton(btnAutoStartRestart, currentModalActions[1]);
  148. configureActionModalButton(btnAutoStartContinue, currentModalActions[2]);
  149. autoStartModal.hidden = false;
  150. return new Promise((resolve) => {
  151. modalChoiceResolver = resolve;
  152. });
  153. }
  154. function openAutoStartChoiceDialog(startStep) {
  155. return openActionModal({
  156. title: '启动自动',
  157. message: `检测到当前已有流程进度。继续当前会从步骤 ${startStep} 开始自动执行,重新开始会清空当前流程进度并从步骤 1 新开一轮。`,
  158. actions: [
  159. { id: null, label: '取消', variant: 'btn-ghost' },
  160. { id: 'restart', label: '重新开始', variant: 'btn-outline' },
  161. { id: 'continue', label: '继续当前', variant: 'btn-primary' },
  162. ],
  163. });
  164. }
  165. async function openConfirmModal({ title, message, confirmLabel = '确认', confirmVariant = 'btn-primary' }) {
  166. const choice = await openActionModal({
  167. title,
  168. message,
  169. actions: [
  170. { id: null, label: '取消', variant: 'btn-ghost' },
  171. { id: 'confirm', label: confirmLabel, variant: confirmVariant },
  172. ],
  173. });
  174. return choice === 'confirm';
  175. }
  176. function isDoneStatus(status) {
  177. return status === 'completed' || status === 'manual_completed' || status === 'skipped';
  178. }
  179. function getStepStatuses(state = latestState) {
  180. return { ...STEP_DEFAULT_STATUSES, ...(state?.stepStatuses || {}) };
  181. }
  182. function getFirstUnfinishedStep(state = latestState) {
  183. const statuses = getStepStatuses(state);
  184. for (let step = 1; step <= 9; step++) {
  185. if (!isDoneStatus(statuses[step])) {
  186. return step;
  187. }
  188. }
  189. return null;
  190. }
  191. function hasSavedProgress(state = latestState) {
  192. const statuses = getStepStatuses(state);
  193. return Object.values(statuses).some((status) => status !== 'pending');
  194. }
  195. function shouldOfferAutoModeChoice(state = latestState) {
  196. return hasSavedProgress(state) && getFirstUnfinishedStep(state) !== null;
  197. }
  198. function syncLatestState(nextState) {
  199. const mergedStepStatuses = nextState?.stepStatuses
  200. ? { ...STEP_DEFAULT_STATUSES, ...(latestState?.stepStatuses || {}), ...nextState.stepStatuses }
  201. : getStepStatuses(latestState);
  202. latestState = {
  203. ...(latestState || {}),
  204. ...(nextState || {}),
  205. stepStatuses: mergedStepStatuses,
  206. };
  207. }
  208. function syncAutoRunState(source = {}) {
  209. const phase = source.autoRunPhase ?? source.phase ?? currentAutoRun.phase;
  210. const autoRunning = source.autoRunning !== undefined
  211. ? Boolean(source.autoRunning)
  212. : (source.autoRunPhase !== undefined || source.phase !== undefined
  213. ? ['running', 'waiting_email', 'retrying'].includes(phase)
  214. : currentAutoRun.autoRunning);
  215. currentAutoRun = {
  216. autoRunning,
  217. phase,
  218. currentRun: source.autoRunCurrentRun ?? source.currentRun ?? currentAutoRun.currentRun,
  219. totalRuns: source.autoRunTotalRuns ?? source.totalRuns ?? currentAutoRun.totalRuns,
  220. attemptRun: source.autoRunAttemptRun ?? source.attemptRun ?? currentAutoRun.attemptRun,
  221. };
  222. }
  223. function isAutoRunLockedPhase() {
  224. return currentAutoRun.phase === 'running' || currentAutoRun.phase === 'retrying';
  225. }
  226. function isAutoRunPausedPhase() {
  227. return currentAutoRun.phase === 'waiting_email';
  228. }
  229. function getAutoRunLabel(payload = currentAutoRun) {
  230. const attemptLabel = payload.attemptRun ? ` · 尝试${payload.attemptRun}` : '';
  231. if ((payload.totalRuns || 1) > 1) {
  232. return ` (${payload.currentRun}/${payload.totalRuns}${attemptLabel})`;
  233. }
  234. return attemptLabel ? ` (${attemptLabel.slice(3)})` : '';
  235. }
  236. function setDefaultAutoRunButton() {
  237. btnAutoRun.disabled = false;
  238. inputRunCount.disabled = false;
  239. 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> 自动';
  240. }
  241. function collectSettingsPayload() {
  242. return {
  243. vpsUrl: inputVpsUrl.value.trim(),
  244. vpsPassword: inputVpsPassword.value,
  245. customPassword: inputPassword.value,
  246. mailProvider: selectMailProvider.value,
  247. inbucketHost: inputInbucketHost.value.trim(),
  248. inbucketMailbox: inputInbucketMailbox.value.trim(),
  249. autoRunSkipFailures: inputAutoSkipFailures.checked,
  250. };
  251. }
  252. function markSettingsDirty(isDirty = true) {
  253. settingsDirty = isDirty;
  254. updateSaveButtonState();
  255. }
  256. function updateSaveButtonState() {
  257. btnSaveSettings.disabled = settingsSaveInFlight || !settingsDirty;
  258. btnSaveSettings.textContent = settingsSaveInFlight ? '保存中' : '保存';
  259. }
  260. function scheduleSettingsAutoSave() {
  261. clearTimeout(settingsAutoSaveTimer);
  262. settingsAutoSaveTimer = setTimeout(() => {
  263. saveSettings({ silent: true }).catch(() => {});
  264. }, 500);
  265. }
  266. async function saveSettings(options = {}) {
  267. const { silent = false } = options;
  268. clearTimeout(settingsAutoSaveTimer);
  269. if (!settingsDirty && !settingsSaveInFlight && silent) {
  270. return;
  271. }
  272. const payload = collectSettingsPayload();
  273. settingsSaveInFlight = true;
  274. updateSaveButtonState();
  275. try {
  276. const response = await chrome.runtime.sendMessage({
  277. type: 'SAVE_SETTING',
  278. source: 'sidepanel',
  279. payload,
  280. });
  281. if (response?.error) {
  282. throw new Error(response.error);
  283. }
  284. syncLatestState(payload);
  285. markSettingsDirty(false);
  286. updateMailProviderUI();
  287. updateButtonStates();
  288. if (!silent) {
  289. showToast('配置已保存', 'success', 1800);
  290. }
  291. } catch (err) {
  292. markSettingsDirty(true);
  293. if (!silent) {
  294. showToast(`保存失败:${err.message}`, 'error');
  295. }
  296. throw err;
  297. } finally {
  298. settingsSaveInFlight = false;
  299. updateSaveButtonState();
  300. }
  301. }
  302. function applyAutoRunStatus(payload = currentAutoRun) {
  303. syncAutoRunState(payload);
  304. const runLabel = getAutoRunLabel(currentAutoRun);
  305. const locked = isAutoRunLockedPhase();
  306. const paused = isAutoRunPausedPhase();
  307. inputRunCount.disabled = currentAutoRun.autoRunning;
  308. btnAutoRun.disabled = currentAutoRun.autoRunning;
  309. btnFetchEmail.disabled = locked;
  310. inputEmail.disabled = locked;
  311. switch (currentAutoRun.phase) {
  312. case 'waiting_email':
  313. autoContinueBar.style.display = 'flex';
  314. btnAutoRun.innerHTML = `已暂停${runLabel}`;
  315. break;
  316. case 'running':
  317. autoContinueBar.style.display = 'none';
  318. btnAutoRun.innerHTML = `运行中${runLabel}`;
  319. break;
  320. case 'retrying':
  321. autoContinueBar.style.display = 'none';
  322. btnAutoRun.innerHTML = `重试中${runLabel}`;
  323. break;
  324. default:
  325. autoContinueBar.style.display = 'none';
  326. setDefaultAutoRunButton();
  327. inputEmail.disabled = false;
  328. if (!locked) {
  329. btnFetchEmail.disabled = false;
  330. }
  331. break;
  332. }
  333. updateStopButtonState(paused || locked || Object.values(getStepStatuses()).some(status => status === 'running'));
  334. }
  335. function initializeManualStepActions() {
  336. document.querySelectorAll('.step-row').forEach((row) => {
  337. const step = Number(row.dataset.step);
  338. const statusEl = row.querySelector('.step-status');
  339. if (!statusEl) return;
  340. const actions = document.createElement('div');
  341. actions.className = 'step-actions';
  342. const manualBtn = document.createElement('button');
  343. manualBtn.type = 'button';
  344. manualBtn.className = 'step-manual-btn';
  345. manualBtn.dataset.step = String(step);
  346. manualBtn.title = '跳过此步';
  347. manualBtn.setAttribute('aria-label', `跳过步骤 ${step}`);
  348. manualBtn.innerHTML = '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="13 17 18 12 13 7"/><polyline points="6 17 11 12 6 7"/></svg>';
  349. manualBtn.addEventListener('click', async (event) => {
  350. event.stopPropagation();
  351. try {
  352. await handleSkipStep(step);
  353. } catch (err) {
  354. showToast(err.message, 'error');
  355. }
  356. });
  357. statusEl.parentNode.replaceChild(actions, statusEl);
  358. actions.appendChild(manualBtn);
  359. actions.appendChild(statusEl);
  360. });
  361. }
  362. // ============================================================
  363. // State Restore on load
  364. // ============================================================
  365. async function restoreState() {
  366. try {
  367. const state = await chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' });
  368. syncLatestState(state);
  369. syncAutoRunState(state);
  370. if (state.oauthUrl) {
  371. displayOauthUrl.textContent = state.oauthUrl;
  372. displayOauthUrl.classList.add('has-value');
  373. }
  374. if (state.localhostUrl) {
  375. displayLocalhostUrl.textContent = state.localhostUrl;
  376. displayLocalhostUrl.classList.add('has-value');
  377. }
  378. if (state.email) {
  379. inputEmail.value = state.email;
  380. }
  381. syncPasswordField(state);
  382. if (state.vpsUrl) {
  383. inputVpsUrl.value = state.vpsUrl;
  384. }
  385. if (state.vpsPassword) {
  386. inputVpsPassword.value = state.vpsPassword;
  387. }
  388. if (state.mailProvider) {
  389. selectMailProvider.value = state.mailProvider;
  390. }
  391. if (state.inbucketHost) {
  392. inputInbucketHost.value = state.inbucketHost;
  393. }
  394. if (state.inbucketMailbox) {
  395. inputInbucketMailbox.value = state.inbucketMailbox;
  396. }
  397. inputAutoSkipFailures.checked = Boolean(state.autoRunSkipFailures);
  398. if (state.stepStatuses) {
  399. for (const [step, status] of Object.entries(state.stepStatuses)) {
  400. updateStepUI(Number(step), status);
  401. }
  402. }
  403. if (state.logs) {
  404. for (const entry of state.logs) {
  405. appendLog(entry);
  406. }
  407. }
  408. applyAutoRunStatus(state);
  409. markSettingsDirty(false);
  410. updateStatusDisplay(latestState);
  411. updateProgressCounter();
  412. updateMailProviderUI();
  413. updateButtonStates();
  414. } catch (err) {
  415. console.error('Failed to restore state:', err);
  416. }
  417. }
  418. function syncPasswordField(state) {
  419. inputPassword.value = state.customPassword || state.password || '';
  420. }
  421. function updateMailProviderUI() {
  422. const useInbucket = selectMailProvider.value === 'inbucket';
  423. rowInbucketHost.style.display = useInbucket ? '' : 'none';
  424. rowInbucketMailbox.style.display = useInbucket ? '' : 'none';
  425. }
  426. // ============================================================
  427. // UI Updates
  428. // ============================================================
  429. function updateStepUI(step, status) {
  430. const statusEl = document.querySelector(`.step-status[data-step="${step}"]`);
  431. const row = document.querySelector(`.step-row[data-step="${step}"]`);
  432. syncLatestState({
  433. stepStatuses: {
  434. ...getStepStatuses(),
  435. [step]: status,
  436. },
  437. });
  438. if (statusEl) statusEl.textContent = STATUS_ICONS[status] || '';
  439. if (row) {
  440. row.className = `step-row ${status}`;
  441. }
  442. updateButtonStates();
  443. updateProgressCounter();
  444. }
  445. function updateProgressCounter() {
  446. const completed = Object.values(getStepStatuses()).filter(isDoneStatus).length;
  447. stepsProgress.textContent = `${completed} / 9`;
  448. }
  449. function updateButtonStates() {
  450. const statuses = getStepStatuses();
  451. const anyRunning = Object.values(statuses).some(s => s === 'running');
  452. const autoLocked = isAutoRunLockedPhase();
  453. for (let step = 1; step <= 9; step++) {
  454. const btn = document.querySelector(`.step-btn[data-step="${step}"]`);
  455. if (!btn) continue;
  456. if (anyRunning || autoLocked) {
  457. btn.disabled = true;
  458. } else if (step === 1) {
  459. btn.disabled = false;
  460. } else {
  461. const prevStatus = statuses[step - 1];
  462. const currentStatus = statuses[step];
  463. btn.disabled = !(isDoneStatus(prevStatus) || currentStatus === 'failed' || isDoneStatus(currentStatus) || currentStatus === 'stopped');
  464. }
  465. }
  466. document.querySelectorAll('.step-manual-btn').forEach((btn) => {
  467. const step = Number(btn.dataset.step);
  468. const currentStatus = statuses[step];
  469. const prevStatus = statuses[step - 1];
  470. if (!SKIPPABLE_STEPS.has(step) || anyRunning || autoLocked || currentStatus === 'running' || isDoneStatus(currentStatus)) {
  471. btn.style.display = 'none';
  472. btn.disabled = true;
  473. btn.title = '当前不可跳过';
  474. return;
  475. }
  476. if (step > 1 && !isDoneStatus(prevStatus)) {
  477. btn.style.display = 'none';
  478. btn.disabled = true;
  479. btn.title = `请先完成步骤 ${step - 1}`;
  480. return;
  481. }
  482. btn.style.display = '';
  483. btn.disabled = false;
  484. btn.title = `跳过步骤 ${step}`;
  485. });
  486. updateStopButtonState(anyRunning || isAutoRunPausedPhase() || autoLocked);
  487. }
  488. function updateStopButtonState(active) {
  489. btnStop.disabled = !active;
  490. }
  491. function updateStatusDisplay(state) {
  492. if (!state || !state.stepStatuses) return;
  493. statusBar.className = 'status-bar';
  494. if (isAutoRunPausedPhase()) {
  495. displayStatus.textContent = `自动已暂停${getAutoRunLabel()},等待邮箱后继续`;
  496. statusBar.classList.add('paused');
  497. return;
  498. }
  499. const running = Object.entries(state.stepStatuses).find(([, s]) => s === 'running');
  500. if (running) {
  501. displayStatus.textContent = `步骤 ${running[0]} 运行中...`;
  502. statusBar.classList.add('running');
  503. return;
  504. }
  505. if (isAutoRunLockedPhase()) {
  506. displayStatus.textContent = `${currentAutoRun.phase === 'retrying' ? '自动重试中' : '自动运行中'}${getAutoRunLabel()}`;
  507. statusBar.classList.add('running');
  508. return;
  509. }
  510. const failed = Object.entries(state.stepStatuses).find(([, s]) => s === 'failed');
  511. if (failed) {
  512. displayStatus.textContent = `步骤 ${failed[0]} 失败`;
  513. statusBar.classList.add('failed');
  514. return;
  515. }
  516. const stopped = Object.entries(state.stepStatuses).find(([, s]) => s === 'stopped');
  517. if (stopped) {
  518. displayStatus.textContent = `步骤 ${stopped[0]} 已停止`;
  519. statusBar.classList.add('stopped');
  520. return;
  521. }
  522. const lastCompleted = Object.entries(state.stepStatuses)
  523. .filter(([, s]) => isDoneStatus(s))
  524. .map(([k]) => Number(k))
  525. .sort((a, b) => b - a)[0];
  526. if (lastCompleted === 9) {
  527. displayStatus.textContent = (state.stepStatuses[9] === 'manual_completed' || state.stepStatuses[9] === 'skipped') ? '全部步骤已跳过/完成' : '全部步骤已完成';
  528. statusBar.classList.add('completed');
  529. } else if (lastCompleted) {
  530. displayStatus.textContent = (state.stepStatuses[lastCompleted] === 'manual_completed' || state.stepStatuses[lastCompleted] === 'skipped')
  531. ? `步骤 ${lastCompleted} 已跳过`
  532. : `步骤 ${lastCompleted} 已完成`;
  533. } else {
  534. displayStatus.textContent = '就绪';
  535. }
  536. }
  537. function appendLog(entry) {
  538. const time = new Date(entry.timestamp).toLocaleTimeString('zh-CN', { hour12: false });
  539. const levelLabel = LOG_LEVEL_LABELS[entry.level] || entry.level;
  540. const line = document.createElement('div');
  541. line.className = `log-line log-${entry.level}`;
  542. const stepMatch = entry.message.match(/(?:Step\s+(\d+)|步骤\s*(\d+))/);
  543. const stepNum = stepMatch ? (stepMatch[1] || stepMatch[2]) : null;
  544. let html = `<span class="log-time">${time}</span> `;
  545. html += `<span class="log-level log-level-${entry.level}">${levelLabel}</span> `;
  546. if (stepNum) {
  547. html += `<span class="log-step-tag step-${stepNum}">步${stepNum}</span>`;
  548. }
  549. html += `<span class="log-msg">${escapeHtml(entry.message)}</span>`;
  550. line.innerHTML = html;
  551. logArea.appendChild(line);
  552. logArea.scrollTop = logArea.scrollHeight;
  553. }
  554. function escapeHtml(text) {
  555. const div = document.createElement('div');
  556. div.textContent = text;
  557. return div.innerHTML;
  558. }
  559. async function fetchDuckEmail(options = {}) {
  560. const { showFailureToast = true } = options;
  561. const defaultLabel = '获取';
  562. btnFetchEmail.disabled = true;
  563. btnFetchEmail.textContent = '...';
  564. try {
  565. const response = await chrome.runtime.sendMessage({
  566. type: 'FETCH_DUCK_EMAIL',
  567. source: 'sidepanel',
  568. payload: { generateNew: true },
  569. });
  570. if (response?.error) {
  571. throw new Error(response.error);
  572. }
  573. if (!response?.email) {
  574. throw new Error('未返回 Duck 邮箱。');
  575. }
  576. inputEmail.value = response.email;
  577. showToast(`已获取 ${response.email}`, 'success', 2500);
  578. return response.email;
  579. } catch (err) {
  580. if (showFailureToast) {
  581. showToast(`自动获取失败:${err.message}`, 'error');
  582. }
  583. throw err;
  584. } finally {
  585. btnFetchEmail.disabled = false;
  586. btnFetchEmail.textContent = defaultLabel;
  587. }
  588. }
  589. function syncToggleButtonLabel(button, input, labels) {
  590. if (!button || !input) return;
  591. const isHidden = input.type === 'password';
  592. button.innerHTML = isHidden ? EYE_OPEN_ICON : EYE_CLOSED_ICON;
  593. button.setAttribute('aria-label', isHidden ? labels.show : labels.hide);
  594. button.title = isHidden ? labels.show : labels.hide;
  595. }
  596. function syncPasswordToggleLabel() {
  597. syncToggleButtonLabel(btnTogglePassword, inputPassword, {
  598. show: '显示密码',
  599. hide: '隐藏密码',
  600. });
  601. }
  602. function syncVpsUrlToggleLabel() {
  603. syncToggleButtonLabel(btnToggleVpsUrl, inputVpsUrl, {
  604. show: '显示 CPA 地址',
  605. hide: '隐藏 CPA 地址',
  606. });
  607. }
  608. async function maybeTakeoverAutoRun(actionLabel) {
  609. if (!isAutoRunPausedPhase()) {
  610. return true;
  611. }
  612. const confirmed = await openConfirmModal({
  613. title: '接管自动',
  614. message: `当前自动流程已暂停。若继续${actionLabel},将停止自动流程并切换为手动控制。是否继续?`,
  615. confirmLabel: '确认接管',
  616. confirmVariant: 'btn-primary',
  617. });
  618. if (!confirmed) {
  619. return false;
  620. }
  621. await chrome.runtime.sendMessage({ type: 'TAKEOVER_AUTO_RUN', source: 'sidepanel', payload: {} });
  622. return true;
  623. }
  624. async function handleSkipStep(step) {
  625. if (!(await maybeTakeoverAutoRun(`跳过步骤 ${step}`))) {
  626. return;
  627. }
  628. const confirmed = await openConfirmModal({
  629. title: '跳过步骤',
  630. message: `这不会真正执行步骤 ${step},只会直接跳过该步骤并放行后续步骤。是否继续?`,
  631. confirmLabel: `跳过步骤 ${step}`,
  632. confirmVariant: 'btn-primary',
  633. });
  634. if (!confirmed) {
  635. return;
  636. }
  637. const response = await chrome.runtime.sendMessage({
  638. type: 'SKIP_STEP',
  639. source: 'sidepanel',
  640. payload: { step },
  641. });
  642. if (response?.error) {
  643. throw new Error(response.error);
  644. }
  645. showToast(`步骤 ${step} 已跳过`, 'success', 2200);
  646. }
  647. // ============================================================
  648. // Button Handlers
  649. // ============================================================
  650. document.querySelectorAll('.step-btn').forEach(btn => {
  651. btn.addEventListener('click', async () => {
  652. try {
  653. const step = Number(btn.dataset.step);
  654. if (!(await maybeTakeoverAutoRun(`执行步骤 ${step}`))) {
  655. return;
  656. }
  657. if (step === 3) {
  658. if (inputPassword.value !== (latestState?.customPassword || '')) {
  659. await chrome.runtime.sendMessage({
  660. type: 'SAVE_SETTING',
  661. source: 'sidepanel',
  662. payload: { customPassword: inputPassword.value },
  663. });
  664. syncLatestState({ customPassword: inputPassword.value });
  665. }
  666. let email = inputEmail.value.trim();
  667. if (!email) {
  668. try {
  669. email = await fetchDuckEmail({ showFailureToast: false });
  670. } catch (err) {
  671. showToast(`自动获取失败:${err.message},请手动粘贴邮箱后重试。`, 'warn');
  672. return;
  673. }
  674. }
  675. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step, email } });
  676. if (response?.error) {
  677. throw new Error(response.error);
  678. }
  679. } else {
  680. const response = await chrome.runtime.sendMessage({ type: 'EXECUTE_STEP', source: 'sidepanel', payload: { step } });
  681. if (response?.error) {
  682. throw new Error(response.error);
  683. }
  684. }
  685. } catch (err) {
  686. showToast(err.message, 'error');
  687. }
  688. });
  689. });
  690. btnFetchEmail.addEventListener('click', async () => {
  691. await fetchDuckEmail().catch(() => {});
  692. });
  693. btnTogglePassword.addEventListener('click', () => {
  694. inputPassword.type = inputPassword.type === 'password' ? 'text' : 'password';
  695. syncPasswordToggleLabel();
  696. });
  697. btnToggleVpsUrl.addEventListener('click', () => {
  698. inputVpsUrl.type = inputVpsUrl.type === 'password' ? 'text' : 'password';
  699. syncVpsUrlToggleLabel();
  700. });
  701. btnSaveSettings.addEventListener('click', async () => {
  702. if (!settingsDirty) {
  703. showToast('配置已是最新', 'info', 1400);
  704. return;
  705. }
  706. await saveSettings({ silent: false }).catch(() => {});
  707. });
  708. btnStop.addEventListener('click', async () => {
  709. btnStop.disabled = true;
  710. await chrome.runtime.sendMessage({ type: 'STOP_FLOW', source: 'sidepanel', payload: {} });
  711. showToast('正在停止当前流程...', 'warn', 2000);
  712. });
  713. autoStartModal?.addEventListener('click', (event) => {
  714. if (event.target === autoStartModal) {
  715. resolveModalChoice(null);
  716. }
  717. });
  718. btnAutoStartClose?.addEventListener('click', () => resolveModalChoice(null));
  719. // Auto Run
  720. btnAutoRun.addEventListener('click', async () => {
  721. try {
  722. const totalRuns = parseInt(inputRunCount.value) || 1;
  723. let mode = 'restart';
  724. if (shouldOfferAutoModeChoice()) {
  725. const startStep = getFirstUnfinishedStep();
  726. const choice = await openAutoStartChoiceDialog(startStep);
  727. if (!choice) {
  728. return;
  729. }
  730. mode = choice;
  731. }
  732. btnAutoRun.disabled = true;
  733. inputRunCount.disabled = true;
  734. 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> 运行中...';
  735. const response = await chrome.runtime.sendMessage({
  736. type: 'AUTO_RUN',
  737. source: 'sidepanel',
  738. payload: {
  739. totalRuns,
  740. autoRunSkipFailures: inputAutoSkipFailures.checked,
  741. mode,
  742. },
  743. });
  744. if (response?.error) {
  745. throw new Error(response.error);
  746. }
  747. } catch (err) {
  748. setDefaultAutoRunButton();
  749. inputRunCount.disabled = false;
  750. showToast(err.message, 'error');
  751. }
  752. });
  753. btnAutoContinue.addEventListener('click', async () => {
  754. const email = inputEmail.value.trim();
  755. if (!email) {
  756. showToast('请先获取或粘贴 DuckDuckGo 邮箱。', 'warn');
  757. return;
  758. }
  759. autoContinueBar.style.display = 'none';
  760. await chrome.runtime.sendMessage({ type: 'RESUME_AUTO_RUN', source: 'sidepanel', payload: { email } });
  761. });
  762. // Reset
  763. btnReset.addEventListener('click', async () => {
  764. const confirmed = await openConfirmModal({
  765. title: '重置流程',
  766. message: '确认重置全部步骤和数据吗?',
  767. confirmLabel: '确认重置',
  768. confirmVariant: 'btn-danger',
  769. });
  770. if (!confirmed) {
  771. return;
  772. }
  773. await chrome.runtime.sendMessage({ type: 'RESET', source: 'sidepanel' });
  774. syncLatestState({ stepStatuses: STEP_DEFAULT_STATUSES });
  775. syncAutoRunState({ autoRunning: false, autoRunPhase: 'idle', autoRunCurrentRun: 0, autoRunTotalRuns: 1, autoRunAttemptRun: 0 });
  776. displayOauthUrl.textContent = '等待中...';
  777. displayOauthUrl.classList.remove('has-value');
  778. displayLocalhostUrl.textContent = '等待中...';
  779. displayLocalhostUrl.classList.remove('has-value');
  780. inputEmail.value = '';
  781. displayStatus.textContent = '就绪';
  782. statusBar.className = 'status-bar';
  783. logArea.innerHTML = '';
  784. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  785. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  786. setDefaultAutoRunButton();
  787. applyAutoRunStatus(currentAutoRun);
  788. markSettingsDirty(false);
  789. updateStopButtonState(false);
  790. updateButtonStates();
  791. updateProgressCounter();
  792. });
  793. // Clear log
  794. btnClearLog.addEventListener('click', () => {
  795. logArea.innerHTML = '';
  796. });
  797. // Save settings on change
  798. inputEmail.addEventListener('change', async () => {
  799. const email = inputEmail.value.trim();
  800. if (email) {
  801. await chrome.runtime.sendMessage({ type: 'SAVE_EMAIL', source: 'sidepanel', payload: { email } });
  802. }
  803. });
  804. inputEmail.addEventListener('input', updateButtonStates);
  805. inputVpsUrl.addEventListener('input', () => {
  806. markSettingsDirty(true);
  807. scheduleSettingsAutoSave();
  808. });
  809. inputVpsUrl.addEventListener('blur', () => {
  810. saveSettings({ silent: true }).catch(() => {});
  811. });
  812. inputVpsPassword.addEventListener('input', () => {
  813. markSettingsDirty(true);
  814. scheduleSettingsAutoSave();
  815. });
  816. inputVpsPassword.addEventListener('blur', () => {
  817. saveSettings({ silent: true }).catch(() => {});
  818. });
  819. inputPassword.addEventListener('input', () => {
  820. markSettingsDirty(true);
  821. updateButtonStates();
  822. scheduleSettingsAutoSave();
  823. });
  824. inputPassword.addEventListener('blur', () => {
  825. saveSettings({ silent: true }).catch(() => {});
  826. });
  827. selectMailProvider.addEventListener('change', () => {
  828. updateMailProviderUI();
  829. markSettingsDirty(true);
  830. saveSettings({ silent: true }).catch(() => {});
  831. });
  832. inputInbucketMailbox.addEventListener('input', () => {
  833. markSettingsDirty(true);
  834. scheduleSettingsAutoSave();
  835. });
  836. inputInbucketMailbox.addEventListener('blur', () => {
  837. saveSettings({ silent: true }).catch(() => {});
  838. });
  839. inputInbucketHost.addEventListener('input', () => {
  840. markSettingsDirty(true);
  841. scheduleSettingsAutoSave();
  842. });
  843. inputInbucketHost.addEventListener('blur', () => {
  844. saveSettings({ silent: true }).catch(() => {});
  845. });
  846. inputAutoSkipFailures.addEventListener('change', () => {
  847. markSettingsDirty(true);
  848. saveSettings({ silent: true }).catch(() => {});
  849. });
  850. // ============================================================
  851. // Listen for Background broadcasts
  852. // ============================================================
  853. chrome.runtime.onMessage.addListener((message) => {
  854. switch (message.type) {
  855. case 'LOG_ENTRY':
  856. appendLog(message.payload);
  857. if (message.payload.level === 'error') {
  858. showToast(message.payload.message, 'error');
  859. }
  860. break;
  861. case 'STEP_STATUS_CHANGED': {
  862. const { step, status } = message.payload;
  863. updateStepUI(step, status);
  864. chrome.runtime.sendMessage({ type: 'GET_STATE', source: 'sidepanel' }).then(state => {
  865. syncLatestState(state);
  866. syncAutoRunState(state);
  867. updateStatusDisplay(latestState);
  868. updateButtonStates();
  869. if (status === 'completed' || status === 'manual_completed' || status === 'skipped') {
  870. syncPasswordField(state);
  871. if (state.oauthUrl) {
  872. displayOauthUrl.textContent = state.oauthUrl;
  873. displayOauthUrl.classList.add('has-value');
  874. }
  875. if (state.localhostUrl) {
  876. displayLocalhostUrl.textContent = state.localhostUrl;
  877. displayLocalhostUrl.classList.add('has-value');
  878. }
  879. }
  880. }
  881. ).catch(() => {});
  882. break;
  883. }
  884. case 'AUTO_RUN_RESET': {
  885. // Full UI reset for next run
  886. syncLatestState({
  887. oauthUrl: null,
  888. localhostUrl: null,
  889. email: null,
  890. password: null,
  891. stepStatuses: STEP_DEFAULT_STATUSES,
  892. logs: [],
  893. });
  894. displayOauthUrl.textContent = '等待中...';
  895. displayOauthUrl.classList.remove('has-value');
  896. displayLocalhostUrl.textContent = '等待中...';
  897. displayLocalhostUrl.classList.remove('has-value');
  898. inputEmail.value = '';
  899. displayStatus.textContent = '就绪';
  900. statusBar.className = 'status-bar';
  901. logArea.innerHTML = '';
  902. document.querySelectorAll('.step-row').forEach(row => row.className = 'step-row');
  903. document.querySelectorAll('.step-status').forEach(el => el.textContent = '');
  904. applyAutoRunStatus(currentAutoRun);
  905. updateProgressCounter();
  906. updateButtonStates();
  907. break;
  908. }
  909. case 'DATA_UPDATED': {
  910. syncLatestState(message.payload);
  911. if (message.payload.email) {
  912. inputEmail.value = message.payload.email;
  913. }
  914. if (message.payload.password !== undefined) {
  915. inputPassword.value = message.payload.password || '';
  916. }
  917. if (message.payload.oauthUrl) {
  918. displayOauthUrl.textContent = message.payload.oauthUrl;
  919. displayOauthUrl.classList.add('has-value');
  920. }
  921. if (message.payload.localhostUrl) {
  922. displayLocalhostUrl.textContent = message.payload.localhostUrl;
  923. displayLocalhostUrl.classList.add('has-value');
  924. }
  925. break;
  926. }
  927. case 'AUTO_RUN_STATUS': {
  928. syncLatestState({
  929. autoRunning: ['running', 'waiting_email', 'retrying'].includes(message.payload.phase),
  930. autoRunPhase: message.payload.phase,
  931. autoRunCurrentRun: message.payload.currentRun,
  932. autoRunTotalRuns: message.payload.totalRuns,
  933. autoRunAttemptRun: message.payload.attemptRun,
  934. });
  935. applyAutoRunStatus(message.payload);
  936. updateStatusDisplay(latestState);
  937. updateButtonStates();
  938. break;
  939. }
  940. }
  941. });
  942. // ============================================================
  943. // Theme Toggle
  944. // ============================================================
  945. const btnTheme = document.getElementById('btn-theme');
  946. function setTheme(theme) {
  947. document.documentElement.setAttribute('data-theme', theme);
  948. localStorage.setItem('multipage-theme', theme);
  949. }
  950. function initTheme() {
  951. const saved = localStorage.getItem('multipage-theme');
  952. if (saved) {
  953. setTheme(saved);
  954. } else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
  955. setTheme('dark');
  956. }
  957. }
  958. btnTheme.addEventListener('click', () => {
  959. const current = document.documentElement.getAttribute('data-theme');
  960. setTheme(current === 'dark' ? 'light' : 'dark');
  961. });
  962. // ============================================================
  963. // Init
  964. // ============================================================
  965. initializeManualStepActions();
  966. initTheme();
  967. updateSaveButtonState();
  968. restoreState().then(() => {
  969. syncPasswordToggleLabel();
  970. syncVpsUrlToggleLabel();
  971. updateButtonStates();
  972. updateStatusDisplay(latestState);
  973. });