-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathtimeline.js
More file actions
2130 lines (1889 loc) · 64.7 KB
/
Copy pathtimeline.js
File metadata and controls
2130 lines (1889 loc) · 64.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
/*
* ChatGPT Conversation Toolkit - Timeline
*/
// ============ 时间线功能 ============
let timelineBoundScrollRoot = null;
let timelineWindowScrollBound = false;
const TIMELINE_SOURCE_SYNC_INTERVAL_MS = 140;
const TIMELINE_JUMP_RETRY_DELAY_MS = 180;
const TIMELINE_JUMP_RETRY_ATTEMPTS = 4;
const TIMELINE_JUMP_STEP_DELAY_MS = 72;
const TIMELINE_JUMP_STEP_MAX_STEPS = 6;
const TIMELINE_PROGRAMMATIC_JUMP_LOCK_MS = 35000;
let timelineJumpResolveTimer = null;
let timelineJumpScrollTimer = null;
let timelineProgrammaticJumpToken = 0;
let timelineProgrammaticJumpUntil = 0;
let timelineJumpUserIntentCleanup = null;
const TIMELINE_SCROLL_INTENT_KEYS = new Set([
"ArrowDown",
"ArrowUp",
"End",
"Home",
"PageDown",
"PageUp",
" ",
"Spacebar",
]);
const getTimelineElements = () => {
const timeline = document.getElementById(TIMELINE_ID);
if (!timeline) {
return null;
}
return {
timeline,
track: timeline.querySelector(`#${TIMELINE_TRACK_ID}`),
count: timeline.querySelector(`#${TIMELINE_COUNT_ID}`),
content: timeline.querySelector(`.${TIMELINE_CONTENT_CLASS}`),
preview: timeline.querySelector(`#${TIMELINE_PREVIEW_ID}`),
hint: timeline.querySelector(`#${TIMELINE_HINT_ID}`),
};
};
const ensureTimelineTrackContent = (track) => {
if (!(track instanceof HTMLElement)) {
return null;
}
const existingContent = track.querySelector(`.${TIMELINE_CONTENT_CLASS}`);
if (existingContent instanceof HTMLElement) {
return existingContent;
}
const content = document.createElement("div");
content.className = TIMELINE_CONTENT_CLASS;
while (track.firstChild) {
content.appendChild(track.firstChild);
}
track.appendChild(content);
return content;
};
const getTimelineMessageKey = (node, index) => {
if (!(node instanceof HTMLElement)) {
return `timeline-user-${index}`;
}
const messageId =
node.getAttribute("data-turn-id") ||
node.querySelector("[data-turn-id]")?.getAttribute("data-turn-id") ||
node.getAttribute("data-message-id") ||
node.querySelector("[data-message-id]")?.getAttribute("data-message-id") ||
"";
if (messageId) {
return `mid:${messageId}`;
}
const turnTestId =
node.getAttribute("data-testid") ||
node.querySelector('[data-testid^="conversation-turn-"]')?.getAttribute("data-testid") ||
"";
if (turnTestId) {
// Append index to avoid collisions when testid is duplicated in nested/virtualized structures.
return `tid:${turnTestId}:${index}`;
}
return `timeline-user-${index}`;
};
const getTimelineSourceKey = (source, index) => {
if (source instanceof HTMLElement) {
return getTimelineMessageKey(source, index);
}
return source?.key || `timeline-user-${index}`;
};
const isTimelineApiSource = (source) =>
!(source instanceof HTMLElement) && (source?.source === "api" || String(source?.key || "").startsWith("api:"));
const getTimelineSourceNode = (source, options = {}) => {
const { resolve = true } = options;
if (source instanceof HTMLElement) {
return source;
}
if (!resolve) {
return source?.node instanceof HTMLElement && source.node.isConnected ? source.node : null;
}
if (isTimelineApiSource(source) && typeof resolveMessageDomNode === "function") {
return resolveMessageDomNode(source);
}
if (typeof resolveCachedMessageNode === "function") {
return resolveCachedMessageNode(source);
}
return source?.node instanceof HTMLElement && source.node.isConnected ? source.node : null;
};
const getTimelineSourceText = (source) => {
if (source instanceof HTMLElement) {
return extractMessageText(source);
}
return source?.previewText || source?.text || "";
};
const getTimelineSourceOrder = (source, index) => {
if (source instanceof HTMLElement && typeof getMessageNodeOrder === "function") {
return getMessageNodeOrder(source, index);
}
if (!(source instanceof HTMLElement) && Number.isFinite(source?.userOrder)) {
return source.userOrder;
}
if (!(source instanceof HTMLElement) && Number.isFinite(source?.order)) {
return source.order;
}
return index + 1;
};
const getTimelineSourceBranchIndex = (source, fallbackIndex) => {
if (!(source instanceof HTMLElement) && Number.isFinite(source?.index)) {
return source.index;
}
return getTimelineSourceOrder(source, fallbackIndex);
};
const getTimelineJumpTarget = (item) => {
if (item?.sourceMessage) {
return item.sourceMessage;
}
return {
messageId: item?.messageId || "",
messageIndex: item?.branchIndex,
role: item?.role || "user",
text: item?.text || "",
previewText: item?.previewText || "",
};
};
const getTimelineSourceNodes = () => {
const conversationIndex =
typeof getReadyConversationIndex === "function" ? getReadyConversationIndex() : null;
if (conversationIndex?.userMessages?.length) {
return conversationIndex.userMessages;
}
if (
typeof loadConversationIndex === "function" &&
!(
conversationIndexState.status === "failed" &&
typeof isConversationIndexForCurrentConversation === "function" &&
isConversationIndexForCurrentConversation()
)
) {
loadConversationIndex()
.then(() => {
if (timelineState.visible) {
scheduleTimelineRefresh();
}
})
.catch(() => {});
}
const sourceItems =
typeof getConversationMessageEntries === "function"
? getConversationMessageEntries({
role: "user",
mode: TOOLKIT_MESSAGE_MODE_EXTENDED,
refreshDom: true,
})
: typeof getCachedMessageEntries === "function"
? getCachedMessageEntries({ role: "user", mode: TOOLKIT_MESSAGE_MODE_EXTENDED })
: getUserMessageNodes();
const fallbackItems =
sourceItems.length > 0
? sourceItems
: typeof getConversationMessageEntries === "function"
? getConversationMessageEntries({
mode: TOOLKIT_MESSAGE_MODE_EXTENDED,
refreshDom: false,
})
: typeof getCachedMessageEntries === "function"
? getCachedMessageEntries({ mode: TOOLKIT_MESSAGE_MODE_EXTENDED })
: getMessageNodes();
const uniqueItems = [];
const seenKeys = new Set();
fallbackItems.forEach((source, index) => {
const key = getTimelineSourceKey(source, index);
if (!key || seenKeys.has(key)) {
return;
}
seenKeys.add(key);
uniqueItems.push(source);
});
return uniqueItems;
};
const normalizeTimelineText = (text) => (text || "").replace(/\s+/g, " ").trim();
const truncateTimelineText = (text, maxLength = 110) =>
text.length <= maxLength ? text : `${text.slice(0, maxLength)}...`;
const clampTimelineValue = (value, min, max) => Math.min(Math.max(value, min), max);
const parseTimelineTimestampCandidate = (value) => {
if (value === null || value === undefined || value === "") {
return null;
}
if (typeof value === "number" && Number.isFinite(value)) {
return value;
}
const text = String(value).trim();
if (!text) {
return null;
}
if (/^\d{10}$/.test(text)) {
const numeric = Number(text);
return Number.isFinite(numeric) ? numeric * 1000 : null;
}
if (/^\d{11,16}$/.test(text)) {
const numeric = Number(text);
return Number.isFinite(numeric) ? numeric : null;
}
const parsed = Date.parse(text);
if (Number.isNaN(parsed)) {
return null;
}
return parsed;
};
const extractTimelineTimestamp = (node, index, previousTimestamp) => {
const directCandidates = [
node.getAttribute("data-timestamp"),
node.getAttribute("data-created-at"),
node.getAttribute("data-time"),
node.getAttribute("datetime"),
];
for (const candidate of directCandidates) {
const parsed = parseTimelineTimestampCandidate(candidate);
if (parsed !== null) {
return parsed;
}
}
const nestedSelectors = [
"time[datetime]",
"[data-timestamp]",
"[data-created-at]",
"[datetime]",
];
for (const selector of nestedSelectors) {
const element = node.querySelector(selector);
if (!(element instanceof HTMLElement)) {
continue;
}
const parsed = parseTimelineTimestampCandidate(
element.getAttribute("datetime") ||
element.getAttribute("data-timestamp") ||
element.getAttribute("data-created-at") ||
element.getAttribute("data-time")
);
if (parsed !== null) {
return parsed;
}
}
if (Number.isFinite(previousTimestamp)) {
return previousTimestamp + 60000;
}
return index * 60000;
};
const assignTimelinePositions = (items) => {
if (items.length <= 1) {
return items.map((item) => ({ ...item, position: 0.5 }));
}
return items.map((item, index) => ({
...item,
position: clampTimelineValue(index / (items.length - 1), 0.02, 0.98),
}));
};
const buildTimelineSignature = (items) =>
items.map((item) => `${item.key}:${Math.round(item.position * 1000)}`).join("|");
const buildTimelineSourceSignature = (sources) =>
`${sources.length}|${sources
.map((source, index) => `${getTimelineSourceKey(source, index)}:${getTimelineSourceText(source).length}`)
.join("|")}`;
const isSameTimelineSource = (sources, signature) =>
timelineState.sourceSignature === signature &&
timelineState.sourceNodes.length === sources.length &&
sources.every(
(source, index) =>
getTimelineSourceKey(source, index) === getTimelineSourceKey(timelineState.sourceNodes[index], index),
);
const calculateTimelineContentHeight = (trackHeight, itemCount) => {
const safeTrackHeight = Math.max(1, Math.round(trackHeight));
if (itemCount <= TIMELINE_VISIBLE_NODE_CAPACITY) {
return safeTrackHeight;
}
const ratio = itemCount / TIMELINE_VISIBLE_NODE_CAPACITY;
return Math.max(safeTrackHeight, Math.round(safeTrackHeight * ratio));
};
const getTimelineTrackMaxScrollTop = (track) =>
Math.max(0, track.scrollHeight - track.clientHeight);
const normalizeTimelineWheelDelta = (event) => {
let delta = event.deltaY;
if (event.deltaMode === 1) {
delta *= 16;
} else if (event.deltaMode === 2) {
delta *= Math.max(window.innerHeight * 0.85, 320);
}
if (delta !== 0 && Math.abs(delta) < 2) {
return delta > 0 ? 2 : -2;
}
return delta;
};
const compressTimelineWheelDelta = (delta) => {
if (delta === 0) {
return 0;
}
const distance = clampTimelineValue(
Math.abs(delta) * TIMELINE_WHEEL_DISTANCE_SCALE,
TIMELINE_WHEEL_MIN_STEP,
TIMELINE_WHEEL_MAX_STEP
);
return delta > 0 ? distance : -distance;
};
const isTimelineProgrammaticJumpLocked = () =>
timelineProgrammaticJumpUntil > 0 && Date.now() < timelineProgrammaticJumpUntil;
const clearTimelineJumpUserIntentListeners = () => {
if (typeof timelineJumpUserIntentCleanup === "function") {
timelineJumpUserIntentCleanup();
}
timelineJumpUserIntentCleanup = null;
};
const isTimelineScrollIntentKeyEvent = (event) => {
if (!(event instanceof KeyboardEvent) || !TIMELINE_SCROLL_INTENT_KEYS.has(event.key)) {
return false;
}
const target = event.target;
if (!(target instanceof HTMLElement)) {
return true;
}
return !(
target.isContentEditable ||
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement
);
};
const cancelTimelineProgrammaticJump = () => {
if (timelineProgrammaticJumpUntil <= 0) {
return;
}
timelineProgrammaticJumpToken += 1;
timelineProgrammaticJumpUntil = 0;
clearTimelineJumpUserIntentListeners();
clearTimelineJumpResolveTimer();
clearTimelineJumpScrollTimer();
if (typeof cancelToolkitVirtualJump === "function") {
cancelToolkitVirtualJump();
}
hideTimelineHint();
const shouldRefresh = timelineState.refreshPending;
timelineState.refreshPending = false;
if (shouldRefresh) {
scheduleTimelineRefresh();
}
};
const bindTimelineJumpUserIntentListeners = () => {
clearTimelineJumpUserIntentListeners();
const cancelOnPointerIntent = (event) => {
if (event.isTrusted) {
cancelTimelineProgrammaticJump();
}
};
const cancelOnKeyIntent = (event) => {
if (event.isTrusted && isTimelineScrollIntentKeyEvent(event)) {
cancelTimelineProgrammaticJump();
}
};
const passiveCapture = { capture: true, passive: true };
window.addEventListener("wheel", cancelOnPointerIntent, passiveCapture);
window.addEventListener("touchstart", cancelOnPointerIntent, passiveCapture);
window.addEventListener("pointerdown", cancelOnPointerIntent, passiveCapture);
window.addEventListener("keydown", cancelOnKeyIntent, true);
timelineJumpUserIntentCleanup = () => {
window.removeEventListener("wheel", cancelOnPointerIntent, true);
window.removeEventListener("touchstart", cancelOnPointerIntent, true);
window.removeEventListener("pointerdown", cancelOnPointerIntent, true);
window.removeEventListener("keydown", cancelOnKeyIntent, true);
};
};
const beginTimelineProgrammaticJump = () => {
timelineProgrammaticJumpToken += 1;
timelineProgrammaticJumpUntil = Date.now() + TIMELINE_PROGRAMMATIC_JUMP_LOCK_MS;
bindTimelineJumpUserIntentListeners();
return timelineProgrammaticJumpToken;
};
const extendTimelineProgrammaticJump = (token) => {
if (token === timelineProgrammaticJumpToken) {
timelineProgrammaticJumpUntil = Date.now() + TIMELINE_PROGRAMMATIC_JUMP_LOCK_MS;
}
};
const finishTimelineProgrammaticJump = (token) => {
if (token === timelineProgrammaticJumpToken) {
const shouldRefresh = timelineState.refreshPending;
timelineProgrammaticJumpUntil = 0;
clearTimelineJumpUserIntentListeners();
if (shouldRefresh) {
timelineState.refreshPending = false;
scheduleTimelineRefresh();
}
}
};
const isTimelineJumpTokenActive = (token) => token === timelineProgrammaticJumpToken;
const isTimelineInteractionLocked = () =>
timelineState.pointerDown || timelineState.dragging || isTimelineProgrammaticJumpLocked();
const markTimelineRefreshPending = () => {
timelineState.refreshPending = true;
};
const updateTimelineBubblePlacement = () => {
const elements = getTimelineElements();
const timeline = elements?.timeline;
if (!(timeline instanceof HTMLElement)) {
return;
}
if (isTimelineInteractionLocked()) {
return;
}
const timelineRect = timeline.getBoundingClientRect();
const previewWidth = elements.preview instanceof HTMLElement
? Math.max(220, Math.round(elements.preview.getBoundingClientRect().width || 0))
: 240;
const hintWidth = elements.hint instanceof HTMLElement
? Math.max(120, Math.round(elements.hint.getBoundingClientRect().width || 0))
: 140;
const sideBubbleWidth = Math.max(previewWidth, hintWidth);
const rightSpace = window.innerWidth - timelineRect.right;
const leftSpace = timelineRect.left;
const shouldFlip = rightSpace < sideBubbleWidth + 20 && leftSpace > rightSpace;
timeline.classList.toggle("is-flipped", shouldFlip);
const hintHeight = elements.hint instanceof HTMLElement
? Math.max(30, Math.round(elements.hint.getBoundingClientRect().height || 0))
: 30;
const bottomSpace = window.innerHeight - timelineRect.bottom;
const shouldShowHintOnTop = bottomSpace < hintHeight + 16;
timeline.classList.toggle("is-hint-top", shouldShowHintOnTop);
};
const hideTimelineHint = () => {
const elements = getTimelineElements();
const hint = elements?.hint;
if (!(hint instanceof HTMLElement)) {
return;
}
hint.classList.remove("is-visible");
hint.textContent = "";
};
const showTimelineHint = (message) => {
const elements = getTimelineElements();
const hint = elements?.hint;
if (!(hint instanceof HTMLElement)) {
return;
}
if (timelineHintTimer) {
clearTimeout(timelineHintTimer);
}
hint.textContent = message;
updateTimelineBubblePlacement();
hint.classList.add("is-visible");
timelineHintTimer = setTimeout(() => {
hint.classList.remove("is-visible");
timelineHintTimer = null;
}, 2000);
};
const hideTimelinePreview = () => {
const elements = getTimelineElements();
const preview = elements?.preview;
if (!(preview instanceof HTMLElement)) {
return;
}
preview.classList.remove("is-visible");
preview.textContent = "";
timelineState.hoverIndex = -1;
};
const showTimelinePreview = (index) => {
if (index < 0 || index >= timelineState.items.length) {
hideTimelinePreview();
return;
}
const elements = getTimelineElements();
const preview = elements?.preview;
if (!(preview instanceof HTMLElement)) {
return;
}
const item = timelineState.items[index];
if (!item) {
hideTimelinePreview();
return;
}
if (timelineState.hoverIndex === index && preview.classList.contains("is-visible")) {
return;
}
timelineState.hoverIndex = index;
preview.textContent = truncateTimelineText(
item.previewText || t("timeline.previewFallback", { index: item.order || index + 1 })
);
updateTimelineBubblePlacement();
preview.classList.add("is-visible");
};
const updateTimelineActiveUi = () => {
const elements = getTimelineElements();
const track = elements?.track;
if (!(track instanceof HTMLElement)) {
return;
}
const nodes = track.querySelectorAll(".chatgpt-toolkit-timeline-node");
nodes.forEach((node) => {
const element = node;
if (!(element instanceof HTMLElement)) {
return;
}
const index = Number(element.dataset.timelineIndex);
if (Number.isNaN(index)) {
return;
}
if (index === timelineState.activeIndex) {
element.classList.add("is-active");
} else {
element.classList.remove("is-active");
}
});
};
const highlightTimelineMessageNode = (node) => {
if (!(node instanceof HTMLElement)) {
return;
}
if (timelineHighlightTimer) {
clearTimeout(timelineHighlightTimer);
}
node.classList.add("chatgpt-toolkit-timeline-target");
timelineHighlightTimer = setTimeout(() => {
node.classList.remove("chatgpt-toolkit-timeline-target");
timelineHighlightTimer = null;
}, 1400);
};
const clearTimelineJumpResolveTimer = () => {
if (timelineJumpResolveTimer) {
clearTimeout(timelineJumpResolveTimer);
timelineJumpResolveTimer = null;
}
};
const clearTimelineJumpScrollTimer = () => {
if (timelineJumpScrollTimer) {
clearTimeout(timelineJumpScrollTimer);
timelineJumpScrollTimer = null;
}
};
const getConversationScrollController = () => {
const scrollRoot =
typeof resolveConversationScrollRoot === "function"
? resolveConversationScrollRoot()
: null;
if (!(scrollRoot instanceof HTMLElement)) {
return null;
}
const isDocumentLike =
typeof isConversationDocumentScrollRoot === "function" &&
isConversationDocumentScrollRoot(scrollRoot);
if (isDocumentLike) {
const doc = document.scrollingElement || document.documentElement || document.body;
return {
isDocumentLike: true,
viewportHeight: Math.max(1, window.innerHeight || document.documentElement?.clientHeight || 0),
getTop: () =>
Math.max(0, window.scrollY || window.pageYOffset || document.documentElement?.scrollTop || 0),
getMaxTop: () => {
const viewportHeight = Math.max(1, window.innerHeight || document.documentElement?.clientHeight || 0);
return Math.max(0, (doc?.scrollHeight || 0) - viewportHeight);
},
setTop: (top, behavior = "auto") => {
window.scrollTo({ top, behavior });
},
};
}
return {
isDocumentLike: false,
viewportHeight: Math.max(1, scrollRoot.clientHeight || 1),
getTop: () => Math.max(0, scrollRoot.scrollTop || 0),
getMaxTop: () => Math.max(0, scrollRoot.scrollHeight - scrollRoot.clientHeight),
setTop: (top, behavior = "auto") => {
scrollRoot.scrollTo({ top, behavior });
},
};
};
const getTimelineOrderTargetTop = (order, totalCount, maxTop) => {
const normalizedOrder = Number.isFinite(order) ? Math.max(1, Math.trunc(order)) : 1;
const normalizedTotal = Number.isFinite(totalCount) ? Math.max(1, Math.trunc(totalCount)) : 1;
const ratio =
normalizedTotal <= 1 ? 1 : clampTimelineValue((normalizedOrder - 1) / (normalizedTotal - 1), 0, 1);
if (ratio <= 0.02) {
return 0;
}
if (ratio >= 0.98) {
return maxTop;
}
return Math.round(maxTop * ratio);
};
const scrollConversationToTimelineOrder = (order, totalCount, options = {}) => {
const { behavior = "smooth" } = options;
const controller = getConversationScrollController();
if (!controller) {
return false;
}
const maxTop = controller.getMaxTop();
const targetTop = getTimelineOrderTargetTop(order, totalCount, maxTop);
controller.setTop(targetTop, behavior);
return true;
};
const simulateConversationScrollTowardsTimelineOrder = (order, totalCount, options = {}) => {
const {
maxSteps = TIMELINE_JUMP_STEP_MAX_STEPS,
stepDelayMs = TIMELINE_JUMP_STEP_DELAY_MS,
onDone = null,
} = options;
const controller = getConversationScrollController();
if (!controller) {
return false;
}
const maxTop = controller.getMaxTop();
const targetTop = getTimelineOrderTargetTop(order, totalCount, maxTop);
const safeMaxSteps = Math.max(1, Math.trunc(maxSteps));
const stepPx = clampTimelineValue(
Math.round(controller.viewportHeight * 0.72),
160,
860,
);
clearTimelineJumpScrollTimer();
let remainingSteps = safeMaxSteps;
const runStep = () => {
const currentTop = controller.getTop();
const distance = targetTop - currentTop;
if (Math.abs(distance) <= stepPx || remainingSteps <= 0) {
controller.setTop(targetTop, "auto");
if (typeof getMessageNodes === "function") {
getMessageNodes({ forceRefresh: true });
}
if (typeof onDone === "function") {
onDone();
}
return;
}
const nextTop = currentTop + Math.sign(distance) * stepPx;
controller.setTop(nextTop, "auto");
if (typeof getMessageNodes === "function") {
getMessageNodes({ forceRefresh: true });
}
remainingSteps -= 1;
timelineJumpScrollTimer = setTimeout(runStep, stepDelayMs);
};
runStep();
return true;
};
const queueTimelineNodeResolveAfterJump = (index, options = {}) => {
clearTimelineJumpResolveTimer();
clearTimelineJumpScrollTimer();
const { highlightMessage = false, attempts = TIMELINE_JUMP_RETRY_ATTEMPTS } = options;
const maxAttempts = Math.max(1, Math.trunc(attempts));
const attemptResolve = (remainingAttempts) => {
timelineJumpResolveTimer = setTimeout(() => {
timelineJumpResolveTimer = null;
if (!timelineState.visible || document.hidden || document.visibilityState === "hidden") {
return;
}
const item = timelineState.items[index];
if (!item) {
return;
}
const liveNode = getTimelineSourceNode(item.source);
if (liveNode instanceof HTMLElement && liveNode.isConnected) {
item.node = liveNode;
if (typeof scrollElementIntoConversationView === "function") {
scrollElementIntoConversationView(liveNode, { behavior: "smooth", block: "center" });
} else {
liveNode.scrollIntoView({ behavior: "smooth", block: "center" });
}
if (highlightMessage) {
highlightTimelineMessageNode(liveNode);
}
return;
}
if (remainingAttempts <= 1) {
showTimelineHint(t("timeline.hintMessageNotLoaded"));
return;
}
const currentOrder = Number.isFinite(item.order) ? item.order : index + 1;
const simulated = simulateConversationScrollTowardsTimelineOrder(
currentOrder,
timelineState.totalUserCount,
{
maxSteps: TIMELINE_JUMP_STEP_MAX_STEPS,
stepDelayMs: TIMELINE_JUMP_STEP_DELAY_MS,
onDone: () => {
attemptResolve(remainingAttempts - 1);
},
},
);
if (!simulated) {
scrollConversationToTimelineOrder(currentOrder, timelineState.totalUserCount, {
behavior: "auto",
});
attemptResolve(remainingAttempts - 1);
return;
}
if (typeof getMessageNodes === "function") {
getMessageNodes({ forceRefresh: true });
}
}, TIMELINE_JUMP_RETRY_DELAY_MS);
};
if (typeof getMessageNodes === "function") {
getMessageNodes({ forceRefresh: true });
}
const currentItem = timelineState.items[index];
if (currentItem) {
const currentOrder = Number.isFinite(currentItem.order) ? currentItem.order : index + 1;
simulateConversationScrollTowardsTimelineOrder(currentOrder, timelineState.totalUserCount, {
maxSteps: Math.max(1, Math.trunc(TIMELINE_JUMP_STEP_MAX_STEPS / 2)),
stepDelayMs: TIMELINE_JUMP_STEP_DELAY_MS,
onDone: () => {
attemptResolve(maxAttempts);
},
});
return;
}
attemptResolve(maxAttempts);
};
const setTimelineActiveIndex = (index, options = {}) => {
if (index < 0 || index >= timelineState.items.length) {
updateTimelineCount(0, timelineState.totalUserCount);
return;
}
const { scrollToMessage = false, highlightMessage = false } = options;
timelineState.activeIndex = index;
updateTimelineActiveUi();
const item = timelineState.items[index];
if (!item) {
updateTimelineCount(0, timelineState.totalUserCount);
return;
}
const currentOrder = Number.isFinite(item.order) ? item.order : index + 1;
updateTimelineCount(currentOrder, timelineState.totalUserCount);
const jumpTarget = scrollToMessage ? getTimelineJumpTarget(item) : null;
let liveNode = null;
if (scrollToMessage && typeof resolveMessageDomNode === "function") {
liveNode = resolveMessageDomNode(jumpTarget, { allowWeak: false });
} else if (!scrollToMessage) {
liveNode = getTimelineSourceNode(item.source);
}
if (liveNode instanceof HTMLElement && liveNode.isConnected) {
item.node = liveNode;
}
if (scrollToMessage) {
clearTimelineJumpResolveTimer();
clearTimelineJumpScrollTimer();
const jumpToken = beginTimelineProgrammaticJump();
if (typeof jumpToConversationMessage === "function") {
const jumpPromise = jumpToConversationMessage(jumpTarget, {
totalMessages:
typeof getReadyConversationIndex === "function"
? getReadyConversationIndex()?.messages?.length
: timelineState.totalUserCount,
onBeforeJump() {
extendTimelineProgrammaticJump(jumpToken);
showTimelineHint(t("timeline.hintJumping"));
},
onProgress() {
extendTimelineProgrammaticJump(jumpToken);
},
onResolved: (resolvedNode) => {
if (!isTimelineJumpTokenActive(jumpToken)) {
return;
}
item.node = resolvedNode;
if (item.sourceMessage) {
item.sourceMessage.node = resolvedNode;
}
if (item.source && !(item.source instanceof HTMLElement)) {
item.source.node = resolvedNode;
}
if (highlightMessage) {
highlightTimelineMessageNode(resolvedNode);
}
hideTimelineHint();
finishTimelineProgrammaticJump(jumpToken);
},
onFailed: () => {
if (!isTimelineJumpTokenActive(jumpToken)) {
return;
}
showTimelineHint(t("timeline.hintMessageNotLoaded"));
finishTimelineProgrammaticJump(jumpToken);
},
});
if (jumpPromise && typeof jumpPromise.then === "function") {
jumpPromise
.then((result) => {
if (isTimelineJumpTokenActive(jumpToken) && !result?.ok) {
finishTimelineProgrammaticJump(jumpToken);
}
})
.catch(() => {
if (isTimelineJumpTokenActive(jumpToken)) {
showTimelineHint(t("timeline.hintMessageNotLoaded"));
finishTimelineProgrammaticJump(jumpToken);
}
});
}
} else {
const jumped = scrollConversationToTimelineOrder(currentOrder, timelineState.totalUserCount, {
behavior: "auto",
});
if (jumped) {
queueTimelineNodeResolveAfterJump(index, { highlightMessage });
setTimeout(() => finishTimelineProgrammaticJump(jumpToken), TIMELINE_PROGRAMMATIC_JUMP_LOCK_MS);
} else {
showTimelineHint(t("timeline.hintMessageNotLoaded"));
finishTimelineProgrammaticJump(jumpToken);
}
}
return;
}
if (highlightMessage && liveNode instanceof HTMLElement && liveNode.isConnected) {
highlightTimelineMessageNode(liveNode);
}
};
const buildTimelineItemsFromSourceNodes = (sources) => {
const withTimestamps = [];
let previousTimestamp = null;
sources.forEach((source, index) => {
const node = getTimelineSourceNode(source, { resolve: false });
const apiTimestamp = isTimelineApiSource(source)
? parseTimelineTimestampCandidate(source.createTime || source.updateTime || "")
: null;
const timestamp =
apiTimestamp !== null
? apiTimestamp
: node instanceof HTMLElement
? extractTimelineTimestamp(node, index, previousTimestamp)
: Number.isFinite(previousTimestamp)
? previousTimestamp + 60000
: getTimelineSourceOrder(source, index) * 60000;
previousTimestamp = timestamp;
const order = getTimelineSourceOrder(source, index);
const branchIndex = getTimelineSourceBranchIndex(source, index);
const previewText = normalizeTimelineText(getTimelineSourceText(source));
withTimestamps.push({
key: getTimelineSourceKey(source, index),
source,
sourceMessage: isTimelineApiSource(source) ? source : null,
node,
messageId: source?.messageId || "",
messageIndex: branchIndex,
userOrder: Number.isFinite(source?.userOrder) ? source.userOrder : order,
role: source?.role || "user",
text: source?.text || previewText,
timestamp,
order,
branchIndex,
previewText,
});
});
return {
items: assignTimelinePositions(withTimestamps),
allItems: withTimestamps,
totalUserCount: withTimestamps.length,
};
};
const syncTimelineNodeButtons = (content, items, contentHeight) => {
if (!(content instanceof HTMLElement)) {
return;
}
const existingButtons = Array.from(content.querySelectorAll(".chatgpt-toolkit-timeline-node"));
const existingByKey = new Map();
existingButtons.forEach((button) => {
if (button instanceof HTMLButtonElement) {
const key = button.dataset.timelineKey || "";
if (key) {
existingByKey.set(key, button);
}
}
});
const fragment = document.createDocumentFragment();
const verticalPadding = 10;
const usableHeight = Math.max(1, contentHeight - verticalPadding * 2);
items.forEach((item, index) => {
let nodeButton = existingByKey.get(item.key);
if (!(nodeButton instanceof HTMLButtonElement)) {
nodeButton = document.createElement("button");