sidepanel.js 35 KB

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