From a763c4e80cec6aef5219a8c9fcfa2ddccbc10b0a Mon Sep 17 00:00:00 2001
From: eleanor-park <eleanor_park@brown.edu>
Date: Wed, 24 Jul 2024 16:52:50 -0400
Subject: bug and render fixes

---
 src/client/views/smartdraw/AnnotationPalette.tsx | 203 ++++++-----------------
 1 file changed, 47 insertions(+), 156 deletions(-)

(limited to 'src/client/views/smartdraw/AnnotationPalette.tsx')

diff --git a/src/client/views/smartdraw/AnnotationPalette.tsx b/src/client/views/smartdraw/AnnotationPalette.tsx
index c8ce9e653..83f173fcb 100644
--- a/src/client/views/smartdraw/AnnotationPalette.tsx
+++ b/src/client/views/smartdraw/AnnotationPalette.tsx
@@ -8,13 +8,13 @@ import * as React from 'react';
 import { AiOutlineSend } from 'react-icons/ai';
 import ReactLoading from 'react-loading';
 import { returnAll, returnEmptyDoclist, returnEmptyFilter, returnFalse, returnOne, returnTrue, returnZero } from '../../../ClientUtils';
-import { ActiveInkWidth, Doc, DocListCast, StrListCast } from '../../../fields/Doc';
+import { ActiveInkWidth, Doc, DocListCast, Opt, StrListCast } from '../../../fields/Doc';
 import { DocData } from '../../../fields/DocSymbols';
 import { InkData, InkField } from '../../../fields/InkField';
 import { BoolCast, DocCast, ImageCast, NumCast } from '../../../fields/Types';
 import { emptyFunction, unimplementedFunction } from '../../../Utils';
 import { Docs } from '../../documents/Documents';
-import { makeUserTemplateButton } from '../../util/DropConverter';
+import { makeUserTemplateButton, makeUserTemplateImage } from '../../util/DropConverter';
 import { SettingsManager } from '../../util/SettingsManager';
 import { Transform } from '../../util/Transform';
 import { undoable, undoBatch } from '../../util/UndoManager';
@@ -28,20 +28,18 @@ import { DrawingOptions, SmartDrawHandler } from './SmartDrawHandler';
 import { DocumentType } from '../../documents/DocumentTypes';
 import { ImageField } from '../../../fields/URLField';
 import { CollectionCarousel3DView } from '../collections/CollectionCarousel3DView';
+import { Copy } from '../../../fields/FieldSymbols';
 
 @observer
-export class AnnotationPalette extends ObservableReactComponent<{}> {
+export class AnnotationPalette extends ObservableReactComponent<{ Document: Doc }> {
     static Instance: AnnotationPalette;
-    @observable private _display: boolean = false;
     @observable private _paletteMode: 'create' | 'view' = 'view';
     @observable private _userInput: string = '';
     @observable private _isLoading: boolean = false;
     @observable private _canInteract: boolean = true;
     @observable private _showRegenerate: boolean = false;
-    @observable private _freeFormCanvas = Docs.Create.FreeformDocument([], {});
-    @observable private _drawingCarousel = Docs.Create.CarouselDocument([], {});
-    @observable private _drawings: Doc[] = [];
-    private _drawing: Doc[] = [];
+    @observable private _docView: DocumentView | null = null;
+    @observable private _docCarouselView: DocumentView | null = null;
     @observable private _opts: DrawingOptions = { text: '', complexity: 5, size: 200, autoColor: true, x: 0, y: 0 };
     private _gptRes: string[] = [];
 
@@ -55,33 +53,16 @@ export class AnnotationPalette extends ObservableReactComponent<{}> {
         return FieldView.LayoutString(AnnotationPalette, fieldKey);
     }
 
-    public get FreeformCanvas() {
-        return this._freeFormCanvas;
-    }
-
-    public get DrawingCarousel() {
-        return this._drawingCarousel;
-    }
-
-    // componentDidUpdate(prevProps: Readonly<{}>) {
-    //     const docView = DocumentView.getDocumentView(this._freeFormCanvas);
-    //     const componentView = docView?.ComponentView as CollectionFreeFormView;
-    //     if (componentView) {
-    //         componentView.fitContentOnce();
-    //     }
-    //     this._freeFormCanvas._freeform_fitContentsToBox = false;
-    // }
+    Contains = (view: DocumentView) => {
+        return (this._docView && (view.containerViewPath?.() ?? []).concat(view).includes(this._docView)) || (this._docCarouselView && (view.containerViewPath?.() ?? []).concat(view).includes(this._docCarouselView));
+    };
 
     return170 = () => 170;
 
     @action
     handleKeyPress = async (event: React.KeyboardEvent) => {
         if (event.key === 'Enter') {
-            // if (this._showRegenerate) {
-            //     this.regenerate();
-            // } else {
             await this.generateDrawing();
-            // }
         }
     };
 
@@ -117,42 +98,34 @@ export class AnnotationPalette extends ObservableReactComponent<{}> {
         this.setDetail(5);
         this.setColor(true);
         this.setSize(200);
-        this._freeFormCanvas = Docs.Create.FreeformDocument([], {});
-        this._drawingCarousel = Docs.Create.CarouselDocument([], {});
         this._showRegenerate = false;
         this._canInteract = true;
-        this._drawing = [];
-        this._drawings = [];
         this._opts = { text: '', complexity: 5, size: 200, autoColor: true, x: 0, y: 0 };
         this._gptRes = [];
     };
 
-    addToPalette = async (doc: Doc) => {
-        if (!doc.savedAsAnno) {
-            const clone = await Doc.MakeClone(doc);
-            clone.clone.title = doc.title;
-            const image = await this.getIcon(doc);
-            if (image) {
-                const imageDoc = Docs.Create.ImageDocument(image);
-                Doc.AddDocToList(Doc.MyAnnos, 'data', imageDoc);
-            }
-            doc.savedAsAnno = true;
-            // const templateBtn = makeUserTemplateButton(clone.clone);
-            // Doc.AddDocToList(Doc.MyAnnos, 'data', templateBtn);
-            // this.resetPalette(true);
-        }
+    public static addToPalette = async (doc: Doc) => {
+        // if (!doc.savedAsAnno) {
+        //     const clone = await Doc.MakeClone(doc);
+        //     clone.clone.title = doc.title;
+        //     const image = (await this.getIcon(doc))?.[Copy]();
+        //     if (image) {
+        //         const imageTemplate = makeUserTemplateImage(clone.clone, image);
+        //         Doc.AddDocToList(Doc.MyAnnos, 'data', imageTemplate);
+        //         doc.savedAsAnno = true;
+        //     }
+        //     this.resetPalette(true);
+        // }
     };
 
-    @action
-    displayPalette = (display: boolean) => {
-        this._display = display;
-    };
+    // @action
+    // displayPalette = (display: boolean) => {
+    //     this._display = display;
+    // };
 
     @undoBatch
     generateDrawing = action(async () => {
         this._isLoading = true;
-        this._drawings = [];
-        this._drawing = [];
         for (var i = 0; i < 3; i++) {
             try {
                 SmartDrawHandler.Instance._addFunc = this.createDrawing;
@@ -177,8 +150,8 @@ export class AnnotationPalette extends ObservableReactComponent<{}> {
     createDrawing = (strokeList: [InkData, string, string][], opts: DrawingOptions, gptRes: string) => {
         this._opts = opts;
         this._gptRes.push(gptRes);
-        this._drawing = [];
-        // const childDocs = DocListCast(this._drawing1[DocData].data);
+        const drawing: Doc[] = [];
+
         strokeList.forEach((stroke: [InkData, string, string]) => {
             const bounds = InkField.getBounds(stroke[0]);
             const inkWidth = ActiveInkWidth();
@@ -199,51 +172,27 @@ export class AnnotationPalette extends ObservableReactComponent<{}> {
                 ActiveDash(),
                 ActiveIsInkMask()
             );
-            this._drawing.push(inkDoc);
-            // childDocs.push(inkDoc);
+            drawing.push(inkDoc);
         });
 
-        const cv = DocumentView.getDocumentView(this._freeFormCanvas)?.ComponentView as CollectionFreeFormView;
-        const collection = cv._marqueeViewRef.current?.collection(undefined, true, this._drawing);
+        const collection = MarqueeView.getCollection(drawing, undefined, true, { left: 1, top: 1, width: 1, height: 1 });
         if (collection) {
-            this._drawings.push(collection);
-            cv.fitContentOnce();
+            Doc.AddDocToList(this._props.Document, 'data', collection);
         }
-        this._drawingCarousel = Docs.Create.CarouselDocument(this._drawings, { childLayoutFitWidth: true, _layout_fitWidth: true, _freeform_fitContentsToBox: true });
-        this._freeFormCanvas = Docs.Create.FreeformDocument(this._drawing, { _freeform_fitContentsToBox: true });
     };
 
     saveDrawing = async () => {
-        // const cv = DocumentView.getDocumentView(this._freeFormCanvas)?.ComponentView as CollectionFreeFormView;
-        // if (cv) {
-        // const collection = cv._marqueeViewRef.current?.collection(undefined, true, this._drawing);
-        const cIndex: number = this._drawingCarousel.carousel_index as number;
-        const focusedDrawing = this._drawings[cIndex];
-
-        const docData = focusedDrawing[DocData];
-        docData.title = this._opts.text.match(/^(.*?)~~~.*$/)?.[1] || this._opts.text;
-        docData.drawingInput = this._opts.text;
-        docData.drawingComplexity = this._opts.complexity;
-        docData.drawingColored = this._opts.autoColor;
-        docData.drawingSize = this._opts.size;
-        docData.drawingData = this._gptRes[cIndex];
-        docData.width = this._opts.size;
-        // const image = await this.getIcon(collection);
-        await this.addToPalette(focusedDrawing);
-
-        // if (collection) {
-        //     const docData = collection[DocData];
-        //     docData.title = this._opts.text.match(/^(.*?)~~~.*$/)?.[1] || this._opts.text;
-        //     docData.drawingInput = this._opts.text;
-        //     docData.drawingComplexity = this._opts.complexity;
-        //     docData.drawingColored = this._opts.autoColor;
-        //     docData.drawingSize = this._opts.size;
-        //     docData.drawingData = this._gptRes;
-        //     docData.width = this._opts.size;
-        //     // const image = await this.getIcon(collection);
-        //     await this.addToPalette(collection);
-        // }
-        // }
+        // const cIndex: number = this._drawingCarousel.carousel_index as number;
+        // const focusedDrawing = this._drawings[cIndex];
+        // const docData = focusedDrawing[DocData];
+        // docData.title = this._opts.text.match(/^(.*?)~~~.*$/)?.[1] || this._opts.text;
+        // docData.drawingInput = this._opts.text;
+        // docData.drawingComplexity = this._opts.complexity;
+        // docData.drawingColored = this._opts.autoColor;
+        // docData.drawingSize = this._opts.size;
+        // docData.drawingData = this._gptRes[cIndex];
+        // docData.width = this._opts.size;
+        // await AnnotationPalette.addToPalette(focusedDrawing);
     };
 
     async getIcon(group: Doc) {
@@ -255,36 +204,13 @@ export class AnnotationPalette extends ObservableReactComponent<{}> {
         return undefined;
     }
 
-    @computed get drawingCreator() {
-        return (
-            <DocumentView
-                Document={this._freeFormCanvas}
-                addDocument={undefined}
-                addDocTab={DocumentViewInternal.addDocTabFunc}
-                pinToPres={DocumentView.PinDoc}
-                containerViewPath={returnEmptyDoclist}
-                styleProvider={DefaultStyleProvider}
-                removeDocument={returnFalse}
-                ScreenToLocalTransform={Transform.Identity}
-                PanelWidth={this.return170}
-                PanelHeight={this.return170}
-                renderDepth={1}
-                isContentActive={returnTrue}
-                focus={emptyFunction}
-                whenChildContentsActiveChanged={emptyFunction}
-                childFilters={returnEmptyFilter}
-                childFiltersByRanges={returnEmptyFilter}
-                searchFilterDocs={returnEmptyDoclist}
-            />
-        );
-    }
-
     render() {
-        return !this._display ? null : (
+        return (
             <div className="annotation-palette" style={{ zIndex: 1000 }}>
                 {this._paletteMode === 'view' && (
                     <>
                         <DocumentView
+                            ref={r => (this._docView = r)}
                             Document={Doc.MyAnnos}
                             addDocument={undefined}
                             addDocTab={DocumentViewInternal.addDocTabFunc}
@@ -303,34 +229,19 @@ export class AnnotationPalette extends ObservableReactComponent<{}> {
                             childFiltersByRanges={returnEmptyFilter}
                             searchFilterDocs={returnEmptyDoclist}
                         />
-                        <Button
-                            // style={{ alignSelf: 'center' }}
-                            text="Add"
-                            icon={<FontAwesomeIcon icon="square-plus" />}
-                            // iconPlacement=""
-                            color={SettingsManager.userColor}
-                            onClick={() => this.setPaletteMode('create')}
-                        />
+                        <Button text="Add" icon={<FontAwesomeIcon icon="square-plus" />} color={SettingsManager.userColor} onClick={() => this.setPaletteMode('create')} />
                     </>
                 )}
                 {this._paletteMode === 'create' && (
                     <>
                         <div style={{ display: 'flex', flexDirection: 'row', width: '170px' }}>
-                            {/* <IconButton
-                                tooltip="Advanced Options"
-                                icon={<FontAwesomeIcon icon="caret-right" />}
-                                color={SettingsManager.userColor}
-                                style={{ width: '14px' }}
-                                // onClick={() => {
-                                //     this._showOptions = !this._showOptions;
-                                // }}
-                            /> */}
                             <input
                                 aria-label="label-input"
                                 id="new-label"
                                 type="text"
                                 style={{ color: 'black', width: '170px' }}
                                 value={this._userInput}
+                                onClick={e => e.stopPropagation()}
                                 onChange={e => {
                                     this.setUserInput(e.target.value);
                                 }}
@@ -423,29 +334,9 @@ export class AnnotationPalette extends ObservableReactComponent<{}> {
                                 />
                             </div>
                         </div>
-                        <div style={{ display: 'none' }}>
-                            <DocumentView
-                                Document={this._freeFormCanvas}
-                                addDocument={undefined}
-                                addDocTab={DocumentViewInternal.addDocTabFunc}
-                                pinToPres={DocumentView.PinDoc}
-                                containerViewPath={returnEmptyDoclist}
-                                styleProvider={DefaultStyleProvider}
-                                removeDocument={returnFalse}
-                                ScreenToLocalTransform={Transform.Identity}
-                                PanelWidth={this.return170}
-                                PanelHeight={this.return170}
-                                renderDepth={1}
-                                isContentActive={returnTrue}
-                                focus={emptyFunction}
-                                whenChildContentsActiveChanged={emptyFunction}
-                                childFilters={returnEmptyFilter}
-                                childFiltersByRanges={returnEmptyFilter}
-                                searchFilterDocs={returnEmptyDoclist}
-                            />
-                        </div>
                         <DocumentView
-                            Document={this._drawingCarousel}
+                            ref={r => (this._docCarouselView = r)}
+                            Document={this._props.Document}
                             addDocument={undefined}
                             addDocTab={DocumentViewInternal.addDocTabFunc}
                             pinToPres={DocumentView.PinDoc}
-- 
cgit v1.2.3-70-g09d2

