env-plugin 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/Container.js +20 -1
  2. package/dist/PostProxyServer.js +37 -12
  3. package/dist/client/assets/element-plus-BN_JcO6B.js +19 -0
  4. package/dist/client/assets/element-plus-SrDBYmqw.css +1 -0
  5. package/dist/client/assets/index-CcOgzo-G.js +1 -0
  6. package/dist/client/assets/index-DcxBCPsx.css +1 -0
  7. package/dist/client/index.html +4 -4
  8. package/dist/controllers/DevServerController.js +10 -2
  9. package/dist/controllers/EnvController.js +43 -3
  10. package/dist/controllers/ImportExportController.js +44 -0
  11. package/dist/controllers/PasswordController.js +1 -0
  12. package/dist/controllers/RequestLogController.js +34 -0
  13. package/dist/controllers/RouteRuleController.js +1 -0
  14. package/dist/controllers/SystemSettingController.js +43 -0
  15. package/dist/index.js +13 -11
  16. package/dist/models/EnvModel.js +31 -3
  17. package/dist/repositories/DevServerRepo.js +14 -69
  18. package/dist/repositories/EnvRepo.js +30 -95
  19. package/dist/repositories/PasswordRepo.js +44 -106
  20. package/dist/repositories/RouteRuleRepo.js +26 -79
  21. package/dist/repositories/SystemSettingRepo.js +21 -0
  22. package/dist/repositories/database.js +11 -84
  23. package/dist/repositories/migrate.js +198 -0
  24. package/dist/repositories/store.js +118 -0
  25. package/dist/routes/index.js +197 -29
  26. package/dist/service/DevServerService.js +4 -2
  27. package/dist/service/EnvService.js +67 -7
  28. package/dist/service/ImportExportService.js +337 -0
  29. package/dist/service/PasswordService.js +11 -9
  30. package/dist/service/PreProxyServer.js +158 -36
  31. package/dist/service/ProxyAutoStarterService.js +3 -0
  32. package/dist/service/RequestLogService.js +77 -0
  33. package/dist/service/RouteRuleService.js +18 -16
  34. package/dist/service/SystemSettingService.js +90 -0
  35. package/dist/types/index.js +3 -0
  36. package/dist/types/shared/EnvItem.js +8 -0
  37. package/dist/types/shared/ImportExport.js +55 -0
  38. package/dist/types/shared/RequestLog.js +28 -0
  39. package/dist/types/shared/SystemSetting.js +18 -0
  40. package/dist/utils/ResolveConfig.js +4 -2
  41. package/dist/utils/asyncHandler.js +12 -0
  42. package/dist/utils/errors.js +2 -0
  43. package/dist/utils/resourceType.js +42 -0
  44. package/dist/utils/routeBuilder.js +19 -0
  45. package/package.json +36 -29
  46. package/templates/inject/envm-switcher.js +1418 -0
  47. package/dist/client/assets/element-plus-4FTV-s7u.js.gz +0 -0
  48. package/dist/client/assets/index-C2AH0x8U.css.gz +0 -0
  49. package/dist/client/assets/index-Db97pusF.js.gz +0 -0
  50. package/dist/client/assets/vue-CRjr1oeH.js.gz +0 -0
@@ -0,0 +1,1418 @@
1
+ /* global fetch, document, window, console, setTimeout, setInterval, clearInterval, URL */
2
+ /**
3
+ * EnvManage 环境快速切换面板
4
+ *
5
+ * 通过 HTML 注入机制加载到被代理页面中,在右下角显示悬浮球,
6
+ * 点击可展开环境列表,支持一键切换环境。
7
+ *
8
+ * 特性:
9
+ * - Shadow DOM 样式隔离,不干扰宿主页面
10
+ * - 纯原生 JS ESM,无框架依赖
11
+ * - 自动检测当前环境并高亮显示
12
+ * - 支持切换/启动/停止操作
13
+ * - 切换后自动重定向到新环境
14
+ */
15
+
16
+ const API_PREFIX = "/dev-manage-api";
17
+
18
+ // ==================== 悬浮球拖拽 / 贴边收起常量 ====================
19
+ const BALL_SIZE = 48; // 悬浮球尺寸(与 CSS 保持一致)
20
+ const EDGE_MARGIN = 24; // 默认距窗口边缘距离
21
+ const DOCK_THRESHOLD = 40; // 距边缘小于该值(px)时吸附到边缘
22
+ const HOVER_THRESHOLD = 48; // 收起后鼠标靠近提示线多少像素内触发展开
23
+ const HOVER_PADDING = 12; // 判断鼠标是否已离开悬浮球的余量
24
+ const POSITION_KEY = "envm-switcher-position"; // localStorage 存储键
25
+
26
+ // ==================== 工具函数 ====================
27
+
28
+ /**
29
+ * 通用 fetch 封装,处理两种响应格式:
30
+ * 1. 标准包裹格式 { code, message, data, timestamp }
31
+ * 2. 原始格式(如 inject/getcurrentenv 返回的 { envId })
32
+ */
33
+ async function apiFetch(url, options = {}) {
34
+ const res = await fetch(url, {
35
+ headers: { "Content-Type": "application/json" },
36
+ ...options,
37
+ });
38
+ if (!res.ok) {
39
+ throw new Error(`HTTP ${res.status}: ${res.statusText}`);
40
+ }
41
+ const json = await res.json();
42
+
43
+ // 如果响应有 code 字段,解包 data
44
+ if (json && typeof json.code === "number") {
45
+ if (json.code !== 200) {
46
+ throw new Error(json.message || "请求失败");
47
+ }
48
+ return json.data;
49
+ }
50
+ // 否则直接返回原始 json
51
+ return json;
52
+ }
53
+
54
+ // ==================== 主类 ====================
55
+
56
+ class EnvmSwitcher {
57
+ constructor() {
58
+ this.envList = [];
59
+ this.devServerList = [];
60
+ this.currentEnvId = null;
61
+ this.isPanelOpen = false;
62
+ this.isSwitching = false;
63
+ this.pollTimer = null;
64
+
65
+ // 悬浮球位置与收起状态
66
+ this.pos = { left: 0, top: 0 };
67
+ this.dockedEdge = null; // null | 'left' | 'right' | 'top' | 'bottom'
68
+ this.isCollapsed = false;
69
+ this.dragState = null;
70
+ this.dragMoved = false;
71
+
72
+ // 创建 Shadow DOM 容器
73
+ this.host = document.createElement("div");
74
+ this.host.id = "__envm_switcher_host";
75
+ this.shadow = this.host.attachShadow({ mode: "open" });
76
+
77
+ // 注入样式
78
+ const style = document.createElement("style");
79
+ style.textContent = this._getStyles();
80
+ this.shadow.appendChild(style);
81
+
82
+ // 创建 UI 结构
83
+ this._render();
84
+
85
+ // 恢复并应用悬浮球位置(在挂载前设置,避免闪烁)
86
+ this._restorePosition();
87
+
88
+ document.body.appendChild(this.host);
89
+
90
+ // 初始化
91
+ this._init();
92
+ }
93
+
94
+ // ==================== CSS 样式 ====================
95
+
96
+ _getStyles() {
97
+ return /* css */ `
98
+ :host {
99
+ --envm-bg: #ffffff;
100
+ --envm-text: #333333;
101
+ --envm-text-secondary: #666666;
102
+ --envm-border: #e4e7ed;
103
+ --envm-accent: #409eff;
104
+ --envm-accent-light: #ecf5ff;
105
+ --envm-running: #67c23a;
106
+ --envm-running-bg: #f0f9eb;
107
+ --envm-stopped: #f56c6c;
108
+ --envm-stopped-bg: #fef0f0;
109
+ --envm-warning: #e6a23c;
110
+ --envm-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
111
+ --envm-shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.08);
112
+ --envm-radius: 12px;
113
+ --envm-radius-sm: 8px;
114
+ --envm-font: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
115
+ --envm-font-size: 13px;
116
+ --envm-font-size-sm: 12px;
117
+ --envm-transition: 0.25s cubic-bezier(0.4, 0, 0.2, 1);
118
+
119
+ all: initial;
120
+ position: fixed;
121
+ top: 0;
122
+ left: 0;
123
+ z-index: 99999;
124
+ font-family: var(--envm-font);
125
+ font-size: var(--envm-font-size);
126
+ color: var(--envm-text);
127
+ line-height: 1.5;
128
+ box-sizing: border-box;
129
+ }
130
+
131
+ *,
132
+ *::before,
133
+ *::after {
134
+ box-sizing: border-box;
135
+ }
136
+
137
+ @media (prefers-color-scheme: dark) {
138
+ :host {
139
+ --envm-bg: #1e1e1e;
140
+ --envm-text: #e0e0e0;
141
+ --envm-text-secondary: #a0a0a0;
142
+ --envm-border: #404040;
143
+ --envm-accent-light: #1a3a5c;
144
+ --envm-running-bg: #1a3a1a;
145
+ --envm-stopped-bg: #3a1a1a;
146
+ --envm-shadow: 0 4px 16px rgba(0, 0, 0, 0.4);
147
+ --envm-shadow-sm: 0 2px 8px rgba(0, 0, 0, 0.3);
148
+ }
149
+ }
150
+
151
+ /* ========== 悬浮球 ========== */
152
+ .ball {
153
+ width: 48px;
154
+ height: 48px;
155
+ border-radius: 50%;
156
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
157
+ border: none;
158
+ box-shadow: 0 4px 20px rgba(102, 126, 234, 0.35);
159
+ cursor: grab;
160
+ touch-action: none;
161
+ display: flex;
162
+ align-items: center;
163
+ justify-content: center;
164
+ flex-direction: column;
165
+ transition: transform var(--envm-transition), box-shadow var(--envm-transition), opacity var(--envm-transition);
166
+ user-select: none;
167
+ position: relative;
168
+ overflow: visible;
169
+ }
170
+
171
+ .ball::after {
172
+ content: "";
173
+ position: absolute;
174
+ inset: -4px;
175
+ border-radius: 50%;
176
+ border: 3px solid transparent;
177
+ transition: border-color var(--envm-transition);
178
+ }
179
+
180
+ .ball.running::after {
181
+ border-color: rgba(103, 194, 58, 0.7);
182
+ box-shadow: 0 0 12px rgba(103, 194, 58, 0.4), inset 0 0 12px rgba(103, 194, 58, 0.15);
183
+ }
184
+
185
+ .ball.stopped::after {
186
+ border-color: rgba(245, 108, 108, 0.7);
187
+ box-shadow: 0 0 12px rgba(245, 108, 108, 0.4), inset 0 0 12px rgba(245, 108, 108, 0.15);
188
+ }
189
+
190
+ .ball.loading::after {
191
+ border-color: rgba(230, 162, 60, 0.7);
192
+ box-shadow: 0 0 12px rgba(230, 162, 60, 0.4), inset 0 0 12px rgba(230, 162, 60, 0.15);
193
+ animation: ringPulse 1.2s ease-in-out infinite;
194
+ }
195
+
196
+ .ball:hover {
197
+ transform: scale(1.1);
198
+ box-shadow: 0 6px 28px rgba(102, 126, 234, 0.5);
199
+ }
200
+
201
+ .ball:active {
202
+ transform: scale(0.94);
203
+ cursor: grabbing;
204
+ }
205
+
206
+ .ball.collapsed {
207
+ transform: scale(0.3);
208
+ opacity: 0;
209
+ pointer-events: none;
210
+ }
211
+
212
+ .ball-label {
213
+ font-size: 12px;
214
+ font-weight: 800;
215
+ color: #ffffff;
216
+ line-height: 1;
217
+ letter-spacing: -0.5px;
218
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
219
+ position: relative;
220
+ z-index: 1;
221
+ }
222
+
223
+ .ball-dot {
224
+ position: absolute;
225
+ top: 2px;
226
+ right: 2px;
227
+ width: 12px;
228
+ height: 12px;
229
+ border-radius: 50%;
230
+ border: 2px solid rgba(255, 255, 255, 0.9);
231
+ z-index: 2;
232
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25);
233
+ }
234
+
235
+ .ball-dot.running {
236
+ background: #67c23a;
237
+ }
238
+
239
+ .ball-dot.stopped {
240
+ background: #f56c6c;
241
+ }
242
+
243
+ .ball-dot.loading {
244
+ background: #e6a23c;
245
+ animation: pulse 1s ease-in-out infinite;
246
+ }
247
+
248
+ @keyframes pulse {
249
+ 0%, 100% { opacity: 1; transform: scale(1); }
250
+ 50% { opacity: 0.5; transform: scale(0.75); }
251
+ }
252
+
253
+ @keyframes ringPulse {
254
+ 0%, 100% { transform: scale(1); opacity: 1; }
255
+ 50% { transform: scale(1.1); opacity: 0.5; }
256
+ }
257
+
258
+ /* ========== 边缘收起提示线 ========== */
259
+ .edge-hint {
260
+ position: absolute;
261
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
262
+ border-radius: 2px;
263
+ opacity: 0;
264
+ pointer-events: none;
265
+ transition: opacity var(--envm-transition);
266
+ box-shadow: 0 0 10px rgba(102, 126, 234, 0.6);
267
+ }
268
+
269
+ .edge-hint.visible {
270
+ opacity: 1;
271
+ }
272
+
273
+ /* ========== 面板 ========== */
274
+ .panel {
275
+ position: absolute;
276
+ bottom: 60px;
277
+ right: 0;
278
+ width: 280px;
279
+ max-height: 420px;
280
+ background: var(--envm-bg);
281
+ border-radius: var(--envm-radius);
282
+ box-shadow: var(--envm-shadow);
283
+ display: flex;
284
+ flex-direction: column;
285
+ overflow: hidden;
286
+ transition: opacity var(--envm-transition), transform var(--envm-transition);
287
+ border: 1px solid var(--envm-border);
288
+ }
289
+
290
+ /* 面板开口方向:根据悬浮球在视口中的位置动态调整,避免超出视口 */
291
+ :host([data-panel-v="down"]) .panel {
292
+ top: 60px;
293
+ bottom: auto;
294
+ }
295
+
296
+ :host([data-panel-v="up"]) .panel {
297
+ bottom: 60px;
298
+ top: auto;
299
+ }
300
+
301
+ :host([data-panel-h="left"]) .panel {
302
+ left: 0;
303
+ right: auto;
304
+ }
305
+
306
+ :host([data-panel-h="right"]) .panel {
307
+ right: 0;
308
+ left: auto;
309
+ }
310
+
311
+ .panel.hidden {
312
+ opacity: 0;
313
+ transform: translateY(8px) scale(0.96);
314
+ pointer-events: none;
315
+ }
316
+
317
+ /* ========== 面板头部 ========== */
318
+ .panel-header {
319
+ padding: 14px 16px 12px;
320
+ display: flex;
321
+ align-items: center;
322
+ justify-content: space-between;
323
+ border-bottom: 1px solid var(--envm-border);
324
+ flex-shrink: 0;
325
+ }
326
+
327
+ .panel-title {
328
+ font-size: 15px;
329
+ font-weight: 600;
330
+ color: var(--envm-text);
331
+ }
332
+
333
+ .panel-actions {
334
+ display: flex;
335
+ gap: 4px;
336
+ }
337
+
338
+ .icon-btn {
339
+ width: 28px;
340
+ height: 28px;
341
+ border: none;
342
+ background: transparent;
343
+ color: var(--envm-text-secondary);
344
+ cursor: pointer;
345
+ border-radius: 6px;
346
+ display: flex;
347
+ align-items: center;
348
+ justify-content: center;
349
+ font-size: 16px;
350
+ transition: background 0.15s, color 0.15s;
351
+ padding: 0;
352
+ }
353
+
354
+ .icon-btn:hover {
355
+ background: var(--envm-border);
356
+ color: var(--envm-text);
357
+ }
358
+
359
+ .icon-btn svg {
360
+ width: 16px;
361
+ height: 16px;
362
+ }
363
+
364
+ /* ========== 当前环境信息条 ========== */
365
+ .current-env-bar {
366
+ padding: 10px 16px;
367
+ background: var(--envm-accent-light);
368
+ border-bottom: 1px solid var(--envm-border);
369
+ flex-shrink: 0;
370
+ }
371
+
372
+ .current-env-name {
373
+ font-weight: 600;
374
+ color: var(--envm-accent);
375
+ font-size: var(--envm-font-size);
376
+ margin-bottom: 2px;
377
+ }
378
+
379
+ .current-env-detail {
380
+ font-size: var(--envm-font-size-sm);
381
+ color: var(--envm-text-secondary);
382
+ }
383
+
384
+ /* ========== 环境列表 ========== */
385
+ .panel-list {
386
+ flex: 1;
387
+ overflow-y: auto;
388
+ padding: 6px 0;
389
+ }
390
+
391
+ .panel-list::-webkit-scrollbar {
392
+ width: 4px;
393
+ }
394
+
395
+ .panel-list::-webkit-scrollbar-thumb {
396
+ background: var(--envm-border);
397
+ border-radius: 2px;
398
+ }
399
+
400
+ .env-item {
401
+ padding: 10px 16px;
402
+ display: flex;
403
+ align-items: center;
404
+ gap: 10px;
405
+ cursor: pointer;
406
+ transition: background 0.15s;
407
+ border-left: 3px solid transparent;
408
+ }
409
+
410
+ .env-item:hover {
411
+ background: var(--envm-accent-light);
412
+ }
413
+
414
+ .env-item.current {
415
+ border-left-color: var(--envm-accent);
416
+ background: var(--envm-accent-light);
417
+ }
418
+
419
+ .env-item.switching {
420
+ pointer-events: none;
421
+ opacity: 0.6;
422
+ }
423
+
424
+ .item-status-dot {
425
+ width: 8px;
426
+ height: 8px;
427
+ border-radius: 50%;
428
+ flex-shrink: 0;
429
+ }
430
+
431
+ .item-status-dot.running {
432
+ background: var(--envm-running);
433
+ box-shadow: 0 0 6px rgba(103, 194, 58, 0.5);
434
+ }
435
+
436
+ .item-status-dot.stopped {
437
+ background: var(--envm-stopped);
438
+ }
439
+
440
+ .item-info {
441
+ flex: 1;
442
+ min-width: 0;
443
+ }
444
+
445
+ .item-name {
446
+ font-weight: 500;
447
+ font-size: var(--envm-font-size);
448
+ color: var(--envm-text);
449
+ white-space: nowrap;
450
+ overflow: hidden;
451
+ text-overflow: ellipsis;
452
+ }
453
+
454
+ .item-url {
455
+ font-size: var(--envm-font-size-sm);
456
+ color: var(--envm-text-secondary);
457
+ white-space: nowrap;
458
+ overflow: hidden;
459
+ text-overflow: ellipsis;
460
+ }
461
+
462
+ .item-port {
463
+ font-size: var(--envm-font-size-sm);
464
+ color: var(--envm-text-secondary);
465
+ flex-shrink: 0;
466
+ font-variant-numeric: tabular-nums;
467
+ }
468
+
469
+ .item-action {
470
+ flex-shrink: 0;
471
+ font-size: var(--envm-font-size-sm);
472
+ padding: 3px 10px;
473
+ border-radius: 4px;
474
+ border: 1px solid var(--envm-accent);
475
+ background: transparent;
476
+ color: var(--envm-accent);
477
+ cursor: pointer;
478
+ font-family: var(--envm-font);
479
+ transition: all 0.15s;
480
+ white-space: nowrap;
481
+ }
482
+
483
+ .item-action:hover {
484
+ background: var(--envm-accent);
485
+ color: #fff;
486
+ }
487
+
488
+ .item-action.stop {
489
+ border-color: var(--envm-stopped);
490
+ color: var(--envm-stopped);
491
+ }
492
+
493
+ .item-action.stop:hover {
494
+ background: var(--envm-stopped);
495
+ color: #fff;
496
+ }
497
+
498
+ /* ========== 代理目标子项(DevServer 切换) ========== */
499
+ .proxy-target-item {
500
+ padding: 7px 16px 7px 36px;
501
+ display: flex;
502
+ align-items: center;
503
+ gap: 10px;
504
+ cursor: default;
505
+ transition: background 0.15s;
506
+ border-left: 3px solid transparent;
507
+ font-size: var(--envm-font-size-sm);
508
+ background: var(--envm-bg);
509
+ }
510
+
511
+ .proxy-target-item:hover {
512
+ background: var(--envm-accent-light);
513
+ }
514
+
515
+ .proxy-target-item.current {
516
+ border-left-color: var(--envm-accent);
517
+ background: var(--envm-accent-light);
518
+ }
519
+
520
+ .proxy-target-item.switching {
521
+ pointer-events: none;
522
+ opacity: 0.6;
523
+ }
524
+
525
+ .proxy-target-indent {
526
+ width: 0;
527
+ flex-shrink: 0;
528
+ }
529
+
530
+ .proxy-target-active {
531
+ flex-shrink: 0;
532
+ color: var(--envm-accent);
533
+ font-size: 10px;
534
+ font-weight: 700;
535
+ }
536
+
537
+ .proxy-target-btn {
538
+ flex-shrink: 0;
539
+ font-size: 11px;
540
+ padding: 2px 8px;
541
+ border-radius: 4px;
542
+ border: 1px solid var(--envm-accent);
543
+ background: transparent;
544
+ color: var(--envm-accent);
545
+ cursor: pointer;
546
+ font-family: var(--envm-font);
547
+ transition: all 0.15s;
548
+ white-space: nowrap;
549
+ }
550
+
551
+ .proxy-target-btn:hover {
552
+ background: var(--envm-accent);
553
+ color: #fff;
554
+ }
555
+
556
+ /* ========== 空状态 ========== */
557
+ .panel-empty {
558
+ padding: 32px 16px;
559
+ text-align: center;
560
+ color: var(--envm-text-secondary);
561
+ font-size: var(--envm-font-size);
562
+ }
563
+
564
+ /* ========== 错误提示 ========== */
565
+ .toast {
566
+ position: absolute;
567
+ bottom: 64px;
568
+ right: 0;
569
+ background: var(--envm-stopped);
570
+ color: #fff;
571
+ padding: 8px 14px;
572
+ border-radius: var(--envm-radius-sm);
573
+ font-size: var(--envm-font-size-sm);
574
+ box-shadow: var(--envm-shadow-sm);
575
+ animation: slideIn 0.3s ease-out;
576
+ max-width: 280px;
577
+ }
578
+
579
+ /* 提示条跟随悬浮球方向对齐,避免贴顶 / 贴左时超出视口 */
580
+ :host([data-panel-v="down"]) .toast {
581
+ top: 64px;
582
+ bottom: auto;
583
+ }
584
+
585
+ :host([data-panel-v="up"]) .toast {
586
+ bottom: 64px;
587
+ top: auto;
588
+ }
589
+
590
+ :host([data-panel-h="left"]) .toast {
591
+ left: 0;
592
+ right: auto;
593
+ }
594
+
595
+ :host([data-panel-h="right"]) .toast {
596
+ right: 0;
597
+ left: auto;
598
+ }
599
+
600
+ @keyframes slideIn {
601
+ from { opacity: 0; transform: translateY(6px); }
602
+ to { opacity: 1; transform: translateY(0); }
603
+ }
604
+ `;
605
+ }
606
+
607
+ // ==================== 渲染 DOM ====================
608
+
609
+ _render() {
610
+ this.shadow.innerHTML += /* html */ `
611
+ <div id="ball" class="ball stopped" title="环境切换">
612
+ <span id="ballLabel" class="ball-label">...</span>
613
+ <span id="ballDot" class="ball-dot stopped"></span>
614
+ </div>
615
+ <div id="edgeHint" class="edge-hint"></div>
616
+ <div id="panel" class="panel hidden">
617
+ <div class="panel-header">
618
+ <span class="panel-title">环境切换</span>
619
+ <div class="panel-actions">
620
+ <button id="refreshBtn" class="icon-btn" title="刷新列表">
621
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
622
+ <polyline points="23 4 23 10 17 10"></polyline>
623
+ <path d="M20.49 15a9 9 0 1 1-2.12-9.36L23 10"></path>
624
+ </svg>
625
+ </button>
626
+ <button id="dashboardBtn" class="icon-btn" title="打开管理页面">
627
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
628
+ <rect x="3" y="3" width="7" height="7"></rect>
629
+ <rect x="14" y="3" width="7" height="7"></rect>
630
+ <rect x="14" y="14" width="7" height="7"></rect>
631
+ <rect x="3" y="14" width="7" height="7"></rect>
632
+ </svg>
633
+ </button>
634
+ <button id="closeBtn" class="icon-btn" title="关闭">
635
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
636
+ <line x1="18" y1="6" x2="6" y2="18"></line>
637
+ <line x1="6" y1="6" x2="18" y2="18"></line>
638
+ </svg>
639
+ </button>
640
+ </div>
641
+ </div>
642
+ <div id="currentEnvBar" class="current-env-bar" style="display:none;">
643
+ <div id="currentEnvName" class="current-env-name"></div>
644
+ <div id="currentEnvDetail" class="current-env-detail"></div>
645
+ </div>
646
+ <div id="envList" class="panel-list"></div>
647
+ <div id="emptyState" class="panel-empty" style="display:none;">暂无可用环境</div>
648
+ </div>
649
+ `;
650
+ }
651
+
652
+ // ==================== DOM 引用缓存 ====================
653
+
654
+ _$(id) {
655
+ return this.shadow.getElementById(id);
656
+ }
657
+
658
+ // ==================== 初始化 ====================
659
+
660
+ async _init() {
661
+ // 绑定事件
662
+ this._$("ball").addEventListener("click", () => {
663
+ // 拖拽移动后不触发点击展开面板
664
+ if (this.dragMoved) return;
665
+ this._togglePanel();
666
+ });
667
+ this._$("closeBtn").addEventListener("click", (e) => {
668
+ e.stopPropagation();
669
+ this._closePanel();
670
+ });
671
+ this._$("refreshBtn").addEventListener("click", (e) => {
672
+ e.stopPropagation();
673
+ this._refresh();
674
+ });
675
+ this._$("dashboardBtn").addEventListener("click", (e) => {
676
+ e.stopPropagation();
677
+ this._openDashboard();
678
+ });
679
+
680
+ // 点击面板外部关闭
681
+ document.addEventListener("click", (e) => {
682
+ if (this.isPanelOpen && !this.host.contains(e.target)) {
683
+ this._closePanel();
684
+ }
685
+ });
686
+
687
+ // ESC 关闭面板
688
+ document.addEventListener("keydown", (e) => {
689
+ if (e.key === "Escape" && this.isPanelOpen) {
690
+ this._closePanel();
691
+ }
692
+ });
693
+
694
+ // 悬浮球拖拽
695
+ this._initDrag();
696
+
697
+ // 窗口尺寸变化时重新校正位置
698
+ window.addEventListener("resize", () => this._onResize());
699
+
700
+ // 全局鼠标移动:驱动边缘收起 / 展开
701
+ document.addEventListener("mousemove", (e) => this._onGlobalMouseMove(e));
702
+
703
+ // 初始化面板开口方向
704
+ this._updatePanelOrientation();
705
+
706
+ // 初始加载时若悬浮球贴边,默认收起(否则需等首次 mousemove 才收起)
707
+ this._collapse();
708
+
709
+ // 加载数据
710
+ await Promise.all([this._fetchCurrentEnv(), this._fetchEnvList()]);
711
+ this._updateUI();
712
+
713
+ // 开始定时轮询(每 5 秒刷新环境列表)
714
+ this._startPolling();
715
+ }
716
+
717
+ // ==================== 悬浮球拖拽与边缘收起 ====================
718
+
719
+ /**
720
+ * 视口内容区宽度(不含滚动条,避免贴边元素遮罩滚动条)
721
+ */
722
+ _viewportWidth() {
723
+ return document.documentElement.clientWidth || window.innerWidth;
724
+ }
725
+
726
+ /**
727
+ * 视口内容区高度(不含滚动条)
728
+ */
729
+ _viewportHeight() {
730
+ return document.documentElement.clientHeight || window.innerHeight;
731
+ }
732
+
733
+ /**
734
+ * 恢复上次保存的悬浮球位置(localStorage),并检测是否贴边
735
+ */
736
+ _restorePosition() {
737
+ const w = this._viewportWidth();
738
+ const h = this._viewportHeight();
739
+
740
+ // 默认:右下角
741
+ this.pos.left = w - BALL_SIZE - EDGE_MARGIN;
742
+ this.pos.top = h - BALL_SIZE - EDGE_MARGIN;
743
+
744
+ try {
745
+ const raw = window.localStorage.getItem(POSITION_KEY);
746
+ if (raw) {
747
+ const saved = JSON.parse(raw);
748
+ if (
749
+ saved &&
750
+ typeof saved.left === "number" &&
751
+ typeof saved.top === "number"
752
+ ) {
753
+ this.pos.left = saved.left;
754
+ this.pos.top = saved.top;
755
+ }
756
+ }
757
+ } catch {
758
+ // localStorage 不可用或数据损坏时使用默认位置
759
+ }
760
+
761
+ this._clampPosition();
762
+ this.dockedEdge = this._detectEdge();
763
+ if (this.dockedEdge) {
764
+ this._snapToEdge(this.dockedEdge);
765
+ }
766
+ this._applyPosition();
767
+ }
768
+
769
+ /**
770
+ * 将位置限制在视口内
771
+ */
772
+ _clampPosition() {
773
+ const w = this._viewportWidth();
774
+ const h = this._viewportHeight();
775
+ this.pos.left = Math.min(Math.max(0, this.pos.left), w - BALL_SIZE);
776
+ this.pos.top = Math.min(Math.max(0, this.pos.top), h - BALL_SIZE);
777
+ }
778
+
779
+ /**
780
+ * 应用位置到宿主元素
781
+ */
782
+ _applyPosition() {
783
+ this.host.style.left = `${this.pos.left}px`;
784
+ this.host.style.top = `${this.pos.top}px`;
785
+ }
786
+
787
+ /**
788
+ * 保存位置到 localStorage
789
+ */
790
+ _savePosition() {
791
+ try {
792
+ window.localStorage.setItem(
793
+ POSITION_KEY,
794
+ JSON.stringify({ left: this.pos.left, top: this.pos.top })
795
+ );
796
+ } catch {
797
+ // 忽略存储失败
798
+ }
799
+ }
800
+
801
+ /**
802
+ * 检测悬浮球是否贴边,返回最近的边缘,否则返回 null
803
+ */
804
+ _detectEdge() {
805
+ const w = this._viewportWidth();
806
+ const h = this._viewportHeight();
807
+ const distLeft = this.pos.left;
808
+ const distRight = w - (this.pos.left + BALL_SIZE);
809
+ const distTop = this.pos.top;
810
+ const distBottom = h - (this.pos.top + BALL_SIZE);
811
+ const min = Math.min(distLeft, distRight, distTop, distBottom);
812
+
813
+ if (min > DOCK_THRESHOLD) return null;
814
+ if (min === distLeft) return "left";
815
+ if (min === distRight) return "right";
816
+ if (min === distTop) return "top";
817
+ return "bottom";
818
+ }
819
+
820
+ /**
821
+ * 将悬浮球吸附到指定边缘(与边缘齐平)
822
+ */
823
+ _snapToEdge(edge) {
824
+ const w = this._viewportWidth();
825
+ const h = this._viewportHeight();
826
+ if (edge === "left") this.pos.left = 0;
827
+ else if (edge === "right") this.pos.left = w - BALL_SIZE;
828
+ else if (edge === "top") this.pos.top = 0;
829
+ else if (edge === "bottom") this.pos.top = h - BALL_SIZE;
830
+ this._applyPosition();
831
+ }
832
+
833
+ /**
834
+ * 更新面板开口方向(上/下、左/右),保证面板不超出视口
835
+ */
836
+ _updatePanelOrientation() {
837
+ const cx = this.pos.left + BALL_SIZE / 2;
838
+ const cy = this.pos.top + BALL_SIZE / 2;
839
+ this.host.dataset.panelV = cy > this._viewportHeight() / 2 ? "up" : "down";
840
+ this.host.dataset.panelH = cx > this._viewportWidth() / 2 ? "right" : "left";
841
+ }
842
+
843
+ // ==================== 拖拽 ====================
844
+
845
+ _initDrag() {
846
+ const ball = this._$("ball");
847
+ ball.addEventListener("pointerdown", (e) => this._onDragStart(e));
848
+ ball.addEventListener("pointermove", (e) => this._onDragMove(e));
849
+ ball.addEventListener("pointerup", (e) => this._onDragEnd(e));
850
+ ball.addEventListener("pointercancel", (e) => this._onDragEnd(e));
851
+ }
852
+
853
+ _onDragStart(e) {
854
+ // 仅响应主键(鼠标左键 / 触摸)
855
+ if (e.button !== undefined && e.button !== 0) return;
856
+
857
+ // 收起状态下被拖拽,先展开
858
+ if (this.isCollapsed) this._expand();
859
+
860
+ this.dragState = {
861
+ pointerId: e.pointerId,
862
+ startX: e.clientX,
863
+ startY: e.clientY,
864
+ origLeft: this.pos.left,
865
+ origTop: this.pos.top,
866
+ moved: false,
867
+ };
868
+ this.dragMoved = false;
869
+
870
+ try {
871
+ this._$("ball").setPointerCapture(e.pointerId);
872
+ } catch {
873
+ // 某些环境下 setPointerCapture 可能不可用
874
+ }
875
+ }
876
+
877
+ _onDragMove(e) {
878
+ if (!this.dragState) return;
879
+
880
+ const dx = e.clientX - this.dragState.startX;
881
+ const dy = e.clientY - this.dragState.startY;
882
+
883
+ // 小于阈值视为点击,不触发拖拽
884
+ if (!this.dragState.moved && Math.hypot(dx, dy) < 4) return;
885
+
886
+ this.dragState.moved = true;
887
+ this.dragMoved = true;
888
+
889
+ this.pos.left = this.dragState.origLeft + dx;
890
+ this.pos.top = this.dragState.origTop + dy;
891
+ this._applyPosition();
892
+ }
893
+
894
+ _onDragEnd() {
895
+ if (!this.dragState) return;
896
+ const wasMoved = this.dragState.moved;
897
+ this.dragState = null;
898
+
899
+ if (wasMoved) {
900
+ this._clampPosition();
901
+ this.dockedEdge = this._detectEdge();
902
+ if (this.dockedEdge) {
903
+ this._snapToEdge(this.dockedEdge);
904
+ }
905
+ this._applyPosition();
906
+ this._savePosition();
907
+ this._updatePanelOrientation();
908
+ }
909
+
910
+ // 延迟清除拖拽标记,确保随后的 click 事件能读取到
911
+ setTimeout(() => {
912
+ this.dragMoved = false;
913
+ }, 0);
914
+ }
915
+
916
+ // ==================== 边缘收起 / 展开 ====================
917
+
918
+ _collapse() {
919
+ if (this.isCollapsed || !this.dockedEdge) return;
920
+ if (this.isPanelOpen) this._closePanel();
921
+ this.isCollapsed = true;
922
+ this._$("ball").classList.add("collapsed");
923
+ this._updateEdgeHint();
924
+ this._$("edgeHint").classList.add("visible");
925
+ // 收起后释放宿主指针事件,避免遮挡页面内容
926
+ this.host.style.pointerEvents = "none";
927
+ }
928
+
929
+ _expand() {
930
+ if (!this.isCollapsed) return;
931
+ this.isCollapsed = false;
932
+ this._$("ball").classList.remove("collapsed");
933
+ this._$("edgeHint").classList.remove("visible");
934
+ this.host.style.pointerEvents = "";
935
+ }
936
+
937
+ /**
938
+ * 更新边缘提示线的位置与朝向
939
+ */
940
+ _updateEdgeHint() {
941
+ if (!this.dockedEdge) return;
942
+ const hint = this._$("edgeHint");
943
+ if (!hint) return;
944
+
945
+ const THICK = 4; // 提示线粗细
946
+ const LEN = 40; // 提示线长度
947
+ const cx = BALL_SIZE / 2; // 悬浮球中心(相对宿主)
948
+ const cy = BALL_SIZE / 2;
949
+
950
+ hint.style.top = "";
951
+ hint.style.right = "";
952
+ hint.style.bottom = "";
953
+ hint.style.left = "";
954
+
955
+ if (this.dockedEdge === "left" || this.dockedEdge === "right") {
956
+ hint.style.width = `${THICK}px`;
957
+ hint.style.height = `${LEN}px`;
958
+ hint.style.top = `${cy - LEN / 2}px`;
959
+ if (this.dockedEdge === "left") hint.style.left = "0";
960
+ else hint.style.right = "0";
961
+ } else {
962
+ hint.style.width = `${LEN}px`;
963
+ hint.style.height = `${THICK}px`;
964
+ hint.style.left = `${cx - LEN / 2}px`;
965
+ if (this.dockedEdge === "top") hint.style.top = "0";
966
+ else hint.style.bottom = "0";
967
+ }
968
+ }
969
+
970
+ /**
971
+ * 判断坐标是否靠近提示线(用于收起后触发展开)
972
+ */
973
+ _isNearHint(x, y) {
974
+ const cx = this.pos.left + BALL_SIZE / 2;
975
+ const cy = this.pos.top + BALL_SIZE / 2;
976
+ const HALF = 20; // 提示线半长
977
+ const PAD = 16;
978
+
979
+ switch (this.dockedEdge) {
980
+ case "left":
981
+ return x < HOVER_THRESHOLD && Math.abs(y - cy) < HALF + PAD;
982
+ case "right":
983
+ return (
984
+ x > this._viewportWidth() - HOVER_THRESHOLD && Math.abs(y - cy) < HALF + PAD
985
+ );
986
+ case "top":
987
+ return y < HOVER_THRESHOLD && Math.abs(x - cx) < HALF + PAD;
988
+ case "bottom":
989
+ return (
990
+ y > this._viewportHeight() - HOVER_THRESHOLD && Math.abs(x - cx) < HALF + PAD
991
+ );
992
+ default:
993
+ return false;
994
+ }
995
+ }
996
+
997
+ /**
998
+ * 判断坐标是否仍悬浮在球附近
999
+ */
1000
+ _isNearBall(x, y) {
1001
+ const cx = this.pos.left + BALL_SIZE / 2;
1002
+ const cy = this.pos.top + BALL_SIZE / 2;
1003
+ const r = BALL_SIZE / 2 + HOVER_PADDING;
1004
+ return Math.hypot(x - cx, y - cy) < r;
1005
+ }
1006
+
1007
+ _onGlobalMouseMove(e) {
1008
+ if (!this.dockedEdge || this.dragState) return;
1009
+
1010
+ if (this.isCollapsed) {
1011
+ if (this._isNearHint(e.clientX, e.clientY)) this._expand();
1012
+ } else if (!this.isPanelOpen && !this._isNearBall(e.clientX, e.clientY)) {
1013
+ this._collapse();
1014
+ }
1015
+ }
1016
+
1017
+ _onResize() {
1018
+ this._clampPosition();
1019
+ this.dockedEdge = this._detectEdge();
1020
+ if (this.dockedEdge) {
1021
+ this._snapToEdge(this.dockedEdge);
1022
+ this._updateEdgeHint();
1023
+ } else {
1024
+ if (this.isCollapsed) this._expand();
1025
+ this._applyPosition();
1026
+ }
1027
+ this._updatePanelOrientation();
1028
+ }
1029
+
1030
+ // ==================== API 调用 ====================
1031
+
1032
+ async _fetchCurrentEnv() {
1033
+ try {
1034
+ const data = await apiFetch(`${API_PREFIX}/inject/getcurrentenv`);
1035
+ this.currentEnvId = (data && data.envId) || null;
1036
+ } catch {
1037
+ // 获取当前环境失败,保持上一次的值
1038
+ }
1039
+ }
1040
+
1041
+ async _fetchEnvList() {
1042
+ try {
1043
+ const data = await apiFetch(`${API_PREFIX}/env/getlist`);
1044
+ this.envList = (data && data.list) || [];
1045
+ } catch {
1046
+ // 保持上一次的列表
1047
+ }
1048
+ }
1049
+
1050
+ async _fetchDevServerList() {
1051
+ try {
1052
+ const data = await apiFetch(`${API_PREFIX}/server/list`);
1053
+ this.devServerList = (data && data.list) || [];
1054
+ } catch {
1055
+ // 保持上一次的列表
1056
+ }
1057
+ }
1058
+
1059
+ async _switchEnv(currentEnvId, targetEnvId) {
1060
+ return await apiFetch(`${API_PREFIX}/env/switch`, {
1061
+ method: "POST",
1062
+ body: JSON.stringify({ currentEnvId, targetEnvId }),
1063
+ });
1064
+ }
1065
+
1066
+ async _switchProxy(envId, devServerId) {
1067
+ return await apiFetch(`${API_PREFIX}/env/proxy/switch`, {
1068
+ method: "POST",
1069
+ body: JSON.stringify({ envId, devServerId }),
1070
+ });
1071
+ }
1072
+
1073
+ // ==================== UI 更新 ====================
1074
+
1075
+ _updateUI() {
1076
+ this._updateBall();
1077
+ this._updatePanel();
1078
+ }
1079
+
1080
+ _updateBall() {
1081
+ const currentEnv = this.envList.find((e) => e.id === this.currentEnvId);
1082
+ const label = this._$("ballLabel");
1083
+ const dot = this._$("ballDot");
1084
+ const ball = this._$("ball");
1085
+
1086
+ if (currentEnv && currentEnv.port) {
1087
+ // 显示端口后两位
1088
+ const portStr = String(currentEnv.port);
1089
+ label.textContent = portStr.slice(-2);
1090
+ } else if (currentEnv && currentEnv.name) {
1091
+ label.textContent = currentEnv.name.slice(0, 3).toUpperCase();
1092
+ } else {
1093
+ label.textContent = "ENV";
1094
+ }
1095
+
1096
+ // 重置状态 class
1097
+ ball.className = "ball";
1098
+ dot.className = "ball-dot";
1099
+
1100
+ let statusClass = "stopped";
1101
+ if (this.isSwitching) {
1102
+ statusClass = "loading";
1103
+ } else if (currentEnv && currentEnv.status === "running") {
1104
+ statusClass = "running";
1105
+ }
1106
+
1107
+ ball.classList.add(statusClass);
1108
+ dot.classList.add(statusClass);
1109
+
1110
+ // className 重置会覆盖 collapsed,若处于收起状态则恢复
1111
+ if (this.isCollapsed) ball.classList.add("collapsed");
1112
+ }
1113
+
1114
+ _updatePanel() {
1115
+ const currentEnv = this.envList.find((e) => e.id === this.currentEnvId);
1116
+
1117
+ // 更新当前环境信息条
1118
+ const currentBar = this._$("currentEnvBar");
1119
+ if (currentEnv) {
1120
+ currentBar.style.display = "block";
1121
+ this._$("currentEnvName").textContent =
1122
+ currentEnv.name || currentEnv.apiBaseUrl || "当前环境";
1123
+
1124
+ // 查找当前绑定的 DevServer 名称
1125
+ const currentDS = this.devServerList.find(
1126
+ (ds) => ds.id === currentEnv.devServerId
1127
+ );
1128
+ const dsLabel = currentDS
1129
+ ? currentDS.name || currentDS.devServerUrl || "未知"
1130
+ : "未绑定";
1131
+
1132
+ this._$("currentEnvDetail").innerHTML =
1133
+ `端口: ${currentEnv.port} | Dev: ${this._escapeHtml(dsLabel)} | 状态: ${currentEnv.status === "running" ? "运行中" : "已停止"}`;
1134
+ } else {
1135
+ currentBar.style.display = "none";
1136
+ }
1137
+
1138
+ // 更新环境列表
1139
+ const listEl = this._$("envList");
1140
+ const emptyEl = this._$("emptyState");
1141
+
1142
+ if (this.envList.length === 0) {
1143
+ listEl.innerHTML = "";
1144
+ emptyEl.style.display = "block";
1145
+ return;
1146
+ }
1147
+
1148
+ emptyEl.style.display = "none";
1149
+ listEl.innerHTML = this.envList
1150
+ .map((env) => this._renderEnvItem(env))
1151
+ .join("");
1152
+
1153
+ // 绑定每个环境项的事件
1154
+ listEl.querySelectorAll(".env-item").forEach((el) => {
1155
+ const envId = el.dataset.envId;
1156
+ const env = this.envList.find((e) => e.id === envId);
1157
+ if (!env) return;
1158
+
1159
+ el.addEventListener("click", (e) => {
1160
+ // 如果点击的是操作按钮,不触发行点击
1161
+ if (e.target.classList.contains("item-action")) return;
1162
+ this._handleEnvAction(env);
1163
+ });
1164
+ });
1165
+
1166
+ listEl.querySelectorAll(".item-action").forEach((btn) => {
1167
+ const envId = btn.dataset.envId;
1168
+ const env = this.envList.find((e) => e.id === envId);
1169
+ if (!env) return;
1170
+
1171
+ btn.addEventListener("click", (e) => {
1172
+ e.stopPropagation();
1173
+ this._handleEnvAction(env);
1174
+ });
1175
+ });
1176
+
1177
+ // 绑定 DevServer 代理目标按钮事件
1178
+ listEl.querySelectorAll(".proxy-target-btn").forEach((btn) => {
1179
+ const dsId = btn.dataset.dsId;
1180
+ const devServer = this.devServerList.find((ds) => ds.id === dsId);
1181
+ if (!devServer) return;
1182
+
1183
+ btn.addEventListener("click", (e) => {
1184
+ e.stopPropagation();
1185
+ const currentEnv = this.envList.find((e) => e.id === this.currentEnvId);
1186
+ if (currentEnv) {
1187
+ this._doSwitchProxy(currentEnv, devServer);
1188
+ }
1189
+ });
1190
+ });
1191
+ }
1192
+
1193
+ _renderEnvItem(env) {
1194
+ const isCurrent = env.id === this.currentEnvId;
1195
+ const isRunning = env.status === "running";
1196
+ const envName = env.name || env.apiBaseUrl || "未命名环境";
1197
+ const isSwitching = this.isSwitching;
1198
+
1199
+ let actionBtn = "";
1200
+ // 当前页面正在访问的环境不显示操作按钮,其它环境统一展示「切换」
1201
+ if (!isCurrent) {
1202
+ actionBtn = `<button class="item-action" data-env-id="${env.id}" ${isSwitching ? "disabled" : ""}>切换</button>`;
1203
+ }
1204
+
1205
+ // 当前运行中的环境:渲染 DevServer 代理目标子列表
1206
+ let proxyTargetsHtml = "";
1207
+ if (isCurrent && isRunning && this.devServerList.length > 0) {
1208
+ proxyTargetsHtml = this._renderDevServerTargets(env);
1209
+ }
1210
+
1211
+ return /* html */ `
1212
+ <div class="env-item ${isCurrent ? "current" : ""} ${isSwitching ? "switching" : ""}"
1213
+ data-env-id="${env.id}">
1214
+ <span class="item-status-dot ${isRunning ? "running" : "stopped"}"></span>
1215
+ <span class="item-info">
1216
+ <span class="item-name">${this._escapeHtml(envName)}</span>
1217
+ <span class="item-url">${this._escapeHtml(env.apiBaseUrl || "")}</span>
1218
+ </span>
1219
+ <span class="item-port">:${env.port}</span>
1220
+ ${actionBtn}
1221
+ </div>
1222
+ ${proxyTargetsHtml}
1223
+ `;
1224
+ }
1225
+
1226
+ /**
1227
+ * 渲染当前环境下的 DevServer 代理目标子列表
1228
+ * @param {Object} env - 当前环境信息
1229
+ * @returns {string} HTML 字符串
1230
+ */
1231
+ _renderDevServerTargets(env) {
1232
+ return this.devServerList
1233
+ .map((ds) => {
1234
+ const isActive = env.devServerId === ds.id;
1235
+ const dsName = ds.name || ds.devServerUrl || "未命名";
1236
+ const actionBtn = isActive
1237
+ ? '<span class="proxy-target-active">◀</span>'
1238
+ : `<button class="proxy-target-btn" data-ds-id="${ds.id}" ${this.isSwitching ? "disabled" : ""}>切换</button>`;
1239
+
1240
+ return /* html */ `
1241
+ <div class="proxy-target-item ${isActive ? "current" : ""} ${this.isSwitching ? "switching" : ""}"
1242
+ data-ds-id="${ds.id}">
1243
+ <span class="proxy-target-indent"></span>
1244
+ <span class="item-info">
1245
+ <span class="item-name">Dev: ${this._escapeHtml(dsName)}</span>
1246
+ <span class="item-url">${this._escapeHtml(ds.devServerUrl || "")}</span>
1247
+ </span>
1248
+ ${actionBtn}
1249
+ </div>
1250
+ `;
1251
+ })
1252
+ .join("");
1253
+ }
1254
+
1255
+ // ==================== 事件处理 ====================
1256
+
1257
+ async _togglePanel() {
1258
+ if (this.isPanelOpen) {
1259
+ this._closePanel();
1260
+ } else {
1261
+ this._openPanel();
1262
+ }
1263
+ }
1264
+
1265
+ async _openPanel() {
1266
+ this.isPanelOpen = true;
1267
+ this._$("panel").classList.remove("hidden");
1268
+ // 展开时刷新数据
1269
+ await this._refresh();
1270
+ }
1271
+
1272
+ _closePanel() {
1273
+ this.isPanelOpen = false;
1274
+ this._$("panel").classList.add("hidden");
1275
+ }
1276
+
1277
+ async _refresh() {
1278
+ await Promise.all([
1279
+ this._fetchCurrentEnv(),
1280
+ this._fetchEnvList(),
1281
+ this._fetchDevServerList(),
1282
+ ]);
1283
+ this._updateUI();
1284
+ }
1285
+
1286
+ _openDashboard() {
1287
+ // 打开管理页面的新标签页
1288
+ // 使用当前页面的同源 URL 拼接 API 前缀,PreProxyServer 会自动代理到 PostProxyServer
1289
+ window.open(`${API_PREFIX}`, "_blank");
1290
+ }
1291
+
1292
+ async _handleEnvAction(env) {
1293
+ if (this.isSwitching) return;
1294
+
1295
+ // 当前页面正在访问的环境不允许操作,忽略点击;其他环境统一走 switch
1296
+ if (this.currentEnvId === env.id) return;
1297
+
1298
+ await this._doSwitch(env);
1299
+ }
1300
+
1301
+ async _doSwitch(targetEnv) {
1302
+ this.isSwitching = true;
1303
+ this._updateUI();
1304
+
1305
+ try {
1306
+ // 调用 switch 端点:服务端原子操作,启动目标环境(不关闭当前环境)
1307
+ const updatedTarget = await this._switchEnv(this.currentEnvId, targetEnv.id);
1308
+
1309
+ // 使用服务端返回的最新环境信息(含端口号)进行重定向
1310
+ this._redirectTo(updatedTarget || targetEnv);
1311
+ } catch (err) {
1312
+ this._showToast(`切换失败: ${err.message}`);
1313
+ await this._refresh();
1314
+ } finally {
1315
+ this.isSwitching = false;
1316
+ this._updateUI();
1317
+ }
1318
+ }
1319
+
1320
+ _redirectTo(env) {
1321
+ const currentUrl = new URL(window.location.href);
1322
+ const newUrl = `${currentUrl.protocol}//${currentUrl.hostname}:${env.port}${currentUrl.pathname}${currentUrl.search}${currentUrl.hash}`;
1323
+ window.location.replace(newUrl);
1324
+ }
1325
+
1326
+ /**
1327
+ * 切换当前环境的 DevServer 绑定
1328
+ * 不换端口、不重启代理,仅更新 devServerId
1329
+ * @param {Object} env - 当前环境信息
1330
+ * @param {Object} devServer - 目标 DevServer 信息
1331
+ */
1332
+ async _doSwitchProxy(env, devServer) {
1333
+ if (this.isSwitching) return;
1334
+
1335
+ this.isSwitching = true;
1336
+ this._updateUI();
1337
+
1338
+ try {
1339
+ await this._switchProxy(env.id, devServer.id);
1340
+ await this._refresh();
1341
+ // 代理切换后刷新当前页面,从新 DevServer 加载资源
1342
+ window.location.reload();
1343
+ } catch (err) {
1344
+ this._showToast(`切换代理失败: ${err.message}`);
1345
+ } finally {
1346
+ this.isSwitching = false;
1347
+ this._updateUI();
1348
+ }
1349
+ }
1350
+
1351
+ // ==================== 辅助方法 ====================
1352
+
1353
+ _showToast(message) {
1354
+ // 移除已有的 toast
1355
+ const existing = this.shadow.querySelector(".toast");
1356
+ if (existing) existing.remove();
1357
+
1358
+ const toast = document.createElement("div");
1359
+ toast.className = "toast";
1360
+ toast.textContent = message;
1361
+ this.shadow.appendChild(toast);
1362
+
1363
+ setTimeout(() => {
1364
+ if (toast.parentNode) toast.remove();
1365
+ }, 3000);
1366
+ }
1367
+
1368
+ _escapeHtml(text) {
1369
+ const div = document.createElement("div");
1370
+ div.textContent = text;
1371
+ return div.innerHTML;
1372
+ }
1373
+
1374
+ _startPolling() {
1375
+ this._stopPolling();
1376
+ this.pollTimer = setInterval(() => {
1377
+ if (!this.isPanelOpen) {
1378
+ this._fetchEnvList().then(() => this._updateBall());
1379
+ }
1380
+ }, 5000);
1381
+ }
1382
+
1383
+ _stopPolling() {
1384
+ if (this.pollTimer) {
1385
+ clearInterval(this.pollTimer);
1386
+ this.pollTimer = null;
1387
+ }
1388
+ }
1389
+
1390
+ // ==================== 销毁 ====================
1391
+
1392
+ destroy() {
1393
+ this._stopPolling();
1394
+ if (this.host.parentNode) {
1395
+ this.host.parentNode.removeChild(this.host);
1396
+ }
1397
+ }
1398
+ }
1399
+
1400
+ // ==================== 启动 ====================
1401
+
1402
+ function bootstrap() {
1403
+ // 避免重复初始化
1404
+ if (window.__envm_switcher) return;
1405
+
1406
+ try {
1407
+ window.__envm_switcher = new EnvmSwitcher();
1408
+ } catch (err) {
1409
+ console.error("[EnvManage] 环境切换面板初始化失败:", err);
1410
+ }
1411
+ }
1412
+
1413
+ // 确保 DOM 就绪后初始化
1414
+ if (document.readyState === "loading") {
1415
+ document.addEventListener("DOMContentLoaded", bootstrap);
1416
+ } else {
1417
+ bootstrap();
1418
+ }