From 9254c4ea7e633c4e1a5eefda9a9d8d2bbe61f6b1 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Sun, 16 Mar 2025 23:28:20 -0400
Subject: more doc Creator template code cleanup

---
 .../DataVizBox/DocCreatorMenu/DocCreatorMenu.tsx   | 120 ++++++++-------------
 1 file changed, 42 insertions(+), 78 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 97faf01c2..444f0a29d 100644
--- a/src/client/views/nodes/DataVizBox/DocCreatorMenu/DocCreatorMenu.tsx
+++ b/src/client/views/nodes/DataVizBox/DocCreatorMenu/DocCreatorMenu.tsx
@@ -73,11 +73,8 @@ export class DocCreatorMenu extends ObservableReactComponent<DocCreateMenuProps>
     static Instance: DocCreatorMenu;
 
     private DEBUG_MODE: boolean = false;
-
     private _disposers: { [name: string]: IDisposer } = {};
-
     private _ref: HTMLDivElement | null = null;
-
     private templateManager: TemplateManager;
 
     @observable _fullyRenderedDocs: Doc[] = []; // collection of templates filled in with content
@@ -371,8 +368,7 @@ export class DocCreatorMenu extends ObservableReactComponent<DocCreateMenuProps>
     }
 
     @action updateRenderedPreviewCollection = async (template: Template) => {
-        this._fullyRenderedDocs = ((await this.createDocsFromTemplate(template)) ?? []).filter(doc => doc).map(doc => doc!);
-        console.log(this._fullyRenderedDocs);
+        this._fullyRenderedDocs = this._dataViz ? ((await this.createDocsFromTemplate(this._dataViz, template)).filter(doc => doc).map(doc => doc!) ?? []) : [];
         this.updateRenderedDocCollection();
     };
 
@@ -711,98 +707,66 @@ export class DocCreatorMenu extends ObservableReactComponent<DocCreateMenuProps>
         return true;
     };
 
-    createDocsFromTemplate = async (template: Template) => {
-        const dv = this._dataViz;
-
-        if (!dv) return;
-
+    createDocsFromTemplate = action((dv: DataVizBox, template: Template) => {
         this._docsRendering = true;
+        const fields = Array.from(Object.keys(dv.records[0]));
 
-        const fields: string[] = Array.from(Object.keys(dv.records[0]));
-        const selectedRows = NumListCast(dv.layoutDoc.dataViz_selectedRows);
-
-        const rowContents: { [title: string]: string }[] = selectedRows.map(row => {
-            const values: { [title: string]: string } = {};
-            fields.forEach(col => {
-                values[col] = dv.records[row][col];
-            });
-
-            return values;
-        });
-
-        const processContent = async (content: { [title: string]: string }) => {
-            const templateCopy = await template.cloneBase();
+        const processContent = (content: { [title: string]: string }) => {
+            const templateCopy = template.cloneBase();
 
             fields
                 .filter(title => title)
                 .forEach(title => {
                     const field = templateCopy.getFieldByTitle(title);
-                    if (field === undefined) return;
-                    field.setContent(content[title], field.viewType);
+                    if (field !== undefined) field.setContent(content[title], field.viewType);
                 });
 
+            const gptFunc = (type: TemplateFieldType) => (type === TemplateFieldType.VISUAL ? this.renderGPTImageCall : this.renderGPTTextCall);
             const gptPromises = this._userCreatedFields
-                .filter(field => field.type === TemplateFieldType.TEXT)
-                .map(field => {
-                    const title = field.title;
-                    const templateField = templateCopy.getFieldByTitle(title);
-                    if (templateField === undefined) return;
-                    const templatefieldID = templateField.getID;
-
-                    return this.renderGPTTextCall(templateCopy, field, templatefieldID);
-                });
-
-            const imagePromises = this._userCreatedFields
-                .filter(field => field.type === TemplateFieldType.VISUAL)
+                .filter(field => field.type !== TemplateFieldType.UNSET)
                 .map(field => {
-                    const title = field.title;
-                    const templateField = templateCopy.getFieldByTitle(title);
-                    if (templateField === undefined) return;
-                    const templatefieldID = templateField.getID;
-
-                    return this.renderGPTImageCall(templateCopy, field, templatefieldID);
+                    const templateField = templateCopy.getFieldByTitle(field.title);
+                    if (templateField !== undefined) {
+                        return gptFunc(field.type)(templateCopy, field, templateField.getID);
+                    }
                 });
 
-            await Promise.all(gptPromises);
-
-            await Promise.all(imagePromises);
-
-            this._DOCCC = templateCopy.mainField.renderedDoc;
-            return templateCopy.mainField.renderedDoc;
+            return Promise.all(gptPromises).then(() => (this._DOCCC = templateCopy.mainField.renderedDoc));
         };
 
-        let docs: Promise<Doc | undefined>[];
-        if (this.DEBUG_MODE) {
-            docs = [1, 2, 3, 4].map(() => processContent({}));
-        } else {
-            docs = rowContents.map(content => processContent(content));
-        }
-
-        const renderedDocs = await Promise.all(docs);
-
-        this._docsRendering = false; // removes loading indicator
-
-        return renderedDocs;
-    };
+        const rowContents = this.DEBUG_MODE
+            ? [{}, {}, {}, {}]
+            : NumListCast(dv.layoutDoc.dataViz_selectedRows).map(row =>
+                  fields.reduce(
+                      (values, col) => {
+                          values[col] = dv.records[row][col];
+                          return values;
+                      },
+                      {} as { [title: string]: string }
+                  )
+              );
+        return Promise.all(rowContents.map(processContent)).then(
+            action(renderedDocs => {
+                this._docsRendering = false; // removes loading indicator
+                return renderedDocs;
+            })
+        );
+    });
 
     addRenderedCollectionToMainview = () => {
         const collection = this._renderedDocCollection;
-        if (!collection) return;
-        const mainCollection = this._dataViz?.DocumentView?.().containerViewPath?.().lastElement()?.ComponentView as CollectionFreeFormView;
-        collection.x = this._pageX - this._menuDimensions.width;
-        collection.y = this._pageY - this._menuDimensions.height;
-        mainCollection.addDocument(collection);
-        this.closeMenu();
+        if (collection) {
+            const mainCollection = this._dataViz?.DocumentView?.().containerViewPath?.().lastElement()?.ComponentView as CollectionFreeFormView;
+            collection.x = this._pageX - this._menuDimensions.width;
+            collection.y = this._pageY - this._menuDimensions.height;
+            mainCollection?.addDocument(collection);
+            this.closeMenu();
+        }
     };
 
     @action setExpandedView = (template: Template | undefined) => {
-        if (template) {
-            this._currEditingTemplate = template;
-            this._expandedPreview = template.doc; //Docs.Create.FreeformDocument([doc], { _height: NumListCast(doc._height)[0], _width: NumListCast(doc._width)[0], title: ''});
-        } else {
-            this._currEditingTemplate = undefined;
-            this._expandedPreview = undefined;
-        }
+        this._currEditingTemplate = template;
+        this._expandedPreview = template?.doc; //Docs.Create.FreeformDocument([doc], { _height: NumListCast(doc._height)[0], _width: NumListCast(doc._width)[0], title: ''});
     };
 
     get editingWindow() {
@@ -1126,7 +1090,7 @@ export class DocCreatorMenu extends ObservableReactComponent<DocCreateMenuProps>
         console.log('changed to: ', collection);
     };
 
-    layoutPreviewContents = () => {
+    layoutPreviewContents = action(() => {
         return this._docsRendering ? (
             <div className="docCreatorMenu-layout-preview-window-wrapper loading">
                 <div className="loading-spinner">
@@ -1159,7 +1123,7 @@ export class DocCreatorMenu extends ObservableReactComponent<DocCreateMenuProps>
                 />
             </div>
         );
-    };
+    });
 
     get optionsMenuContents() {
         const layoutOption = (option: LayoutType, optStyle?: object, specialFunc?: () => void) => {
-- 
cgit v1.2.3-70-g09d2

