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
|
import { Button, IconButton, Size, Toggle, ToggleType, Type } from '@dash/components';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { action, makeObservable, observable, reaction } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { AiOutlineSend } from 'react-icons/ai';
import { 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 { List } from '../../../../fields/List';
import { NumCast, StrCast } from '../../../../fields/Types';
import { ImageField } from '../../../../fields/URLField';
import { Upload } from '../../../../server/SharedMediaTypes';
import { Networking } from '../../../Network';
import { DataSeperator, DescriptionSeperator, DocSeperator, GPTCallType, GPTDocCommand, 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 { undoable } from '../../../util/UndoManager';
import { DictationButton } from '../../DictationButton';
import { ObservableReactComponent } from '../../ObservableReactComponent';
import { TagItem } from '../../TagsView';
import { ChatSortField, docSortings } from '../../collections/CollectionSubView';
import { ComparisonBox } from '../../nodes/ComparisonBox';
import { DocumentView, DocumentViewInternal } from '../../nodes/DocumentView';
import { OpenWhere } from '../../nodes/OpenWhere';
import { DrawingFillHandler } from '../../smartdraw/DrawingFillHandler';
import { FireflyImageDimensions } from '../../smartdraw/FireflyConstants';
import { SmartDrawHandler } from '../../smartdraw/SmartDrawHandler';
import { AnchorMenu } from '../AnchorMenu';
import './GPTPopup.scss';
export enum GPTPopupMode {
SUMMARY, // summary of seleted document text
IMAGE, // generate image from image description
DATA,
GPT_MENU, // menu for choosing type of prompts user will provide
USER_PROMPT, // user prompts for sorting,filtering and asking about docs
QUIZ_RESPONSE, // user definitions or explanations to be evaluated by GPT
FIREFLY, // firefly image generation
}
@observer
export class GPTPopup extends ObservableReactComponent<object> {
static Instance: GPTPopup;
static ChatTag = '#chat'; // tag used by GPT popup to filter docs
private _askDictation: DictationButton | null = null;
private _messagesEndRef: React.RefObject<HTMLDivElement>;
private _correlatedColumns: string[] = [];
private _dataChatPrompt: string | undefined = undefined;
private _imgTargetDoc: Doc | undefined;
private _textAnchor: Doc | undefined;
private _dataJson: string = '';
private _documentDescriptions: Promise<string> | undefined; // a cache of the descriptions of all docs in the selected collection. makes it more efficient when asking GPT multiple questions about the collection.
private _sidebarFieldKey: string = '';
private _aiReferenceText: string = '';
private _imageDescription: string = '';
private _textToDocMap = new Map<string, Doc>(); // when GPT answers with a doc's content, this helps us find the Doc
private _addToCollection: ((doc: Doc | Doc[], annotationKey?: string | undefined) => boolean) | undefined;
constructor(props: object) {
super(props);
makeObservable(this);
GPTPopup.Instance = this;
this._messagesEndRef = React.createRef();
}
public addDoc: ((doc: Doc | Doc[], sidebarKey?: string | undefined) => boolean) | undefined;
public createFilteredDoc: (axes?: string[]) => boolean = () => false;
public setSidebarFieldKey = (id: string) => (this._sidebarFieldKey = id);
public setImgTargetDoc = (anchor: Doc) => (this._imgTargetDoc = anchor);
public setTextAnchor = (anchor: Doc) => (this._textAnchor = anchor);
public setDataJson = (text: string) => {
if (text === '') this._dataChatPrompt = '';
this._dataJson = text;
};
componentDidUpdate() {
//this._gptProcessing && this.setStopAnimatingResponse(false);
}
componentDidMount(): void {
reaction(
() => ({ selDoc: DocumentView.Selected().lastElement(), visible: SnappingManager.ChatVisible }),
({ selDoc, visible }) => {
const hasChildDocs = visible && selDoc?.ComponentView?.hasChildDocs;
if (hasChildDocs) {
this._textToDocMap.clear();
this.setCollectionContext(selDoc.Document);
this.onGptResponse = (sortResult: string, questionType: GPTDocCommand) => this.processGptResponse(selDoc, this._textToDocMap, sortResult, questionType);
this.onQuizRandom = () => this.randomlyChooseDoc(selDoc.Document, hasChildDocs());
this._documentDescriptions = Promise.all(hasChildDocs().map(doc =>
Doc.getDescription(doc).then(text => text.replace(/\n/g, ' ').trim())
.then(text => this._textToDocMap.set(text, doc) && `${DescriptionSeperator}${text}${DescriptionSeperator}`)
)).then(docDescriptions => docDescriptions.join()); // prettier-ignore
this._documentDescriptions.then(descs => {
console.log(descs);
});
}
},
{ fireImmediately: true }
);
}
@observable private _showOriginal = true;
@observable private _responseText: string = '';
@observable private _conversationArray: string[] = ['Hi! In this pop up, you can ask ChatGPT questions about your documents and filter / sort them. '];
@observable private _fireflyArray: string[] = ['Hi! In this pop up, you can ask Firefly to create images. '];
@observable private _chatEnabled: boolean = false;
@action private setChatEnabled = (start: boolean) => (this._chatEnabled = start);
@observable private _gptProcessing: boolean = false;
@action private setGptProcessing = (loading: boolean) => (this._gptProcessing = loading);
@observable private _imgUrls: string[][] = [];
@action private setImgUrls = (imgs: string[][]) => (this._imgUrls = imgs);
@observable private _collectionContext: Doc | undefined = undefined;
@action setCollectionContext = (doc: Doc | undefined) => (this._collectionContext = doc);
@observable private _userPrompt: string = '';
@action setUserPrompt = (e: string) => (this._userPrompt = e);
@observable private _quizAnswer: string = '';
@action setQuizAnswer = (e: string) => (this._quizAnswer = e);
@observable private _stopAnimatingResponse: boolean = false;
@action private setStopAnimatingResponse = (done: boolean) => (this._stopAnimatingResponse = done);
@observable private _mode: GPTPopupMode = GPTPopupMode.SUMMARY;
@action public setMode = (mode: GPTPopupMode) => (this._mode = mode);
onQuizRandom?: () => void;
onGptResponse?: (sortResult: string, questionType: GPTDocCommand, args?: string) => void;
NumberToCommandType = (questionType: string) => +questionType.split(' ')[0][0];
/**
* Processes gpt's output depending on the type of question the user asked. Converts gpt's string output to
* usable code
* @param gptOutput
* @param questionType
* @param tag
*/
processGptResponse = (docView: DocumentView, textToDocMap: Map<string, Doc>, gptOutput: string, questionType: GPTDocCommand) =>
undoable(() => {
switch (questionType) { // reset collection based on question typefc
case GPTDocCommand.Sort:
docView.Document[docView.ComponentView?.fieldKey + '_sort'] = docSortings.Chat;
break;
case GPTDocCommand.Filter:
docView.ComponentView?.hasChildDocs?.().forEach(d => TagItem.removeTagFromDoc(d, GPTPopup.ChatTag));
break;
} // prettier-ignore
gptOutput.split(DescriptionSeperator).filter(item => item.trim() !== '') // Split output into individual document contents
.map(docContentRaw => docContentRaw.replace(/\n/g, ' ').trim())
.map(docContentRaw => ({doc: textToDocMap.get(docContentRaw.split(DataSeperator)[0]), data: docContentRaw.split(DataSeperator)[1] })) // the find the corresponding Doc using textToDoc map
.filter(({doc}) => doc).map(({doc, data}) => ({doc:doc!, data})) // filter out undefined values
.forEach(({doc, data}, index) => {
switch (questionType) {
case GPTDocCommand.Sort:
doc[ChatSortField] = index;
break;
case GPTDocCommand.AssignTags:
data && TagItem.addTagToDoc(doc, data.startsWith('#') ? data : '#'+data[0].toLowerCase()+data.slice(1) );
break;
case GPTDocCommand.Filter:
TagItem.addTagToDoc(doc, GPTPopup.ChatTag);
Doc.setDocFilter(docView.Document, 'tags', GPTPopup.ChatTag, 'check');
break;
}
}); // prettier-ignore
}, '')();
/**
* When in quiz mode, randomly selects a document
*/
randomlyChooseDoc = (doc: Doc, childDocs: Doc[]) => DocumentView.getDocumentView(childDocs[Math.floor(Math.random() * childDocs.length)])?.select(false);
/**
* Generates a rubric for evaluating the user's description of the document's text
* @param doc the doc the user is providing info about
* @returns gpt's response rubric
*/
generateRubric = (doc: Doc) =>
StrCast(doc.gptRubric)
? Promise.resolve(StrCast(doc.gptRubric))
: Doc.getDescription(doc).then(desc =>
gptAPICall(desc, GPTCallType.MAKERUBRIC)
.then(res => (doc.gptRubric = res))
.catch(err => console.error('GPT call failed', err))
);
/**
* When the cards are in quiz mode in the card view, allows gpt to determine whether the user's answer was correct
* @param doc the doc the user is providing info about
* @param quizAnswer the user's answer/description for the document
* @returns
*/
generateQuizAnswerAnalysis = (doc: Doc, quizAnswer: string) =>
this.generateRubric(doc).then(() =>
Doc.getDescription(doc).then(desc =>
gptAPICall(
`Question: ${desc};
UserAnswer: ${quizAnswer};
Rubric: ${StrCast(doc.gptRubric)}`,
GPTCallType.QUIZDOC
).then(res => {
this._conversationArray.push(res || 'GPT provided no answer');
this.onQuizRandom?.();
})
.catch(err => console.error('GPT call failed', err))
)) // prettier-ignore
generateFireflyImage = (imgDesc: string) => {
const selView = DocumentView.Selected().lastElement();
const selDoc = selView?.Document;
if (selDoc && (selView._props.renderDepth > 1 || selDoc[Doc.LayoutDataKey(selDoc)] instanceof ImageField)) {
const oldPrompt = StrCast(selDoc.ai_prompt, StrCast(selDoc.title));
const newPrompt = oldPrompt ? `${oldPrompt} ~~~ ${imgDesc}` : imgDesc;
return DrawingFillHandler.drawingToImage(selDoc, 100, newPrompt, selDoc)
.then(action(() => (this._userPrompt = '')))
.catch(e => {
alert(e);
return undefined;
});
}
return SmartDrawHandler.CreateWithFirefly(imgDesc, FireflyImageDimensions.Square, 0)
.then(
action(doc => {
doc instanceof Doc && DocumentViewInternal.addDocTabFunc(doc, OpenWhere.addRight);
this._userPrompt = '';
})
)
.catch(e => {
alert(e);
return undefined;
});
};
/**
* Generates a response to the user's question about the docs in the collection.
* The type of response depends on the chat's analysis of the type of their question
* @param userPrompt the user's input that chat will respond to
*/
generateUserPromptResponse = (userPrompt: string) =>
gptAPICall(userPrompt, GPTCallType.COMMANDTYPE, undefined, true).then(commandType =>
(async () => {
switch (this.NumberToCommandType(commandType)) {
case GPTDocCommand.AssignTags:return this._documentDescriptions?.then(descs => gptAPICall(userPrompt, GPTCallType.TAGDOCS, descs)) ?? "";
case GPTDocCommand.Filter: return this._documentDescriptions?.then(descs => gptAPICall(userPrompt, GPTCallType.SUBSETDOCS, descs)) ?? "";
case GPTDocCommand.Sort: return this._documentDescriptions?.then(descs => gptAPICall(userPrompt, GPTCallType.SORTDOCS, descs)) ?? "";
default: return Doc.getDescription(DocumentView.SelectedDocs().lastElement()).then(desc => gptAPICall(userPrompt, GPTCallType.DOCINFO, desc));
} // prettier-ignore
})().then(
action(res => {
// Trigger the callback with the result
this.onGptResponse?.(res || 'Something went wrong :(', this.NumberToCommandType(commandType));
this._conversationArray.push(
this.NumberToCommandType(commandType) === GPTDocCommand.GetInfo ? res:
// Extract explanation surrounded by the DocSeperator string (defined in GPT.ts) at the top or both at the top and bottom
(res.match(new RegExp(`${DocSeperator}\\s*([\\s\\S]*?)\\s*(?:${DocSeperator}|$)`)) ?? [])[1]?.trim() ?? 'No explanation found'
);
})
).catch(err => console.log(err))
).catch(err => console.log(err)); // prettier-ignore
/**
* Generates a Dalle image and uploads it to the server.
*/
generateImage = (imgDesc: string, imgTarget: Doc, addToCollection?: (doc: Doc | Doc[], annotationKey?: string | undefined) => boolean) => {
this._imgTargetDoc = imgTarget;
SnappingManager.SetChatVisible(true);
this.addDoc = addToCollection;
this.setImgUrls([]);
this.setMode(GPTPopupMode.IMAGE);
this.setGptProcessing(true);
this._imageDescription = imgDesc;
return gptImageCall(imgDesc)
.then(imageUrls =>
imageUrls?.[0]
? Networking.PostToServer('/uploadRemoteImage', { sources: [imageUrls[0]] }).then(res => {
const source = ClientUtils.prepend((res as Upload.FileInformation[])[0].accessPaths.agnostic.client);
return this.setImgUrls([[imageUrls[0]!, source]]);
})
: undefined
)
.catch(err => console.error(err))
.finally(() => this.setGptProcessing(false));
};
/**
* Completes an API call to generate a summary of the specified text
*
* @param text the text to summarize
*/
private generateSummary = action((text: string) => {
SnappingManager.SetChatVisible(true);
this._showOriginal = false;
this.setGptProcessing(true);
return gptAPICall(text, GPTCallType.SUMMARY)
.then(action(res => (this._responseText = res || 'Something went wrong.')))
.catch(err => console.error(err))
.finally(() => this.setGptProcessing(false));
});
/**
* Completes an API call to generate a summary of the specified text
*
* @param text the text to summarizz
*/
askAIAboutSelection = action((text: string) => {
SnappingManager.SetChatVisible(true);
this._aiReferenceText = text;
this._responseText = '';
this._showOriginal = true;
this.setMode(GPTPopupMode.SUMMARY);
});
/**
* Completes an API call to generate an analysis of
* this.dataJson in the popup.
*/
generateDataAnalysis = () => {
this.setGptProcessing(true);
return gptAPICall(this._dataJson, GPTCallType.DATA, this._dataChatPrompt)
.then(
action(res => {
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]]);
this._responseText = json[keys[2]] || 'Something went wrong.';
})
)
.catch(err => console.error(err))
.finally(() => this.setGptProcessing(false));
};
/**
* Transfers the summarization text to a sidebar annotation text document.
*/
private transferToText = () => {
const newDoc = Docs.Create.TextDocument(this._responseText.trim(), {
_width: 200,
_height: 50,
_layout_fitWidth: true,
_layout_autoHeight: true,
});
this.addDoc?.(newDoc, this._sidebarFieldKey);
const anchor = AnchorMenu.Instance?.GetAnchor(undefined, false);
if (anchor) {
DocUtils.MakeLink(newDoc, anchor, {
link_relationship: 'GPT Summary',
});
}
};
/**
* Create Flashcards for the selected text
*/
private createFlashcards = action(
() =>
this.setGptProcessing(true) &&
gptAPICall(this._aiReferenceText, GPTCallType.FLASHCARD, undefined, true)
.then(res =>
ComparisonBox.createFlashcardDeck(res, 250, 200, 'data_front', 'data_back').then(
action(newCol => {
newCol.zIndex = 1000;
DocumentViewInternal.addDocTabFunc(newCol, OpenWhere.addRight);
})
)
)
.catch(console.error)
.finally(action(() => (this._gptProcessing = false)))
);
/**
* 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) {
const newDoc = Docs.Create.ImageDocument(source, {
x: NumCast(textAnchor.x) + NumCast(textAnchor._width) + 10,
y: NumCast(textAnchor.y),
_height: 200,
_width: 200,
ai: 'dall-e',
tags: new List<string>(['@ai']),
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.addDoc?.(newDoc);
}
// Create link between prompt and image
DocUtils.MakeLink(textAnchor, newDoc, { link_relationship: 'Image Prompt' });
}
};
scrollToBottom = () => setTimeout(() => this._messagesEndRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' }), 50);
gptMenu = () => (
<div style={{ display: 'flex', maxHeight: 'calc(100% - 32px)', overflow: 'auto' }}>
<div className="btns-wrapper-gpt">
<Button
tooltip="Ask Firefly to create images"
text="Ask Firefly"
onClick={() => this.setMode(GPTPopupMode.FIREFLY)}
color={SettingsManager.userColor}
background={SettingsManager.userVariantColor}
type={Type.TERT}
style={{
width: '100%',
height: '40%',
textAlign: 'center',
color: '#ffffff',
fontSize: '16px',
marginBottom: '10px',
}}
/>
<Button
tooltip="Ask GPT to sort, tag, define, or filter your Docs!"
text="Ask GPT"
onClick={() => this.setMode(GPTPopupMode.USER_PROMPT)}
color={SettingsManager.userColor}
background={SettingsManager.userVariantColor}
type={Type.TERT}
style={{
width: '100%',
height: '40%',
textAlign: 'center',
color: '#ffffff',
fontSize: '16px',
marginBottom: '10px',
}}
/>
<Button
tooltip="Test your knowledge by verifying answers with ChatGPT"
text="Take Quiz"
onClick={() => {
this._conversationArray = ['Define the selected card!'];
this.setMode(GPTPopupMode.QUIZ_RESPONSE);
this.onQuizRandom?.();
}}
color={SettingsManager.userColor}
background={SettingsManager.userVariantColor}
type={Type.TERT}
style={{
width: '100%',
height: '40%',
textAlign: 'center',
color: '#ffffff',
fontSize: '16px',
}}
/>
</div>
</div>
);
callGpt = action((mode: GPTPopupMode) => {
this.setGptProcessing(true);
const reset = action(() => {
this.setGptProcessing(false);
this._userPrompt = '';
this._quizAnswer = '';
});
switch (mode) {
case GPTPopupMode.FIREFLY:
this._fireflyArray.push(this._userPrompt);
return this.generateFireflyImage(this._userPrompt).then(reset);
case GPTPopupMode.USER_PROMPT:
this._conversationArray.push(this._userPrompt);
return this.generateUserPromptResponse(this._userPrompt).then(reset);
case GPTPopupMode.QUIZ_RESPONSE:
this._conversationArray.push(this._quizAnswer);
return this.generateQuizAnswerAnalysis(DocumentView.SelectedDocs().lastElement(), this._quizAnswer).then(reset);
}
});
@action
handleKeyPress = async (e: React.KeyboardEvent, mode: GPTPopupMode) => {
this._askDictation?.stopDictation();
if (e.key === 'Enter') {
e.stopPropagation();
this.callGpt(mode)?.then(() => {
this.setGptProcessing(false);
this.scrollToBottom();
});
}
};
gptUserInput = () => (
<div style={{ display: 'flex', maxHeight: 'calc(100% - 32px)', overflow: 'auto' }}>
<div className="btns-wrapper-gpt">
<div className="chat-wrapper">
<div className="chat-bubbles">
{(this._mode === GPTPopupMode.FIREFLY ? this._fireflyArray : this._conversationArray).map((message, index) => (
<div key={index} className={`chat-bubble ${index % 2 === 1 ? 'user-message' : 'chat-message'}`}>
{message}
</div>
))}
{this._gptProcessing && <div className="chat-bubble chat-message">...</div>}
</div>
<div ref={this._messagesEndRef} style={{ height: '40px' }} />
</div>
</div>
</div>
);
setDictationRef = (r: DictationButton | null) => (this._askDictation = r);
promptBox = (heading: string, value: string, onChange: (e: string) => string, placeholder: string) => (
<>
<div className="gptPopup-sortBox">
{this.heading(heading)}
{this.gptUserInput()}
</div>
<div className="inputWrapper">
<input
className="searchBox-input"
value={value} // Controlled input
autoComplete="off"
onChange={e => onChange(e.target.value)}
onKeyDown={e => this.handleKeyPress(e, this._mode)}
type="text"
style={{ color: 'black' }}
placeholder={placeholder}
/>
<Button //\
type={Type.PRIM}
tooltip="Send to AI"
icon={<AiOutlineSend />}
iconPlacement="right"
background={SnappingManager.userVariantColor}
onClick={() => this.callGpt(this._mode)}
size={Size.LARGE}
/>
<DictationButton ref={this.setDictationRef} setInput={onChange} />
</div>
</>
);
menuBox = () => (
<div className="gptPopup-sortBox">
{this.heading('CHOOSE')}
{this.gptMenu()}
</div>
);
imageBox = () => (
<div style={{ display: 'flex', flexDirection: 'column', gap: '1rem', overflow: 'auto', height: '100%', pointerEvents: 'all' }}>
{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>
<div key={rawSrc[0] + i + 'btn'} className="btn-container">
<Button text="Save Image" onClick={() => this.transferToImage(rawSrc[1])} color={SettingsManager.userColor} background={SettingsManager.userVariantColor} type={Type.TERT} />
</div>
</>
))}
</div>
{this._gptProcessing ? null : (
<IconButton
tooltip="Generate Again"
onClick={() => this._imgTargetDoc && this.generateImage(this._imageDescription, this._imgTargetDoc, this._addToCollection)}
icon={<FontAwesomeIcon icon="redo-alt" size="lg" />}
color={SettingsManager.userColor}
background={SettingsManager.userVariantColor}
/>
)}
</div>
);
summaryBox = () => (
<>
<div className="gptPopup-summaryBox-content">
<div onClick={action(() => (this._showOriginal = !this._showOriginal))}>{this.heading(this._showOriginal ? 'SELECTION' : 'SUMMARY')}</div>
<div className="gptPopup-content-wrapper">
{!this._gptProcessing && !this._stopAnimatingResponse && this._responseText ? (
<TypeAnimation
speed={50}
sequence={[
this._responseText,
() => {
setTimeout(() => this.setStopAnimatingResponse(true), 500);
},
]}
/>
) : this._showOriginal ? (
this._gptProcessing ? (
'...generating cards...'
) : (
this._aiReferenceText
)
) : (
this._responseText || (this._gptProcessing ? '...generating summary...' : '-no ai summary-')
)}
</div>
</div>
{this._gptProcessing ? null : (
<div className="btns-wrapper" style={{ position: 'relative', width: 'calc(100% - 32px)' }}>
{this._stopAnimatingResponse || !this._responseText ? (
<div style={{ display: 'flex' }}>
{!this._showOriginal ? (
<>
<Button
tooltip="Show originally selected text" //
text="Selection"
onClick={action(() => (this._showOriginal = true))}
color={SettingsManager.userColor}
background={SettingsManager.userVariantColor}
type={Type.TERT}
/>
<Button
tooltip="Create a text Doc with this text and link to the text selection" //
text="Transfer To Text"
onClick={this.transferToText}
color={SettingsManager.userColor}
background={SettingsManager.userVariantColor}
type={Type.TERT}
/>
</>
) : (
<>
<Button
tooltip="Show AI summary of original selection text (Shift+Click to regenerate)"
text="Summary"
onClick={action(e => {
if (e.shiftKey) {
this.setStopAnimatingResponse(false);
this._aiReferenceText += ' ';
this._responseText = '';
}
this.generateSummary(this._aiReferenceText);
})}
color={SettingsManager.userColor}
background={SettingsManager.userVariantColor}
type={Type.TERT}
/>
<Button
tooltip="Create Flashcards" //
text="Create Flashcards"
onClick={this.createFlashcards}
color={SettingsManager.userColor}
background={SettingsManager.userVariantColor}
type={Type.TERT}
/>
</>
)}
</div>
) : (
<div className="summarizing">
<span>{this._showOriginal ? 'Creating Cards...' : 'Summarizing'}</span>
<ReactLoading type="bubbles" color="#bcbcbc" width={20} height={20} />
<Button text="Stop Animation" onClick={() => this.setStopAnimatingResponse(true)} color={SettingsManager.userColor} background={SettingsManager.userVariantColor} type={Type.TERT} />
</div>
)}
</div>
)}
</>
);
dataAnalysisBox = () => (
<>
<div>
{this.heading('ANALYSIS')}
<div className="gptPopup-content-wrapper">
{!this._gptProcessing &&
(!this._stopAnimatingResponse ? (
<TypeAnimation
speed={50}
sequence={[
this._responseText,
() => {
setTimeout(() => this.setStopAnimatingResponse(true), 500);
},
]}
/>
) : (
this._responseText
))}
</div>
</div>
{!this._gptProcessing && (
<div className="btns-wrapper">
{this._stopAnimatingResponse ? (
this._chatEnabled ? (
<input
defaultValue=""
autoComplete="off"
onChange={e => (this._dataChatPrompt = e.target.value)}
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%', color: SnappingManager.userColor }}
/>
) : (
<>
<Button tooltip="Transfer to text" text="Transfer To Text" onClick={this.transferToText} color={SettingsManager.userColor} background={SettingsManager.userVariantColor} type={Type.TERT} />
<Button tooltip="Chat with AI" text="Chat with AI" onClick={() => this.setChatEnabled(true)} color={SettingsManager.userColor} background={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.setStopAnimatingResponse(true)} color={SettingsManager.userColor} background={SettingsManager.userVariantColor} type={Type.TERT} />
</div>
)}
</div>
)}
</>
);
aiWarning = () =>
!this._stopAnimatingResponse ? null : (
<div className="ai-warning">
<FontAwesomeIcon icon="exclamation-circle" size="sm" style={{ paddingRight: '5px' }} />
AI generated responses can contain inaccurate or misleading content.
</div>
);
heading = (headingText: string) => (
<div className="summary-heading" style={{ color: SnappingManager.userBackgroundColor }}>
<label className="summary-text">{headingText}</label>
{this._gptProcessing ? (
<ReactLoading type="spin" color="#bcbcbc" width={14} height={14} />
) : (
<>
<Toggle
tooltip="Clear Chat filter"
toggleType={ToggleType.BUTTON}
type={Type.PRIM}
toggleStatus={Doc.hasDocFilter(this._collectionContext, 'tags', GPTPopup.ChatTag)}
text={Doc.hasDocFilter(this._collectionContext, 'tags', GPTPopup.ChatTag) ? 'filtered' : ''}
color={Doc.hasDocFilter(this._collectionContext, 'tags', GPTPopup.ChatTag) ? 'red' : 'transparent'}
onClick={() => this._collectionContext && Doc.setDocFilter(this._collectionContext, 'tags', GPTPopup.ChatTag, 'remove')}
/>
{[GPTPopupMode.USER_PROMPT, GPTPopupMode.QUIZ_RESPONSE, GPTPopupMode.FIREFLY].includes(this._mode) && (
<IconButton color={SettingsManager.userVariantColor} background={SettingsManager.userColor} tooltip="back" icon={<CgCornerUpLeft size="16px" />} onClick={action(() => (this._mode = GPTPopupMode.GPT_MENU))} />
)}
</>
)}
</div>
);
render() {
return (
<div className="gptPopup-summary-box" style={{ background: SnappingManager.userColor, color: SnappingManager.userBackgroundColor, display: SnappingManager.ChatVisible ? 'flex' : 'none' }}>
{(() => {
//prettier-ignore
switch (this._mode) {
case GPTPopupMode.USER_PROMPT: return this.promptBox("ASK", this._userPrompt, this.setUserPrompt, 'Ask GPT to sort, tag, define, or filter your documents for you!');
case GPTPopupMode.FIREFLY: return this.promptBox("CREATE", this._userPrompt, this.setUserPrompt, StrCast(DocumentView.Selected().lastElement()?.Document.ai_prompt, 'Ask Firefly to generate images'));
case GPTPopupMode.QUIZ_RESPONSE: return this.promptBox("QUIZ", this._quizAnswer, this.setQuizAnswer, 'Describe/answer the selected document!');
case GPTPopupMode.GPT_MENU: return this.menuBox();
case GPTPopupMode.SUMMARY: return this.summaryBox();
case GPTPopupMode.DATA: return this.dataAnalysisBox();
case GPTPopupMode.IMAGE: return this.imageBox();
default: return null;
}
})()}
</div>
);
}
}
|