sidepanel.js 36 KB

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