From dd27b5aaafa2a6976e7745d57da6521159da2a83 Mon Sep 17 00:00:00 2001
From: Nathan-SR <144961007+Nathan-SR@users.noreply.github.com>
Date: Tue, 5 Nov 2024 05:28:18 -0500
Subject: fixed a bunch of slowdowns

---
 .../DataVizBox/DocCreatorMenu/DocCreatorMenu.tsx   | 137 ++++++++++-----------
 1 file changed, 62 insertions(+), 75 deletions(-)

(limited to 'src/client/views/nodes/DataVizBox/DocCreatorMenu/DocCreatorMenu.tsx')

diff --git a/src/client/views/nodes/DataVizBox/DocCreatorMenu/DocCreatorMenu.tsx b/src/client/views/nodes/DataVizBox/DocCreatorMenu/DocCreatorMenu.tsx
index fcf237e02..f075dc737 100644
--- a/src/client/views/nodes/DataVizBox/DocCreatorMenu/DocCreatorMenu.tsx
+++ b/src/client/views/nodes/DataVizBox/DocCreatorMenu/DocCreatorMenu.tsx
@@ -66,10 +66,10 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
     @observable _layoutPreview: boolean = true;
     @observable _layoutPreviewScale: number = 1;
     @observable _savedLayouts: DataVizTemplateLayout[] = [];
-    @observable _expandedPreview: { icon: ImageField; doc: Doc } | undefined = undefined;
+    @observable _expandedPreview: Doc | undefined = undefined;
 
     @observable _suggestedTemplates: Template[] = [];
-    @observable _suggestedTemplateDocs
+    @observable _suggestedTemplatePreviews: {doc: Doc, template: Template}[] = [];
     @observable _GPTOpt: boolean = false;
     @observable _userPrompt: string = '';
     @observable _callCount: number = 0;
@@ -113,8 +113,16 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
     @action setTemplateDocs = (docs: Doc[]) => {
         this._templateDocs = docs.map(doc => (doc.annotationOn ? DocCast(doc.annotationOn) : doc));
     };
+    @action updateTemplatePreviews = (templates: Template[]) => {
+        this._suggestedTemplatePreviews = templates.map(template => {
+            const doc = template.mainField.renderedDoc();
+            const wrapper: Doc = Docs.Create.FreeformDocument([doc], { _height: NumListCast(doc._height)[0], _width: NumListCast(doc._width)[0], title: ''});
+            return {doc: wrapper, template: template};
+        });
+    }
     @action setSuggestedTemplates = (templates: Template[]) => {
         this._suggestedTemplates = templates;
+        this.updateTemplatePreviews(templates);
     };
 
     @computed get docsToRender() {
@@ -157,45 +165,6 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
         return StrListCast(this._dataViz?.layoutDoc._dataViz_axes);
     }
 
-    @computed get selectedTemplateDocs(): {doc: React.JSX.Element, template: Template}[] {
-        const docs: {doc: Doc, template: Template}[] = this._suggestedTemplates?.map(template => { return {doc: template.mainField.renderedDoc(), template: template}});
-        const docPreviews: {doc: Doc, template: Template}[] = docs.map(info => 
-            {return {doc: Docs.Create.FreeformDocument([info.doc], { _height: NumListCast(info.doc._height)[0], _width: NumListCast(info.doc._width)[0], title: ''}), template: info.template}
-        });
-        const renderedComponents = docPreviews.map(info => 
-            {return {doc: <CollectionFreeFormView
-            Document={info.doc}
-            docViewPath={returnEmptyDocViewList}
-            childLayoutTemplate={() => Cast(info.doc.childLayoutTemplate, Doc, null)}
-            isContentActive={emptyFunction}
-            isAnyChildContentActive={() => true}
-            select={emptyFunction}
-            isSelected={returnFalse}
-            fieldKey={Doc.LayoutFieldKey(info.doc)}
-            addDocument={returnFalse}
-            moveDocument={returnFalse}
-            removeDocument={returnFalse}
-            PanelWidth={() => 100}
-            PanelHeight={() => 100}
-            ScreenToLocalTransform={() => new Transform(-this._pageX - 5,-this._pageY - 35, 1)}
-            renderDepth={5}
-            whenChildContentsActiveChanged={emptyFunction}
-            focus={emptyFunction}
-            styleProvider={DefaultStyleProvider}
-            addDocTab={this._props.addDocTab}
-            // eslint-disable-next-line no-use-before-define
-            pinToPres={() => undefined}
-            childFilters={returnEmptyFilter}
-            childFiltersByRanges={returnEmptyFilter}
-            searchFilterDocs={returnEmptyDoclist}
-            fitContentsToBox={returnTrue}
-            xPadding={0}
-            yPadding={0}
-            />, template: info.template}
-        });
-        return renderedComponents;
-    }
-
     @computed get fieldsInfos(): Col[] {
         const colInfo = this._dataViz?.colsInfo;
         return this.selectedFields
@@ -274,14 +243,6 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
     componentDidMount() {
         document.addEventListener('pointerdown', this.onPointerDown, true);
         document.addEventListener('pointerup', this.onPointerUp);
-        this._disposers.templates = reaction(
-            () => this._templateDocs.slice(),
-            docs => this.updateIcons(docs)
-        );
-        this._disposers.gpt = reaction(
-            () => this._suggestedTemplates.slice(),
-            templates => this.updateIcons(templates.map(t => t.doc))
-        );
         //this._disposers.columns = reaction(() => this._dataViz?.layoutDoc._dataViz_axes, () => {this.generateTemplates('')})
         this._disposers.lightbox = reaction(
             () => LightboxView.LightboxDoc(),
@@ -302,11 +263,6 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
         document.removeEventListener('pointerup', this.onPointerUp);
     }
 
-    updateIcons = (docs: Doc[]) => {
-        console.log('called')
-        docs.map(this.getIcon);
-    };
-
     @action
     updateSelectedCols = (cols: string[]) => {
         this._selectedCols;
@@ -450,7 +406,7 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
 
     testTemplate = async () => {
 
-        console.log(this.templateManager.templates)
+        //console.log(this.templateManager.templates)
 
         this.forceUpdate();
 
@@ -723,8 +679,6 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
         const cols = this.fieldsInfos;
         const templates = this.templateManager.getValidTemplates(cols);
 
-        console.log('templates: ', templates)
-
         const assignments: [Template, { [field: number]: Col }][] = await this.assignColsToFields(templates, cols);
 
         const renderedTemplatePromises: Promise<Template>[] = assignments.map(([template, assignments]) => this.applyGPTContentToTemplate(template, assignments));
@@ -741,6 +695,7 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
         const dv = this._dataViz;
         if (!dv) return;
         const fields: string[] = Array.from(Object.keys(dv.records[0]));
+        console.log('columns: ', fields)    
         const selectedRows = NumListCast(dv.layoutDoc.dataViz_selectedRows);
 
         const fieldContents: {[title: string]: string}[] = selectedRows.map(row => {
@@ -752,36 +707,41 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
             return values;
         });
 
+        console.log("fieldcontents: ", fieldContents)
+
         const renderedDocs: Doc[] = [];
 
         fieldContents.forEach(content => {
-            fields.forEach(title => {
+            fields.filter(title => title).forEach(title => {
                 const field = template.getFieldByTitle(title);
+                if (field === undefined){
+                    return;
+                }
+                console.log('title: ', title, 'field: ', field)
                 field.setContent(content[title]);
             });
 
             renderedDocs.push(template.mainField.renderedDoc());
         });
 
+        console.log("rendered ", renderedDocs);
         return renderedDocs;
     }
 
     @action setExpandedView = (doc: Doc | undefined) => {
         if (doc) {
-            const wrapper: Doc = Docs.Create.FreeformDocument([doc], { _height: NumListCast(doc._height)[0], _width: NumListCast(doc._width)[0], title: ''});
-            const newInfo = {icon: new ImageField(''), doc: wrapper}
-            this._expandedPreview = newInfo;
+            this._expandedPreview = Docs.Create.FreeformDocument([doc], { _height: NumListCast(doc._height)[0], _width: NumListCast(doc._width)[0], title: ''});
         } else {
-            this._expandedPreview = {icon: new ImageField(''), doc: doc ?? new Doc()}; //!!! get rid of image stuff
+            this._expandedPreview = undefined;
         }
     };
 
     get editingWindow(){
-        const doc = this._expandedPreview?.doc ?? new Doc();
+        const doc = this._expandedPreview ?? new Doc();
         const rendered = 
             <div className="docCreatorMenu-expanded-template-preview">
                 <CollectionFreeFormView
-                    Document={this._expandedPreview!.doc}
+                    Document={this._expandedPreview ?? new Doc()}
                     docViewPath={returnEmptyDocViewList}
                     childLayoutTemplate={() => Cast(doc.childLayoutTemplate, Doc, null)}
                     isContentActive={emptyFunction}
@@ -817,10 +777,10 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
                 <div className="top-panel"/>
                 {rendered}
                 <div className="right-buttons-panel">
-                    <button className="docCreatorMenu-menu-button section-reveal-options top-right" onPointerDown={e => this.setUpButtonClick(e, () => {this._expandedPreview && this.updateIcons(this._suggestedTemplates.map(template => template.doc).slice()); this.setExpandedView(undefined)})}>
+                    <button className="docCreatorMenu-menu-button section-reveal-options top-right" onPointerDown={e => this.setUpButtonClick(e, () => {this.updateTemplatePreviews(this._suggestedTemplates); this.setExpandedView(undefined)})}>
                         <FontAwesomeIcon icon="minimize" />
                     </button>
-                    <button className="docCreatorMenu-menu-button section-reveal-options top-right-lower" onPointerDown={e => this.setUpButtonClick(e, () => this._expandedPreview && this._templateDocs.push(this._expandedPreview.doc))}>
+                    <button className="docCreatorMenu-menu-button section-reveal-options top-right-lower" onPointerDown={e => this.setUpButtonClick(e, () => this._expandedPreview && this._templateDocs.push(this._expandedPreview))}>
                         <FontAwesomeIcon icon="plus" color="white" />
                     </button>
                 </div>
@@ -836,7 +796,6 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
 
         //<img className='docCreatorMenu-preview-image expanded' src={this._expandedPreview.icon!.url.href.replace(".png", "_o.png")} />
 
-        console.log('rendered')
         return (
             <div className={`docCreatorMenu-templates-view`}>
                 {this._expandedPreview ? (
@@ -856,7 +815,7 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
                                         <ReactLoading type="spin" color={StrCast(Doc.UserDoc().userVariantColor)} height={30} width={30} />
                                     </div>
                                 ) : (
-                                    this.selectedTemplateDocs
+                                    this._suggestedTemplatePreviews
                                         .map(({doc, template}) => (
                                             <div
                                                 className="docCreatorMenu-preview-window"
@@ -877,7 +836,35 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
                                                 <button className="option-button right" onPointerDown={e => this.setUpButtonClick(e, () => this._templateDocs.push(template.mainField.renderedDoc()))}>
                                                     <FontAwesomeIcon icon="plus" color="white" />
                                                 </button>
-                                                {doc}
+                                                <CollectionFreeFormView
+                                                    Document={doc}
+                                                    docViewPath={returnEmptyDocViewList}
+                                                    childLayoutTemplate={() => Cast(doc.childLayoutTemplate, Doc, null)}
+                                                    isContentActive={returnFalse}
+                                                    isAnyChildContentActive={() => true}
+                                                    select={emptyFunction}
+                                                    isSelected={returnFalse}
+                                                    fieldKey={Doc.LayoutFieldKey(doc)}
+                                                    addDocument={returnFalse}
+                                                    moveDocument={returnFalse}
+                                                    removeDocument={returnFalse}
+                                                    PanelWidth={() => 100}
+                                                    PanelHeight={() => 100}
+                                                    ScreenToLocalTransform={() => new Transform(-this._pageX - 5,-this._pageY - 35, 1)}
+                                                    renderDepth={1}
+                                                    whenChildContentsActiveChanged={emptyFunction}
+                                                    focus={emptyFunction}
+                                                    styleProvider={DefaultStyleProvider}
+                                                    addDocTab={this._props.addDocTab}
+                                                    // eslint-disable-next-line no-use-before-define
+                                                    pinToPres={() => undefined}
+                                                    childFilters={returnEmptyFilter}
+                                                    childFiltersByRanges={returnEmptyFilter}
+                                                    searchFilterDocs={returnEmptyDoclist}
+                                                    fitContentsToBox={returnTrue}
+                                                    xPadding={0}
+                                                    yPadding={0}
+                                                    />
                                             </div>
                                         ))
                                 )}
@@ -1108,7 +1095,7 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
             }
         }
 
-        const docWithBasicOpts: Doc = collectionFactory()(this._fullyRenderedDocs, {
+        const collection: Doc = collectionFactory()(this._fullyRenderedDocs, {
             isDefaultTemplateDoc: true,
             x: 40000,
             y: 40000,
@@ -1118,19 +1105,19 @@ export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> {
             backgroundColor: 'gray',
         });
 
-        this.applyLayout(docWithBasicOpts, this._fullyRenderedDocs);
+        this.applyLayout(collection, this._fullyRenderedDocs);
 
-        const wrapper: Doc = Docs.Create.FreeformDocument([docWithBasicOpts], { _height: 200, _width: 200, title: ''});
+        const wrapper: Doc = Docs.Create.FreeformDocument([collection], { _height: 200, _width: 200, title: ''});
 
         const mainCollection = this._dataViz?.DocumentView?.().containerViewPath?.().lastElement()?.ComponentView as CollectionFreeFormView;
-        mainCollection.addDocument(docWithBasicOpts);
+        mainCollection.addDocument(collection);
 
         this._renderedDocCollectionPreview = wrapper;
-        this._renderedDocCollection = docWithBasicOpts;
+        this._renderedDocCollection = collection;
     }
 
     layoutPreviewContents = (outerSpan: number, altLayout?: DataVizTemplateLayout, small: boolean = false, id?: number) => {
-        const doc: Doc | undefined = altLayout ? altLayout.template : this._selectedTemplate?.mainField.renderedDoc(); //!!! might cause a slow down
+        const doc: Doc | undefined = altLayout ? altLayout.template : this._fullyRenderedDocs[0]; //!!! might cause a slow down
         if (!doc) return;
 
         return (
-- 
cgit v1.2.3-70-g09d2

