aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/pdf/GPTPopup/GPTPopup.tsx
blob: ed3f993772937a90fde205cd8cb9c0faf33044dd (plain)
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
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Button, IconButton, Type } from 'browndash-components';
import { action, makeObservable, observable } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { CgClose, CgCornerUpLeft } from 'react-icons/cg';
import ReactLoading from 'react-loading';
import { TypeAnimation } from 'react-type-animation';
import { ClientUtils } from '../../../../ClientUtils';
import { Doc } from '../../../../fields/Doc';
import { NumCast, StrCast } from '../../../../fields/Types';
import { Networking } from '../../../Network';
import { GPTCallType, gptAPICall, gptImageCall } from '../../../apis/gpt/GPT';
import { DocUtils } from '../../../documents/DocUtils';
import { Docs } from '../../../documents/Documents';
import { SettingsManager } from '../../../util/SettingsManager';
import { SnappingManager } from '../../../util/SnappingManager';
import { ObservableReactComponent } from '../../ObservableReactComponent';
import { DocumentView } from '../../nodes/DocumentView';
import { AnchorMenu } from '../AnchorMenu';
import './GPTPopup.scss';

export enum GPTPopupMode {
    SUMMARY,
    EDIT,
    IMAGE,
    FLASHCARD,
    DATA,
    CARD,
    SORT,
    QUIZ,
}

export enum GPTQuizType {
    CURRENT = 0,
    CHOOSE = 1,
    MULTIPLE = 2,
}

interface GPTPopupProps {}

@observer
export class GPTPopup extends ObservableReactComponent<GPTPopupProps> {
    // eslint-disable-next-line no-use-before-define
    static Instance: GPTPopup;
    private messagesEndRef: React.RefObject<HTMLDivElement>;

    @observable private chatMode: boolean = false;
    private correlatedColumns: string[] = [];

    @observable
    public visible: boolean = false;
    @action
    public setVisible = (vis: boolean) => {
        this.visible = vis;
    };
    @observable
    public loading: boolean = false;
    @action
    public setLoading = (loading: boolean) => {
        this.loading = loading;
    };
    @observable
    public text: string = '';
    @action
    public setText = (text: string) => {
        this.text = text;
    };
    @observable
    public selectedText: string = '';
    @action
    public setSelectedText = (text: string) => {
        this.selectedText = text;
    };
    @observable
    public dataJson: string = '';
    public dataChatPrompt: string | null = null;
    @action
    public setDataJson = (text: string) => {
        if (text === '') this.dataChatPrompt = '';
        this.dataJson = text;
    };

    @observable
    public imgDesc: string = '';
    @action
    public setImgDesc = (text: string) => {
        this.imgDesc = text;
    };

    @observable
    public imgUrls: string[][] = [];
    @action
    public setImgUrls = (imgs: string[][]) => {
        this.imgUrls = imgs;
    };

    @observable
    public mode: GPTPopupMode = GPTPopupMode.SUMMARY;
    @action
    public setMode = (mode: GPTPopupMode) => {
        this.mode = mode;
    };

    @observable
    public highlightRange: number[] = [];
    @action callSummaryApi = () => {};

    @observable
    private done: boolean = false;
    @action
    public setDone = (done: boolean) => {
        this.done = done;
        this.chatMode = false;
    };

    @observable
    private sortDone: boolean = false; // this is so redundant but the og done variable was causing weird unknown problems and im just a girl

    @action
    public setSortDone = (done: boolean) => {
        this.sortDone = done;
    };

    // change what can be a ref into a ref
    @observable
    private sidebarId: string = '';
    @action
    public setSidebarId = (id: string) => {
        this.sidebarId = id;
    };

    @observable
    private imgTargetDoc: Doc | undefined;
    @action
    public setImgTargetDoc = (anchor: Doc) => {
        this.imgTargetDoc = anchor;
    };

    @observable
    private textAnchor: Doc | undefined;
    @action
    public setTextAnchor = (anchor: Doc) => {
        this.textAnchor = anchor;
    };

    @observable
    public sortDesc: string = '';

    @action public setSortDesc = (t: string) => {
        this.sortDesc = t;
    };

    @observable onSortComplete?: (sortResult: string, questionType: string, tag?: string) => void;
    @observable onQuizRandom?: () => void;
    @observable cardsDoneLoading = false;

    @action setCardsDoneLoading(done: boolean) {
        console.log(done + 'HI HIHI');
        this.cardsDoneLoading = done;
    }

    @observable sortRespText: string = '';

    @action setSortRespText(resp: string) {
        this.sortRespText = resp;
    }

    @observable chatSortPrompt: string = '';

    sortPromptChanged = action((e: React.ChangeEvent<HTMLInputElement>) => {
        this.chatSortPrompt = e.target.value;
    });

    @observable quizAnswer: string = '';

    quizAnswerChanged = action((e: React.ChangeEvent<HTMLInputElement>) => {
        this.quizAnswer = e.target.value;
    });

    @observable conversationArray: string[] = ['Hi! In this pop up, you can ask ChatGPT questions about your documents and filter / sort them. '];

    /**
     * When the cards are in quiz mode in the card view, allows gpt to determine whether the user's answer was correct
     * @returns
     */
    generateQuiz = async () => {
        this.setLoading(true);
        this.setSortDone(false);

        const quizType = this.quizMode;

        const selected = DocumentView.SelectedDocs().lastElement();

        const questionText = 'Question: ' + StrCast(selected['gptInputText']);

        if (StrCast(selected['gptRubric']) === '') {
            const rubricText = 'Rubric: ' + (await this.generateRubric(StrCast(selected['gptInputText']), selected));
        }

        const rubricText = 'Rubric: ' + StrCast(selected['gptRubric']);
        const queryText = questionText + ' UserAnswer: ' + this.quizAnswer + '. ' + 'Rubric' + rubricText;

        try {
            const res = await gptAPICall(queryText, GPTCallType.QUIZ);
            if (!res) {
                console.error('GPT call failed');
                return;
            }
            console.log(res);
            this.setQuizResp(res);
            this.conversationArray.push(res);

            this.setLoading(false);
            this.setSortDone(true);
        } catch (err) {
            console.error('GPT call failed');
        }

        if (this.onQuizRandom) {
            this.onQuizRandom();
        }
    };

    /**
     * Generates a rubric by which to compare the user's answer to
     * @param inputText user's answer
     * @param doc the doc the user is providing info about
     * @returns gpt's response
     */
    generateRubric = async (inputText: string, doc: Doc) => {
        try {
            const res = await gptAPICall(inputText, GPTCallType.RUBRIC);
            doc['gptRubric'] = res;
            return res;
        } catch (err) {
            console.error('GPT call failed');
        }
    };

    @observable private regenerateCallback: (() => Promise<void>) | null = null;

    /**
     * Callback function that causes the card view to update the childpair string list
     * @param callback
     */
    @action public setRegenerateCallback(callback: () => Promise<void>) {
        this.regenerateCallback = callback;
    }

    public addDoc: (doc: Doc | Doc[], sidebarKey?: string | undefined) => boolean = () => false;
    public createFilteredDoc: (axes?: string[]) => boolean = () => false;
    public addToCollection: ((doc: Doc | Doc[], annotationKey?: string | undefined) => boolean) | undefined;

    @observable quizRespText: string = '';

    @action setQuizResp(resp: string) {
        this.quizRespText = resp;
    }

    /**
     * Generates a response to the user's question depending on the type of their question
     */
    generateCard = async () => {
        console.log(this.chatSortPrompt + 'USER PROMPT');
        this.setLoading(true);
        this.setSortDone(false);

        if (this.regenerateCallback) {
            await this.regenerateCallback();
        }

        try {
            // const res = await gptAPICall(this.sortDesc, GPTCallType.SORT, this.chatSortPrompt);
            const questionType = await gptAPICall(this.chatSortPrompt, GPTCallType.TYPE);
            const questionNumber = questionType.split(' ')[0];
            console.log(questionType);
            let res = '';

            switch (questionNumber) {
                case '1':
                case '2':
                case '4':
                    res = await gptAPICall(this.sortDesc, GPTCallType.SUBSET, this.chatSortPrompt);
                    break;
                case '6':
                    res = await gptAPICall(this.sortDesc, GPTCallType.SORT, this.chatSortPrompt);
                    break;
                default:
                    const selected = DocumentView.SelectedDocs().lastElement();
                    const questionText = StrCast(selected!['gptInputText']);

                    res = await gptAPICall(questionText, GPTCallType.INFO, this.chatSortPrompt);
                    break;
            }

            // Trigger the callback with the result
            if (this.onSortComplete) {
                this.onSortComplete(res || 'Something went wrong :(', questionNumber, questionType.split(' ').slice(1).join(' '));

                let explanation = res;

                if (questionType != '5' && questionType != '3') {
                    // Extract explanation surrounded by ------ at the top or both at the top and bottom
                    const explanationMatch = res.match(/------\s*([\s\S]*?)\s*(?:------|$)/) || [];
                    explanation = explanationMatch[1] ? explanationMatch[1].trim() : 'No explanation found';
                }

                // Set the extracted explanation to sortRespText
                this.setSortRespText(explanation);
                this.conversationArray.push(this.sortRespText);
                this.scrollToBottom();

                console.log(res);
            }
        } catch (err) {
            console.error(err);
        }

        this.setLoading(false);
        this.setSortDone(true);
    };

    /**
     * Generates a Dalle image and uploads it to the server.
     */
    generateImage = async () => {
        if (this.imgDesc === '') return undefined;
        this.setImgUrls([]);
        this.setMode(GPTPopupMode.IMAGE);
        this.setVisible(true);
        this.setLoading(true);

        try {
            const imageUrls = await gptImageCall(this.imgDesc);
            if (imageUrls && imageUrls[0]) {
                const [result] = await Networking.PostToServer('/uploadRemoteImage', { sources: [imageUrls[0]] });
                const source = ClientUtils.prepend(result.accessPaths.agnostic.client);
                this.setImgUrls([[imageUrls[0], source]]);
            }
        } catch (err) {
            console.error(err);
        }
        this.setLoading(false);
        return undefined;
    };

    /**
     * Completes an API call to generate a summary of
     * this.selectedText in the popup.
     */
    generateSummary = async () => {
        GPTPopup.Instance.setVisible(true);
        GPTPopup.Instance.setMode(GPTPopupMode.SUMMARY);
        GPTPopup.Instance.setLoading(true);

        try {
            const res = await gptAPICall(this.selectedText, GPTCallType.SUMMARY);
            GPTPopup.Instance.setText(res || 'Something went wrong.');
        } catch (err) {
            console.error(err);
        }
        GPTPopup.Instance.setLoading(false);
    };

    /**
     * Completes an API call to generate an analysis of
     * this.dataJson in the popup.
     */
    generateDataAnalysis = async () => {
        GPTPopup.Instance.setVisible(true);
        GPTPopup.Instance.setLoading(true);
        try {
            const res = await gptAPICall(this.dataJson, GPTCallType.DATA, this.dataChatPrompt);
            const json = JSON.parse(res! as string);
            const keys = Object.keys(json);
            this.correlatedColumns = [];
            this.correlatedColumns.push(json[keys[0]]);
            this.correlatedColumns.push(json[keys[1]]);
            GPTPopup.Instance.setText(json[keys[2]] || 'Something went wrong.');
        } catch (err) {
            console.error(err);
        }
        GPTPopup.Instance.setLoading(false);
    };

    /**
     * Transfers the summarization text to a sidebar annotation text document.
     */
    private transferToText = () => {
        const newDoc = Docs.Create.TextDocument(this.text.trim(), {
            _width: 200,
            _height: 50,
            _layout_fitWidth: true,
            _layout_autoHeight: true,
        });
        this.addDoc(newDoc, this.sidebarId);
        // newDoc.data = 'Hello world';
        const anchor = AnchorMenu.Instance?.GetAnchor(undefined, false);
        if (anchor) {
            DocUtils.MakeLink(newDoc, anchor, {
                link_relationship: 'GPT Summary',
            });
        }
    };

    /**
     * Creates a histogram to show the correlation relationship that was found
     */
    private createVisualization = () => {
        this.createFilteredDoc(this.correlatedColumns);
    };

    /**
     * Transfers the image urls to actual image docs
     */
    private transferToImage = (source: string) => {
        const textAnchor = this.textAnchor ?? this.imgTargetDoc;
        if (!textAnchor) return;
        const newDoc = Docs.Create.ImageDocument(source, {
            x: NumCast(textAnchor.x) + NumCast(textAnchor._width) + 10,
            y: NumCast(textAnchor.y),
            _height: 200,
            _width: 200,
            data_nativeWidth: 1024,
            data_nativeHeight: 1024,
        });
        if (Doc.IsInMyOverlay(textAnchor)) {
            newDoc.overlayX = textAnchor.x;
            newDoc.overlayY = NumCast(textAnchor.y) + NumCast(textAnchor._height);
            Doc.AddToMyOverlay(newDoc);
        } else {
            this.addToCollection?.(newDoc);
        }
        // Create link between prompt and image
        DocUtils.MakeLink(textAnchor, newDoc, { link_relationship: 'Image Prompt' });
    };

    /**
     * Creates a chatbox for analyzing data so that users can ask specific questions.
     */
    private chatWithAI = () => {
        this.chatMode = true;
    };
    dataPromptChanged = action((e: React.ChangeEvent<HTMLInputElement>) => {
        this.dataChatPrompt = e.target.value;
    });

    private getPreviewUrl = (source: string) => source.split('.').join('_m.');

    constructor(props: GPTPopupProps) {
        super(props);
        makeObservable(this);
        GPTPopup.Instance = this;
        this.messagesEndRef = React.createRef();
    }

    scrollToBottom = () => {
        setTimeout(() => {
            // Code to execute after 1 second (1000 ms)
            if (this.messagesEndRef.current) {
                this.messagesEndRef.current.scrollIntoView({ behavior: 'smooth', block: 'end' });
            }
        }, 50);
    };

    componentDidUpdate = () => {
        if (this.loading) {
            this.setDone(false);
        }
    };

    @observable quizMode: GPTQuizType = GPTQuizType.CURRENT;
    @action setQuizMode(g: GPTQuizType) {
        this.quizMode = g;
    }

    cardMenu = () => (
        <div className="btns-wrapper-gpt">
            <Button
                tooltip="Have ChatGPT sort, tag, define, or filter your cards for you!"
                text="Modify/Sort Cards!"
                onClick={() => this.setMode(GPTPopupMode.SORT)}
                color={StrCast(Doc.UserDoc().userVariantColor)}
                type={Type.TERT}
                style={{
                    width: '100%',
                    height: '40%',
                    textAlign: 'center',
                    color: '#ffffff',
                    fontSize: '16px',
                    marginBottom: '10px',
                }}
            />
            <Button
                tooltip="Test your knowledge with ChatGPT!"
                text="Quiz Cards!"
                onClick={() => {
                    this.conversationArray = ['Define the selected card!'];
                    this.setMode(GPTPopupMode.QUIZ);
                    if (this.onQuizRandom) {
                        this.onQuizRandom();
                    }
                }}
                color={StrCast(Doc.UserDoc().userVariantColor)}
                type={Type.TERT}
                style={{
                    width: '100%',
                    textAlign: 'center',
                    color: '#ffffff',
                    fontSize: '16px',
                    height: '40%',
                }}
            />
        </div>
    );

    handleKeyPress = async (e: React.KeyboardEvent, isSort: boolean) => {
        if (e.key === 'Enter') {
            e.stopPropagation();

            if (isSort) {
                this.conversationArray.push(this.chatSortPrompt);
                await this.generateCard();
                this.chatSortPrompt = '';
            } else {
                this.conversationArray.push(this.quizAnswer);
                await this.generateQuiz();
                this.quizAnswer = '';
            }

            this.scrollToBottom();
        }
    };

    cardActual = (opt: GPTPopupMode) => {
        const isSort = opt === GPTPopupMode.SORT;
        return (
            <div className="btns-wrapper-gpt">
                <div className="chat-wrapper">
                    <div className="chat-bubbles">
                        {this.conversationArray.map((message, index) => (
                            <div key={index} className={`chat-bubble ${index % 2 === 1 ? 'user-message' : 'chat-message'}`}>
                                {message}
                            </div>
                        ))}
                        {(!this.cardsDoneLoading || this.loading) && <div className={`chat-bubble chat-message`}>...</div>}
                    </div>

                    <div ref={this.messagesEndRef} style={{ height: '100px' }} />
                </div>

                <div className="inputWrapper">
                    <input
                        className="searchBox-input"
                        defaultValue=""
                        value={isSort ? this.chatSortPrompt : this.quizAnswer} // Controlled input
                        autoComplete="off"
                        onChange={isSort ? this.sortPromptChanged : this.quizAnswerChanged}
                        onKeyDown={e => {
                            this.handleKeyPress(e, isSort);
                        }}
                        type="text"
                        placeholder={`${isSort ? 'Have ChatGPT sort, tag, define, or filter your cards for you!' : 'Define the selected card!'}`}
                    />
                </div>
            </div>
        );
    };

    sortBox = () => (
        <div style={{ height: '80%' }}>
            {this.heading(this.mode === GPTPopupMode.SORT ? 'SORTING' : 'QUIZ')}
            <>
                {!this.cardsDoneLoading ? (
                    <div className="content-wrapper">
                        <div className="loading-spinner">
                            <ReactLoading type="spin" color={StrCast(Doc.UserDoc().userVariantColor)} height={30} width={30} />
                            {this.loading ? <span>Loading...</span> : <span>Reading Cards...</span>}
                        </div>
                    </div>
                ) : this.mode === GPTPopupMode.CARD ? (
                    this.cardMenu()
                ) : (
                    this.cardActual(this.mode)
                ) // Call the functions to render JSX
                }
            </>
        </div>
    );

    imageBox = () => (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}>
            {this.heading('GENERATED IMAGE')}
            <div className="image-content-wrapper">
                {this.imgUrls.map((rawSrc, i) => (
                    <div key={rawSrc[0] + i} className="img-wrapper">
                        <div className="img-container">
                            <img key={rawSrc[0]} src={rawSrc[0]} width={150} height={150} alt="dalle generation" />
                        </div>
                        <div className="btn-container">
                            <Button text="Save Image" onClick={() => this.transferToImage(rawSrc[1])} color={StrCast(Doc.UserDoc().userColor)} type={Type.TERT} />
                        </div>
                    </div>
                ))}
            </div>
            {!this.loading && <IconButton tooltip="Generate Again" onClick={this.generateImage} icon={<FontAwesomeIcon icon="redo-alt" size="lg" />} color={StrCast(Doc.UserDoc().userVariantColor)} />}
        </div>
    );

    summaryBox = () => (
        <>
            <div>
                {this.heading('SUMMARY')}
                <div className="content-wrapper">
                    {!this.loading &&
                        (!this.done ? (
                            <TypeAnimation
                                speed={50}
                                sequence={[
                                    this.text,
                                    () => {
                                        setTimeout(() => {
                                            this.setDone(true);
                                        }, 500);
                                    },
                                ]}
                            />
                        ) : (
                            this.text
                        ))}
                </div>
            </div>
            {!this.loading && (
                <div className="btns-wrapper">
                    {this.done ? (
                        <>
                            <IconButton tooltip="Generate Again" onClick={this.generateSummary /* this.callSummaryApi */} icon={<FontAwesomeIcon icon="redo-alt" size="lg" />} color={StrCast(SettingsManager.userVariantColor)} />
                            <Button tooltip="Transfer to text" text="Transfer To Text" onClick={this.transferToText} color={StrCast(SettingsManager.userVariantColor)} type={Type.TERT} />
                        </>
                    ) : (
                        <div className="summarizing">
                            <span>Summarizing</span>
                            <ReactLoading type="bubbles" color="#bcbcbc" width={20} height={20} />
                            <Button
                                text="Stop Animation"
                                onClick={() => {
                                    this.setDone(true);
                                }}
                                color={StrCast(SettingsManager.userVariantColor)}
                                type={Type.TERT}
                            />
                        </div>
                    )}
                </div>
            )}
        </>
    );

    dataAnalysisBox = () => (
        <>
            <div>
                {this.heading('ANALYSIS')}
                <div className="content-wrapper">
                    {!this.loading &&
                        (!this.done ? (
                            <TypeAnimation
                                speed={50}
                                sequence={[
                                    this.text,
                                    () => {
                                        setTimeout(() => {
                                            this.setDone(true);
                                        }, 500);
                                    },
                                ]}
                            />
                        ) : (
                            this.text
                        ))}
                </div>
            </div>
            {!this.loading && (
                <div className="btns-wrapper">
                    {this.done ? (
                        this.chatMode ? (
                            <input
                                defaultValue=""
                                autoComplete="off"
                                onChange={this.dataPromptChanged}
                                onKeyDown={e => {
                                    e.key === 'Enter' ? this.generateDataAnalysis() : null;
                                    e.stopPropagation();
                                }}
                                type="text"
                                placeholder="Ask GPT a question about the data..."
                                id="search-input"
                                className="searchBox-input"
                                style={{ width: '100%' }}
                            />
                        ) : (
                            <>
                                <Button tooltip="Transfer to text" text="Transfer To Text" onClick={this.transferToText} color={StrCast(SnappingManager.userVariantColor)} type={Type.TERT} />
                                <Button tooltip="Chat with AI" text="Chat with AI" onClick={this.chatWithAI} color={StrCast(SnappingManager.userVariantColor)} type={Type.TERT} />
                            </>
                        )
                    ) : (
                        <div className="summarizing">
                            <span>Summarizing</span>
                            <ReactLoading type="bubbles" color="#bcbcbc" width={20} height={20} />
                            <Button
                                text="Stop Animation"
                                onClick={() => {
                                    this.setDone(true);
                                }}
                                color={StrCast(SnappingManager.userVariantColor)}
                                type={Type.TERT}
                            />
                        </div>
                    )}
                </div>
            )}
        </>
    );

    aiWarning = () =>
        this.done ? (
            <div className="ai-warning">
                <FontAwesomeIcon icon="exclamation-circle" size="sm" style={{ paddingRight: '5px' }} />
                AI generated responses can contain inaccurate or misleading content.
            </div>
        ) : null;

    heading = (headingText: string) => (
        <div className="summary-heading">
            <label className="summary-text">{headingText}</label>
            {this.loading ? (
                <ReactLoading type="spin" color="#bcbcbc" width={14} height={14} />
            ) : (
                <>
                    {(this.mode === GPTPopupMode.SORT || this.mode === GPTPopupMode.QUIZ) && (
                        <IconButton color={StrCast(SettingsManager.userVariantColor)} tooltip="back" icon={<CgCornerUpLeft size="16px" />} onClick={() => (this.mode = GPTPopupMode.CARD)} style={{ right: '50px', position: 'absolute' }} />
                    )}
                    <IconButton
                        color={StrCast(SettingsManager.userVariantColor)}
                        tooltip="close"
                        icon={<CgClose size="16px" />}
                        onClick={() => {
                            this.setVisible(false);
                        }}
                    />
                </>
            )}
        </div>
    );

    render() {
        let content;

        switch (this.mode) {
            case GPTPopupMode.SUMMARY:
                content = this.summaryBox();
                break;
            case GPTPopupMode.DATA:
                content = this.dataAnalysisBox();
                break;
            case GPTPopupMode.IMAGE:
                content = this.imageBox();
                break;
            case GPTPopupMode.SORT:
            case GPTPopupMode.CARD:
            case GPTPopupMode.QUIZ:
                content = this.sortBox();
                break;
            default:
                content = null;
        }

        return (
            <div className="summary-box" style={{ display: this.visible ? 'flex' : 'none' }}>
                {content}
                <div className="resize-handle" />
            </div>
        );
    }
}