From 8ec3055971ed3d79289e90c1fc2d0db5df131fe5 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Thu, 13 Feb 2025 10:19:35 -0500
Subject: trying to cleanup GPTpopup

---
 src/client/views/pdf/GPTPopup/GPTPopup.tsx | 159 +++++++++++++----------------
 1 file changed, 69 insertions(+), 90 deletions(-)

(limited to 'src/client/views/pdf/GPTPopup/GPTPopup.tsx')

diff --git a/src/client/views/pdf/GPTPopup/GPTPopup.tsx b/src/client/views/pdf/GPTPopup/GPTPopup.tsx
index f5a9f9e6a..628766209 100644
--- a/src/client/views/pdf/GPTPopup/GPTPopup.tsx
+++ b/src/client/views/pdf/GPTPopup/GPTPopup.tsx
@@ -19,6 +19,7 @@ import { ObservableReactComponent } from '../../ObservableReactComponent';
 import { DocumentView } from '../../nodes/DocumentView';
 import { AnchorMenu } from '../AnchorMenu';
 import './GPTPopup.scss';
+import { isJSDocProtectedTag } from 'typescript';
 
 export enum GPTPopupMode {
     SUMMARY,
@@ -116,17 +117,12 @@ export class GPTPopup extends ObservableReactComponent<object> {
 
     onSortComplete?: (sortResult: string, questionType: string, tag?: string) => void;
     onQuizRandom?: () => void;
-    @observable cardsDoneLoading = false;
 
     @observable collectionDoc: Doc | undefined = undefined;
     @action setCollectionDoc(doc: Doc | undefined) {
         this.collectionDoc = doc;
     }
 
-    @action setCardsDoneLoading(done: boolean) {
-        this.cardsDoneLoading = done;
-    }
-
     @observable sortRespText: string = '';
 
     @action setSortRespText(resp: string) {
@@ -151,31 +147,22 @@ export class GPTPopup extends ObservableReactComponent<object> {
      * 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);
-
-        await this.regenerateCallback?.();
-
-        const selected = DocumentView.SelectedDocs().lastElement();
-        if (!StrCast(selected.gptRubric)) {
-            await this.generateRubric(StrCast(selected.gptInputText), selected);
-        }
-
-        try {
-            const res = await gptAPICall('Question: ' + StrCast(selected.gptInputText) + ' UserAnswer: ' + this.quizAnswer + '.  Rubric: ' + StrCast(selected.gptRubric), GPTCallType.QUIZ);
-            if (res) {
-                this.setQuizResp(res);
-                this.conversationArray.push(res);
-
-                this.setLoading(false);
-                this.onQuizRandom?.();
-            } else {
-                console.error('GPT provided no response');
-            }
-        } catch (err) {
-            console.error('GPT call failed', err);
-        }
-    };
+    generateQuiz = (selected: Doc) =>
+        (this.regenerateCallback?.() ?? Promise.resolve()).then(() =>
+            this.generateRubric(selected).then(() =>
+                gptAPICall('Question: ' + StrCast(selected.gptInputText) + ' UserAnswer: ' + this.quizAnswer + '.  Rubric: ' + StrCast(selected.gptRubric), GPTCallType.QUIZ)
+                    .then(res => {
+                        if (res) {
+                            this.setQuizResp(res);
+                            this.conversationArray.push(res);
+                            this.onQuizRandom?.();
+                        } else {
+                            console.error('GPT provided no response');
+                        }
+                    })
+                    .catch(err => console.error('GPT call failed', err))
+            )
+        );
 
     /**
      * Generates a rubric by which to compare the user's answer to
@@ -183,15 +170,12 @@ export class GPTPopup extends ObservableReactComponent<object> {
      * @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', err);
-        }
-    };
+    generateRubric = (doc: Doc) =>
+        StrCast(doc.gptRubric)
+            ? Promise.resolve(StrCast(doc.gptRubric))
+            : gptAPICall(StrCast(doc.gptInputText), GPTCallType.RUBRIC)
+                  .then(res => (doc.gptRubric = res))
+                  .catch(err => console.error('GPT call failed', err));
 
     @observable private regenerateCallback: (() => Promise<void>) | null = null;
 
@@ -466,9 +450,11 @@ export class GPTPopup extends ObservableReactComponent<object> {
                 );
             } else {
                 this.conversationArray.push(this.quizAnswer);
-                this.generateQuiz().then(
+                this.setLoading(true);
+                this.generateQuiz(DocumentView.SelectedDocs().lastElement()).then(
                     action(() => {
                         this.quizAnswer = '';
+                        this.setLoading(false);
                     })
                 );
             }
@@ -477,60 +463,53 @@ export class GPTPopup extends ObservableReactComponent<object> {
         }
     };
 
-    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' }} />
+    cardActual = (isSort: boolean) => (
+        <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.loading && <div className={`chat-bubble chat-message`}>...</div>}
                 </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 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 = () => (
+    sortBox = (isSort: boolean) => (
         <div className="gptPopup-sortBox" 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
-                }
-            </>
+            {this.heading(isSort ? 'SORTING' : 'QUIZ')}
+            {!this.cardsDoneLoading ? (
+                <div className="content-wrapper">
+                    <div className="loading-spinner">
+                        a
+                        <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(isSort)
+            )}
         </div>
     );
 
@@ -724,7 +703,7 @@ export class GPTPopup extends ObservableReactComponent<object> {
             case GPTPopupMode.SORT:
             case GPTPopupMode.CARD:
             case GPTPopupMode.QUIZ:
-                content = this.sortBox();
+                content = this.sortBox(this.mode === GPTPopupMode.SORT);
                 break;
             default:
                 content = null;
-- 
cgit v1.2.3-70-g09d2

