forked from Project-N-E-K-O/N.E.K.O
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsurface-floating-controls.js
More file actions
1729 lines (1626 loc) · 90.2 KB
/
Copy pathsurface-floating-controls.js
File metadata and controls
1729 lines (1626 loc) · 90.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* app-ui/surface-floating-controls.js
* UI display helpers extracted from app.js.
*
* Exposed as window.appUi.
* Dependencies:
* - window.appState (S) - shared mutable state
* - window.appConst (C) - frozen constants
* - window.appUtils - utility helpers
* - window.t / window.safeT - i18n
* - window.lanlan_config - character config
* Load all parts in filename order; this is a classic global script (no import/export).
*/
(function () {
'use strict';
window.appUi = window.appUi || {};
const I = window.__appUiParts || (window.__appUiParts = {});
function initFloatingButtonListeners() {
// DOM refs from orchestrator
const micButton = I.S.dom.micButton;
const screenButton = I.S.dom.screenButton;
const resetSessionButton = I.S.dom.resetSessionButton;
const muteButton = I.S.dom.muteButton;
const stopButton = I.S.dom.stopButton;
const textSendButton = I.S.dom.textSendButton;
const textInputBox = I.S.dom.textInputBox;
const screenshotButton = I.S.dom.screenshotButton;
// 麦克风按钮(toggle模式) — Live2D / VRM 浮动按钮共用
function isScreenSharingActive() {
return !!(screenButton && screenButton.classList.contains('active'));
}
let screenSharingStartedByVoice = false;
async function startScreenSharingFromVoiceButton() {
if (isScreenSharingActive()) {
return;
}
if (typeof window.startScreenSharing !== 'function') {
console.error('startScreenSharing function not found');
return;
}
await window.startScreenSharing();
// startScreenSharing handles user cancellation internally, so a
// resolved Promise alone does not prove capture actually started.
screenSharingStartedByVoice = isScreenSharingActive();
}
async function stopScreenSharingFromVoiceButton() {
if (!screenSharingStartedByVoice) {
return;
}
if (!isScreenSharingActive()) {
screenSharingStartedByVoice = false;
return;
}
if (typeof window.stopScreenSharing !== 'function') {
console.error('stopScreenSharing function not found');
return;
}
await window.stopScreenSharing();
screenSharingStartedByVoice = false;
}
// 「语音时自动共享屏幕」开关:默认关(隐私安全)——只想开麦的用户不会被静默录屏
// (Electron 下若存过采集源,startScreenSharing 会无提示直接续采)。想要旧的
// 「语音=顺带共享屏幕」统一体验的人可显式打开;localStorage 持久化,可被设置项同步覆盖。
function voiceAutoScreenEnabled() {
try { return localStorage.getItem('neko_voice_auto_screen') === '1'; }
catch (_) { return false; }
}
try {
window.nekoVoiceAutoScreen = {
get: voiceAutoScreenEnabled,
set: function (on) {
try { localStorage.setItem('neko_voice_auto_screen', on ? '1' : '0'); } catch (_) {}
},
};
} catch (_) {}
function waitForVoiceRecordingReady(timeoutMs) {
const startedAt = Date.now();
return new Promise((resolve) => {
const check = () => {
if (I.S.isRecording || Date.now() - startedAt >= timeoutMs) {
resolve(!!I.S.isRecording);
return;
}
setTimeout(check, 50);
};
check();
});
}
window.addEventListener('live2d-mic-toggle', async (e) => {
if (e.detail.active) {
if (I.S.isRecording) {
// 已在录音:仅按需联动自动共享屏幕
if (voiceAutoScreenEnabled()) {
await startScreenSharingFromVoiceButton();
}
return;
}
if (I.S.voiceStartPending || window.isMicStarting) {
return;
}
if (!micButton.classList.contains('active')) {
micButton.click();
await waitForVoiceRecordingReady(5000);
} else {
// 按钮卡在 active 但未真正录音:清状态后重试
micButton.classList.remove('active');
micButton.classList.remove('recording');
micButton.disabled = false;
micButton.click();
await waitForVoiceRecordingReady(5000);
}
// 仅当用户显式开启「语音时自动共享屏幕」才联动起屏;默认关 = 开麦只开麦。
if (I.S.isRecording && voiceAutoScreenEnabled()) {
await startScreenSharingFromVoiceButton();
}
} else {
// 只清理由本次语音流程自动开启的共享;用户之后即使关掉了自动共享
// 设置,也仍需释放此前由语音开启的采集。
await stopScreenSharingFromVoiceButton();
if (!I.S.isRecording) {
return;
}
if (typeof window.stopMicCapture === 'function') {
await window.stopMicCapture();
}
}
});
// 屏幕分享按钮(toggle模式)
window.addEventListener('live2d-screen-toggle', async (e) => {
try {
if (e.detail.active) {
if (typeof window.startScreenSharing === 'function') {
await window.startScreenSharing();
} else {
console.error('startScreenSharing function not found');
}
} else {
if (typeof window.stopScreenSharing === 'function') {
await window.stopScreenSharing();
screenSharingStartedByVoice = false;
} else {
console.error('stopScreenSharing function not found');
}
}
} finally {
if (typeof window.syncFloatingScreenButtonState === 'function') {
window.syncFloatingScreenButtonState(isScreenSharingActive());
}
}
});
// Agent工具按钮
window.addEventListener('live2d-agent-click', () => {
console.log('Agent工具按钮被点击,显示弹出框');
});
const SOCIAL_OPEN_DEDUPE_MS = 1200;
const SOCIAL_OPEN_RELEASE_DELAY_MS = 800;
function getSocialOpenState() {
if (!window.__nekoSocialOpenState || typeof window.__nekoSocialOpenState !== 'object') {
window.__nekoSocialOpenState = {
inFlight: false,
lastStartedAt: 0,
releaseTimer: null
};
}
return window.__nekoSocialOpenState;
}
function shouldIgnoreSocialOpenRequest() {
const now = Date.now();
const state = getSocialOpenState();
if (state.inFlight || (now - (state.lastStartedAt || 0)) < SOCIAL_OPEN_DEDUPE_MS) {
console.debug('[social] duplicate open request ignored');
return true;
}
if (state.releaseTimer) {
clearTimeout(state.releaseTimer);
state.releaseTimer = null;
}
state.inFlight = true;
state.lastStartedAt = now;
return false;
}
function releaseSocialOpenRequest() {
const state = getSocialOpenState();
if (state.releaseTimer) {
clearTimeout(state.releaseTimer);
}
state.releaseTimer = setTimeout(() => {
const latestState = getSocialOpenState();
latestState.inFlight = false;
latestState.releaseTimer = null;
}, SOCIAL_OPEN_RELEASE_DELAY_MS);
}
// 喵宇宙(社交平台)按钮:占用原 screen 槽位。
// 从 /api/system/social/config 拿云端 base URL,从 /api/system/client-id 拿 device 身份。
// Electron:window.open → setWindowOpenHandler 识别 social feed,以带 OS chrome 的内置
// framed 子窗口打开(见 NEKO-PC pet-window-lifecycle)。浏览器:预开 about:blank 保手势。
// Desktop OAuth 仍走系统浏览器(loopback 回调 + 文案提示在浏览器完成登录)。
window.addEventListener('live2d-social-click', async () => {
if (window.nekoSocialUnlock && window.nekoSocialUnlock.isLocked()) {
return;
}
if (shouldIgnoreSocialOpenRequest()) {
return;
}
const isElectron = !!(window.electronShell && typeof window.electronShell.openExternal === 'function');
let socialOpenRequestReleased = false;
let popupRef = null;
const closePopup = () => {
if (!popupRef) {
return;
}
try {
if (!popupRef.closed) {
popupRef.close();
}
} catch (_) { /* ignore */ }
popupRef = null;
};
const navigateBrowserPopup = (targetUrl, options = {}) => {
if (!popupRef) {
return false;
}
const currentPopup = popupRef;
try { currentPopup.opener = null; } catch (_) { /* ignore */ }
let navigated = true;
try {
currentPopup.location.replace(targetUrl);
} catch (_) {
// Once OAuth has moved the popup cross-origin, Location methods may
// be inaccessible even though assigning a new URL is still allowed.
try {
currentPopup.location = targetUrl;
} catch (_) {
navigated = false;
}
}
try { currentPopup.focus && currentPopup.focus(); } catch (_) { /* ignore */ }
if (navigated && !options.keepReference) {
popupRef = null;
}
return navigated;
};
const waitForOAuthCompletion = async (timeoutMs, requirePopup) => {
const deadline = Date.now() + timeoutMs;
let pollDelayMs = 1000;
while (Date.now() < deadline) {
if (requirePopup) {
if (!popupRef) {
return false;
}
try {
if (popupRef.closed) {
popupRef = null;
return false;
}
} catch (_) { /* ignore */ }
}
const remainingMs = deadline - Date.now();
if (remainingMs <= 0) {
return false;
}
await new Promise((resolve) => setTimeout(
resolve,
Math.min(pollDelayMs, remainingMs)
));
pollDelayMs = Math.min(Math.ceil(pollDelayMs * 1.5), 5000);
try {
const statusRes = await fetch('/api/card-drop/oauth/status', { cache: 'no-store' });
if (statusRes.ok) {
const statusJson = await statusRes.json();
if (statusJson && statusJson.logged_in) {
return true;
}
}
} catch (_) { /* retry until the OAuth window closes or expires */ }
}
return false;
};
const openElectronSocialWindow = (targetUrl) => {
// frameName=neko-social:NEKO-PC setWindowOpenHandler 靠名字识别社区窗,
// 强制 frame/thickFrame + 原生最小/最大/关(尤其 Windows 右上角)。
// features 为兜底提示;最终以主进程 overrideBrowserWindowOptions 为准。
const socialWin = window.open(
String(targetUrl),
'neko-social',
'popup=yes,width=1200,height=800,resizable=yes'
);
if (!socialWin) {
return false;
}
try { socialWin.focus && socialWin.focus(); } catch (_) { /* ignore */ }
return true;
};
const fetchNativeSyncTicket = async () => {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 4000);
try {
const response = await fetch('/api/card-drop/sync-ticket', {
cache: 'no-store',
signal: controller.signal,
});
if (!response.ok) {
console.warn(`[social] native session sync ticket fetch failed: HTTP ${response.status}`);
return '';
}
const payload = await response.json();
return payload && payload.sync_ticket ? String(payload.sync_ticket) : '';
} catch (error) {
console.warn('[social] native session sync ticket fetch failed (non-fatal):', error);
return '';
} finally {
clearTimeout(timeoutId);
}
};
const fetchNativeDelegate = async () => {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 4000);
try {
const response = await fetch('/api/card-drop/native-delegate', {
cache: 'no-store',
signal: controller.signal,
});
if (!response.ok) {
const reason = response.status === 409
? 'desktop not logged in'
: `HTTP ${response.status}`;
console.warn(`[social] native delegate fetch failed (non-fatal): ${reason}`);
return '';
}
const payload = await response.json();
return payload && payload.native_delegate
? String(payload.native_delegate)
: '';
} catch (error) {
console.warn('[social] native delegate fetch failed (non-fatal):', error);
return '';
} finally {
clearTimeout(timeoutId);
}
};
const attachNativeSyncTicket = async (targetUrl) => {
targetUrl.hash = '';
const hashParams = new URLSearchParams();
const syncTicket = await fetchNativeSyncTicket();
if (syncTicket) {
hashParams.set('native_sync', syncTicket);
}
const hash = hashParams.toString();
if (hash) targetUrl.hash = hash;
return targetUrl;
};
const attachNativeDelegate = (targetUrl, nativeDelegate) => {
const hashParams = new URLSearchParams(targetUrl.hash.replace(/^#/, ''));
// Scoped credits/facts proof — never the platform OAuth bearer.
if (nativeDelegate) {
hashParams.set('native_delegate', nativeDelegate);
}
const hash = hashParams.toString();
targetUrl.hash = hash;
return targetUrl;
};
const completeInitialCommunityHandoff = async (targetUrl) => {
if (!isElectron) {
// 先让用户看到 Community;保留 WindowProxy 仅用于随后补发 delegate。
navigateBrowserPopup(targetUrl, { keepReference: true });
}
// auth-status 已完成且无需等待 OAuth 后才启动,避免可放弃的
// delegate 校验占住 OAuth 状态解析锁并阻塞登录态判断。
const nativeDelegate = await fetchNativeDelegate();
if (nativeDelegate) {
// 二次导航使用新签发的 native_sync,并与 delegate 一次性交付。
// 即使首次页面尚未读取 fragment 而被替换,也不会丢失同步能力;
// 同时不会重放首次导航中的一次性票据。
const delegateTargetUrl = await attachNativeSyncTicket(
new URL(targetUrl, window.location.href)
);
attachNativeDelegate(delegateTargetUrl, nativeDelegate);
if (isElectron) {
if (!openElectronSocialWindow(delegateTargetUrl.toString())) {
console.warn('[social] failed to refresh Electron community window with native delegate');
}
} else if (popupRef) {
navigateBrowserPopup(delegateTargetUrl.toString());
}
} else if (!isElectron) {
// 只释放本地引用,不关闭已打开的 Community 页面。
popupRef = null;
}
};
try {
if (!isElectron) {
// 浏览器通常只为一次用户手势放行一个弹窗。先保留唯一的
// WindowProxy,完成登录态判断后再决定导航到社区或 OAuth。
// Chromium 在 windowFeatures 里指定 noopener 时可能直接返回 null。
popupRef = window.open('about:blank', '_blank');
if (!popupRef) {
if (typeof window.showStatusToast === 'function') {
window.showStatusToast(
(window.t && window.t('app.socialOpenFailed', { error: 'popup blocked' }))
|| '社交窗口打开失败:请允许弹窗',
4000
);
}
return;
}
}
const cfgRes = await fetch('/api/system/social/config');
if (!cfgRes.ok) {
if (typeof window.showStatusToast === 'function') {
window.showStatusToast(
(window.t && window.t('app.socialUnavailable')) || '社交服务不可用 (config fetch failed)',
3000
);
}
closePopup();
return;
}
const cfg = await cfgRes.json();
if (cfg && cfg.enabled === false) {
if (typeof window.showStatusToast === 'function') {
window.showStatusToast(
(window.t && window.t('app.socialDisabled')) || '社交服务已禁用',
3000
);
}
closePopup();
return;
}
let url = (cfg && cfg.social_base_url) ? cfg.social_base_url.replace(/\/+$/, '') + '/feed' : null;
if (!url) {
console.warn('[social] no social_base_url from /api/system/social/config');
closePopup();
return;
}
const targetUrl = new URL(url, window.location.href);
if (targetUrl.protocol !== 'http:' && targetUrl.protocol !== 'https:') {
throw new Error('unsupported social URL protocol');
}
// 只有从本体按钮打开的页面才能拿到一次性同步票据。票据放 fragment,
// 不进入社区服务器 access log / Referer;社区页读取后会立即从地址栏移除。
await attachNativeSyncTicket(targetUrl);
// 顺手把 client_id 拼进 URL(仅关联游客身份,不构成登录态同步授权)。
try {
const cidRes = await fetch('/api/system/client-id');
if (cidRes.ok) {
const cidJson = await cidRes.json();
if (cidJson && cidJson.client_id) {
targetUrl.searchParams.set('cid', cidJson.client_id);
}
}
} catch (cidErr) {
console.warn('[social] client_id fetch failed (non-fatal):', cidErr);
}
url = targetUrl.toString();
// 先打开猫娘社区;Desktop 未登录时再额外拉起平台 Desktop OAuth(不挡社区)。
if (isElectron) {
// 目标 URL 直接交给 setWindowOpenHandler,才能命中 isSocialFeedUrl → framed 内置窗。
// 复用 'neko-social' 名:已开则聚焦/导航同一窗口,避免叠多个社区窗。
if (!openElectronSocialWindow(url)) {
throw new Error('popup blocked');
}
}
let communityLoggedIn = false;
try {
const statusRes = await fetch('/api/card-drop/auth-status', { cache: 'no-store' });
if (statusRes.ok) {
const statusJson = await statusRes.json();
communityLoggedIn = !!(statusJson && statusJson.logged_in);
}
} catch (statusErr) {
console.warn('[social] auth-status fetch failed (non-fatal):', statusErr);
}
if (!communityLoggedIn) {
let browserOAuthStarted = false;
let browserOAuthTimeoutMs = 10 * 60 * 1000;
let oauthLaunched = false;
try {
const oauthRes = await fetch('/api/card-drop/oauth/start', {
method: 'POST',
cache: 'no-store',
});
if (oauthRes.ok) {
const oauthJson = await oauthRes.json();
const authUrl = oauthJson && oauthJson.auth_url
? String(oauthJson.auth_url)
: '';
if (authUrl) {
const expiresInSec = Number(oauthJson && oauthJson.expires_in);
if (Number.isFinite(expiresInSec) && expiresInSec > 0) {
browserOAuthTimeoutMs = Math.min(
browserOAuthTimeoutMs,
expiresInSec * 1000
);
}
if (window.electronShell && typeof window.electronShell.openExternal === 'function') {
await window.electronShell.openExternal(authUrl);
oauthLaunched = true;
} else if (!navigateBrowserPopup(authUrl, { keepReference: true })) {
closePopup();
if (typeof window.showStatusToast === 'function') {
window.showStatusToast(
(window.t && window.t('app.socialOpenFailed', { error: 'OAuth popup blocked' }))
|| '登录窗口打开失败:请允许弹窗后重试',
4000
);
}
} else {
oauthLaunched = true;
browserOAuthStarted = true;
}
if (oauthLaunched && typeof window.showStatusToast === 'function') {
const oauthPromptKey = 'app.socialOAuthPrompt';
const oauthPrompt = (typeof window.t === 'function')
? window.t(oauthPromptKey)
: '';
window.showStatusToast(
(oauthPrompt && oauthPrompt !== oauthPromptKey)
? oauthPrompt
: '请在浏览器完成统一账号登录',
4000
);
}
}
}
} catch (oauthErr) {
console.warn('[social] oauth/start failed (non-fatal):', oauthErr);
} finally {
const shouldWaitForOAuth = (isElectron && oauthLaunched)
|| (!isElectron && browserOAuthStarted);
if (shouldWaitForOAuth) {
releaseSocialOpenRequest();
socialOpenRequestReleased = true;
const oauthCompleted = await waitForOAuthCompletion(
browserOAuthTimeoutMs,
!isElectron
);
if (oauthCompleted) {
const refreshedDelegatePromise = fetchNativeDelegate();
const refreshedTargetUrl = await attachNativeSyncTicket(
new URL(url, window.location.href)
);
attachNativeDelegate(
refreshedTargetUrl,
await refreshedDelegatePromise
);
if (isElectron) {
if (!openElectronSocialWindow(refreshedTargetUrl.toString())) {
console.warn('[social] failed to refresh Electron community window after OAuth');
}
} else if (popupRef) {
navigateBrowserPopup(refreshedTargetUrl.toString());
}
}
} else {
await completeInitialCommunityHandoff(url);
}
}
} else {
await completeInitialCommunityHandoff(url);
}
return;
} catch (err) {
closePopup();
console.error('[social] open failed:', err);
if (typeof window.showStatusToast === 'function') {
window.showStatusToast(
(window.t && window.t('app.socialOpenFailed', { error: err.message }))
|| `社交窗口打开失败:${err.message}`,
4000
);
}
} finally {
if (!socialOpenRequestReleased) {
releaseSocialOpenRequest();
}
}
});
// 睡觉按钮(请她离开)
window.addEventListener('live2d-goodbye-click', (event) => {
const goodbyeDetail = event && event.detail && typeof event.detail === 'object' ? event.detail : {};
const live2DPeekEdgeAnchor = goodbyeDetail.edgeAnchor
|| (event && event.__nekoLive2DPeekEdgeAnchor)
|| null;
const goodbyeTransitionToken = I.reserveNekoModelCatTransition('model-to-cat');
if (!goodbyeTransitionToken) {
console.log('[App] 模型/猫切换进行中,忽略本次请她离开点击');
return;
}
// 第零步:在任何状态变更之前立即捕获模型位置。
// return-ball 会出现在这个位置;后续 return 时也以它作为模型位移基准。
const requestedRestoreRect = event && event.detail && event.detail.restoreSavedGoodbyeRect;
// 教程结束恢复猫咪态时,用户模型刚被临时重载到教程站位;必须沿用教程前
// 猫咪/返回按钮锚点,不能把临时模型位置误存成新的猫咪位置。
const savedModelRect = requestedRestoreRect
&& Number.isFinite(Number(requestedRestoreRect.left))
&& Number.isFinite(Number(requestedRestoreRect.top))
&& Number(requestedRestoreRect.width) > 0
&& Number(requestedRestoreRect.height) > 0
? {
left: Number(requestedRestoreRect.left),
top: Number(requestedRestoreRect.top),
width: Number(requestedRestoreRect.width),
height: Number(requestedRestoreRect.height)
}
: I.getActiveModelTransitionRect();
// 按钮位置只作为模型 bounds 不可用时的兜底。
// 其他 handler(VRM/MMD goodbyeHandler)可能先于此处执行并隐藏按钮容器,
// 所以必须在最前面读取位置。
const _live2dGoodbyeBtn = document.getElementById('live2d-btn-goodbye');
const _vrmGoodbyeBtn = document.getElementById('vrm-btn-goodbye');
const _mmdGoodbyeBtn = document.getElementById('mmd-btn-goodbye');
const _pngtuberGoodbyeBtn = document.getElementById('pngtuber-btn-goodbye');
let savedGoodbyeRect = null;
for (const btn of [_mmdGoodbyeBtn, _vrmGoodbyeBtn, _pngtuberGoodbyeBtn, _live2dGoodbyeBtn]) {
if (!btn) continue;
try {
const r = btn.getBoundingClientRect();
if (r.width > 0 && r.height > 0) {
savedGoodbyeRect = I.toNekoVirtualTransitionRect(r);
break;
}
} catch (_) { /* ignore */ }
}
savedGoodbyeRect = savedModelRect || savedGoodbyeRect;
console.log('[App] 请她离开按钮被点击,savedGoodbyeRect:', savedGoodbyeRect ? `${Math.round(savedGoodbyeRect.left)},${Math.round(savedGoodbyeRect.top)}` : 'null', 'source:', savedModelRect ? 'model' : 'button-fallback');
window._savedGoodbyeRect = savedGoodbyeRect ? {
left: savedGoodbyeRect.left,
top: savedGoodbyeRect.top,
width: savedGoodbyeRect.width,
height: savedGoodbyeRect.height
} : null;
// 第一步:立即设置标志位
if (window.live2dManager) {
window.live2dManager._goodbyeClicked = true;
}
if (window.vrmManager) {
window.vrmManager._goodbyeClicked = true;
}
if (window.mmdManager) {
window.mmdManager._goodbyeClicked = true;
}
if (window.appInterpage && typeof window.appInterpage.postGoodbyeChatComposerHiddenState === 'function') {
window.appInterpage.postGoodbyeChatComposerHiddenState(true, 'live2d-goodbye-click');
} else if (typeof window.postGoodbyeChatComposerHiddenState === 'function') {
window.postGoodbyeChatComposerHiddenState(true, 'live2d-goodbye-click');
}
console.log('[App] 设置 goodbyeClicked 为 true,当前状态:', window.live2dManager ? window.live2dManager._goodbyeClicked : 'undefined', 'VRM:', window.vrmManager ? window.vrmManager._goodbyeClicked : 'undefined');
// 立即关闭所有弹窗
const allLive2dPopups = document.querySelectorAll('[id^="live2d-popup-"]');
allLive2dPopups.forEach(popup => {
popup.style.setProperty('display', 'none', 'important');
popup.style.setProperty('visibility', 'hidden', 'important');
popup.style.setProperty('opacity', '0', 'important');
popup.style.setProperty('pointer-events', 'none', 'important');
});
const allVrmPopups = document.querySelectorAll('[id^="vrm-popup-"]');
allVrmPopups.forEach(popup => {
popup.style.setProperty('display', 'none', 'important');
popup.style.setProperty('visibility', 'hidden', 'important');
popup.style.setProperty('opacity', '0', 'important');
popup.style.setProperty('pointer-events', 'none', 'important');
});
const allPngtuberPopups = document.querySelectorAll('[id^="pngtuber-popup-"]');
allPngtuberPopups.forEach(popup => {
popup.style.setProperty('display', 'none', 'important');
popup.style.setProperty('visibility', 'hidden', 'important');
popup.style.setProperty('opacity', '0', 'important');
popup.style.setProperty('pointer-events', 'none', 'important');
});
// 关闭 MMD 弹窗
document.querySelectorAll('[id^="mmd-popup-"]').forEach(popup => {
popup.style.setProperty('display', 'none', 'important');
});
if (window.live2dManager && window.live2dManager._popupTimers) {
Object.values(window.live2dManager._popupTimers).forEach(timer => {
if (timer) clearTimeout(timer);
});
window.live2dManager._popupTimers = {};
}
console.log('[App] 已关闭所有弹窗,Live2D数量:', allLive2dPopups.length, 'VRM数量:', allVrmPopups.length);
// 使用统一的状态管理方法重置所有浮动按钮
if (window.live2dManager && typeof window.live2dManager.resetAllButtons === 'function') {
window.live2dManager.resetAllButtons();
}
if (window.vrmManager && typeof window.vrmManager.resetAllButtons === 'function') {
window.vrmManager.resetAllButtons();
}
if (window.pngtuberManager && typeof window.pngtuberManager.resetAllButtons === 'function') {
window.pngtuberManager.resetAllButtons();
}
// 判断当前 PNGTuber 是否激活,告别态只锁定正在使用的 2D 图片模型。
const pngtuberContainerForState = document.getElementById('pngtuber-container');
const isPngtuberActiveForState = (window.lanlan_config?.model_type || '').toLowerCase() === 'pngtuber'
&& pngtuberContainerForState
&& pngtuberContainerForState.style.display !== 'none'
&& !pngtuberContainerForState.classList.contains('hidden');
// 设置锁定状态
if (window.live2dManager && typeof window.live2dManager.setLocked === 'function') {
window.live2dManager.setLocked(true, { updateFloatingButtons: false });
}
if (window.vrmManager && window.vrmManager.core && typeof window.vrmManager.core.setLocked === 'function') {
window.vrmManager.core.setLocked(true);
}
if (window.mmdManager && window.mmdManager.core && typeof window.mmdManager.core.setLocked === 'function') {
window.mmdManager.core.setLocked(true);
}
if (isPngtuberActiveForState && window.pngtuberManager && typeof window.pngtuberManager.setLocked === 'function') {
window.pngtuberManager.setLocked(true, { updateFloatingButtons: false });
}
// 不立即隐藏 canvas,先仅禁用交互
const live2dCanvas = document.getElementById('live2d-canvas');
if (live2dCanvas) {
live2dCanvas.style.setProperty('pointer-events', 'none', 'important');
console.log('[App] 已禁用 live2d-canvas 交互(pointer-events: none),等待过渡动画完成后再隐藏');
}
// 语音启动中 resetSessionButton 会短暂 disabled;先在 goodbye 事件内让 Live2D
// 立即进入退出态,避免旧 reset click 被浏览器吞掉时模型停在原位。
const live2dContainerForGoodbye = document.getElementById('live2d-container');
if (live2dContainerForGoodbye) {
I.playModelGoodbyeExit(live2dContainerForGoodbye, savedGoodbyeRect);
console.log('[App] goodbye 事件已立即最小化 live2d-container');
}
// 判断当前激活的模型类型
const vrmContainer = document.getElementById('vrm-container');
const live2dContainer = document.getElementById('live2d-container');
const mmdContainer = document.getElementById('mmd-container');
const pngtuberContainer = document.getElementById('pngtuber-container');
const isVrmActive = vrmContainer &&
vrmContainer.style.display !== 'none' &&
!vrmContainer.classList.contains('hidden');
const isMmdActive = mmdContainer &&
mmdContainer.style.display !== 'none' &&
!mmdContainer.classList.contains('hidden');
const isPngtuberActive = (window.lanlan_config?.model_type || '').toLowerCase() === 'pngtuber' && pngtuberContainer &&
pngtuberContainer.style.display !== 'none' &&
!pngtuberContainer.classList.contains('hidden');
console.log('[App] 判断当前模型类型 - isVrmActive:', isVrmActive, 'isMmdActive:', isMmdActive);
const activeGoodbyeModelType = isMmdActive
? 'mmd'
: (isVrmActive ? 'vrm' : (isPngtuberActive ? 'pngtuber' : 'live2d'));
const goodbyeResourceToken = I.beginGoodbyeResourceSuspend({
activeModelType: activeGoodbyeModelType
});
// VRM 也先仅禁用交互
const vrmCanvas = document.getElementById('vrm-canvas');
if (vrmContainer) {
vrmContainer.style.setProperty('pointer-events', 'none', 'important');
console.log('[App] 已禁用 vrm-container 交互,等待过渡动画完成后再隐藏');
}
if (vrmCanvas) {
vrmCanvas.style.setProperty('pointer-events', 'none', 'important');
console.log('[App] 已禁用 vrm-canvas 交互');
}
// MMD:禁用交互 + 立即停物理;容器退场统一走 playModelGoodbyeExit。
const mmdCanvas = document.getElementById('mmd-canvas');
if (mmdContainer) {
mmdContainer.style.setProperty('pointer-events', 'none', 'important');
}
if (mmdCanvas) {
mmdCanvas.style.setProperty('pointer-events', 'none', 'important');
}
if (window._mmdCanvasFadeInId) {
clearTimeout(window._mmdCanvasFadeInId);
window._mmdCanvasFadeInId = null;
}
if (isMmdActive && window.mmdManager) {
window.mmdManager.enablePhysics = false;
}
if (isMmdActive && mmdContainer) {
I.playModelGoodbyeExit(mmdContainer, savedGoodbyeRect);
}
if (isPngtuberActive && pngtuberContainer) {
pngtuberContainer.style.setProperty('pointer-events', 'none', 'important');
const pngtuberImage = pngtuberContainer.querySelector('.pngtuber-image');
if (pngtuberImage) {
pngtuberImage.style.setProperty('pointer-events', 'none', 'important');
}
}
if (isPngtuberActive && pngtuberContainer) {
I.playModelGoodbyeExit(pngtuberContainer, savedGoodbyeRect);
}
// 为 VRM 容器添加 minimized 类
if (isVrmActive && vrmContainer) {
if (window._vrmCanvasFadeInId) {
clearInterval(window._vrmCanvasFadeInId);
window._vrmCanvasFadeInId = null;
}
const vrmCanvasForHide = document.getElementById('vrm-canvas');
if (vrmCanvasForHide) {
vrmCanvasForHide.style.opacity = '';
}
I.playModelGoodbyeExit(vrmContainer, savedGoodbyeRect);
console.log('[App] 已为 vrm-container 添加 minimized 类,触发退出动画');
}
// 延迟隐藏 canvas / container
if (window._goodbyeHideTimerId) clearTimeout(window._goodbyeHideTimerId);
window._goodbyeHideTimerId = setTimeout(() => {
window._goodbyeHideTimerId = null;
if (live2dCanvas) {
live2dCanvas.style.setProperty('visibility', 'hidden', 'important');
console.log('[App] 过渡完成,已隐藏 live2d-canvas(visibility: hidden)');
}
if (vrmContainer) {
vrmContainer.style.setProperty('visibility', 'hidden', 'important');
vrmContainer.style.setProperty('display', 'none', 'important');
console.log('[App] 过渡完成,已隐藏 vrm-container');
}
if (vrmCanvas) {
vrmCanvas.style.setProperty('visibility', 'hidden', 'important');
console.log('[App] 过渡完成,已隐藏 vrm-canvas');
}
if (mmdContainer) {
mmdContainer.style.setProperty('visibility', 'hidden', 'important');
mmdContainer.style.setProperty('display', 'none', 'important');
}
if (mmdCanvas) {
mmdCanvas.style.setProperty('visibility', 'hidden', 'important');
mmdCanvas.style.transition = '';
}
if (isPngtuberActive && pngtuberContainer) {
pngtuberContainer.style.setProperty('visibility', 'hidden', 'important');
pngtuberContainer.style.setProperty('display', 'none', 'important');
}
I.completeGoodbyeResourceSuspend(goodbyeResourceToken);
}, I.NEKO_MODEL_CAT_TRANSITION_DURATION_MS);
// 隐藏所有浮动按钮和锁按钮
const live2dFloatingButtons = document.getElementById('live2d-floating-buttons');
if (live2dFloatingButtons) {
live2dFloatingButtons.style.setProperty('display', 'none', 'important');
live2dFloatingButtons.style.setProperty('visibility', 'hidden', 'important');
live2dFloatingButtons.style.setProperty('opacity', '0', 'important');
}
const vrmFloatingButtons = document.getElementById('vrm-floating-buttons');
if (vrmFloatingButtons) {
vrmFloatingButtons.style.setProperty('display', 'none', 'important');
vrmFloatingButtons.style.setProperty('visibility', 'hidden', 'important');
vrmFloatingButtons.style.setProperty('opacity', '0', 'important');
}
const live2dLockIcon = document.getElementById('live2d-lock-icon');
if (live2dLockIcon) {
live2dLockIcon.style.setProperty('display', 'none', 'important');
live2dLockIcon.style.setProperty('visibility', 'hidden', 'important');
live2dLockIcon.style.setProperty('opacity', '0', 'important');
}
const vrmLockIcon = document.getElementById('vrm-lock-icon');
if (vrmLockIcon) {
vrmLockIcon.style.setProperty('display', 'none', 'important');
vrmLockIcon.style.setProperty('visibility', 'hidden', 'important');
vrmLockIcon.style.setProperty('opacity', '0', 'important');
}
const mmdFloatingButtons = document.getElementById('mmd-floating-buttons');
if (mmdFloatingButtons) {
mmdFloatingButtons.style.setProperty('display', 'none', 'important');
mmdFloatingButtons.style.setProperty('visibility', 'hidden', 'important');
mmdFloatingButtons.style.setProperty('opacity', '0', 'important');
}
const mmdLockIcon = document.getElementById('mmd-lock-icon');
if (mmdLockIcon) {
mmdLockIcon.style.setProperty('display', 'none', 'important');
mmdLockIcon.style.setProperty('visibility', 'hidden', 'important');
mmdLockIcon.style.setProperty('opacity', '0', 'important');
}
const pngtuberFloatingButtons = document.getElementById('pngtuber-floating-buttons');
if (pngtuberFloatingButtons) {
pngtuberFloatingButtons.style.setProperty('display', 'none', 'important');
pngtuberFloatingButtons.style.setProperty('visibility', 'hidden', 'important');
pngtuberFloatingButtons.style.setProperty('opacity', '0', 'important');
}
const isReturningToPngtuber = (window.lanlan_config?.model_type || '').toLowerCase() === 'pngtuber';
const pngtuberLockIcon = document.getElementById('pngtuber-lock-icon');
if (isReturningToPngtuber && pngtuberLockIcon) {
pngtuberLockIcon.style.setProperty('display', 'none', 'important');
pngtuberLockIcon.style.setProperty('visibility', 'hidden', 'important');
pngtuberLockIcon.style.setProperty('opacity', '0', 'important');
}
// 显示独立的"请她回来"按钮
const live2dReturnButtonContainer = document.getElementById('live2d-return-button-container');
let vrmReturnButtonContainer = document.getElementById('vrm-return-button-container');
let mmdReturnButtonContainer = document.getElementById('mmd-return-button-container');
let pngtuberReturnButtonContainer = document.getElementById('pngtuber-return-button-container');
const useMmdReturn = isMmdActive;
const useVrmReturn = isVrmActive && !isMmdActive;
const usePngtuberReturn = isPngtuberActive && !isVrmActive && !isMmdActive;
let activeReturnButtonContainer = null;
// MMD 返回按钮
if (useMmdReturn && !mmdReturnButtonContainer && window.mmdManager) {
if (typeof window.mmdManager.setupFloatingButtons === 'function') {
window.mmdManager.setupFloatingButtons();
mmdReturnButtonContainer = document.getElementById('mmd-return-button-container');
}
}
if (useMmdReturn && mmdReturnButtonContainer) {
activeReturnButtonContainer = I.showReturnBallContainer(mmdReturnButtonContainer, savedGoodbyeRect, { deferReveal: true });
} else {
I.hideReturnBallContainer(mmdReturnButtonContainer);
}
// 显示Live2D的返回按钮(仅在非VRM/非MMD/非PNGTuber模式时显示)
const useLive2dReturn = !useVrmReturn && !useMmdReturn && !usePngtuberReturn;
let live2dReturnContainer = live2dReturnButtonContainer;
// 与 VRM/MMD/PNGTuber 分支对齐:返回球容器缺失时(模型切换 / 打开过模型管理 / 上一次告别拆除
// 了浮动按钮)用 setupFloatingButtons 重建,否则 Live2D 会"自动变猫后直接消失"——模型已最小化,
// 却没有任何可点的毛线球留下,且无法点回来。这是四种模型里唯一漏掉自愈重建的分支。
if (useLive2dReturn && !live2dReturnContainer && window.live2dManager
&& typeof window.live2dManager.setupFloatingButtons === 'function') {
const live2dModelForReturn = typeof window.live2dManager.getCurrentModel === 'function'
? window.live2dManager.getCurrentModel()
: window.live2dManager.currentModel;
if (live2dModelForReturn && !live2dModelForReturn.destroyed) {
window.live2dManager.setupFloatingButtons(live2dModelForReturn);
live2dReturnContainer = document.getElementById('live2d-return-button-container');
// setupFloatingButtons 会重新显示主浮动按钮工具栏与锁图标;告别态需再次隐藏,
// 并恢复上面 setLocked(true) 的锁定,保持与本 handler 既有隐藏逻辑一致。
const rebuiltFloatingButtons = document.getElementById('live2d-floating-buttons');
if (rebuiltFloatingButtons) {
rebuiltFloatingButtons.style.setProperty('display', 'none', 'important');
rebuiltFloatingButtons.style.setProperty('visibility', 'hidden', 'important');
rebuiltFloatingButtons.style.setProperty('opacity', '0', 'important');
}
const rebuiltLockIcon = document.getElementById('live2d-lock-icon');
if (rebuiltLockIcon) {
rebuiltLockIcon.style.setProperty('display', 'none', 'important');
rebuiltLockIcon.style.setProperty('visibility', 'hidden', 'important');
rebuiltLockIcon.style.setProperty('opacity', '0', 'important');
}
if (typeof window.live2dManager.setLocked === 'function') {
window.live2dManager.setLocked(true, { updateFloatingButtons: false });
}
}
}
if (useLive2dReturn && live2dReturnContainer) {
activeReturnButtonContainer = I.showReturnBallContainer(live2dReturnContainer, savedGoodbyeRect, {
deferReveal: true,
edgeAnchor: live2DPeekEdgeAnchor
});
} else {
I.hideReturnBallContainer(live2dReturnContainer);
}
if (usePngtuberReturn && !pngtuberReturnButtonContainer && window.pngtuberManager) {
if (typeof window.pngtuberManager.setupFloatingButtons === 'function') {
window.pngtuberManager.setupFloatingButtons();
pngtuberReturnButtonContainer = document.getElementById('pngtuber-return-button-container');
}
}
if (usePngtuberReturn && pngtuberReturnButtonContainer) {
activeReturnButtonContainer = I.showReturnBallContainer(pngtuberReturnButtonContainer, savedGoodbyeRect);
} else {
I.hideReturnBallContainer(pngtuberReturnButtonContainer);
}
// 显示VRM的返回按钮
console.log('[App] VRM返回按钮检查 - useVrmReturn:', useVrmReturn, 'vrmReturnButtonContainer存在:', !!vrmReturnButtonContainer);
if (useVrmReturn && !vrmReturnButtonContainer && window.vrmManager) {
console.log('[App] VRM返回按钮不存在,重新创建浮动按钮系统');
if (typeof window.vrmManager.setupFloatingButtons === 'function') {
window.vrmManager.setupFloatingButtons();
vrmReturnButtonContainer = document.getElementById('vrm-return-button-container');
console.log('[App] 重新创建后VRM返回按钮存在:', !!vrmReturnButtonContainer);
}
}