-
Notifications
You must be signed in to change notification settings - Fork 159
Expand file tree
/
Copy pathApp.tsx
More file actions
5311 lines (4965 loc) · 216 KB
/
App.tsx
File metadata and controls
5311 lines (4965 loc) · 216 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,
type MouseEvent as ReactMouseEvent,
type PointerEvent as ReactPointerEvent,
type WheelEvent as ReactWheelEvent,
} from 'react';
import { createPortal } from 'react-dom';
import AvatarToolItemManager, { type AvatarToolManagerAnchorRect } from './AvatarToolItemManager';
import AvatarToolQuickbar from './AvatarToolQuickbar';
import CompactExportHistoryPanel, {
COMPACT_EXPORT_SELECTION_LIMIT,
isCompactExportMessageSelectable,
type CompactExportActionRequest,
type CompactExportPreviewResult,
type CompactHistoryDropRequest,
} from './CompactExportHistoryPanel';
import { i18n } from './i18n';
import {
type ChatMessage,
type MessageAction,
type ChatWindowSchemaProps,
type ComposerSubmitPayload,
type ComposerAttachment,
type CompactHistoryDropPayload,
type CompactHistoryDragStatePayload,
type AvatarInteractionPayload,
type AvatarToolStatePayload,
type CompactChatState,
type MessageBlock,
type GalgameOption,
type ChoiceOption,
type ChoicePromptSource,
} from './message-schema';
import {
AVAILABLE_AVATAR_TOOLS,
persistActiveAvatarToolIds,
readPersistedActiveAvatarToolIds,
resolveAvatarToolImagePaths,
sanitizeAvatarToolIds,
withAvatarToolAssetVersion,
type AvatarToolId,
type AvatarToolItem,
type CursorVariant,
} from './avatarTools';
export type ChatWindowProps = ChatWindowSchemaProps & {
onMessageAction?: (message: ChatMessage, action: MessageAction) => void;
onComposerImportImage?: () => void;
onComposerScreenshot?: () => void;
onComposerRemoveAttachment?: (attachmentId: ComposerAttachment['id']) => void;
onComposerSubmit?: (payload: ComposerSubmitPayload) => void;
onCompactHistoryDrop?: (payload: CompactHistoryDropPayload) => unknown;
onCompactHistoryDragStateChange?: (payload: CompactHistoryDragStatePayload) => void;
onAvatarInteraction?: (payload: AvatarInteractionPayload) => void;
onAvatarToolStateChange?: (payload: AvatarToolStatePayload) => void;
onJukeboxClick?: () => void;
onExportConversationClick?: () => void;
onTranslateToggle?: () => void;
onGalgameModeToggle?: () => void;
onGalgameOptionSelect?: (option: GalgameOption) => void;
// ChoicePrompt remains part of ChatWindowSchemaProps. Keep the legacy galgame
// callback path until the host fully migrates to the shared choice slot.
onChoiceSelect?: (option: ChoiceOption, source: ChoicePromptSource) => void;
onCompactChatStateChange?: (state: CompactChatState) => void;
};
type CompactInlineExportBridge = {
buildCompactInlinePreview?: (request: CompactExportActionRequest) => Promise<CompactExportPreviewResult> | CompactExportPreviewResult;
copyCompactInlineSelection?: (request: CompactExportActionRequest) => Promise<void> | void;
downloadCompactInlineSelection?: (request: CompactExportActionRequest) => Promise<void> | void;
};
const defaultMessages: ChatMessage[] = [];
function getEffectiveCompactChatState(
requestedState: CompactChatState,
hasVisibleChoices: boolean,
composerHidden: boolean,
): CompactChatState {
if (composerHidden) {
return 'default';
}
if (requestedState === 'input') {
return 'input';
}
if (hasVisibleChoices) {
return 'options';
}
if (requestedState === 'options') {
return 'default';
}
return requestedState;
}
const COMPACT_SPEECH_REVEAL_MAX_CHARS_PER_SECOND = 8;
const COMPACT_SPEECH_TURN_MERGE_WINDOW_MS = 12000;
const COMPACT_SPEECH_FALLBACK_REVEAL_DELAY_MS = 700;
const SPEECH_PLAYBACK_STATE_STORAGE_KEY = 'neko_speech_playback_state';
const SPEECH_PLAYBACK_CHANNEL_NAME = 'neko_speech_playback_channel';
const COMPACT_EXPORT_HISTORY_OPEN_STORAGE_KEY = 'neko.reactChatWindow.compactExportHistoryOpen';
export const COMPACT_EXPORT_HISTORY_VISIBILITY_ANIMATION_MS = 560;
const COMPACT_INPUT_TOOL_WHEEL_ITEM_COUNT = 7;
const COMPACT_INPUT_TOOL_WHEEL_DRAG_THRESHOLD = 22;
const COMPACT_INPUT_TOOL_WHEEL_SCROLL_THRESHOLD = 64;
const COMPACT_INPUT_TOOL_WHEEL_DRAG_GUARD_MS = 4000;
const COMPACT_INPUT_TOOL_WHEEL_FAST_GESTURE_MS = 140;
const COMPACT_INPUT_TOOL_WHEEL_FAST_ANIMATION_MS = 180;
const COMPACT_INPUT_TOOL_WHEEL_CHARGE_START_STEPS = COMPACT_INPUT_TOOL_WHEEL_ITEM_COUNT * 4;
const COMPACT_INPUT_TOOL_WHEEL_CHARGE_LAP_STEPS = COMPACT_INPUT_TOOL_WHEEL_ITEM_COUNT * 2;
const COMPACT_INPUT_TOOL_WHEEL_CHARGE_MAX_STEPS = COMPACT_INPUT_TOOL_WHEEL_CHARGE_LAP_STEPS * 2;
const COMPACT_INPUT_TOOL_WHEEL_CHARGE_RELEASE_STEP_MS = 36;
const COMPACT_INPUT_TOOL_WHEEL_CENTER_X = 116;
const COMPACT_INPUT_TOOL_WHEEL_CENTER_Y = 116;
// Drag-to-rotate sensitivity scalar (arc = radius * angleDelta), NOT a layout
// value. Kept at 91.92 so the rotate-by-drag feel is unchanged even though the
// visual orbit radius (--compact-tool-wheel-orbit-radius in styles.css) was
// halved — the angle itself is measured from real geometry, this only scales
// how much angular travel counts as one step.
const COMPACT_INPUT_TOOL_WHEEL_ORBIT_RADIUS = 91.92;
const COMPACT_INPUT_TOOL_WHEEL_HOVER_RADIUS = 116;
const COMPACT_INPUT_TOOL_WHEEL_ANGLE_MIN_RADIUS = 16;
const COMPACT_INPUT_TOOL_TOGGLE_HOVER_OUTSET = 14;
const COMPACT_INPUT_TOOL_FAN_ORIGIN_CLOSE_SIZE = 48;
// 在工具轮盘中心(toggle / fan 原点)按下后,指针移动超过此像素阈值即视为「拖动文本框」
// 而非「点一下展开/关闭轮盘」。与宿主 surface 拖拽的 CLICK_THRESHOLD(5px) 量级一致。
const COMPACT_INPUT_TOOL_ORIGIN_DRAG_THRESHOLD = 6;
const COMPACT_INPUT_TOOL_FAN_INTERACTIVE_DELAY_MS = 220;
const COMPACT_INPUT_TOOL_FAN_TRANSIENT_CLOSE_DELAY_MS = 360;
const COMPACT_INPUT_TOOL_FAN_OUTSIDE_CLOSE_DELAY_MS = 650;
const COMPACT_SURFACE_RESIZE_MIN_WIDTH = 430;
const COMPACT_SURFACE_RESIZE_MAX_WIDTH = 720;
const COMPACT_SURFACE_RESIZE_VIEWPORT_GUTTER = 32;
const COMPACT_CHOICE_PLACEMENT_HYSTERESIS = 24;
type CompactSurfaceResizeSide = 'left' | 'right';
type CompactSurfaceResizeState = {
pointerId: number;
side: CompactSurfaceResizeSide;
startPointerX: number;
startWidth: number;
lastWidth: number;
anchorLeftScreen: number;
anchorRightScreen: number;
anchorTopScreen: number;
surfaceHeight: number;
captureTarget: Element | null;
};
function createCompactHistoryDropRequestId() {
return `compact-history-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
}
function normalizeCompactHistoryTextFragment(value: string | undefined) {
return typeof value === 'string' ? value.trim() : '';
}
function getCompactHistoryTextFromBlock(block: MessageBlock) {
if (block.type === 'text' || block.type === 'status') {
return normalizeCompactHistoryTextFragment(block.text);
}
if (block.type === 'link') {
return [
normalizeCompactHistoryTextFragment(block.title),
normalizeCompactHistoryTextFragment(block.description),
normalizeCompactHistoryTextFragment(block.url),
].filter(Boolean).join('\n');
}
if (block.type === 'buttons') {
return block.buttons
.map(button => normalizeCompactHistoryTextFragment(button.label))
.filter(Boolean)
.join(' / ');
}
return '';
}
function buildCompactHistoryDropPayload(request: CompactHistoryDropRequest): CompactHistoryDropPayload {
const textParts: string[] = [];
const images: NonNullable<CompactHistoryDropPayload['images']> = [];
if (request.payload.type === 'image') {
images.push({
url: request.payload.url,
alt: request.payload.alt,
width: request.payload.width,
height: request.payload.height,
});
} else {
for (const block of request.payload.blocks) {
if (block.type === 'image') {
images.push({
url: block.url,
alt: block.alt,
width: block.width,
height: block.height,
});
continue;
}
const text = getCompactHistoryTextFromBlock(block);
if (text) {
textParts.push(text);
}
}
}
return {
text: textParts.join('\n').trim(),
images,
requestId: createCompactHistoryDropRequestId(),
sourceMessageId: request.messageId,
dragType: request.type,
compactHistoryDragSessionId: request.sessionId,
};
}
function normalizeCompactHistoryDropResult(result: unknown): Promise<boolean | void> | boolean | void {
if (result && typeof (result as PromiseLike<unknown>).then === 'function') {
return Promise.resolve(result).then(value => (value === false ? false : undefined));
}
return result === false ? false : undefined;
}
type CompactToolWheelPointerState = {
id: number;
x: number;
y: number;
angle: number | null;
angleRemainder: number;
didRotate: boolean;
captureTarget: Element | null;
};
type CompactToolWheelChargeState = {
direction: 1 | -1 | null;
sameDirectionSteps: number;
chargeSteps: number;
};
type CompactToolWheelDragPoint = {
x: number;
y: number;
angle: number | null;
};
type CompactToolWheelDragInput = {
pointerId: number;
clientX: number;
clientY: number;
buttons?: number;
pointerType?: string;
preventDefault?: () => void;
};
function normalizeCompactToolWheelAngleDelta(delta: number): number {
const fullTurn = Math.PI * 2;
return ((((delta + Math.PI) % fullTurn) + fullTurn) % fullTurn) - Math.PI;
}
function getCompactToolWheelTimestamp(): number {
return window.performance?.now?.() ?? Date.now();
}
function createCompactToolWheelChargeState(): CompactToolWheelChargeState {
return {
direction: null,
sameDirectionSteps: 0,
chargeSteps: 0,
};
}
type CompactMessagePreview = {
messageId: string;
// Stable identity of the whole merged turn: the id of the earliest message
// folded into this preview. Unchanged as more bubbles stream into the same
// turn (messageId re-keys to the latest bubble, this does not), and changes
// when a genuinely new turn begins. Used to tell an appended bubble from a
// new turn without relying on text-prefix matching.
turnStartId: string;
turnId?: string;
author: string;
text: string;
fullText: string;
isStreaming: boolean;
isAssistant: boolean;
};
type CompactCaptionState = {
turnId: string;
segmentId: string;
lastSegmentText: string;
segments: Array<{
segmentId: string;
text: string;
}>;
text: string;
isEnded?: boolean;
};
type DesktopCompactChoicePlacementLayout = {
compactChoicePlacement?: 'above' | 'below' | null;
surface?: {
left?: number;
top?: number;
width?: number;
height?: number;
} | null;
windowBounds?: {
x?: number;
y?: number;
width?: number;
height?: number;
} | null;
workArea?: {
x?: number;
y?: number;
width?: number;
height?: number;
} | null;
};
function clampCompactSurfaceResizeWidth(width: number, maxAvailableWidth: number): number {
const maxWidth = Math.max(
0,
Math.min(COMPACT_SURFACE_RESIZE_MAX_WIDTH, maxAvailableWidth - COMPACT_SURFACE_RESIZE_VIEWPORT_GUTTER),
);
const minWidth = Math.min(COMPACT_SURFACE_RESIZE_MIN_WIDTH, maxWidth || COMPACT_SURFACE_RESIZE_MIN_WIDTH);
return Math.round(Math.max(minWidth, Math.min(width, Math.max(minWidth, maxWidth))));
}
function getCompactSurfaceResizePointerX(event: ReactPointerEvent<HTMLDivElement>): number {
const screenX = Number(event.screenX);
if (Number.isFinite(screenX)) {
return screenX;
}
return event.clientX;
}
function isDesktopCompactSurfaceLayoutActive(): boolean {
return typeof window !== 'undefined'
&& !!(window as typeof window & {
__nekoDesktopCompactLayout?: { windowBounds?: unknown } | null;
}).__nekoDesktopCompactLayout?.windowBounds;
}
function readPersistedCompactExportHistoryOpen(): boolean {
if (typeof window === 'undefined') return true;
try {
const persisted = window.localStorage?.getItem(COMPACT_EXPORT_HISTORY_OPEN_STORAGE_KEY);
return persisted === null ? true : persisted === 'true';
} catch {
return true;
}
}
function persistCompactExportHistoryOpen(open: boolean) {
if (typeof window === 'undefined') return;
try {
window.localStorage?.setItem(COMPACT_EXPORT_HISTORY_OPEN_STORAGE_KEY, open ? 'true' : 'false');
} catch {
// localStorage can be unavailable in restricted hosts; keep the in-memory state.
}
}
type SpeechPlaybackState = {
active: boolean;
turnId?: string | null;
playbackTurnId?: string | null;
speechId?: string | null;
audioContextTime: number;
playbackStartAudioTime: number;
playbackEndAudioTime: number;
updatedAt: number;
};
function normalizeCompactPreviewText(text: string): string {
return text
.replace(/\[play_music:[^\]]*(\]|$)/g, '')
.replace(/\s+/g, ' ')
.trim();
}
function splitCompactPreviewGraphemes(text: string): string[] {
const segmenter = (Intl as typeof Intl & {
Segmenter?: new (
locale?: string,
options?: { granularity?: 'grapheme' },
) => { segment(input: string): Iterable<{ segment: string }> };
}).Segmenter;
if (typeof segmenter === 'function') {
return Array.from(new segmenter(undefined, { granularity: 'grapheme' }).segment(text), part => part.segment);
}
return Array.from(text);
}
function getCompactSpeechRevealDuration(textLength: number, audioDuration: number): number {
const readableDuration = textLength / COMPACT_SPEECH_REVEAL_MAX_CHARS_PER_SECOND;
return Math.max(audioDuration, readableDuration, 0.05);
}
function getEstimatedSpeechAudioTime(state: SpeechPlaybackState): number {
if (!state.active) {
return state.audioContextTime;
}
const elapsedSinceUpdate = Math.max(0, (Date.now() - state.updatedAt) / 1000);
return state.audioContextTime + elapsedSinceUpdate;
}
function isSpeechPlaybackStateForCompactPreview(
state: SpeechPlaybackState | null,
preview: { turnId?: string } | null,
): state is SpeechPlaybackState {
if (!state) return false;
const previewTurnId = preview?.turnId;
if (!previewTurnId) return true;
const stateTurnIds = [state.playbackTurnId, state.turnId].filter((value): value is string => !!value);
if (stateTurnIds.length === 0) return true;
return stateTurnIds.includes(previewTurnId);
}
function getMessageBlockPreviewText(message: ChatMessage): string {
if (!Array.isArray(message.blocks)) {
return '';
}
const text = message.blocks.flatMap((block) => {
switch (block.type) {
case 'text':
case 'status':
return [block.text];
case 'link':
return [block.title || block.description || block.url];
default:
return [];
}
}).join(' ');
return normalizeCompactPreviewText(text);
}
function getCompactMessagePreview(messages: ChatMessage[]): CompactMessagePreview | null {
let latestStreamingAssistantIndex = -1;
for (let index = messages.length - 1; index >= 0; index -= 1) {
const message = messages[index];
if (
message?.role === 'assistant'
&& message.status === 'streaming'
&& getMessageBlockPreviewText(message)
) {
latestStreamingAssistantIndex = index;
break;
}
}
if (latestStreamingAssistantIndex >= 0) {
const turnTexts: string[] = [];
let turnAuthor = '';
const latestStreamingMessage = messages[latestStreamingAssistantIndex];
const latestStreamingTurnId = latestStreamingMessage?.turnId;
const turnMessageId = String(latestStreamingMessage?.id || 'assistant-streaming');
// Walks backward to the earliest merged bubble, so the last assignment in
// the loop is the turn's anchor id.
let turnStartId = latestStreamingTurnId ? `assistant-turn:${latestStreamingTurnId}` : turnMessageId;
let previousIncludedCreatedAt = typeof latestStreamingMessage?.createdAt === 'number'
&& Number.isFinite(latestStreamingMessage.createdAt)
? latestStreamingMessage.createdAt
: null;
for (let index = latestStreamingAssistantIndex; index >= 0; index -= 1) {
const message = messages[index];
if (!message) continue;
if (message.role !== 'assistant') {
break;
}
if (index !== latestStreamingAssistantIndex && latestStreamingTurnId && message.turnId !== latestStreamingTurnId) {
break;
}
if (index !== latestStreamingAssistantIndex && message.status !== 'streaming') {
const createdAt = typeof message.createdAt === 'number' && Number.isFinite(message.createdAt)
? message.createdAt
: null;
if (!latestStreamingTurnId && (
previousIncludedCreatedAt === null
|| createdAt === null
|| Math.abs(previousIncludedCreatedAt - createdAt) > COMPACT_SPEECH_TURN_MERGE_WINDOW_MS
)) {
break;
}
previousIncludedCreatedAt = createdAt;
}
// Anchor the turn to every message folded in, before the empty-text skip.
// A bubble can be momentarily text-less (still streaming, image-only) then
// gain text; if the anchor only moved on text-bearing bubbles it would
// drift to a later bubble and back, re-keying the same turn as a new one
// and replaying the caption.
if (!latestStreamingTurnId) {
turnStartId = String(message.id || turnMessageId);
}
const text = getMessageBlockPreviewText(message);
if (!text) continue;
turnTexts.unshift(text);
turnAuthor = message.author || turnAuthor;
}
if (turnTexts.length > 0) {
const turnText = normalizeCompactPreviewText(turnTexts.join(' '));
return {
messageId: turnMessageId || 'assistant-streaming',
turnStartId,
turnId: latestStreamingTurnId,
author: turnAuthor,
text: turnText,
fullText: turnText,
isStreaming: true,
isAssistant: true,
};
}
}
return null;
}
type ToolIconItem = AvatarToolItem;
const toolIconItems = AVAILABLE_AVATAR_TOOLS;
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',
'.compact-input-tool-fan',
'.compact-input-tool-toggle',
'.avatar-tool-quickbar',
'.avatar-tool-manager-overlay',
'.avatar-tool-manager-dialog',
'.compact-export-history-anchor',
'.compact-history-visibility-handle',
'.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 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 CompactHistoryDesktopDropTargetDetail = {
active?: boolean;
sessionId?: string;
desktopOverAvatar?: boolean | null;
timestamp?: number;
};
function normalizeHostAvatarBounds(bounds: unknown): HostAvatarBounds | null {
if (!bounds || typeof bounds !== 'object') return null;
const raw = bounds as Partial<HostAvatarBounds>;
const left = Number(raw.left);
const top = Number(raw.top);
const width = Number(raw.width);
const height = Number(raw.height);
if (
!Number.isFinite(left)
|| !Number.isFinite(top)
|| !Number.isFinite(width)
|| !Number.isFinite(height)
|| width <= 0
|| height <= 0
) {
return null;
}
const right = Number.isFinite(Number(raw.right)) ? Number(raw.right) : left + width;
const bottom = Number.isFinite(Number(raw.bottom)) ? Number(raw.bottom) : top + height;
return {
left,
top,
right,
bottom,
width,
height,
centerX: Number.isFinite(Number(raw.centerX)) ? Number(raw.centerX) : left + width / 2,
centerY: Number.isFinite(Number(raw.centerY)) ? Number(raw.centerY) : top + height / 2,
};
}
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 resolveAvatarToolImagePaths(item, variant);
}
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;
__nekoDesktopAvatarBounds?: HostAvatarBounds | null;
};
const desktopAvatarBounds = normalizeHostAvatarBounds(hostWindow.__nekoDesktopAvatarBounds);
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: [
...(desktopAvatarBounds ? [{ bounds: desktopAvatarBounds }] : []),
...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)}`;
}