-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathApp.tsx
More file actions
2180 lines (2034 loc) · 84.7 KB
/
App.tsx
File metadata and controls
2180 lines (2034 loc) · 84.7 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
import { useState, useEffect, useMemo, useRef, useCallback, type CSSProperties } from 'react';
import MessageList from './MessageList';
import { i18n } from './i18n';
import {
type ChatMessage,
type MessageAction,
type ChatWindowSchemaProps,
type ComposerSubmitPayload,
type ComposerAttachment,
type AvatarInteractionPayload,
type AvatarToolStatePayload,
type GalgameOption,
type ChoiceOption,
type ChoicePrompt,
type ChoicePromptSource,
} from './message-schema';
import CommandPalette, { type CommandItem, type UserPreferences } from './CommandPalette';
export type ChatWindowProps = ChatWindowSchemaProps & {
onMessageAction?: (message: ChatMessage, action: MessageAction) => void;
onComposerImportImage?: () => void;
onComposerScreenshot?: () => void;
onComposerRemoveAttachment?: (attachmentId: ComposerAttachment['id']) => void;
onComposerSubmit?: (payload: ComposerSubmitPayload) => void;
onAvatarInteraction?: (payload: AvatarInteractionPayload) => void;
onAvatarToolStateChange?: (payload: AvatarToolStatePayload) => void;
onJukeboxClick?: () => void;
onTranslateToggle?: () => void;
onGalgameModeToggle?: () => void;
onGalgameOptionSelect?: (option: GalgameOption) => void;
quickActions?: CommandItem[];
quickActionsPreferences?: UserPreferences;
quickActionsLoading?: boolean;
onQuickActionExecute?: (actionId: string, value: unknown) => Promise<CommandItem | null>;
onQuickActionsRequest?: () => void;
onQuickActionsPreferencesChange?: (prefs: UserPreferences) => void;
// Generic ChoicePrompt(mini-game invite 等通用三选项框架)。
// galgame mode 现有路径继续走 galgameOptions / onGalgameOptionSelect(BC);
// 本框架先只承载 mini_game_invite,未来可把 galgame 也迁过来。
choicePrompt?: ChoicePrompt | null;
onChoiceSelect?: (option: ChoiceOption, source: ChoicePromptSource) => void;
};
const defaultMessages: ChatMessage[] = [];
type AvatarToolId = AvatarInteractionPayload['toolId'];
type ToolIconItem = {
id: AvatarToolId;
labelKey: string;
labelFallback: string;
iconImagePath: string;
iconImagePathAlt?: string;
iconImagePathAlt2?: string;
menuIconScale?: number;
menuIconOffsetX?: number;
menuIconOffsetY?: number;
menuIconOffsetXAlt?: number;
menuIconOffsetYAlt?: number;
menuIconOffsetXAlt2?: number;
menuIconOffsetYAlt2?: number;
cursorImagePath: string;
cursorImagePathAlt?: string;
cursorImagePathAlt2?: string;
cursorHotspotX?: number;
cursorHotspotY?: number;
};
const toolIconItems: ToolIconItem[] = [
{
id: 'lollipop',
labelKey: 'chat.toolLollipop',
labelFallback: '棒棒糖',
iconImagePath: '/static/icons/chat_sugar1.png',
iconImagePathAlt: '/static/icons/chat_sugar2.png',
iconImagePathAlt2: '/static/icons/chat_sugar3.png',
cursorImagePath: '/static/icons/chat_sugar1_cursor.png',
cursorImagePathAlt: '/static/icons/chat_sugar2_cursor.png',
menuIconScale: 1.18,
cursorHotspotX: 27,
cursorHotspotY: 46,
},
{
id: 'fist',
labelKey: 'chat.toolFist',
labelFallback: '猫爪',
iconImagePath: '/static/icons/cat_claw1.png',
iconImagePathAlt: '/static/icons/cat_claw2.png',
cursorImagePath: '/static/icons/cat_claw1_cursor.png',
cursorImagePathAlt: '/static/icons/cat_claw2_cursor.png',
cursorHotspotX: 39,
cursorHotspotY: 46,
},
{
id: 'hammer',
labelKey: 'chat.toolHammer',
labelFallback: '锤子',
iconImagePath: '/static/icons/chat_hammer1.png',
iconImagePathAlt: '/static/icons/chat_hammer2.png',
cursorImagePath: '/static/icons/chat_hammer1_cursor.png',
cursorImagePathAlt: '/static/icons/chat_hammer2_cursor.png',
menuIconScale: 1.42,
menuIconOffsetX: -6,
menuIconOffsetY: 1,
menuIconOffsetXAlt: 1,
menuIconOffsetYAlt: -1,
cursorHotspotX: 50,
cursorHotspotY: 54,
},
];
const hammerToolItem = toolIconItems.find(item => item.id === 'hammer') ?? null;
const hammerOverlayTransformOrigin = {
x: 60,
y: 118,
};
const avatarToolSoundPaths = {
lollipopBite: '/static/sounds/avatar-tools/lollipop-bite.mp3',
coinDrop: '/static/sounds/avatar-tools/coin-drop.mp3',
hammerSmall: '/static/sounds/avatar-tools/hammer-small.mp3',
hammerBig: '/static/sounds/avatar-tools/hammer-big.mp3',
} as const;
function getToolItemLabel(item: ToolIconItem): string {
return i18n(item.labelKey, item.labelFallback);
}
const avatarToolRangePadding = 100;
const avatarToolRangeHoldMs = 180;
const compactCursorZoneSelector = [
'.composer-bottom-tools',
'.composer-tool-menu',
'.composer-icon-popover',
'.composer-tool-btn',
'.composer-icon-button',
'.send-button-circle',
'.window-topbar-actions',
'.topbar-action-btn',
'.message-action-button',
'#live2d-floating-buttons',
'#vrm-floating-buttons',
'#mmd-floating-buttons',
'#live2d-return-button-container',
'#vrm-return-button-container',
'#mmd-return-button-container',
'#live2d-lock-icon',
'#vrm-lock-icon',
'#mmd-lock-icon',
'.live2d-floating-btn',
'.vrm-floating-btn',
'.mmd-floating-btn',
'.live2d-trigger-btn',
'.vrm-trigger-btn',
'.mmd-trigger-btn',
'.live2d-return-btn',
'.vrm-return-btn',
'.mmd-return-btn',
'.live2d-popup',
'.vrm-popup',
'.mmd-popup',
'[id^="live2d-popup-"]',
'[id^="vrm-popup-"]',
'[id^="mmd-popup-"]',
'[data-neko-sidepanel]',
].join(', ');
type CursorVariant = 'primary' | 'secondary' | 'tertiary';
type ToolCursorVariantState = Record<string, CursorVariant>;
type InteractionIntensity = NonNullable<AvatarInteractionPayload['intensity']>;
type AvatarInteractionToolId = AvatarToolId;
type AvatarTouchZone = 'ear' | 'head' | 'face' | 'body';
type AvatarInteractionPayloadByTool = {
[K in AvatarInteractionToolId]: Extract<AvatarInteractionPayload, { toolId: K }>;
};
type HostAvatarBounds = {
left: number;
right: number;
top: number;
bottom: number;
width: number;
height: number;
centerX?: number;
centerY?: number;
};
type HostAvatarManager = {
currentModel?: unknown;
getModelScreenBounds?: () => HostAvatarBounds | null;
};
type AvatarBoundsCacheEntry = {
bounds: HostAvatarBounds;
};
type AvatarToolCacheState = {
loadedCursorImageCache: Map<string, Promise<HTMLImageElement>>;
compactCursorValueCache: Map<string, Promise<string>>;
avatarBoundsCacheTtlMs: number;
avatarBoundsCache: {
expiresAt: number;
entries: AvatarBoundsCacheEntry[];
};
};
type AvatarRangeHit = {
bounds: HostAvatarBounds;
touchZone: AvatarTouchZone;
};
type FloatingHeart = {
id: number;
x: number;
y: number;
driftX: number;
driftY: number;
scale: number;
delayMs: number;
};
type FloatingFistDrop = {
id: number;
x: number;
y: number;
driftX: number;
driftY: number;
rotation: number;
scale: number;
delayMs: number;
};
function resolveToolImagePaths(item: ToolIconItem, variant: CursorVariant) {
return {
iconImagePath: variant === 'tertiary' && item.iconImagePathAlt2
? item.iconImagePathAlt2
: variant === 'secondary' && item.iconImagePathAlt
? item.iconImagePathAlt
: item.iconImagePath,
cursorImagePath: variant === 'tertiary' && item.cursorImagePathAlt2
? item.cursorImagePathAlt2
: variant === 'secondary' && item.cursorImagePathAlt
? item.cursorImagePathAlt
: variant === 'tertiary' && item.cursorImagePathAlt
? item.cursorImagePathAlt
: item.cursorImagePath,
};
}
function resolveMenuIconVisual(item: ToolIconItem, variant: CursorVariant) {
const imagePath = variant === 'tertiary' && item.iconImagePathAlt2
? item.iconImagePathAlt2
: variant === 'secondary' && item.iconImagePathAlt
? item.iconImagePathAlt
: item.iconImagePath;
const offsetX = variant === 'tertiary'
? (item.menuIconOffsetXAlt2 ?? item.menuIconOffsetXAlt ?? item.menuIconOffsetX ?? 0)
: variant === 'secondary'
? (item.menuIconOffsetXAlt ?? item.menuIconOffsetX ?? 0)
: (item.menuIconOffsetX ?? 0);
const offsetY = variant === 'tertiary'
? (item.menuIconOffsetYAlt2 ?? item.menuIconOffsetYAlt ?? item.menuIconOffsetY ?? 0)
: variant === 'secondary'
? (item.menuIconOffsetYAlt ?? item.menuIconOffsetY ?? 0)
: (item.menuIconOffsetY ?? 0);
return {
imagePath,
offsetX,
offsetY,
};
}
function loadCursorImage(imagePath: string, cacheState: AvatarToolCacheState): Promise<HTMLImageElement> {
const cached = cacheState.loadedCursorImageCache.get(imagePath);
if (cached) return cached;
const pending = new Promise<HTMLImageElement>((resolve, reject) => {
const image = new Image();
image.decoding = 'async';
image.onload = () => resolve(image);
image.onerror = () => reject(new Error(`Failed to load cursor image: ${imagePath}`));
image.src = imagePath;
});
cacheState.loadedCursorImageCache.set(imagePath, pending);
return pending;
}
function clamp(value: number, min: number, max: number): number {
return Math.min(Math.max(value, min), max);
}
async function resolveCompactCursorValue(
item: ToolIconItem,
variant: CursorVariant,
cacheState: AvatarToolCacheState,
): Promise<string> {
const { iconImagePath, cursorImagePath } = resolveToolImagePaths(item, variant);
const cursorScale = item.menuIconScale ?? 1;
const cacheKey = [
iconImagePath,
cursorImagePath,
cursorScale,
item.cursorHotspotX ?? 18,
item.cursorHotspotY ?? 18,
].join('|');
const cached = cacheState.compactCursorValueCache.get(cacheKey);
if (cached) return cached;
const pending = Promise.all([
loadCursorImage(iconImagePath, cacheState),
loadCursorImage(cursorImagePath, cacheState),
]).then(([iconImage, cursorImage]) => {
const boxSize = Math.max(32, Math.round(40 * cursorScale));
const scale = Math.min(boxSize / iconImage.naturalWidth, boxSize / iconImage.naturalHeight);
const drawWidth = Math.max(1, Math.round(iconImage.naturalWidth * scale));
const drawHeight = Math.max(1, Math.round(iconImage.naturalHeight * scale));
const offsetX = Math.round((boxSize - drawWidth) / 2);
const offsetY = Math.round((boxSize - drawHeight) / 2);
const canvas = document.createElement('canvas');
canvas.width = boxSize;
canvas.height = boxSize;
const context = canvas.getContext('2d');
if (!context) {
return resolveCursorValue(item, variant);
}
context.clearRect(0, 0, boxSize, boxSize);
context.drawImage(iconImage, offsetX, offsetY, drawWidth, drawHeight);
const hotspotRatioX = (item.cursorHotspotX ?? 18) / Math.max(cursorImage.naturalWidth, 1);
const hotspotRatioY = (item.cursorHotspotY ?? 18) / Math.max(cursorImage.naturalHeight, 1);
const hotspotX = clamp(Math.round(offsetX + drawWidth * hotspotRatioX), 0, boxSize - 1);
const hotspotY = clamp(Math.round(offsetY + drawHeight * hotspotRatioY), 0, boxSize - 1);
return `url("${canvas.toDataURL('image/png')}") ${hotspotX} ${hotspotY}, auto`;
}).catch(() => resolveCursorValue(item, variant));
cacheState.compactCursorValueCache.set(cacheKey, pending);
return pending;
}
function resolveCursorValue(item: ToolIconItem, variant: CursorVariant): string {
const { cursorImagePath: imagePath } = resolveToolImagePaths(item, variant);
const hotspotX = typeof item.cursorHotspotX === 'number' ? item.cursorHotspotX : 18;
const hotspotY = typeof item.cursorHotspotY === 'number' ? item.cursorHotspotY : 18;
return `url("${imagePath}") ${hotspotX} ${hotspotY}, auto`;
}
function playAvatarToolSound(soundPath: string) {
if (typeof Audio === 'undefined') return;
try {
const audio = new Audio(soundPath);
audio.preload = 'auto';
audio.volume = 0.9;
const playPromise = audio.play();
if (playPromise && typeof playPromise.catch === 'function') {
playPromise.catch(() => {});
}
} catch {
// Ignore autoplay or unsupported-audio failures; the interaction itself should continue.
}
}
function supportsDesktopFinePointer(): boolean {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
return true;
}
try {
return window.matchMedia('(pointer: fine)').matches;
} catch {
return true;
}
}
function isElectronMultiWindowHost(): boolean {
return typeof window !== 'undefined'
&& (window as Window & { __NEKO_MULTI_WINDOW__?: boolean }).__NEKO_MULTI_WINDOW__ === true;
}
function clearForcedNativeCursorFallback() {
if (typeof document === 'undefined') return;
const root = document.documentElement;
root.style.removeProperty('cursor');
document.body?.style.removeProperty('cursor');
}
function clearGlobalToolCursorState() {
if (typeof document === 'undefined') return;
const root = document.documentElement;
root.classList.remove('neko-tool-cursor-active');
root.style.removeProperty('--neko-chat-tool-cursor');
root.style.setProperty('cursor', 'auto', 'important');
document.body?.style.setProperty('cursor', 'auto', 'important');
}
function isElementVisible(elementId: string): boolean {
const element = document.getElementById(elementId);
if (!element) return false;
const computedStyle = window.getComputedStyle(element);
return computedStyle.display !== 'none'
&& computedStyle.visibility !== 'hidden'
&& computedStyle.opacity !== '0'
&& element.getClientRects().length > 0;
}
function isPointInsideAvatarBounds(bounds: HostAvatarBounds, clientX: number, clientY: number): boolean {
if (
clientX < bounds.left - avatarToolRangePadding
|| clientX > bounds.right + avatarToolRangePadding
|| clientY < bounds.top - avatarToolRangePadding
|| clientY > bounds.bottom + avatarToolRangePadding
) {
return false;
}
const centerX = typeof bounds.centerX === 'number'
? bounds.centerX
: (bounds.left + bounds.right) / 2;
const centerY = typeof bounds.centerY === 'number'
? bounds.centerY
: (bounds.top + bounds.bottom) / 2;
const radiusX = bounds.width * 0.3 + avatarToolRangePadding;
const radiusY = bounds.height * 0.475 + avatarToolRangePadding;
if (radiusX <= 0 || radiusY <= 0) return false;
const normalizedX = (clientX - centerX) / radiusX;
const normalizedY = (clientY - centerY) / radiusY;
return normalizedX * normalizedX + normalizedY * normalizedY <= 1;
}
function getAvatarBoundsEntries(cacheState: AvatarToolCacheState): AvatarBoundsCacheEntry[] {
const now = performance.now();
if (cacheState.avatarBoundsCache.expiresAt <= now) {
const hostWindow = window as Window & {
mmdManager?: HostAvatarManager;
vrmManager?: HostAvatarManager;
live2dManager?: HostAvatarManager;
};
const candidates: Array<{ containerId: string; manager: HostAvatarManager | undefined }> = [
{ containerId: 'mmd-container', manager: hostWindow.mmdManager },
{ containerId: 'vrm-container', manager: hostWindow.vrmManager },
{ containerId: 'live2d-container', manager: hostWindow.live2dManager },
];
cacheState.avatarBoundsCache = {
expiresAt: now + cacheState.avatarBoundsCacheTtlMs,
entries: candidates.flatMap(({ containerId, manager }) => {
if (!manager?.currentModel || typeof manager.getModelScreenBounds !== 'function') {
return [];
}
if (!isElementVisible(containerId)) return [];
try {
const bounds = manager.getModelScreenBounds();
return bounds ? [{ bounds }] : [];
} catch {
return [];
}
}),
};
}
return cacheState.avatarBoundsCache.entries;
}
function classifyAvatarTouchZone(bounds: HostAvatarBounds, clientX: number, clientY: number): AvatarTouchZone {
if (bounds.width <= 0 || bounds.height <= 0) {
return 'body';
}
const relativeX = clamp((clientX - bounds.left) / bounds.width, 0, 1);
const relativeY = clamp((clientY - bounds.top) / bounds.height, 0, 1);
if (relativeY <= 0.24 && (relativeX <= 0.24 || relativeX >= 0.76)) {
return 'ear';
}
if (relativeY <= 0.34) {
return 'head';
}
if (relativeY <= 0.62) {
return 'face';
}
return 'body';
}
function getAvatarRangeHit(
clientX: number,
clientY: number,
cacheState: AvatarToolCacheState,
): AvatarRangeHit | null {
const matchedEntry = getAvatarBoundsEntries(cacheState).find(({ bounds }) => (
isPointInsideAvatarBounds(bounds, clientX, clientY)
));
if (!matchedEntry) {
return null;
}
return {
bounds: matchedEntry.bounds,
touchZone: classifyAvatarTouchZone(matchedEntry.bounds, clientX, clientY),
};
}
function isPointerWithinAvatarRange(
clientX: number,
clientY: number,
cacheState: AvatarToolCacheState,
): boolean {
return getAvatarRangeHit(clientX, clientY, cacheState) !== null;
}
function clearAvatarBoundsCache(cacheState: AvatarToolCacheState) {
cacheState.avatarBoundsCache = {
expiresAt: 0,
entries: [],
};
}
function isPointerOverCompactCursorZone(target: EventTarget | null): boolean {
return target instanceof Element && !!target.closest(compactCursorZoneSelector);
}
function isPointWithinCompactCursorZone(clientX: number, clientY: number): boolean {
if (typeof document === 'undefined') return false;
const hitElements = typeof document.elementsFromPoint === 'function'
? document.elementsFromPoint(clientX, clientY)
: (
typeof document.elementFromPoint === 'function'
? [document.elementFromPoint(clientX, clientY)].filter((element): element is Element => element instanceof Element)
: []
);
return hitElements.some(element => !!element.closest(compactCursorZoneSelector));
}
function resolveEffectiveCursorVariant(
toolId: string | null,
avatarRangeVariants: ToolCursorVariantState,
outsideRangeVariants: ToolCursorVariantState,
isWithinAvatarRange: boolean,
): CursorVariant {
const avatarRangeVariant = toolId ? (avatarRangeVariants[toolId] ?? 'primary') : 'primary';
const outsideRangeVariant = toolId ? (outsideRangeVariants[toolId] ?? 'primary') : 'primary';
if (toolId === 'lollipop') {
return avatarRangeVariant;
}
if (toolId === 'hammer') {
return isWithinAvatarRange
? 'primary'
: outsideRangeVariant;
}
return isWithinAvatarRange ? avatarRangeVariant : outsideRangeVariant;
}
function createDefaultToolCursorVariantState(): ToolCursorVariantState {
return Object.fromEntries(toolIconItems.map(item => [item.id, 'primary'])) as ToolCursorVariantState;
}
function createAvatarInteractionId(): string {
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
return `avatar-int-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
}
function sanitizeInteractionTextContext(text: string): string | undefined {
const trimmed = text.trim();
if (!trimmed) return undefined;
return trimmed.length > 80 ? trimmed.slice(0, 80).trimEnd() : trimmed;
}
export default function App({
title = i18n('chat.title', 'N.E.K.O Chat'),
iconSrc = '/static/icons/chat_icon.png',
messages = defaultMessages,
inputPlaceholder = i18n('chat.textInputPlaceholder', 'Type a message...'),
sendButtonLabel = i18n('chat.send', 'Send'),
chatWindowAriaLabel = i18n('chat.reactWindowAriaLabel', 'Neko chat window'),
messageListAriaLabel = i18n('chat.messageListAriaLabel', 'Chat messages'),
composerToolsAriaLabel = i18n('chat.composerToolsAriaLabel', 'Composer tools'),
composerHidden = false,
composerDisabled = false,
composerAttachments = [],
composerAttachmentsAriaLabel = i18n('chat.pendingImagesAriaLabel', 'Pending attachments'),
importImageButtonLabel = i18n('chat.importImage', 'Import Image'),
screenshotButtonLabel = i18n('chat.screenshot', 'Screenshot'),
importImageButtonAriaLabel,
screenshotButtonAriaLabel,
removeAttachmentButtonAriaLabel = i18n('chat.removePendingImage', 'Remove image'),
failedStatusLabel = i18n('chat.messageFailed', 'Failed'),
jukeboxButtonLabel = i18n('chat.jukeboxLabel', 'Jukebox'),
jukeboxButtonAriaLabel = i18n('chat.jukebox', 'Jukebox'),
translateEnabled = false,
translateButtonLabel = i18n('subtitle.enable', 'Subtitle Translation'),
translateButtonAriaLabel,
galgameModeEnabled = false,
galgameOptions = [],
galgameOptionsLoading = false,
galgameToggleButtonLabel = i18n('chat.galgameToggle', 'GalGame Mode'),
galgameToggleButtonAriaLabel,
galgameLoadingLabel = i18n('chat.galgameLoading', '生成回复选项中…'),
onMessageAction,
onComposerImportImage,
onComposerScreenshot,
onComposerRemoveAttachment,
onComposerSubmit,
onAvatarInteraction,
onAvatarToolStateChange,
onJukeboxClick,
onTranslateToggle,
onGalgameModeToggle,
onGalgameOptionSelect,
quickActions,
quickActionsPreferences,
quickActionsLoading,
onQuickActionExecute,
onQuickActionsRequest,
onQuickActionsPreferencesChange,
choicePrompt = null,
onChoiceSelect,
rollbackDraft,
_rollbackKey,
_toolCursorResetKey,
}: ChatWindowProps) {
const [draft, setDraft] = useState('');
const [toolMenuOpen, setToolMenuOpen] = useState(false);
const [quickActionsPanelOpen, setQuickActionsPanelOpen] = useState(false);
const [quickActionsSlashMode, setQuickActionsSlashMode] = useState(false);
// 当 composer-bottom-bar 宽度 < 阈值时,把右侧 4 个工具按钮折叠成 ··· 菜单。
// 用四态机让进出过渡都跑完动画再切稳态:
// expanded → collapsing (右→左级联收起) → compact (··· 入场)
// compact → expanding (··· 退场) → expanded (左→右级联展开)
// 中途 resize 反向:collapsing↔expanded、expanding↔compact 直接跳回稳态。
type ComposerLayout = 'expanded' | 'collapsing' | 'compact' | 'expanding';
const [composerLayout, setComposerLayout] = useState<ComposerLayout>('expanded');
const showRightTools = composerLayout === 'expanded' || composerLayout === 'collapsing';
// 折叠瞬间记录右 4 按钮组的实际宽度,喂给 CSS keyframe 做 width 动画。
// 没这个 layout 不会跟着动画收缩,发送按钮就被"顶住"直到 scaleX 跑完。
const [collapseFromWidth, setCollapseFromWidth] = useState<number | null>(null);
const [overflowMenuOpen, setOverflowMenuOpen] = useState(false);
const [activeCursorToolId, setActiveCursorToolId] = useState<string | null>(null);
const [avatarRangeCursorVariants, setAvatarRangeCursorVariants] = useState<ToolCursorVariantState>(() => createDefaultToolCursorVariantState());
const [outsideRangeCursorVariants, setOutsideRangeCursorVariants] = useState<ToolCursorVariantState>(() => createDefaultToolCursorVariantState());
const [isCursorOverAvatarRange, setIsCursorOverAvatarRange] = useState(false);
const [isCursorOverCompactCursorZone, setIsCursorOverCompactCursorZone] = useState(false);
const [isCursorInsideHostWindow, setIsCursorInsideHostWindow] = useState(true);
const [hammerSwingPhase, setHammerSwingPhase] = useState<'idle' | 'windup' | 'swing' | 'impact' | 'recover'>('idle');
const [isInnerHammerEasterEggActive, setIsInnerHammerEasterEggActive] = useState(false);
const toolMenuRef = useRef<HTMLDivElement | null>(null);
const composerBottomBarRef = useRef<HTMLDivElement | null>(null);
const composerToolsRightRef = useRef<HTMLDivElement | null>(null);
// 镜像 composerLayout 到 ref,让 ResizeObserver 闭包能读到最新稳态
const composerLayoutRef = useRef<ComposerLayout>('expanded');
const overflowMenuRef = useRef<HTMLDivElement | null>(null);
const avatarCursorOverlayRef = useRef<HTMLDivElement | null>(null);
const hammerCursorOverlayRef = useRef<HTMLDivElement | null>(null);
const hammerSwingTimeoutIdsRef = useRef<number[]>([]);
const outsideHammerResetTimeoutRef = useRef<number | null>(null);
const floatingHeartIdRef = useRef(0);
const floatingHeartTimeoutIdsRef = useRef<number[]>([]);
const floatingFistDropIdRef = useRef(0);
const floatingFistDropTimeoutIdsRef = useRef<number[]>([]);
const interactionBurstHistoryRef = useRef<Record<string, number[]>>({});
const latestPointerPositionRef = useRef({ x: 0, y: 0 });
const latestPointerTargetRef = useRef<EventTarget | null>(null);
const avatarRangeHoldUntilRef = useRef(0);
const avatarRangeHoldTimerRef = useRef<number | null>(null);
const draftRef = useRef(draft);
const avatarInteractionCallbackRef = useRef(onAvatarInteraction);
const avatarToolCacheState = useMemo<AvatarToolCacheState>(() => ({
loadedCursorImageCache: new Map<string, Promise<HTMLImageElement>>(),
compactCursorValueCache: new Map<string, Promise<string>>(),
avatarBoundsCacheTtlMs: 80,
avatarBoundsCache: {
expiresAt: 0,
entries: [],
},
}), []);
const [floatingHearts, setFloatingHearts] = useState<FloatingHeart[]>([]);
const [floatingFistDrops, setFloatingFistDrops] = useState<FloatingFistDrop[]>([]);
const submittingRef = useRef(false);
const composerTextareaRef = useRef<HTMLTextAreaElement | null>(null);
const lastRollbackKeyRef = useRef('');
const lastToolCursorResetKeyRef = useRef('');
const canSubmit = !composerDisabled && (draft.trim().length > 0 || composerAttachments.length > 0);
const clearActiveCursorToolSelection = useCallback(() => {
clearGlobalToolCursorState();
latestPointerTargetRef.current = null;
avatarRangeHoldUntilRef.current = 0;
if (avatarRangeHoldTimerRef.current !== null) {
window.clearTimeout(avatarRangeHoldTimerRef.current);
avatarRangeHoldTimerRef.current = null;
}
setActiveCursorToolId(null);
setToolMenuOpen(false);
setIsCursorOverAvatarRange(false);
setIsCursorOverCompactCursorZone(false);
}, []);
const setCursorOverAvatarRange = useCallback((nextValue: boolean, options?: { allowHold?: boolean }) => {
if (avatarRangeHoldTimerRef.current !== null) {
window.clearTimeout(avatarRangeHoldTimerRef.current);
avatarRangeHoldTimerRef.current = null;
}
if (nextValue) {
const holdUntil = performance.now() + avatarToolRangeHoldMs;
avatarRangeHoldUntilRef.current = holdUntil;
setIsCursorOverAvatarRange(previousValue => (
previousValue === true ? previousValue : true
));
return;
}
setIsCursorOverAvatarRange(previousValue => {
const shouldHold = options?.allowHold !== false
&& previousValue
&& performance.now() <= avatarRangeHoldUntilRef.current;
if (shouldHold) {
if (avatarRangeHoldTimerRef.current === null) {
const delay = Math.max(0, avatarRangeHoldUntilRef.current - performance.now());
avatarRangeHoldTimerRef.current = window.setTimeout(() => {
avatarRangeHoldTimerRef.current = null;
if (performance.now() < avatarRangeHoldUntilRef.current) return;
avatarRangeHoldUntilRef.current = 0;
setIsCursorOverAvatarRange(currentValue => (currentValue ? false : currentValue));
}, delay);
}
return true;
}
if (avatarRangeHoldTimerRef.current !== null) {
window.clearTimeout(avatarRangeHoldTimerRef.current);
avatarRangeHoldTimerRef.current = null;
}
if (avatarRangeHoldUntilRef.current !== 0) {
avatarRangeHoldUntilRef.current = 0;
}
return previousValue ? false : previousValue;
});
}, []);
// Rollback draft when host signals a RESPONSE_TOO_LONG error
// Use _rollbackKey for dedup — it changes on every rollbackLastDraft() call
// and stays the same across intermediate renderWindow() calls, so the rollback
// is applied exactly once regardless of how many times renderWindow fires.
useEffect(() => {
if (rollbackDraft && _rollbackKey && _rollbackKey !== lastRollbackKeyRef.current) {
lastRollbackKeyRef.current = _rollbackKey;
if (!draft || draft.trim() === '') {
setDraft(rollbackDraft);
}
}
}, [rollbackDraft, _rollbackKey, draft]);
useEffect(() => {
if (_toolCursorResetKey && _toolCursorResetKey !== lastToolCursorResetKeyRef.current) {
lastToolCursorResetKeyRef.current = _toolCursorResetKey;
clearActiveCursorToolSelection();
}
}, [_toolCursorResetKey, clearActiveCursorToolSelection]);
useEffect(() => {
const markImage = (img: HTMLImageElement) => {
img.draggable = false;
img.setAttribute('draggable', 'false');
};
const markImages = (root: ParentNode | HTMLImageElement = document) => {
if (root instanceof HTMLImageElement) {
markImage(root);
return;
}
root.querySelectorAll?.<HTMLImageElement>('img').forEach(markImage);
};
const handleDragStart = (event: DragEvent) => {
if (event.target instanceof HTMLImageElement) {
event.preventDefault();
}
};
markImages(document);
document.addEventListener('dragstart', handleDragStart, true);
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (node instanceof Element) {
markImages(node);
}
});
});
});
observer.observe(document.documentElement, { childList: true, subtree: true });
return () => {
observer.disconnect();
document.removeEventListener('dragstart', handleDragStart, true);
};
}, []);
const resolvedImportImageAriaLabel = importImageButtonAriaLabel || importImageButtonLabel;
const resolvedScreenshotAriaLabel = screenshotButtonAriaLabel || screenshotButtonLabel;
const resolvedTranslateAriaLabel = translateButtonAriaLabel || translateButtonLabel;
const resolvedGalgameAriaLabel = galgameToggleButtonAriaLabel || galgameToggleButtonLabel;
// ChoicePrompt(mini-game invite 等)和 galgame options 共用 composer 底部
// 同一块 slot 视觉位。两者同时活跃会渲染出 6 个按钮挤一起;invite 是少见
// 且需要用户即时响应的 transient event,galgame options 是常驻 mode →
// invite 优先,galgame slot 临时让位。invite resolve 后下一轮 assistant
// turn-end 会重新触发 galgame fetch,自然回归。
const choicePromptHasOptions = !!(choicePrompt && choicePrompt.options.length > 0);
// 模式开启 ≠ 选项实际占位。光开开关、还没收到 AI 新一轮时 slot 不撑开;
// 选项到位(loading 占位也算)才让 slot 长出来,输入壳跟着自然变高。
const galgameOptionsVisible =
galgameModeEnabled && !choicePromptHasOptions
&& (galgameOptionsLoading || galgameOptions.length > 0);
const emojiButtonAriaLabel = i18n('chat.emojiButtonAriaLabel', 'Emoji');
const toolIconsAriaLabel = i18n('chat.toolIconsAriaLabel', 'Tool icons');
const clearCursorToolAriaLabel = i18n('chat.clearCursorToolAriaLabel', '恢复鼠标');
const overflowMenuAriaLabel = i18n('chat.composerOverflowMenu', '更多工具');
const effectiveCursorVariant = resolveEffectiveCursorVariant(
activeCursorToolId,
avatarRangeCursorVariants,
outsideRangeCursorVariants,
isCursorOverAvatarRange,
);
const avatarRangeCursorVariant = activeCursorToolId
? (avatarRangeCursorVariants[activeCursorToolId] ?? 'primary')
: 'primary';
const activeToolItem = toolIconItems.find(item => item.id === activeCursorToolId) ?? null;
const activeToolImagePaths = activeToolItem
? resolveToolImagePaths(activeToolItem, avatarRangeCursorVariant)
: null;
const isElectronMultiWindow = isElectronMultiWindowHost();
const shouldUseLocalDesktopCursorOverlay = !!activeToolItem
&& supportsDesktopFinePointer()
&& !isElectronMultiWindow;
const shouldRenderLocalDesktopCursorOverlay = shouldUseLocalDesktopCursorOverlay
&& isCursorInsideHostWindow;
const shouldRenderAvatarRangeOverlay = isCursorOverAvatarRange && !isCursorOverCompactCursorZone;
const avatarCursorOverlayActive = !!activeToolItem
&& activeCursorToolId !== 'hammer'
&& shouldRenderLocalDesktopCursorOverlay;
const avatarCursorOverlayCompact = avatarCursorOverlayActive && !shouldRenderAvatarRangeOverlay;
const hammerCursorOverlayActive = activeCursorToolId === 'hammer' && shouldRenderLocalDesktopCursorOverlay;
const hammerCursorOverlayCompact = hammerCursorOverlayActive && !shouldRenderAvatarRangeOverlay;
const hammerCursorOverlayMotionActive = hammerSwingPhase !== 'idle';
const hammerCompactImagePaths = hammerToolItem
? resolveToolImagePaths(hammerToolItem, effectiveCursorVariant)
: null;
const hammerCursorOverlayUsesCompactImage = hammerCursorOverlayCompact && !hammerCursorOverlayMotionActive;
const avatarCursorOverlayImagePath = activeToolItem && activeCursorToolId !== 'hammer'
? (
avatarCursorOverlayCompact
? (activeToolImagePaths?.cursorImagePath ?? '')
: (activeToolImagePaths?.iconImagePath ?? '')
)
: '';
const hammerCursorOverlayCompactImagePath = hammerCursorOverlayUsesCompactImage
? (hammerCompactImagePaths?.cursorImagePath ?? '')
: '';
const hammerCursorOverlayPrimaryImagePath = hammerToolItem
? resolveToolImagePaths(hammerToolItem, 'primary').iconImagePath
: '';
const hammerCursorOverlaySecondaryImagePath = hammerToolItem
? resolveToolImagePaths(hammerToolItem, 'secondary').iconImagePath
: '';
const activeToolMenuVisual = activeToolItem
? resolveMenuIconVisual(activeToolItem, effectiveCursorVariant)
: null;
const activeToolLabel = activeToolItem ? getToolItemLabel(activeToolItem) : '';
const selectedEmojiButtonAriaLabel = activeToolItem
? `${emojiButtonAriaLabel}: ${activeToolLabel}`
: emojiButtonAriaLabel;
const isCursorWithinAvatarToolRange = isCursorInsideHostWindow
&& isCursorOverAvatarRange
&& !isCursorOverCompactCursorZone;
const avatarToolImageKind = activeToolItem
? (isCursorWithinAvatarToolRange ? 'icon' : 'cursor')
: 'cursor';
useEffect(() => {
draftRef.current = draft;
}, [draft]);
useEffect(() => {
avatarInteractionCallbackRef.current = onAvatarInteraction;
}, [onAvatarInteraction]);
useEffect(() => {
if (!onAvatarToolStateChange) return;
const outsideRangeVariant = activeCursorToolId
? (outsideRangeCursorVariants[activeCursorToolId] ?? 'primary')
: 'primary';
const textContext = sanitizeInteractionTextContext(draft);
onAvatarToolStateChange({
active: !!activeToolItem,
toolId: activeToolItem?.id ?? null,
variant: effectiveCursorVariant,
avatarRangeVariant: avatarRangeCursorVariant,
outsideRangeVariant,
imageKind: avatarToolImageKind,
withinAvatarRange: isCursorWithinAvatarToolRange,
overCompactZone: isCursorOverCompactCursorZone,
insideHostWindow: isCursorInsideHostWindow,
tool: activeToolItem
? {
id: activeToolItem.id,
label: getToolItemLabel(activeToolItem),
iconImagePath: activeToolItem.iconImagePath,
iconImagePathAlt: activeToolItem.iconImagePathAlt,
iconImagePathAlt2: activeToolItem.iconImagePathAlt2,
cursorImagePath: activeToolItem.cursorImagePath,
cursorImagePathAlt: activeToolItem.cursorImagePathAlt,
cursorImagePathAlt2: activeToolItem.cursorImagePathAlt2,
cursorHotspotX: activeToolItem.cursorHotspotX,
cursorHotspotY: activeToolItem.cursorHotspotY,
menuIconScale: activeToolItem.menuIconScale,
}
: null,
textContext,
timestamp: Date.now(),
});
}, [
activeCursorToolId,
activeToolItem,
avatarRangeCursorVariant,
draft,
effectiveCursorVariant,
avatarToolImageKind,
isCursorInsideHostWindow,
isCursorOverCompactCursorZone,
isCursorWithinAvatarToolRange,
onAvatarToolStateChange,
outsideRangeCursorVariants,
]);
function clearHammerSwingAnimation() {
hammerSwingTimeoutIdsRef.current.forEach(timeoutId => window.clearTimeout(timeoutId));
hammerSwingTimeoutIdsRef.current = [];
setHammerSwingPhase('idle');
setIsInnerHammerEasterEggActive(false);
}
function clearOutsideHammerResetTimer(shouldResetToPrimary = true) {
if (outsideHammerResetTimeoutRef.current !== null) {
window.clearTimeout(outsideHammerResetTimeoutRef.current);
outsideHammerResetTimeoutRef.current = null;
}
if (shouldResetToPrimary) {
setOutsideRangeCursorVariants(prev => ({ ...prev, hammer: 'primary' }));
}
}
function spawnLollipopHearts(clientX: number, clientY: number) {
const hearts: FloatingHeart[] = [
{ id: floatingHeartIdRef.current += 1, x: clientX - 12, y: clientY - 26, driftX: -26, driftY: -124, scale: 0.92, delayMs: 0 },
{ id: floatingHeartIdRef.current += 1, x: clientX + 10, y: clientY - 20, driftX: 24, driftY: -138, scale: 1.06, delayMs: 110 },
{ id: floatingHeartIdRef.current += 1, x: clientX - 4, y: clientY - 40, driftX: -18, driftY: -154, scale: 0.84, delayMs: 190 },
];
setFloatingHearts(prev => [...prev, ...hearts]);
hearts.forEach(heart => {
const timeoutId = window.setTimeout(() => {
setFloatingHearts(prev => prev.filter(item => item.id !== heart.id));
floatingHeartTimeoutIdsRef.current = floatingHeartTimeoutIdsRef.current.filter(id => id !== timeoutId);
}, 2100 + heart.delayMs);
floatingHeartTimeoutIdsRef.current.push(timeoutId);
});
}
function spawnFistDrops(clientX: number, clientY: number) {
const drops: FloatingFistDrop[] = Array.from({ length: 3 }, () => {
const launchAngleDeg = -140 + Math.random() * 100;
const launchAngleRad = (launchAngleDeg * Math.PI) / 180;
const distance = 76 + Math.random() * 42;
return {
id: floatingFistDropIdRef.current += 1,
x: clientX - 8 + (Math.random() * 28 - 14),
y: clientY - 24 + (Math.random() * 18 - 9),
driftX: Math.round(Math.cos(launchAngleRad) * distance),
driftY: Math.round(Math.sin(launchAngleRad) * distance),
rotation: Math.round(-120 + Math.random() * 240),
scale: Number((0.82 + Math.random() * 0.38).toFixed(2)),
delayMs: Math.round(Math.random() * 140),
};
});
setFloatingFistDrops(prev => [...prev, ...drops]);
drops.forEach(drop => {
const timeoutId = window.setTimeout(() => {
setFloatingFistDrops(prev => prev.filter(item => item.id !== drop.id));
floatingFistDropTimeoutIdsRef.current = floatingFistDropTimeoutIdsRef.current.filter(id => id !== timeoutId);
}, 920 + drop.delayMs);
floatingFistDropTimeoutIdsRef.current.push(timeoutId);
});