sidepanel.js 39 KB

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