From 972839216c14baa5c9eaf80e1fb2fb2694bbb72c Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Tue, 8 Oct 2024 22:51:46 -0400
Subject: modified how buttons are laid out on carousel and comparison views so
 that text boxes can reflow around them.  extracted flashcard pratice into its
 own component and applied it to carousel3D and carousel

---
 .../views/collections/CollectionCarousel3DView.tsx | 70 ++++++++++++++++++----
 1 file changed, 57 insertions(+), 13 deletions(-)

(limited to 'src/client/views/collections/CollectionCarousel3DView.tsx')

diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx
index c5da8e037..1583f0e0c 100644
--- a/src/client/views/collections/CollectionCarousel3DView.tsx
+++ b/src/client/views/collections/CollectionCarousel3DView.tsx
@@ -1,5 +1,5 @@
 import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
-import { computed, makeObservable } from 'mobx';
+import { action, computed, makeObservable, observable } from 'mobx';
 import { observer } from 'mobx-react';
 import * as React from 'react';
 import { returnZero } from '../../../ClientUtils';
@@ -9,12 +9,13 @@ import { Id } from '../../../fields/FieldSymbols';
 import { DocCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
 import { DocumentType } from '../../documents/DocumentTypes';
 import { DragManager } from '../../util/DragManager';
+import { Transform } from '../../util/Transform';
 import { StyleProp } from '../StyleProp';
 import { DocumentView } from '../nodes/DocumentView';
 import { FocusViewOptions } from '../nodes/FocusViewOptions';
 import './CollectionCarousel3DView.scss';
 import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView';
-import { Transform } from '../../util/Transform';
+import { FlashcardPracticeUI } from './FlashcardPracticeUI';
 
 // eslint-disable-next-line @typescript-eslint/no-require-imports
 const { CAROUSEL3D_CENTER_SCALE, CAROUSEL3D_SIDE_SCALE, CAROUSEL3D_TOP } = require('../global/globalCssVariables.module.scss');
@@ -24,6 +25,9 @@ export class CollectionCarousel3DView extends CollectionSubView() {
     @computed get scrollSpeed() {
         return this.layoutDoc._autoScrollSpeed ? NumCast(this.layoutDoc._autoScrollSpeed) : 1000; // default scroll speed
     }
+    _sideBtnWidth = 35;
+    @observable _filterFunc: ((doc: Doc) => boolean) | undefined = undefined;
+
     constructor(props: SubCollectionViewProps) {
         super(props);
         makeObservable(this);
@@ -43,7 +47,7 @@ export class CollectionCarousel3DView extends CollectionSubView() {
     };
 
     @computed get carouselItems() {
-        return this.childLayoutPairs.filter(pair => pair.layout.type !== DocumentType.LINK);
+        return this.childLayoutPairs.filter(pair => pair.layout.type !== DocumentType.LINK).filter(pair => !this._filterFunc?.(pair.layout));
     }
 
     centerScale = Number(CAROUSEL3D_CENTER_SCALE);
@@ -53,22 +57,17 @@ export class CollectionCarousel3DView extends CollectionSubView() {
     onChildDoubleClick = () => ScriptCast(this.layoutDoc.onChildDoubleClick);
     isContentActive = () => this._props.isSelected() || this._props.isContentActive() || this._props.isAnyChildContentActive();
     isChildContentActive = () => !!this.isContentActive();
+    contentScreenToLocalXf = () => this._props.ScreenToLocalTransform().scale(this._props.NativeDimScaling?.() || 1);
     childScreenLeftToLocal = () =>
-        this._props
-            .ScreenToLocalTransform()
-            .scale(this._props.NativeDimScaling?.() || 1)
+        this.contentScreenToLocalXf()
             .translate(-(this.panelWidth() - this.panelWidth() * this.sideScale) / 2, -(this.panelHeight() - this.panelHeight() * this.sideScale) / 2 - (Number(CAROUSEL3D_TOP) / 100) * this._props.PanelHeight())
             .scale(1 / this.sideScale);
     childScreenRightToLocal = () =>
-        this._props
-            .ScreenToLocalTransform()
-            .scale(this._props.NativeDimScaling?.() || 1)
+        this.contentScreenToLocalXf()
             .translate(-2 * this.panelWidth() - (this.panelWidth() - this.panelWidth() * this.sideScale) / 2, -(this.panelHeight() - this.panelHeight() * this.sideScale) / 2 - (Number(CAROUSEL3D_TOP) / 100) * this._props.PanelHeight())
             .scale(1 / this.sideScale);
     childCenterScreenToLocal = () =>
-        this._props
-            .ScreenToLocalTransform()
-            .scale(this._props.NativeDimScaling?.() || 1)
+        this.contentScreenToLocalXf()
             .translate(
                 -this.panelWidth() + ((this.centerScale - 1) * this.panelWidth()) / 2, // Focused Doc is shifted right by 1/3 panel width then left by increased size percent of center * 1/2 * panel width / 3
                 -((Number(CAROUSEL3D_TOP) / 100) * this._props.PanelHeight()) + ((this.centerScale - 1) * this.panelHeight()) / 2
@@ -119,7 +118,7 @@ export class CollectionCarousel3DView extends CollectionSubView() {
 
     changeSlide = (direction: number) => {
         DocumentView.DeselectAll();
-        this.layoutDoc._carousel_index = (NumCast(this.layoutDoc._carousel_index) + direction + this.carouselItems.length) % this.carouselItems.length;
+        this.layoutDoc._carousel_index = !this.curDoc() ? 0 : (NumCast(this.layoutDoc._carousel_index) + direction + this.carouselItems.length) % (this.carouselItems.length || 1);
     };
 
     onArrowClick = (direction: number) => {
@@ -192,6 +191,35 @@ export class CollectionCarousel3DView extends CollectionSubView() {
         return this.panelWidth() * (1 - index);
     }
 
+    /**
+     * How much the content of the carousel view is being scaled based on its nesting and its fit-to-width settings
+     */
+    @computed get contentScaling() { return this.ScreenToLocalBoxXf().Scale * (this._props.NativeDimScaling?.() ?? 1); } // prettier-ignore
+
+    /**
+     * The maximum size a UI widget can be scaled so that it won't be bigger in screen pixels than its normal 35 pixel size.
+     */
+    @computed get maxWidgetScale() {
+        const maxWidgetSize = Math.min(this._sideBtnWidth * this.contentScaling, 0.1 * NumCast(this.layoutDoc.width, 1));
+        return Math.max(maxWidgetSize / this._sideBtnWidth, 1);
+    }
+    /**
+     * How much to reactively scale a UI element so that it is as big as it can be (up to its normal 35pixel size) without being too big for the Doc content
+     */
+    @computed get uiBtnScaleTransform() {  return this.maxWidgetScale * Math.min(1, this.contentScaling); } // prettier-ignore
+    screenXPadding = () => (this.uiBtnScaleTransform * this._sideBtnWidth - NumCast(this.layoutDoc.xMargin)) / this._props.ScreenToLocalTransform().Scale;
+
+    docViewProps = () => ({
+        ...this._props, //
+        isDocumentActive: this._props.childDocumentsActive?.() ? this._props.isDocumentActive : this._props.isContentActive,
+        isContentActive: this.isChildContentActive,
+        ScreenToLocalTransform: this.contentScreenToLocalXf,
+    });
+    carouselItemsFunc = () => this.carouselItems.map(pair => pair.layout);
+    @action setFilterFunc = (func?: (doc: Doc) => boolean) => { this._filterFunc = func; }; // prettier-ignore
+    answered = (correct: boolean) => (!correct || !this.curDoc()) && this.changeSlide(1);
+    curDoc = () => this.carouselItems[NumCast(this.layoutDoc._carousel_index)]?.layout;
+
     render() {
         return (
             <div
@@ -206,6 +234,22 @@ export class CollectionCarousel3DView extends CollectionSubView() {
                 </div>
                 {this.buttons}
                 <div className="dot-bar">{this.dots}</div>
+                <FlashcardPracticeUI
+                    setFilterFunc={this.setFilterFunc}
+                    fieldKey={this.fieldKey}
+                    sideBtnWidth={this._sideBtnWidth}
+                    carouselItems={this.carouselItemsFunc}
+                    childDocs={this.childDocs}
+                    advance={this.answered}
+                    curDoc={this.curDoc}
+                    practiceBtnOffset={this._sideBtnWidth * 4}
+                    layoutDoc={this.layoutDoc}
+                    maxWidgetScale={this.maxWidgetScale}
+                    uiBtnScaleTransform={this.uiBtnScaleTransform}
+                    ScreenToLocalBoxXf={this.ScreenToLocalBoxXf}
+                    renderDepth={this._props.renderDepth}
+                    docViewProps={this.docViewProps}
+                />
             </div>
         );
     }
-- 
cgit v1.2.3-70-g09d2


From c9f90fbda9f9b3fc3e5fe5ade134f32af6074617 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Wed, 9 Oct 2024 09:26:26 -0400
Subject: made sizing of flashcard messages and 3d carousel's dots reactive to
 doc size

---
 src/client/views/collections/CollectionCarousel3DView.tsx | 4 +++-
 src/client/views/collections/FlashcardPracticeUI.tsx      | 1 +
 2 files changed, 4 insertions(+), 1 deletion(-)

(limited to 'src/client/views/collections/CollectionCarousel3DView.tsx')

diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx
index 1583f0e0c..3bcf3450f 100644
--- a/src/client/views/collections/CollectionCarousel3DView.tsx
+++ b/src/client/views/collections/CollectionCarousel3DView.tsx
@@ -233,7 +233,9 @@ export class CollectionCarousel3DView extends CollectionSubView() {
                     {this.content}
                 </div>
                 {this.buttons}
-                <div className="dot-bar">{this.dots}</div>
+                <div className="dot-bar" style={{ transform: `scale(${this.uiBtnScaleTransform})` }}>
+                    {this.dots}
+                </div>
                 <FlashcardPracticeUI
                     setFilterFunc={this.setFilterFunc}
                     fieldKey={this.fieldKey}
diff --git a/src/client/views/collections/FlashcardPracticeUI.tsx b/src/client/views/collections/FlashcardPracticeUI.tsx
index 072a2edef..a643c95b0 100644
--- a/src/client/views/collections/FlashcardPracticeUI.tsx
+++ b/src/client/views/collections/FlashcardPracticeUI.tsx
@@ -78,6 +78,7 @@ export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProp
         return !practiceMessage && !filterMessage ? null : (
             <p
                 className="FlashcardPracticeUI-message"
+                style={{ transform: `scale(${this._props.uiBtnScaleTransform})` }}
                 onClick={() => {
                     if (filterMessage || practiceMessage) {
                         this.setPracticeMode(undefined);
-- 
cgit v1.2.3-70-g09d2


From 01db98ebdd02729729222bdd20ab65b57cbbe94c Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Wed, 9 Oct 2024 13:27:56 -0400
Subject: more refactoring to of collection flashcards into CollectioSubView to
 simplify using it in diferent collection views.

---
 .../views/collections/CollectionCardDeckView.scss  | 13 +---
 .../views/collections/CollectionCardDeckView.tsx   | 81 ++++++----------------
 .../views/collections/CollectionCarousel3DView.tsx | 72 +++++--------------
 .../views/collections/CollectionCarouselView.scss  |  1 +
 .../views/collections/CollectionCarouselView.tsx   | 53 ++------------
 src/client/views/collections/CollectionSubView.tsx | 51 +++++++++++++-
 .../views/collections/FlashcardPracticeUI.scss     |  2 +-
 .../views/collections/FlashcardPracticeUI.tsx      | 27 ++++----
 .../collectionFreeForm/CollectionFreeFormView.tsx  |  2 +-
 src/client/views/nodes/ComparisonBox.tsx           | 18 ++---
 10 files changed, 113 insertions(+), 207 deletions(-)

(limited to 'src/client/views/collections/CollectionCarousel3DView.tsx')

diff --git a/src/client/views/collections/CollectionCardDeckView.scss b/src/client/views/collections/CollectionCardDeckView.scss
index 0520e38d4..0637cd4e9 100644
--- a/src/client/views/collections/CollectionCardDeckView.scss
+++ b/src/client/views/collections/CollectionCardDeckView.scss
@@ -6,6 +6,7 @@
     position: relative;
     background-color: white;
     overflow: hidden;
+    display: flex;
 
     button {
         border-radius: 50%;
@@ -48,15 +49,3 @@
 .card-item-active {
     z-index: 100;
 }
-
-.collectionCardDeckView-flashcards {
-    width: 100%;
-    height: 100%;
-    position: absolute;
-    top: 0;
-    left: 0;
-    display: flex;
-    transform-origin: top left;
-    pointer-events: none;
-    z-index: 100;
-}
diff --git a/src/client/views/collections/CollectionCardDeckView.tsx b/src/client/views/collections/CollectionCardDeckView.tsx
index 7272b22e2..8f351d8a7 100644
--- a/src/client/views/collections/CollectionCardDeckView.tsx
+++ b/src/client/views/collections/CollectionCardDeckView.tsx
@@ -22,7 +22,6 @@ import { DocumentView } from '../nodes/DocumentView';
 import { GPTPopup, GPTPopupMode } from '../pdf/GPTPopup/GPTPopup';
 import './CollectionCardDeckView.scss';
 import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView';
-import { FlashcardPracticeUI } from './FlashcardPracticeUI';
 
 enum cardSortings {
     Time = 'time',
@@ -47,8 +46,6 @@ export class CollectionCardView extends CollectionSubView() {
     private _textToDoc = new Map<string, Doc>();
     private _dropped = false; // set when a card doc has just moved and the drop method has been called - prevents the pointerUp method from hiding doc decorations (which needs to be done when clicking on a card to animate it to front/center)
 
-    _sideBtnWidth = 35;
-    @observable _filterFunc: ((doc: Doc) => boolean) | undefined = undefined;
     @observable _forceChildXf = 0;
     @observable _hoveredNodeIndex = -1;
     @observable _docRefs = new ObservableMap<Doc, DocumentView>();
@@ -119,15 +116,15 @@ export class CollectionCardView extends CollectionSubView() {
     /**
      * The child documents to be rendered-- everything other than ink/link docs (which are marks as being svg's)
      */
-    @computed get childDocsWithoutLinks() {
-        return this.childDocs.filter(l => !l.layout_isSvg).filter(doc => !this._filterFunc?.(doc));
+    @computed get childCards() {
+        return this.childLayoutPairs.filter(pair => !pair.layout.layout_isSvg);
     }
 
     /**
      * how much to scale down the contents of the view so that everything will fit
      */
     @computed get fitContentScale() {
-        const length = Math.min(this.childDocsWithoutLinks.length, this._maxRowCount);
+        const length = Math.min(this.childCards.length, this._maxRowCount);
         return (this.childPanelWidth() * length) / this._props.PanelWidth();
     }
 
@@ -280,7 +277,12 @@ export class CollectionCardView extends CollectionSubView() {
     );
 
     @computed get sortedDocs() {
-        return this.sort(this.childDocsWithoutLinks, this.cardSort, BoolCast(this.Document.cardSort_isDesc), this._docDraggedIndex);
+        return this.sort(
+            this.childCards.map(card => card.layout),
+            this.cardSort,
+            BoolCast(this.Document.cardSort_isDesc),
+            this._docDraggedIndex
+        );
     }
 
     /**
@@ -428,12 +430,14 @@ export class CollectionCardView extends CollectionSubView() {
                 default:                return StrCast(doc.title);
             } // prettier-ignore
         };
-        const docTextPromises = this.childDocsWithoutLinks.map(async doc => {
-            const docText = (await docToText(doc)) ?? '';
-            doc.gptInputText = docText;
-            this._textToDoc.set(docText.replace(/\n/g, ' ').trim(), doc);
-            return `======${docText.replace(/\n/g, ' ').trim()}======`;
-        });
+        const docTextPromises = this.childCards
+            .map(pair => pair.layout)
+            .map(async doc => {
+                const docText = (await docToText(doc)) ?? '';
+                doc.gptInputText = docText;
+                this._textToDoc.set(docText.replace(/\n/g, ' ').trim(), doc);
+                return `======${docText.replace(/\n/g, ' ').trim()}======`;
+            });
         return Promise.all<string>(docTextPromises);
     };
 
@@ -567,7 +571,7 @@ export class CollectionCardView extends CollectionSubView() {
      * Actually renders all the cards
      */
     @computed get renderCards() {
-        if (!this.childDocsWithoutLinks.length) {
+        if (!this.childCards.length) {
             return null;
         }
 
@@ -611,36 +615,16 @@ export class CollectionCardView extends CollectionSubView() {
     }
 
     contentScreenToLocalXf = () => this._props.ScreenToLocalTransform().scale(this._props.NativeDimScaling?.() || 1);
+    curDoc = () => this.childCards.find(card => DocumentView.getDocumentView(card.layout, this.DocumentView?.())?.IsSelected)?.layout;
     docViewProps = () => ({
         ...this._props, //
         isDocumentActive: this._props.childDocumentsActive?.() ? this._props.isDocumentActive : this._props.isContentActive,
         isContentActive: this.isChildContentActive,
         ScreenToLocalTransform: this.contentScreenToLocalXf,
     });
-    carouselItemsFunc = () => this.childDocsWithoutLinks;
-    @action setFilterFunc = (func?: (doc: Doc) => boolean) => { this._filterFunc = func; }; // prettier-ignore
-    answered = (correct: boolean) => !correct || !this.curDoc();
-    curDoc = () => this.sortedDocs.find(doc => DocumentView.getDocumentView(doc, this.DocumentView?.())?.IsSelected);
-    /**
-     * How much the content of the carousel view is being scaled based on its nesting and its fit-to-width settings
-     */
-    @computed get contentScaling() { return this.ScreenToLocalBoxXf().Scale * (this._props.NativeDimScaling?.() ?? 1); } // prettier-ignore
-
-    /**
-     * The maximum size a UI widget can be scaled so that it won't be bigger in screen pixels than its normal 35 pixel size.
-     */
-    @computed get maxWidgetScale() {
-        const maxWidgetSize = Math.min(this._sideBtnWidth * this.contentScaling, 0.1 * NumCast(this.layoutDoc.width, 1));
-        return Math.max(maxWidgetSize / this._sideBtnWidth, 1);
-    }
-    /**
-     * How much to reactively scale a UI element so that it is as big as it can be (up to its normal 35pixel size) without being too big for the Doc content
-     */
-    @computed get uiBtnScaleTransform() {  return this.maxWidgetScale * Math.min(1, this.contentScaling); } // prettier-ignore
 
     render() {
-        const isEmpty = this.childDocsWithoutLinks.length === 0;
-
+        const isEmpty = this.childCards.length === 0;
         return (
             <div
                 className="collectionCardView-outer"
@@ -661,31 +645,8 @@ export class CollectionCardView extends CollectionSubView() {
                         gridAutoRows: `${100 / this.numRows}%`,
                     }}>
                     {this.renderCards}
-                    <div
-                        className="collectionCardDeckView-flashcards"
-                        style={{
-                            transform: `scale(${this.fitContentScale || 1})`,
-                            width: `${100 / (this.fitContentScale || 1)}%`,
-                            height: `${100 / (this.fitContentScale || 1)}%`,
-                            pointerEvents: !this.childDocsWithoutLinks.length ? 'unset' : undefined,
-                        }}>
-                        <FlashcardPracticeUI
-                            setFilterFunc={this.setFilterFunc}
-                            fieldKey={this.fieldKey}
-                            sideBtnWidth={this._sideBtnWidth}
-                            carouselItems={this.carouselItemsFunc}
-                            childDocs={this.childDocs}
-                            advance={this.answered}
-                            curDoc={this.curDoc}
-                            layoutDoc={this.layoutDoc}
-                            maxWidgetScale={this.maxWidgetScale}
-                            uiBtnScaleTransform={this.uiBtnScaleTransform}
-                            ScreenToLocalBoxXf={this.ScreenToLocalBoxXf}
-                            renderDepth={this._props.renderDepth}
-                            docViewProps={this.docViewProps}
-                        />
-                    </div>
                 </div>
+                {this.flashCardUI(this.curDoc, this.docViewProps)}
             </div>
         );
     }
diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx
index 3bcf3450f..9ccac0e0f 100644
--- a/src/client/views/collections/CollectionCarousel3DView.tsx
+++ b/src/client/views/collections/CollectionCarousel3DView.tsx
@@ -1,5 +1,5 @@
 import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
-import { action, computed, makeObservable, observable } from 'mobx';
+import { computed, makeObservable } from 'mobx';
 import { observer } from 'mobx-react';
 import * as React from 'react';
 import { returnZero } from '../../../ClientUtils';
@@ -15,26 +15,19 @@ import { DocumentView } from '../nodes/DocumentView';
 import { FocusViewOptions } from '../nodes/FocusViewOptions';
 import './CollectionCarousel3DView.scss';
 import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView';
-import { FlashcardPracticeUI } from './FlashcardPracticeUI';
 
 // eslint-disable-next-line @typescript-eslint/no-require-imports
 const { CAROUSEL3D_CENTER_SCALE, CAROUSEL3D_SIDE_SCALE, CAROUSEL3D_TOP } = require('../global/globalCssVariables.module.scss');
 
 @observer
 export class CollectionCarousel3DView extends CollectionSubView() {
-    @computed get scrollSpeed() {
-        return this.layoutDoc._autoScrollSpeed ? NumCast(this.layoutDoc._autoScrollSpeed) : 1000; // default scroll speed
-    }
-    _sideBtnWidth = 35;
-    @observable _filterFunc: ((doc: Doc) => boolean) | undefined = undefined;
+    private _dropDisposer?: DragManager.DragDropDisposer;
 
     constructor(props: SubCollectionViewProps) {
         super(props);
         makeObservable(this);
     }
 
-    private _dropDisposer?: DragManager.DragDropDisposer;
-
     componentWillUnmount() {
         this._dropDisposer?.();
     }
@@ -46,8 +39,11 @@ export class CollectionCarousel3DView extends CollectionSubView() {
         }
     };
 
+    @computed get scrollSpeed() {
+        return this.layoutDoc._autoScrollSpeed ? NumCast(this.layoutDoc._autoScrollSpeed) : 1000; // default scroll speed
+    }
     @computed get carouselItems() {
-        return this.childLayoutPairs.filter(pair => pair.layout.type !== DocumentType.LINK).filter(pair => !this._filterFunc?.(pair.layout));
+        return this.childLayoutPairs.filter(pair => !pair.layout.layout_isSvg);
     }
 
     centerScale = Number(CAROUSEL3D_CENTER_SCALE);
@@ -86,11 +82,11 @@ export class CollectionCarousel3DView extends CollectionSubView() {
 
     @computed get content() {
         const currentIndex = NumCast(this.layoutDoc._carousel_index);
-        const displayDoc = (childPair: { layout: Doc; data: Doc }, dxf: () => Transform) => (
+        const displayDoc = (child: Doc, dxf: () => Transform) => (
             <DocumentView
                 {...this._props}
-                Document={childPair.layout}
-                TemplateDataDocument={childPair.data}
+                Document={child}
+                TemplateDataDocument={undefined}
                 // suppressSetHeight={true}
                 NativeWidth={returnZero}
                 NativeHeight={returnZero}
@@ -109,9 +105,9 @@ export class CollectionCarousel3DView extends CollectionSubView() {
             />
         );
 
-        return this.carouselItems.map((childPair, index) => (
-            <div key={childPair.layout[Id]} className={`collectionCarousel3DView-item${index === currentIndex ? '-active' : ''} ${index}`} style={{ width: this.panelWidth() }}>
-                {displayDoc(childPair, index < currentIndex ? this.childScreenLeftToLocal : index === currentIndex ? this.childCenterScreenToLocal : this.childScreenRightToLocal)}
+        return this.carouselItems.map((child, index) => (
+            <div key={child.layout[Id]} className={`collectionCarousel3DView-item${index === currentIndex ? '-active' : ''} ${index}`} style={{ width: this.panelWidth() }}>
+                {displayDoc(child.layout, index < currentIndex ? this.childScreenLeftToLocal : index === currentIndex ? this.childCenterScreenToLocal : this.childScreenRightToLocal)}
             </div>
         ));
     }
@@ -191,35 +187,14 @@ export class CollectionCarousel3DView extends CollectionSubView() {
         return this.panelWidth() * (1 - index);
     }
 
-    /**
-     * How much the content of the carousel view is being scaled based on its nesting and its fit-to-width settings
-     */
-    @computed get contentScaling() { return this.ScreenToLocalBoxXf().Scale * (this._props.NativeDimScaling?.() ?? 1); } // prettier-ignore
-
-    /**
-     * The maximum size a UI widget can be scaled so that it won't be bigger in screen pixels than its normal 35 pixel size.
-     */
-    @computed get maxWidgetScale() {
-        const maxWidgetSize = Math.min(this._sideBtnWidth * this.contentScaling, 0.1 * NumCast(this.layoutDoc.width, 1));
-        return Math.max(maxWidgetSize / this._sideBtnWidth, 1);
-    }
-    /**
-     * How much to reactively scale a UI element so that it is as big as it can be (up to its normal 35pixel size) without being too big for the Doc content
-     */
-    @computed get uiBtnScaleTransform() {  return this.maxWidgetScale * Math.min(1, this.contentScaling); } // prettier-ignore
-    screenXPadding = () => (this.uiBtnScaleTransform * this._sideBtnWidth - NumCast(this.layoutDoc.xMargin)) / this._props.ScreenToLocalTransform().Scale;
-
+    curDoc = () => this.carouselItems[NumCast(this.layoutDoc._carousel_index)]?.layout;
+    answered = (correct: boolean) => (!correct || !this.curDoc()) && this.changeSlide(1);
     docViewProps = () => ({
         ...this._props, //
         isDocumentActive: this._props.childDocumentsActive?.() ? this._props.isDocumentActive : this._props.isContentActive,
         isContentActive: this.isChildContentActive,
         ScreenToLocalTransform: this.contentScreenToLocalXf,
     });
-    carouselItemsFunc = () => this.carouselItems.map(pair => pair.layout);
-    @action setFilterFunc = (func?: (doc: Doc) => boolean) => { this._filterFunc = func; }; // prettier-ignore
-    answered = (correct: boolean) => (!correct || !this.curDoc()) && this.changeSlide(1);
-    curDoc = () => this.carouselItems[NumCast(this.layoutDoc._carousel_index)]?.layout;
-
     render() {
         return (
             <div
@@ -233,25 +208,10 @@ export class CollectionCarousel3DView extends CollectionSubView() {
                     {this.content}
                 </div>
                 {this.buttons}
-                <div className="dot-bar" style={{ transform: `scale(${this.uiBtnScaleTransform})` }}>
+                <div className="dot-bar" style={{ transform: `scale(${this.uiBtnScaling})` }}>
                     {this.dots}
                 </div>
-                <FlashcardPracticeUI
-                    setFilterFunc={this.setFilterFunc}
-                    fieldKey={this.fieldKey}
-                    sideBtnWidth={this._sideBtnWidth}
-                    carouselItems={this.carouselItemsFunc}
-                    childDocs={this.childDocs}
-                    advance={this.answered}
-                    curDoc={this.curDoc}
-                    practiceBtnOffset={this._sideBtnWidth * 4}
-                    layoutDoc={this.layoutDoc}
-                    maxWidgetScale={this.maxWidgetScale}
-                    uiBtnScaleTransform={this.uiBtnScaleTransform}
-                    ScreenToLocalBoxXf={this.ScreenToLocalBoxXf}
-                    renderDepth={this._props.renderDepth}
-                    docViewProps={this.docViewProps}
-                />
+                {this.flashCardUI(this.curDoc, this.docViewProps, this.answered)}
             </div>
         );
     }
diff --git a/src/client/views/collections/CollectionCarouselView.scss b/src/client/views/collections/CollectionCarouselView.scss
index 757072453..544b3e262 100644
--- a/src/client/views/collections/CollectionCarouselView.scss
+++ b/src/client/views/collections/CollectionCarouselView.scss
@@ -2,6 +2,7 @@
     height: 100%;
     position: relative;
     overflow: hidden;
+    display: flex;
     .collectionCarouselView-caption {
         height: 50;
         display: inline-block;
diff --git a/src/client/views/collections/CollectionCarouselView.tsx b/src/client/views/collections/CollectionCarouselView.tsx
index 64ddaac79..538eba356 100644
--- a/src/client/views/collections/CollectionCarouselView.tsx
+++ b/src/client/views/collections/CollectionCarouselView.tsx
@@ -5,7 +5,6 @@ import * as React from 'react';
 import { StopEvent, returnOne, returnZero } from '../../../ClientUtils';
 import { Doc, Opt } from '../../../fields/Doc';
 import { BoolCast, DocCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
-import { DocumentType } from '../../documents/DocumentTypes';
 import { DragManager } from '../../util/DragManager';
 import { StyleProp } from '../StyleProp';
 import { DocumentView } from '../nodes/DocumentView';
@@ -13,15 +12,12 @@ import { FieldViewProps } from '../nodes/FieldView';
 import { FormattedTextBox } from '../nodes/formattedText/FormattedTextBox';
 import './CollectionCarouselView.scss';
 import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView';
-import { FlashcardPracticeUI } from './FlashcardPracticeUI';
 
 @observer
 export class CollectionCarouselView extends CollectionSubView() {
     private _dropDisposer?: DragManager.DragDropDisposer;
 
     _fadeTimer: NodeJS.Timeout | undefined;
-    _sideBtnWidth = 35;
-    @observable _filterFunc: ((doc: Doc) => boolean) | undefined = undefined;
     @observable _last_index = this.carouselIndex;
     @observable _last_opacity = 1;
 
@@ -43,28 +39,7 @@ export class CollectionCarouselView extends CollectionSubView() {
 
     @computed get captionMarginX(){ return NumCast(this.layoutDoc.caption_xMargin, 50); } // prettier-ignore
     @computed get carouselIndex() { return NumCast(this.layoutDoc._carousel_index) % this.carouselItems.length; } // prettier-ignore
-    @computed get carouselItems() { return this.childDocs
-        .filter(doc => doc.type !== DocumentType.LINK)
-        .filter(doc => !this._filterFunc?.(doc))
-    } // prettier-ignore
-
-    /**
-     * How much the content of the carousel view is being scaled based on its nesting and its fit-to-width settings
-     */
-    @computed get contentScaling() { return this.ScreenToLocalBoxXf().Scale * (this._props.NativeDimScaling?.() ?? 1); } // prettier-ignore
-
-    /**
-     * The maximum size a UI widget can be scaled so that it won't be bigger in screen pixels than its normal 35 pixel size.
-     */
-    @computed get maxWidgetScale() {
-        const maxWidgetSize = Math.min(this._sideBtnWidth * this.contentScaling, 0.1 * NumCast(this.layoutDoc.width, 1));
-        return Math.max(maxWidgetSize / this._sideBtnWidth, 1);
-    }
-    /**
-     * How much to reactively scale a UI element so that it is as big as it can be (up to its normal 35pixel size) without being too big for the Doc content
-     */
-    @computed get uiBtnScaleTransform() {  return this.maxWidgetScale * Math.min(1, this.contentScaling); } // prettier-ignore
-    screenXPadding = () => (this.uiBtnScaleTransform * this._sideBtnWidth - NumCast(this.layoutDoc.xMargin)) / this._props.ScreenToLocalTransform().Scale;
+    @computed get carouselItems() { return this.childLayoutPairs.filter(pair => !pair.layout.layout_isSvg); } // prettier-ignore
 
     /**
      * Move forward or backward the specified number of Docs
@@ -91,7 +66,7 @@ export class CollectionCarouselView extends CollectionSubView() {
         this.move(-1);
     };
 
-    curDoc = () => this.carouselItems[this.carouselIndex];
+    curDoc = () => this.carouselItems[this.carouselIndex]?.layout;
 
     captionStyleProvider = (doc: Doc | undefined, captionProps: Opt<FieldViewProps>, property: string) => {
         // first look for properties on the document in the carousel, then fallback to properties on the container
@@ -153,7 +128,7 @@ export class CollectionCarouselView extends CollectionSubView() {
      */
     @computed get overlay() {
         const fadeTime = 500;
-        const lastDoc = this.carouselItems?.[this._last_index];
+        const lastDoc = this.carouselItems?.[this._last_index]?.layout;
         return !lastDoc || this.carouselIndex === this._last_index ? null : (
             <div className="collectionCarouselView-image" style={{ opacity: this._last_opacity, transition: `opacity ${fadeTime}ms` }}>
                 {this.renderDoc(
@@ -211,10 +186,10 @@ export class CollectionCarouselView extends CollectionSubView() {
     @computed get navButtons() {
         return this.Document._chromeHidden || !this.curDoc() ? null : (
             <>
-                <div key="back" className="carouselView-back" style={{ transform: `scale(${this.uiBtnScaleTransform})` }} onClick={this.goback}>
+                <div key="back" className="carouselView-back" style={{ transform: `scale(${this.uiBtnScaling})` }} onClick={this.goback}>
                     <FontAwesomeIcon icon="chevron-left" size="2x" />
                 </div>
-                <div key="fwd" className="carouselView-fwd" style={{ transform: `scale(${this.uiBtnScaleTransform})` }} onClick={this.advance}>
+                <div key="fwd" className="carouselView-fwd" style={{ transform: `scale(${this.uiBtnScaling})` }} onClick={this.advance}>
                     <FontAwesomeIcon icon="chevron-right" size="2x" />
                 </div>
             </>
@@ -227,9 +202,7 @@ export class CollectionCarouselView extends CollectionSubView() {
         isContentActive: this.isChildContentActive,
         ScreenToLocalTransform: this.contentScreenToLocalXf,
     });
-    carouselItemsFunc = () => this.carouselItems;
     answered = () => this.advance();
-    @action setFilterFunc = (func?: (doc: Doc) => boolean) => { this._filterFunc = func; }; // prettier-ignore
 
     render() {
         return (
@@ -245,21 +218,7 @@ export class CollectionCarouselView extends CollectionSubView() {
                     top: NumCast(this.layoutDoc._yMargin),
                 }}>
                 {this.content}
-                <FlashcardPracticeUI
-                    setFilterFunc={this.setFilterFunc}
-                    fieldKey={this.fieldKey}
-                    sideBtnWidth={this._sideBtnWidth}
-                    carouselItems={this.carouselItemsFunc}
-                    childDocs={this.childDocs}
-                    advance={this.answered}
-                    curDoc={this.curDoc}
-                    layoutDoc={this.layoutDoc}
-                    maxWidgetScale={this.maxWidgetScale}
-                    uiBtnScaleTransform={this.uiBtnScaleTransform}
-                    ScreenToLocalBoxXf={this.ScreenToLocalBoxXf}
-                    renderDepth={this._props.renderDepth}
-                    docViewProps={this.docViewProps}
-                />
+                {this.flashCardUI(this.curDoc, this.docViewProps, this.answered)}
                 {this.navButtons}
             </div>
         );
diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx
index 581201a20..c057d2402 100644
--- a/src/client/views/collections/CollectionSubView.tsx
+++ b/src/client/views/collections/CollectionSubView.tsx
@@ -9,7 +9,7 @@ import { Id } from '../../../fields/FieldSymbols';
 import { List } from '../../../fields/List';
 import { listSpec } from '../../../fields/Schema';
 import { ScriptField } from '../../../fields/ScriptField';
-import { BoolCast, Cast, ScriptCast, StrCast } from '../../../fields/Types';
+import { BoolCast, Cast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
 import { WebField } from '../../../fields/URLField';
 import { GetEffectiveAcl, TraceMobx } from '../../../fields/util';
 import { GestureUtils } from '../../../pen-gestures/GestureUtils';
@@ -25,7 +25,8 @@ import { SnappingManager } from '../../util/SnappingManager';
 import { UndoManager } from '../../util/UndoManager';
 import { ViewBoxBaseComponent } from '../DocComponent';
 import { FieldViewProps } from '../nodes/FieldView';
-import { DocumentView } from '../nodes/DocumentView';
+import { DocumentView, DocumentViewProps } from '../nodes/DocumentView';
+import { FlashcardPracticeUI } from './FlashcardPracticeUI';
 
 export interface CollectionViewProps extends React.PropsWithChildren<FieldViewProps> {
     isAnnotationOverlay?: boolean; // is the collection an annotation overlay (eg an overlay on an image/video/etc)
@@ -119,7 +120,8 @@ export function CollectionSubView<X>() {
                     pair =>
                         // filter out any documents that have a proto that we don't have permissions to
                         !pair.layout?.hidden && pair.layout && (!pair.layout.proto || (pair.layout.proto instanceof Doc && GetEffectiveAcl(pair.layout.proto) !== AclPrivate))
-                );
+                )
+                .filter(pair => !this._filterFunc?.(pair.layout!));
             return validPairs.map(({ data, layout }) => ({ data: data as Doc, layout: layout! })); // this mapping is a bit of a hack to coerce types
         }
         /**
@@ -515,6 +517,49 @@ export function CollectionSubView<X>() {
                 alert('Document upload failed - possibly an unsupported file type.');
             }
         };
+
+        protected _sideBtnWidth = 35;
+        @observable _filterFunc: ((doc: Doc) => boolean) | undefined = undefined;
+        /**
+         * How much the content of the collection is being scaled based on its nesting and its fit-to-width settings
+         */
+        @computed get contentScaling() { return this.ScreenToLocalBoxXf().Scale * (this._props.NativeDimScaling?.() ?? 1); } // prettier-ignore
+        /**
+         * The maximum size a UI widget can be in collection coordinates based on not wanting the widget to visually obscure too much of the collection
+         * This takes the desired screen space size and converts into collection coordinates.  It then returns the smaller of the converted
+         * size or a fraction of the collection view.
+         */
+        @computed get maxWidgetSize() { return Math.min(this._sideBtnWidth * this.contentScaling, 0.25 * NumCast(this.layoutDoc.width, 1));  } // prettier-ignore
+        /**
+         * This computes a scale factor for UI elements so that they shrink and grow as the collection does in screen space.
+         * Note, the scale factor does not allow for elements to grow larger than their native screen space size.
+         */
+        @computed get uiBtnScaling() { return this.maxWidgetSize / this._sideBtnWidth; } // prettier-ignore
+
+        screenXPadding = () => (this.uiBtnScaling * this._sideBtnWidth - NumCast(this.layoutDoc.xMargin)) / this._props.ScreenToLocalTransform().Scale;
+        filteredChildDocs = () => this.childLayoutPairs.map(pair => pair.layout);
+        childDocsFunc = () => this.childDocs;
+        @action setFilterFunc = (func?: (doc: Doc) => boolean) => { this._filterFunc = func; }; // prettier-ignore
+
+        public flashCardUI = (curDoc: () => Doc | undefined, docViewProps: () => DocumentViewProps, answered?: (correct: boolean) => void) => {
+            return (
+                <FlashcardPracticeUI
+                    setFilterFunc={this.setFilterFunc}
+                    fieldKey={this.fieldKey}
+                    sideBtnWidth={this._sideBtnWidth}
+                    allChildDocs={this.childDocsFunc}
+                    filteredChildDocs={this.filteredChildDocs}
+                    advance={answered}
+                    curDoc={curDoc}
+                    practiceBtnOffset={this._sideBtnWidth * 4}
+                    layoutDoc={this.layoutDoc}
+                    uiBtnScaling={this.uiBtnScaling}
+                    ScreenToLocalBoxXf={this.ScreenToLocalBoxXf}
+                    renderDepth={this._props.renderDepth}
+                    docViewProps={docViewProps}
+                />
+            );
+        };
     }
 
     return CollectionSubViewInternal;
diff --git a/src/client/views/collections/FlashcardPracticeUI.scss b/src/client/views/collections/FlashcardPracticeUI.scss
index 2f99500f8..c5252bbfa 100644
--- a/src/client/views/collections/FlashcardPracticeUI.scss
+++ b/src/client/views/collections/FlashcardPracticeUI.scss
@@ -50,7 +50,7 @@
             height: 20px;
             align-items: center;
             margin: auto;
-            padding: 3px;
+            // padding: 3px;
             &:hover {
                 color: white;
             }
diff --git a/src/client/views/collections/FlashcardPracticeUI.tsx b/src/client/views/collections/FlashcardPracticeUI.tsx
index a643c95b0..7bf4d86d1 100644
--- a/src/client/views/collections/FlashcardPracticeUI.tsx
+++ b/src/client/views/collections/FlashcardPracticeUI.tsx
@@ -23,15 +23,14 @@ enum practiceVal {
 interface PracticeUIProps {
     fieldKey: string;
     layoutDoc: Doc;
-    carouselItems: () => Doc[];
-    childDocs: Doc[];
+    filteredChildDocs: () => Doc[];
+    allChildDocs: () => Doc[];
     curDoc: () => Doc | undefined;
-    advance: (correct: boolean) => void;
+    advance?: (correct: boolean) => void;
     renderDepth: number;
     sideBtnWidth: number;
-    uiBtnScaleTransform: number;
+    uiBtnScaling: number;
     ScreenToLocalBoxXf: () => Transform;
-    maxWidgetScale: number;
     docViewProps: () => DocumentViewProps;
     setFilterFunc: (func?: (doc: Doc) => boolean) => void;
     practiceBtnOffset?: number;
@@ -51,7 +50,7 @@ export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProp
     get practiceField() { return this._props.fieldKey + "_practice"; } // prettier-ignore
 
     @computed get filterDoc() { return DocListCast(Doc.MyContextMenuBtns.data).find(doc => doc.title === 'Filter'); } // prettier-ignore
-    @computed get practiceMode() {  return this._props.childDocs.some(doc => doc._layout_isFlashcard) ? StrCast(this._props.layoutDoc.practiceMode) : ''; } // prettier-ignore
+    @computed get practiceMode() {  return this._props.allChildDocs().some(doc => doc._layout_isFlashcard) ? StrCast(this._props.layoutDoc.practiceMode) : ''; } // prettier-ignore
 
     btnHeight = () => NumCast(this.filterDoc?.height) * Math.min(1, this._props.ScreenToLocalBoxXf().Scale);
     btnWidth = () => (!this.filterDoc ? 1 : (this.btnHeight() * NumCast(this.filterDoc._width)) / NumCast(this.filterDoc._height));
@@ -62,12 +61,12 @@ export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProp
      */
     setPracticeMode = (mode: practiceMode | undefined) => {
         this._props.layoutDoc.practiceMode = mode;
-        this._props.carouselItems().map(doc => (doc[this.practiceField] = undefined));
+        this._props.allChildDocs().map(doc => (doc[this.practiceField] = undefined));
     };
 
     @computed get emptyMessage() {
-        const cardCount = this._props.carouselItems().length;
-        const practiceMessage = this.practiceMode && !Doc.hasDocFilter(this._props.layoutDoc, 'tags', Doc.FilterAny) && !this._props.carouselItems().length ? 'Finished! Click here to view all flashcards.' : '';
+        const cardCount = this._props.filteredChildDocs().length;
+        const practiceMessage = this.practiceMode && !Doc.hasDocFilter(this._props.layoutDoc, 'tags', Doc.FilterAny) && !cardCount ? 'Finished! Click here to view all flashcards.' : '';
         const filterMessage = practiceMessage
             ? ''
             : Doc.hasDocFilter(this._props.layoutDoc, 'tags', Doc.FilterAny) && !cardCount
@@ -78,7 +77,7 @@ export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProp
         return !practiceMessage && !filterMessage ? null : (
             <p
                 className="FlashcardPracticeUI-message"
-                style={{ transform: `scale(${this._props.uiBtnScaleTransform})` }}
+                style={{ transform: `scale(${this._props.uiBtnScaling})` }}
                 onClick={() => {
                     if (filterMessage || practiceMessage) {
                         this.setPracticeMode(undefined);
@@ -102,7 +101,7 @@ export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProp
         };
 
         return this.practiceMode == practiceMode.PRACTICE && this._props.curDoc() ? (
-            <div className="FlashcardPracticeUI-practice" style={{ transform: `scale(${this._props.uiBtnScaleTransform})`, bottom: `${this._props.practiceBtnOffset ?? this._props.sideBtnWidth}px`, height: `${this._props.sideBtnWidth}px` }}>
+            <div className="FlashcardPracticeUI-practice" style={{ transform: `scale(${this._props.uiBtnScaling})`, bottom: `${this._props.practiceBtnOffset ?? this._props.sideBtnWidth}px`, height: `${this._props.sideBtnWidth}px` }}>
                 <Tooltip title="Incorrect. View again later.">
                     <div key="remove" className="FlashcardPracticeUI-remove" onClick={e => setPracticeVal(e, practiceVal.MISSED)}>
                         <FontAwesomeIcon icon="xmark" color="red" size="1x" />
@@ -120,12 +119,12 @@ export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProp
         const setColor = (mode: practiceMode) => (StrCast(this.practiceMode) === mode ? 'white' : 'light gray');
         const togglePracticeMode = (mode: practiceMode) => this.setPracticeMode(mode === this.practiceMode ? undefined : mode);
 
-        return !this._props.childDocs.some(doc => doc._layout_isFlashcard) ? null : (
+        return !this._props.allChildDocs().some(doc => doc._layout_isFlashcard) ? null : (
             <div
                 className="FlashcardPracticeUI-practiceModes"
                 style={{
                     transformOrigin: `0px ${-this.btnHeight()}px`,
-                    transform: `scale(${Math.max(1, 1 / this._props.ScreenToLocalBoxXf().Scale / this._props.maxWidgetScale)})`,
+                    transform: `scale(${Math.max(1, 1 / this._props.ScreenToLocalBoxXf().Scale)})`,
                 }}>
                 <Tooltip title="Practice flashcards using GPT">
                     <div key="back" className="FlashcardPracticeUI-quiz" style={{ width: this.btnWidth(), height: this.btnHeight() }} onClick={() => togglePracticeMode(practiceMode.QUIZ)}>
@@ -146,7 +145,7 @@ export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProp
             <>
                 {this.emptyMessage}
                 {this.practiceButtons}
-                <div className="FlashcardPracticeUI-menu" style={{ height: this.btnHeight(), width: this.btnHeight(), transform: `scale(${this._props.uiBtnScaleTransform})` }}>
+                <div className="FlashcardPracticeUI-menu" style={{ height: this.btnHeight(), width: this.btnHeight(), transform: `scale(${this._props.uiBtnScaling})` }}>
                     {!this.filterDoc || this._props.layoutDoc._chromeHidden ? null : (
                         <DocumentView
                             {...this._props.docViewProps()}
diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
index d8678eebc..0cc63d632 100644
--- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
+++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
@@ -138,7 +138,7 @@ export class CollectionFreeFormView extends CollectionSubView<Partial<collection
         return this._props.layoutEngine?.() || StrCast(this.layoutDoc._layoutEngine);
     }
     @computed get childPointerEvents() {
-        return falseSnappingManager.IsResizing
+        return SnappingManager.IsResizing
             ? 'none'
             : (this._props.childPointerEvents?.() ??
                   (this._props.viewDefDivClick || //
diff --git a/src/client/views/nodes/ComparisonBox.tsx b/src/client/views/nodes/ComparisonBox.tsx
index 81e223028..a8c91aae8 100644
--- a/src/client/views/nodes/ComparisonBox.tsx
+++ b/src/client/views/nodes/ComparisonBox.tsx
@@ -87,34 +87,26 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
         );
     }
 
-    _sideBtnWidth = 30;
+    _sideBtnWidth = 35;
     /**
      * How much the content of the view is being scaled based on its nesting and its fit-to-width settings
      */
-    @computed get contentScaling() {
-        return this.ScreenToLocalBoxXf().Scale * (this._props.NativeDimScaling?.() ?? 1);
-    }
+    @computed get viewScaling() { return this.ScreenToLocalBoxXf().Scale; } // prettier-ignore
     /**
      * The maximum size a UI widget can be scaled so that it won't be bigger in screen pixels than its normal 35 pixel size.
      */
-    @computed get maxWidgetScale() {
-        const maxWidgetSize = Math.min(this._sideBtnWidth * this.contentScaling, 0.25 * Math.min(NumCast(this.Document.width), NumCast(this.Document.height)));
-        return Math.max(maxWidgetSize / this._sideBtnWidth, 1);
-    }
+    @computed get maxWidgetSize() { return  Math.min(this._sideBtnWidth * this.viewScaling, 0.25 * Math.min(NumCast(this.Document.width), NumCast(this.Document.height))); } // prettier-ignore
     /**
      * How much to reactively scale a UI element so that it is as big as it can be (up to its normal 35pixel size) without being too big for the Doc content
      */
-    @computed get uiBtnScaleTransform() {
-        return this.maxWidgetScale * Math.min(1, this.contentScaling);
-    }
+    @computed get uiBtnScaling() { return Math.max(this.maxWidgetSize / this._sideBtnWidth, 1) * Math.min(1, this.viewScaling)* (this._props.NativeDimScaling?.() ?? 1); } // prettier-ignore
 
     @computed get flashcardMenu() {
         return (
-            <div className="comparisonBox-bottomMenu" style={{ transform: `scale(${this.uiBtnScaleTransform})` }}>
+            <div className="comparisonBox-bottomMenu" style={{ transform: `scale(${this.uiBtnScaling})` }}>
                 {this.overlayAlternateIcon}
                 {!this._props.isContentActive() ? null : (
                     <>
-                        {' '}
                         {!this._frontSide ? null : (
                             <Tooltip
                                 title={
-- 
cgit v1.2.3-70-g09d2


From a0b0dc415f21535782239b471bd4b4942dea6daf Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Wed, 9 Oct 2024 13:54:32 -0400
Subject: removing more commented out code, fixing lint.  fixed carousel3Dview
 child active

---
 src/client/apis/gpt/GPT.ts                         |  3 +-
 .../views/collections/CollectionCarousel3DView.tsx | 11 +++-
 .../views/collections/FlashcardPracticeUI.scss     |  2 +-
 src/client/views/nodes/ComparisonBox.tsx           | 67 ++++++++++------------
 4 files changed, 41 insertions(+), 42 deletions(-)

(limited to 'src/client/views/collections/CollectionCarousel3DView.tsx')

diff --git a/src/client/apis/gpt/GPT.ts b/src/client/apis/gpt/GPT.ts
index 88352110b..e8c6cc02f 100644
--- a/src/client/apis/gpt/GPT.ts
+++ b/src/client/apis/gpt/GPT.ts
@@ -72,7 +72,6 @@ const callTypeMap: { [type: string]: GPTCallOpts } = {
         model: 'gpt-4-turbo',
         maxTokens: 1024,
         temp: 0.1, //0.3
-        prompt: '',
         prompt: "BRIEFLY (<50 words) describe any differences between the rubric and the user's answer answer in second person. If there are no differences, say correct",
     },
 
@@ -125,7 +124,7 @@ let lastResp = '';
  * @param inputText Text to process
  * @returns AI Output
  */
-const gptAPICall = async (inputTextIn: string, callType: GPTCallType, prompt?: any, dontCache?: boolean) => {
+const gptAPICall = async (inputTextIn: string, callType: GPTCallType, prompt?: string, dontCache?: boolean) => {
     const inputText = [GPTCallType.SUMMARY, GPTCallType.FLASHCARD, GPTCallType.QUIZ, GPTCallType.STACK].includes(callType) ? inputTextIn + '.' : inputTextIn;
     const opts: GPTCallOpts = callTypeMap[callType];
     if (lastCall === inputText && dontCache !== true) return lastResp;
diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx
index 9ccac0e0f..f2ba90c78 100644
--- a/src/client/views/collections/CollectionCarousel3DView.tsx
+++ b/src/client/views/collections/CollectionCarousel3DView.tsx
@@ -6,7 +6,7 @@ import { returnZero } from '../../../ClientUtils';
 import { Utils } from '../../../Utils';
 import { Doc, DocListCast, Opt } from '../../../fields/Doc';
 import { Id } from '../../../fields/FieldSymbols';
-import { DocCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
+import { BoolCast, DocCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
 import { DocumentType } from '../../documents/DocumentTypes';
 import { DragManager } from '../../util/DragManager';
 import { Transform } from '../../util/Transform';
@@ -52,7 +52,14 @@ export class CollectionCarousel3DView extends CollectionSubView() {
     panelHeight = () => this._props.PanelHeight() * this.sideScale;
     onChildDoubleClick = () => ScriptCast(this.layoutDoc.onChildDoubleClick);
     isContentActive = () => this._props.isSelected() || this._props.isContentActive() || this._props.isAnyChildContentActive();
-    isChildContentActive = () => !!this.isContentActive();
+    isChildContentActive = () =>
+        this._props.isContentActive?.() === false
+            ? false
+            : this._props.isDocumentActive?.() && (this._props.childDocumentsActive?.() || BoolCast(this.Document.childDocumentsActive))
+              ? true
+              : this._props.childDocumentsActive?.() === false || this.Document.childDocumentsActive === false
+                ? false
+                : undefined;
     contentScreenToLocalXf = () => this._props.ScreenToLocalTransform().scale(this._props.NativeDimScaling?.() || 1);
     childScreenLeftToLocal = () =>
         this.contentScreenToLocalXf()
diff --git a/src/client/views/collections/FlashcardPracticeUI.scss b/src/client/views/collections/FlashcardPracticeUI.scss
index c5252bbfa..2f99500f8 100644
--- a/src/client/views/collections/FlashcardPracticeUI.scss
+++ b/src/client/views/collections/FlashcardPracticeUI.scss
@@ -50,7 +50,7 @@
             height: 20px;
             align-items: center;
             margin: auto;
-            // padding: 3px;
+            padding: 3px;
             &:hover {
                 color: white;
             }
diff --git a/src/client/views/nodes/ComparisonBox.tsx b/src/client/views/nodes/ComparisonBox.tsx
index 00ca0078e..9b75feba8 100644
--- a/src/client/views/nodes/ComparisonBox.tsx
+++ b/src/client/views/nodes/ComparisonBox.tsx
@@ -451,36 +451,33 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
         const senArr = text?.split('Question: ') ?? [];
         const collectionArr: Doc[] = [];
         for (let i = 1; i < senArr.length; i++) {
-            const newDoc = Docs.Create.ComparisonDocument(senArr![i], { _layout_isFlashcard: true, _width: 300, _height: 300 });
+            const newDoc = Docs.Create.ComparisonDocument(senArr[i], { _layout_isFlashcard: true, _width: 300, _height: 300 });
 
-            if (StrCast(senArr![i]).includes('Keyword: ')) {
+            if (senArr[i].includes('Keyword: ')) {
                 const question = StrCast(senArr![i]).split('Keyword: ');
-                const img = await this.fetchImages(question[1]);
-                const textSide1 = question[0].includes('Answer: ') ? question[0].split('Answer: ')[0] : question[0];
-                const textDoc1 = Docs.Create.TextDocument(question[0]);
-                const rtfiel = new RichTextField(
-                    JSON.stringify({
-                        doc: {
-                            type: 'doc',
-                            content: [
-                                {
-                                    type: 'paragraph',
-                                    attrs: { align: null, color: null, id: null, indent: null, inset: null, lineSpacing: null, paddingBottom: null, paddingTop: null },
-                                    content: [
-                                        { type: 'text', text: question[0].includes('Answer: ') ? question[0].split('Answer: ')[0] : question[0] },
-                                        { type: 'dashDoc', attrs: { width: '200px', height: '200px', title: 'dashDoc', float: 'unset', hidden: false, docId: img![Id] } },
-                                    ],
-                                },
-                            ],
-                        },
-                        selection: { type: 'text', anchor: 2, head: 2 },
-                    }),
-                    textSide1
-                );
-
-                textDoc1[DocData].text = rtfiel;
-                DocCast(newDoc)[DocData][this.fieldKey + '_1'] = textDoc1;
-                DocCast(newDoc)[DocData][this.fieldKey + '_0'] = Docs.Create.TextDocument(question[0].includes('Answer: ') ? question[0].split('Answer: ')[1] : question[1]);
+                const questionTxt = question[0].includes('Answer: ') ? question[0].split('Answer: ')[0] : question[0];
+                const answerTxt = question[0].includes('Answer: ') ? question[0].split('Answer: ')[1] : question[1];
+                this.fetchImages(question[1]).then(img => {
+                    const rtfiel = new RichTextField(
+                        JSON.stringify({
+                            // this is a RichText json that has the question text placed above a related image
+                            doc: {
+                                type: 'doc',
+                                content: [
+                                    {
+                                        type: 'paragraph',
+                                        attrs: { align: null, color: null, id: null, indent: null, inset: null, lineSpacing: null, paddingBottom: null, paddingTop: null },
+                                        content: [{ type: 'text', text: questionTxt }, img ? { type: 'dashDoc', attrs: { width: '200px', height: '200px', title: 'dashDoc', float: 'unset', hidden: false, docId: img[Id] } } : {}],
+                                    },
+                                ],
+                            },
+                            selection: { type: 'text', anchor: 2, head: 2 },
+                        }),
+                        questionTxt
+                    );
+                    newDoc[DocData][this.fieldKey + '_1'] = Docs.Create.TextDocument(questionTxt, { text: rtfiel });
+                    newDoc[DocData][this.fieldKey + '_0'] = Docs.Create.TextDocument(answerTxt);
+                });
             }
 
             collectionArr.push(newDoc);
@@ -493,8 +490,8 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
      */
     askGPT = async (callType: GPTCallType): Promise<string | undefined> => {
         const questionText = 'Question: ' + StrCast(RTFCast(DocCast(this.dataDoc[this.fieldKey + '_1']).text)?.Text);
-        const rubricText = ' Rubric: ' + StrCast(RTFCast(DocCast(this.dataDoc[this.fieldKey + '_0']).text)?.Text);
-        const queryText = questionText + ' UserAnswer: ' + this._inputValue + '. ' + rubricText;
+        // const rubricText = ' Rubric: ' + StrCast(RTFCast(DocCast(this.dataDoc[this.fieldKey + '_0']).text)?.Text);
+        // const queryText = questionText + ' UserAnswer: ' + this._inputValue + '. ' + rubricText;
         this._loading = true;
 
         if (callType == GPTCallType.CHATCARD) {
@@ -504,7 +501,6 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
             }
         }
         try {
-            console.log(queryText);
             const res = await gptAPICall(questionText, GPTCallType.FLASHCARD);
             if (!res) {
                 console.error('GPT call failed');
@@ -513,7 +509,6 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
             if (callType == GPTCallType.CHATCARD) {
                 DocCast(this.dataDoc[this.props.fieldKey + '_0'])[DocData].text = res;
             } else if (callType == GPTCallType.QUIZ) {
-                console.log(this._inputValue);
                 this._frontSide = true;
                 this._outputValue = res.replace(/UserAnswer/g, "user's answer").replace(/Rubric/g, 'rubric');
             } else if (callType === GPTCallType.FLASHCARD) {
@@ -531,13 +526,12 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     layoutHeight = () => NumCast(this.layoutDoc.height, 200);
 
     findImageTags = async () => {
-        const c = this.DocumentView?.().ContentDiv!.getElementsByTagName('img');
-        if (c?.length === 0) await this.askGPT(GPTCallType.CHATCARD);
+        const c = this.DocumentView?.().ContentDiv?.getElementsByTagName('img');
+        if (c?.length === 0) this.askGPT(GPTCallType.CHATCARD);
         if (c) {
             this._loading = true;
             for (const i of c) {
-                console.log(i);
-                if (i.className !== 'ProseMirror-separator') await this.getImageDesc(i.src);
+                if (i.className !== 'ProseMirror-separator') this.getImageDesc(i.src);
             }
             this._loading = false;
         }
@@ -611,7 +605,6 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     fetchImages = async (selection: string) => {
         try {
             const { data } = await axios.get(`${API_URL}?query=${selection}&page=1&per_page=${1}&client_id=Q4zruu6k6lum2kExiGhLNBJIgXDxD6NNj0SRHH_XXU0`);
-            console.log(data.results);
             const imageSnapshot = Docs.Create.ImageDocument(data.results[0].urls.small, {
                 _nativeWidth: Doc.NativeWidth(this.layoutDoc),
                 _nativeHeight: Doc.NativeHeight(this.layoutDoc),
-- 
cgit v1.2.3-70-g09d2


From 76abb174684f2cd231a0dd9f6b71484c16e0498a Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Fri, 11 Oct 2024 15:55:19 -0400
Subject: fixes for quiz mode - comparisonbox renderSide fixes. scrolling
 doesn't propagate out of carousel or card views.   fix for text with image
 Doc - now gets saved to UPDATE_CACHE working  set.

---
 .../views/collections/CollectionCardDeckView.tsx   |   6 ++
 .../views/collections/CollectionCarousel3DView.tsx |   6 ++
 .../views/collections/CollectionCarouselView.tsx   |   6 ++
 src/client/views/nodes/ComparisonBox.tsx           | 114 +++++++++++----------
 .../nodes/formattedText/DashDocCommentView.tsx     |   4 +-
 src/fields/Doc.ts                                  |  13 +++
 src/server/GarbageCollector.ts                     |   3 -
 7 files changed, 95 insertions(+), 57 deletions(-)

(limited to 'src/client/views/collections/CollectionCarousel3DView.tsx')

diff --git a/src/client/views/collections/CollectionCardDeckView.tsx b/src/client/views/collections/CollectionCardDeckView.tsx
index 286df30aa..14ce9d2af 100644
--- a/src/client/views/collections/CollectionCardDeckView.tsx
+++ b/src/client/views/collections/CollectionCardDeckView.tsx
@@ -46,6 +46,7 @@ export class CollectionCardView extends CollectionSubView() {
     private _dropDisposer?: DragManager.DragDropDisposer;
     private _disposers: { [key: string]: IReactionDisposer } = {};
     private _textToDoc = new Map<string, Doc>();
+    private _oldWheel: HTMLElement | null = null;
     private _dropped = false; // set when a card doc has just moved and the drop method has been called - prevents the pointerUp method from hiding doc decorations (which needs to be done when clicking on a card to animate it to front/center)
     private _clickScript = () => ScriptField.MakeScript('scriptContext._curDoc=this', { scriptContext: 'any' })!;
 
@@ -66,6 +67,10 @@ export class CollectionCardView extends CollectionSubView() {
         if (ele) {
             this._dropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.layoutDoc);
         }
+        this._oldWheel?.removeEventListener('wheel', this.onPassiveWheel);
+        this._oldWheel = ele;
+        // prevent wheel events from passively propagating up through containers and prevents containers from preventDefault which would block scrolling
+        ele?.addEventListener('wheel', this.onPassiveWheel, { passive: false });
     };
     /**
      * Callback to ensure gpt's text versions of the child docs are updated
@@ -621,6 +626,7 @@ export class CollectionCardView extends CollectionSubView() {
             );
         });
     }
+    onPassiveWheel = (e: WheelEvent) => e.stopPropagation();
 
     contentScreenToLocalXf = () => this._props.ScreenToLocalTransform().scale(this._props.NativeDimScaling?.() || 1);
     docViewProps = (): DocumentViewProps => ({
diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx
index f2ba90c78..05be376ca 100644
--- a/src/client/views/collections/CollectionCarousel3DView.tsx
+++ b/src/client/views/collections/CollectionCarousel3DView.tsx
@@ -22,6 +22,7 @@ const { CAROUSEL3D_CENTER_SCALE, CAROUSEL3D_SIDE_SCALE, CAROUSEL3D_TOP } = requi
 @observer
 export class CollectionCarousel3DView extends CollectionSubView() {
     private _dropDisposer?: DragManager.DragDropDisposer;
+    private _oldWheel: HTMLElement | null = null;
 
     constructor(props: SubCollectionViewProps) {
         super(props);
@@ -37,6 +38,10 @@ export class CollectionCarousel3DView extends CollectionSubView() {
         if (ele) {
             this._dropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.layoutDoc);
         }
+        this._oldWheel?.removeEventListener('wheel', this.onPassiveWheel);
+        this._oldWheel = ele;
+        // prevent wheel events from passively propagating up through containers and prevents containers from preventDefault which would block scrolling
+        ele?.addEventListener('wheel', this.onPassiveWheel, { passive: false });
     };
 
     @computed get scrollSpeed() {
@@ -194,6 +199,7 @@ export class CollectionCarousel3DView extends CollectionSubView() {
         return this.panelWidth() * (1 - index);
     }
 
+    onPassiveWheel = (e: WheelEvent) => e.stopPropagation();
     curDoc = () => this.carouselItems[NumCast(this.layoutDoc._carousel_index)]?.layout;
     answered = (correct: boolean) => (!correct || !this.curDoc()) && this.changeSlide(1);
     docViewProps = () => ({
diff --git a/src/client/views/collections/CollectionCarouselView.tsx b/src/client/views/collections/CollectionCarouselView.tsx
index aa447c7bf..ef66a2c83 100644
--- a/src/client/views/collections/CollectionCarouselView.tsx
+++ b/src/client/views/collections/CollectionCarouselView.tsx
@@ -17,6 +17,7 @@ import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView';
 export class CollectionCarouselView extends CollectionSubView() {
     private _dropDisposer?: DragManager.DragDropDisposer;
 
+    _oldWheel: HTMLElement | null = null;
     _fadeTimer: NodeJS.Timeout | undefined;
     @observable _last_index = this.carouselIndex;
     @observable _last_opacity = 1;
@@ -35,6 +36,10 @@ export class CollectionCarouselView extends CollectionSubView() {
         if (ele) {
             this._dropDisposer = DragManager.MakeDropTarget(ele, this.onInternalDrop.bind(this), this.layoutDoc);
         }
+        this._oldWheel?.removeEventListener('wheel', this.onPassiveWheel);
+        this._oldWheel = ele;
+        // prevent wheel events from passively propagating up through containers and prevents containers from preventDefault which would block scrolling
+        ele?.addEventListener('wheel', this.onPassiveWheel, { passive: false });
     };
 
     @computed get captionMarginX(){ return NumCast(this.layoutDoc.caption_xMargin, 50); } // prettier-ignore
@@ -91,6 +96,7 @@ export class CollectionCarouselView extends CollectionSubView() {
               : this._props.childDocumentsActive?.() === false || this.Document.childDocumentsActive === false
                 ? false
                 : undefined;
+    onPassiveWheel = (e: WheelEvent) => e.stopPropagation();
     renderDoc = (doc: Doc, showCaptions: boolean, overlayFunc?: (r: DocumentView | null) => void) => {
         return (
             <DocumentView
diff --git a/src/client/views/nodes/ComparisonBox.tsx b/src/client/views/nodes/ComparisonBox.tsx
index a57090e99..111fabca3 100644
--- a/src/client/views/nodes/ComparisonBox.tsx
+++ b/src/client/views/nodes/ComparisonBox.tsx
@@ -39,6 +39,9 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     public static LayoutString(fieldKey: string) {
         return FieldView.LayoutString(ComparisonBox, fieldKey);
     }
+    static qtoken = 'Question: ';
+    static ktoken = 'Keyword: ';
+    static atoken = 'Answer: ';
     private SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
     private _closeRef = React.createRef<HTMLDivElement>();
     private _disposers: { [key: string]: DragManager.DragDropDisposer | undefined } = {};
@@ -55,11 +58,11 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     @observable private _childActive = false;
     @observable private _animating = '';
     @observable private _listening = false;
-    @observable private _renderSide = this.fieldKey;
+    @observable private _renderSide = this.frontKey;
     @observable private _recognition = new this.SpeechRecognition();
 
     @computed get isFlashcard()   { return BoolCast(this.Document.layout_isFlashcard); } // prettier-ignore
-    @computed get frontKey()      { return this._props.fieldKey; } // prettier-ignore
+    @computed get frontKey()      { return this._props.fieldKey + '_front'; } // prettier-ignore
     @computed get backKey()       { return this._props.fieldKey + '_back'; } // prettier-ignore
     @computed get revealOpKey()   { return `_${this._props.fieldKey}_revealOp`; } // prettier-ignore
     @computed get clipHeightKey() { return `_${this._props.fieldKey}_clipHeight`; } // prettier-ignore
@@ -124,7 +127,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
                                 </div>
                             </Tooltip>
                         )}
-                        {DocCast(this.Document.embedContainer)?.type_collection !== CollectionViewType.Freeform ? null : (
+                        {DocCast(this.Document.embedContainer)?.type_collection !== CollectionViewType.Freeform || this._renderSide === this.backKey ? null : (
                             <Tooltip title={<div className="dash-tooltip">Create new flashcard stack based on text</div>}>
                                 <div className="comparisonBox-button" onClick={this.gptFlashcardPile}>
                                     <FontAwesomeIcon icon="layer-group" size="xl" />
@@ -150,9 +153,9 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
         if (phonTrans) {
             this._inputValue = StrCast(phonTrans);
             this.askGPTPhonemes(this._inputValue);
+            this._renderSide = this.backKey;
+            this._outputValue = '';
         } else if (this._inputValue) this.askGPT(GPTCallType.QUIZ);
-        this._renderSide = this.backKey;
-        this._outputValue = '';
     };
 
     onPointerMove = ({ movementX }: PointerEvent) => {
@@ -444,38 +447,41 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
             }),
             text
         );
-    /**
-     * Transfers the content of flashcards into a flashcard pile.
-     */
-    gptFlashcardPile = async () => {
-        this.askGPT(GPTCallType.STACK).then(text => {
-            const [qtoken, ktoken, atoken] = ['Question: ', 'Keyword: ', 'Answer: '];
-            const collectionArr: Doc[] = [];
-            const promises = text
-                .split(qtoken)
+
+    createFlashcard = (tuple: string, useDoc?: Doc) => {
+        const [ktoken, atoken] = [ComparisonBox.ktoken, ComparisonBox.atoken];
+        const newDoc = useDoc ?? Docs.Create.ComparisonDocument('', { _layout_isFlashcard: true, _width: 300, _height: 300 });
+        const question = (tuple.includes(ktoken) ? tuple.split(ktoken)[0] : tuple).split(atoken)[0];
+        const rest = tuple.replace(question, '');
+        // prettier-ignore
+        const answer = rest.startsWith(ktoken) ?     // if keyword comes first, 
+                            tuple.includes(atoken) ? tuple.split(atoken)[1] : "" : //if tuple includes answer, split at answer and take what's left, otherwise there's no answer
+                        rest.includes(ktoken) ?      // otherwise if keyword is present it must come after answer, 
+                            rest.split(ktoken)[0].split(atoken)[1] :  // split at keyword and take what comes first and split that at answer and take what's left
+                            rest.replace(atoken,""); // finally if there's no keyword, just get rid of answer token and take what's left
+        const keyword = rest.replace(atoken, '').replace(answer, '').replace(ktoken, '').trim();
+        const fillInFlashcard = (img?: Doc) => {
+            newDoc[DocData][this.frontKey] = this.textCreator('question', question, img);
+            newDoc[DocData][this.backKey] = this.textCreator('answer', answer);
+            return newDoc;
+        };
+        return keyword && keyword !== 'none' ? this.fetchImages(keyword).then(img => fillInFlashcard(img)) : fillInFlashcard();
+    };
+
+    createFlashcardDeck = (text: string) => {
+        Promise.all(
+            text
+                .split(ComparisonBox.qtoken)
                 .filter(t => t)
-                .map(tuple => {
-                    const newDoc = Docs.Create.ComparisonDocument('', { _layout_isFlashcard: true, _width: 300, _height: 300 });
-                    const question = (tuple.includes(ktoken) ? tuple.split(ktoken)[0] : tuple).split(atoken)[0];
-                    const rest = tuple.replace(question, '');
-                    // prettier-ignore
-                    const answer = rest.startsWith(ktoken) ?     // if keyword comes first, 
-                                        tuple.includes(atoken) ? tuple.split(atoken)[1] : "" : //if tuple includes answer, split at answer and take what's left, otherwise there's no answer
-                                    rest.includes(ktoken) ?      // otherwise if keyword is present it must come after answer, 
-                                        rest.split(ktoken)[0].split(atoken)[1] :  // split at keyword and take what comes first and split that at answer and take what's left
-                                        rest.replace(atoken,""); // finally if there's no keyword, just get rid of answer token and take what's left
-                    const keyword = rest.replace(atoken, '').replace(answer, '').replace(ktoken, '').trim();
-                    const fillInFlashcard = (img?: Doc) => {
-                        newDoc[DocData][this.frontKey] = this.textCreator('question', question, img);
-                        newDoc[DocData][this.backKey] = this.textCreator('answer', answer);
-                        collectionArr.push(newDoc);
-                    };
-                    return keyword && keyword !== 'none' ? this.fetchImages(keyword).then(img => fillInFlashcard(img)) : fillInFlashcard();
-                });
-            Promise.all(promises).then(() => this.createFlashcardPile(collectionArr, true));
-        });
+                .map(tuple => this.createFlashcard(tuple))
+        ).then(docs => this.createFlashcardPile(docs, true));
     };
 
+    /**
+     * queries GPT about a topic and then creates a flashcard deck from the results.
+     */
+    gptFlashcardPile = () => this.askGPT(GPTCallType.STACK).then(this.createFlashcardDeck);
+
     /**
      * Calls GPT for each flashcard type.
      */
@@ -498,7 +504,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
                             break;
                         case GPTCallType.QUIZ:
                             runInAction(() => {
-                                this._renderSide = this.frontKey;
+                                this._renderSide = this.backKey;
                                 this._outputValue = res.replace(/UserAnswer/g, "user's answer").replace(/Rubric/g, 'rubric');
                             });
                             break;
@@ -728,20 +734,24 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
         );
 
         if (this.isFlashcard) {
-            const dataSplit = StrCast(this.dataDoc.data).includes('Keyword: ') ? StrCast(this.dataDoc.data).split('Keyword: ') : StrCast(this.dataDoc.data).split('Answer: ');
-
-            // add text box to each side when comparison box is first created
-            if (!this.dataDoc[this.backKey] && !this._isEmpty) {
-                this.dataDoc[this.backKey] = this.textCreator('answer', dataSplit[1]);
+            if (this.dataDoc.data) {
+                if (!this.dataDoc[this.backKey] || !this.dataDoc[this.frontKey]) this.createFlashcard(StrCast(this.dataDoc.data), this.Document);
+            } else {
+                // add text box to each side when comparison box is first created
+                if (!this.dataDoc[this.backKey] && !this._isEmpty) {
+                    const answer = this.textCreator('answer', 'answer here');
+                    this.dataDoc[this.backKey] = answer;
+                    answer[DocData].text_placeholder = true;
+                }
+
+                if (!this.dataDoc[this.frontKey] && !this._isEmpty) {
+                    const question = this.textCreator('question', 'hint: Enter a topic, select this document and click the stack button to have GPT create a deck of cards');
+                    this.dataDoc[this.frontKey] = question;
+                    question[DocData].text_placeholder = true;
+                }
             }
 
-            if (!this.dataDoc[this.frontKey] && !this._isEmpty) {
-                const question = this.textCreator('question', dataSplit[0] || 'hint: Enter a topic, select this document and click the stack button to have GPT create a deck of cards');
-                this.dataDoc[this.frontKey] = question;
-                !dataSplit[0] && (question[DocData].text_placeholder = true);
-            }
-
-            if (DocCast(this.Document.embedContainer).practiceMode === practiceMode.QUIZ) {
+            if (DocCast(this.Document.embedContainer)?.practiceMode === practiceMode.QUIZ) {
                 const text = StrCast(RTFCast(DocCast(this.dataDoc[this.frontKey]).text)?.Text);
                 return (
                     <div className={`comparisonBox${this._props.isContentActive() ? '-interactive' : ''}`}>
@@ -749,15 +759,15 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
                         <p style={{ display: text === '' ? 'flex' : 'none', color: 'white', marginLeft: '10px' }}>Return to all flashcards and add text to both sides. </p>
                         <div className="input-box">
                             <textarea
-                                value={this._renderSide ? this._outputValue : this._inputValue}
+                                value={this._renderSide === this.backKey ? this._outputValue : this._inputValue}
                                 onChange={this.handleInputChange}
                                 onScroll={e => {
                                     e.stopPropagation();
                                     e.preventDefault();
                                 }}
                                 placeholder={!this.layoutDoc[`_${this._props.fieldKey}_usePath`] ? 'Enter a response for GPT to evaluate.' : ''}
-                                readOnly={this._renderSide === this.frontKey}></textarea>
-
+                                readOnly={this._renderSide === this.backKey}
+                            />
                             {!this.loading ? null : (
                                 <div className="loading-spinner">
                                     <ReactLoading type="spin" height={30} width={30} color={'blue'} />
@@ -778,8 +788,8 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
                                 <button className="submit-buttonpronunciation" onClick={this.evaluatePronunciation}>
                                     Evaluate Pronunciation
                                 </button>
-                                <button className="submit-buttonsubmit" type="button" onClick={this._renderSide === this.frontKey ? this.flipFlashcard : this.handleRenderGPTClick}>
-                                    {this._renderSide === this.frontKey ? 'Redo the Question' : 'Submit'}
+                                <button className="submit-buttonsubmit" type="button" onClick={this._renderSide === this.backKey ? this.flipFlashcard : this.handleRenderGPTClick}>
+                                    {this._renderSide === this.backKey ? 'Redo the Question' : 'Submit'}
                                 </button>
                             </div>
                         </div>
diff --git a/src/client/views/nodes/formattedText/DashDocCommentView.tsx b/src/client/views/nodes/formattedText/DashDocCommentView.tsx
index 0304ddc86..967f4aa5b 100644
--- a/src/client/views/nodes/formattedText/DashDocCommentView.tsx
+++ b/src/client/views/nodes/formattedText/DashDocCommentView.tsx
@@ -68,7 +68,7 @@ export class DashDocCommentViewInternal extends React.Component<IDashDocCommentV
                 expand && this._dashDoc.then(async dashDoc => dashDoc instanceof Doc && Doc.linkFollowHighlight(dashDoc));
                 try {
                     this.props.view.dispatch(this.props.view.state.tr.setSelection(TextSelection.create(this.props.view.state.tr.doc, (this.props.getPos() ?? 0) + (expand ? 2 : 1))));
-                } catch (err) {
+                } catch {
                     /* empty */
                 }
             }, 0);
@@ -95,7 +95,7 @@ export class DashDocCommentViewInternal extends React.Component<IDashDocCommentV
         setTimeout(() => {
             try {
                 this.props.view.dispatch(state.tr.setSelection(TextSelection.create(state.tr.doc, this.props.getPos() + 2)));
-            } catch (err) {
+            } catch {
                 /* empty */
             }
         }, 0);
diff --git a/src/fields/Doc.ts b/src/fields/Doc.ts
index 81241f9fe..45dfe233f 100644
--- a/src/fields/Doc.ts
+++ b/src/fields/Doc.ts
@@ -960,6 +960,19 @@ export namespace Doc {
                         }
                     } else if (field instanceof PrefetchProxy) {
                         Doc.FindReferences(field.value, references, system);
+                    } else if (field instanceof RichTextField) {
+                        const re = /"docId"\s*:\s*"(.*?)"/g;
+                        let match: string[] | null;
+                        while ((match = re.exec(field.Data)) !== null) {
+                            const urlString = match[1];
+                            if (urlString) {
+                                const rdoc = DocServer.GetCachedRefField(urlString);
+                                if (rdoc) {
+                                    references.add(rdoc);
+                                    Doc.FindReferences(rdoc, references, system);
+                                }
+                            }
+                        }
                     }
                 } else if (field instanceof Promise) {
                     // eslint-disable-next-line no-debugger
diff --git a/src/server/GarbageCollector.ts b/src/server/GarbageCollector.ts
index 041f65592..74e8c288a 100644
--- a/src/server/GarbageCollector.ts
+++ b/src/server/GarbageCollector.ts
@@ -1,7 +1,4 @@
 /* eslint-disable no-await-in-loop */
-/* eslint-disable no-continue */
-/* eslint-disable no-cond-assign */
-/* eslint-disable no-restricted-syntax */
 import * as fs from 'fs';
 import * as path from 'path';
 import { Database } from './database';
-- 
cgit v1.2.3-70-g09d2


From 29b83f023442c313ca5cf95f70f6430f101060e6 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Mon, 14 Oct 2024 19:55:32 -0400
Subject: reorganized comparisonBox related components -- moved stuff down into
 Docs.Crete and CurrentUserUtils.  changed Doc.Copy to copy Doc's in fields
 tagged with cloneOnCopy.  Changed ComparisonBox to support hover for slide or
 flip views. Fixed pointerEfvents for hover in comparisonBox

---
 src/client/documents/DocUtils.ts                   |   2 -
 src/client/documents/Documents.ts                  |  43 ++++-
 src/client/util/CurrentUserUtils.ts                |   4 +-
 .../views/collections/CollectionCarousel3DView.tsx |  33 ++--
 .../views/collections/CollectionCarouselView.tsx   |  58 +++---
 src/client/views/collections/CollectionSubView.tsx |   2 +-
 src/client/views/collections/CollectionView.tsx    |   6 +-
 .../views/collections/FlashcardPracticeUI.tsx      |  36 ++--
 src/client/views/nodes/ComparisonBox.scss          |   3 +-
 src/client/views/nodes/ComparisonBox.tsx           | 196 +++++++++++----------
 .../views/nodes/formattedText/FormattedTextBox.tsx |  20 ---
 src/fields/Doc.ts                                  |   2 +-
 12 files changed, 223 insertions(+), 182 deletions(-)

(limited to 'src/client/views/collections/CollectionCarousel3DView.tsx')

diff --git a/src/client/documents/DocUtils.ts b/src/client/documents/DocUtils.ts
index 5f54f9d0a..19f3c89ef 100644
--- a/src/client/documents/DocUtils.ts
+++ b/src/client/documents/DocUtils.ts
@@ -103,7 +103,6 @@ export namespace DocUtils {
                       return false;
                   }
                   const facetKeys = Object.keys(filterFacets).filter(fkey => fkey !== 'cookies' && fkey !== ClientUtils.noDragDocsFilter.split(Doc.FilterSep)[0]);
-                  // eslint-disable-next-line no-restricted-syntax
                   for (const facetKey of facetKeys) {
                       const facet = filterFacets[facetKey];
 
@@ -288,7 +287,6 @@ export namespace DocUtils {
         return doc;
     }
     export function AssignDocField(doc: Doc, field: string, creator: (reqdOpts: DocumentOptions, items?: Doc[]) => Doc, reqdOpts: DocumentOptions, items?: Doc[], scripts?: { [key: string]: string }, funcs?: { [key: string]: string }) {
-        // eslint-disable-next-line no-return-assign
         return DocUtils.AssignScripts(DocUtils.AssignOpts(DocCast(doc[field]), reqdOpts, items) ?? (doc[field] = creator(reqdOpts, items)), scripts, funcs);
     }
 
diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts
index f71b9f879..99af1f1a9 100644
--- a/src/client/documents/Documents.ts
+++ b/src/client/documents/Documents.ts
@@ -18,6 +18,7 @@ import { PointData } from '../../pen-gestures/GestureTypes';
 import { DocServer } from '../DocServer';
 import { dropActionType } from '../util/DropActionTypes';
 import { CollectionViewType, DocumentType } from './DocumentTypes';
+import { Id } from '../../fields/FieldSymbols';
 
 class EmptyBox {
     public static LayoutString() {
@@ -360,6 +361,7 @@ export class DocumentOptions {
     isFolder?: BOOLt = new BoolInfo('is document a tree view folder');
     _isTimelineLabel?: BOOLt = new BoolInfo('is document a timeline label');
     _isLightbox?: BOOLt = new BoolInfo('whether a collection acts as a lightbox by opening lightbox links by hiding all other documents in collection besides link target');
+    cloneOnCopy?: BOOLt = new BoolInfo('if this Doc is a field of another Doc, then it should be copied when the other Doc is copied');
 
     mapPin?: DOCt = new DocInfo('pin associated with a config anchor', false);
     config_latitude?: NUMt = new NumInfo('latitude of a map', false);
@@ -420,6 +422,12 @@ export class DocumentOptions {
     flexGap?: NUMt = new NumInfo('Linear view flex gap');
     flexDirection?: 'unset' | 'row' | 'column' | 'row-reverse' | 'column-reverse';
 
+    // Comparison
+    data_revealOp?: STRt = new StrInfo("visual reveal type for front and back of comparison - 'slide' or 'flip' ");
+    data_revealOp_hover?: BOOLt = new BoolInfo('reveal back of comparison manually or by hovering');
+    data_front?: DOCt = new DocInfo('contents of front of flashcard/comparison');
+    data_back?: DOCt = new DocInfo('contents of back of flashcard/comparison');
+
     link?: string;
     link_description?: string; // added for links
     link_relationship?: string; // type of relatinoship a link represents
@@ -784,8 +792,39 @@ export namespace Docs {
             return InstanceFromProto(Prototypes.get(DocumentType.SCREENSHOT), '', options);
         }
 
-        export function ComparisonDocument(text: string, options: DocumentOptions = { title: 'Comparison Box' }) {
-            return InstanceFromProto(Prototypes.get(DocumentType.COMPARISON), text, options);
+        export function ComparisonDocument(title: string, options: DocumentOptions) {
+            return InstanceFromProto(Prototypes.get(DocumentType.COMPARISON), '', options);
+        }
+        /**
+         * Creates a text box where the supplied text (and optional iimage) will be vertically
+         * and horizontally centered.  If text_placeholder is set to true, then the text will be
+         * treated as placeholder text and automatically selected when the text box is selected.
+         * @param title name of text box
+         * @param text text to display in text box
+         * @param opts metadata fields to set on text box
+         * @param img optional image to add to text box
+         * @returns
+         */
+        export function CenteredTextCreator(title: string, text: string, opts: DocumentOptions, img?: Doc) {
+            return TextDocument(RichTextField.textToRtf(text, img?.[Id]), {
+                title, //
+                _layout_autoHeight: true,
+                _layout_centered: true,
+                text_align: 'center',
+                _layout_fitWidth: true,
+                ...opts,
+            });
+        }
+
+        export function FlashcardDocument(title: string, front?: Doc, back?: Doc, options: DocumentOptions = { title: 'Flashcard' }) {
+            return InstanceFromProto(Prototypes.get(DocumentType.COMPARISON), '', {
+                data_front: front ?? CenteredTextCreator('question', 'hint: Enter a topic, select this document and click the stack button to have GPT create a deck of cards', { text_placeholder: true, cloneOnCopy: true }, undefined),
+                data_back: back ?? CenteredTextCreator('answer', 'answer here', { text_placeholder: true, cloneOnCopy: true }, undefined),
+                _layout_fitWidth: true,
+                _layout_isFlashcard: true,
+                title,
+                ...options,
+            });
         }
         export function DiagramDocument(options: DocumentOptions = { title: '' }) {
             return InstanceFromProto(Prototypes.get(DocumentType.DIAGRAM), undefined, options);
diff --git a/src/client/util/CurrentUserUtils.ts b/src/client/util/CurrentUserUtils.ts
index 798cdf5a9..555ccdd88 100644
--- a/src/client/util/CurrentUserUtils.ts
+++ b/src/client/util/CurrentUserUtils.ts
@@ -369,14 +369,14 @@ pie title Minerals in my tap water
                           creator:(opts:DocumentOptions)=> Doc // how to create the empty thing if it doesn't exist
               }[] = [
             {key: "Note",       creator: opts => Docs.Create.TextDocument("", opts),        opts: { _width: 200, _layout_autoHeight: true }},
-            {key: "Flashcard",  creator: opts => Docs.Create.ComparisonDocument("", opts),  opts: { _layout_isFlashcard: true, _layout_fitWidth: true, _width: 300, _height: 300}},
+            {key: "Flashcard",  creator: opts => Docs.Create.FlashcardDocument("", undefined, undefined, opts),opts: { _width: 300, _height: 300}},
             {key: "Image",      creator: opts => Docs.Create.ImageDocument("", opts),       opts: { _width: 400, _height:400 }},
             {key: "Equation",   creator: opts => Docs.Create.EquationDocument("",opts),     opts: { _width: 300, _height: 35, }},
             {key: "Noteboard",  creator: opts => Docs.Create.NoteTakingDocument([], opts),  opts: { _width: 250, _height: 200, _layout_fitWidth: true}},
             {key: "Simulation", creator: opts => Docs.Create.SimulationDocument(opts),      opts: { _width: 300, _height: 300, }},
             {key: "Collection", creator: opts => Docs.Create.FreeformDocument([], opts),    opts: { _width: 150, _height: 100, _layout_fitWidth: true }},
             {key: "Webpage",    creator: opts => Docs.Create.WebDocument("",opts),          opts: { _width: 400, _height: 512, _nativeWidth: 850, data_useCors: true, }},
-            {key: "Comparison", creator: opts => Docs.Create.ComparisonDocument("",opts),   opts: { _width: 300, _height: 300 }},
+            {key: "Comparison", creator: opts => Docs.Create.ComparisonDocument("", opts),  opts: { _width: 300, _height: 300 }},
             {key: "Diagram",    creator: Docs.Create.DiagramDocument,                       opts: { _width: 300, _height: 300, _type_collection: CollectionViewType.Freeform, layout_diagramEditor: CollectionView.LayoutString("data") }, scripts: { onPaint: `toggleDetail(documentView, "diagramEditor","")`}},
             {key: "Audio",      creator: opts => Docs.Create.AudioDocument(nullAudio, opts),opts: { _width: 200, _height: 100, }},
             {key: "Audio",      creator: opts => Docs.Create.AudioDocument(nullAudio, opts),opts: { _width: 200, _height: 100, _layout_fitWidth: true, }},
diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx
index 05be376ca..e9ace733e 100644
--- a/src/client/views/collections/CollectionCarousel3DView.tsx
+++ b/src/client/views/collections/CollectionCarousel3DView.tsx
@@ -15,6 +15,7 @@ import { DocumentView } from '../nodes/DocumentView';
 import { FocusViewOptions } from '../nodes/FocusViewOptions';
 import './CollectionCarousel3DView.scss';
 import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView';
+import { computedFn } from 'mobx-utils';
 
 // eslint-disable-next-line @typescript-eslint/no-require-imports
 const { CAROUSEL3D_CENTER_SCALE, CAROUSEL3D_SIDE_SCALE, CAROUSEL3D_TOP } = require('../global/globalCssVariables.module.scss');
@@ -53,18 +54,22 @@ export class CollectionCarousel3DView extends CollectionSubView() {
 
     centerScale = Number(CAROUSEL3D_CENTER_SCALE);
     sideScale = Number(CAROUSEL3D_SIDE_SCALE);
-    panelWidth = () => this._props.PanelWidth() / 3;
-    panelHeight = () => this._props.PanelHeight() * this.sideScale;
+    panelWidth = () => this._props.PanelWidth() / 3 / this.nativeScaling();
+    panelHeight = () => (this._props.PanelHeight() * this.sideScale) / this.nativeScaling();
     onChildDoubleClick = () => ScriptCast(this.layoutDoc.onChildDoubleClick);
     isContentActive = () => this._props.isSelected() || this._props.isContentActive() || this._props.isAnyChildContentActive();
-    isChildContentActive = () =>
-        this._props.isContentActive?.() === false
-            ? false
-            : this._props.isDocumentActive?.() && (this._props.childDocumentsActive?.() || BoolCast(this.Document.childDocumentsActive))
-              ? true
-              : this._props.childDocumentsActive?.() === false || this.Document.childDocumentsActive === false
+    isChildContentActive = computedFn(
+        (doc: Doc) => () =>
+            this._props.isContentActive?.() === false
                 ? false
-                : undefined;
+                : this._props.isDocumentActive?.() && (this._props.childDocumentsActive?.() || BoolCast(this.Document.childDocumentsActive))
+                  ? true
+                  : this._props.isContentActive?.() && this.curDoc() === doc
+                    ? true
+                    : this._props.childDocumentsActive?.() === false || this.Document.childDocumentsActive === false
+                      ? false
+                      : undefined
+    );
     contentScreenToLocalXf = () => this._props.ScreenToLocalTransform().scale(this._props.NativeDimScaling?.() || 1);
     childScreenLeftToLocal = () =>
         this.contentScreenToLocalXf()
@@ -110,7 +115,7 @@ export class CollectionCarousel3DView extends CollectionSubView() {
                 LayoutTemplateString={this._props.childLayoutString}
                 focus={this.focus}
                 ScreenToLocalTransform={dxf}
-                isContentActive={this.isChildContentActive}
+                isContentActive={this.isChildContentActive(child)}
                 isDocumentActive={this._props.childDocumentsActive?.() || this.Document._childDocumentsActive ? this._props.isDocumentActive : this.isContentActive}
                 PanelWidth={this.panelWidth}
                 PanelHeight={this.panelHeight}
@@ -125,7 +130,6 @@ export class CollectionCarousel3DView extends CollectionSubView() {
     }
 
     changeSlide = (direction: number) => {
-        DocumentView.DeselectAll();
         this.layoutDoc._carousel_index = !this.curDoc() ? 0 : (NumCast(this.layoutDoc._carousel_index) + direction + this.carouselItems.length) % (this.carouselItems.length || 1);
     };
 
@@ -205,9 +209,10 @@ export class CollectionCarousel3DView extends CollectionSubView() {
     docViewProps = () => ({
         ...this._props, //
         isDocumentActive: this._props.childDocumentsActive?.() ? this._props.isDocumentActive : this._props.isContentActive,
-        isContentActive: this.isChildContentActive,
+        isContentActive: this._props.isContentActive,
         ScreenToLocalTransform: this.contentScreenToLocalXf,
     });
+    nativeScaling = () => this._props.NativeDimScaling?.() || 1;
     render() {
         return (
             <div
@@ -216,6 +221,10 @@ export class CollectionCarousel3DView extends CollectionSubView() {
                 style={{
                     background: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.BackgroundColor) as string,
                     color: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.Color) as string,
+                    transformOrigin: 'top left',
+                    transform: `scale(${this.nativeScaling()})`,
+                    width: `${100 / this.nativeScaling()}%`,
+                    height: `${100 / this.nativeScaling()}%`,
                 }}>
                 <div className="carousel-wrapper" style={{ transform: `translateX(${this.translateX}px)` }}>
                     {this.content}
diff --git a/src/client/views/collections/CollectionCarouselView.tsx b/src/client/views/collections/CollectionCarouselView.tsx
index ef66a2c83..ff587b199 100644
--- a/src/client/views/collections/CollectionCarouselView.tsx
+++ b/src/client/views/collections/CollectionCarouselView.tsx
@@ -58,18 +58,12 @@ export class CollectionCarouselView extends CollectionSubView() {
     /**
      * Goes to the next Doc in the stack subject to the currently selected filter option.
      */
-    advance = (e?: React.MouseEvent) => {
-        e?.stopPropagation();
-        this.move(1);
-    };
+    advance = () => this.move(1);
 
     /**
      * Goes to the previous Doc in the stack subject to the currently selected filter option.
      */
-    goback = (e: React.MouseEvent) => {
-        e.stopPropagation();
-        this.move(-1);
-    };
+    goback = () => this.move(-1);
 
     curDoc = () => this.carouselItems[this.carouselIndex]?.layout;
 
@@ -78,24 +72,23 @@ export class CollectionCarouselView extends CollectionSubView() {
         const childValue = doc?.['caption_' + property] ? this._props.styleProvider?.(doc, captionProps, property) : undefined;
         return childValue ?? this._props.styleProvider?.(this.layoutDoc, captionProps, property);
     };
-    contentPanelWidth = () => this._props.PanelWidth() - 2 * NumCast(this.layoutDoc.xMargin);
-    contentPanelHeight = () => this._props.PanelHeight() - (StrCast(this.layoutDoc._layout_showCaption) ? 50 : 0) - 2 * NumCast(this.layoutDoc.yMargin);
+    contentPanelWidth = () => (this._props.PanelWidth() - 2 * NumCast(this.layoutDoc.xMargin)) / this.nativeScaling();
+    contentPanelHeight = () => (this._props.PanelHeight() - (StrCast(this.layoutDoc._layout_showCaption) ? 50 : 0) - 2 * NumCast(this.layoutDoc.yMargin)) / this.nativeScaling();
     onContentDoubleClick = () => ScriptCast(this.layoutDoc.onChildDoubleClick);
     onContentClick = () => ScriptCast(this.layoutDoc.onChildClick);
     captionWidth = () => this._props.PanelWidth() - 2 * this.captionMarginX;
     contentScreenToLocalXf = () =>
         this._props
-            .ScreenToLocalTransform()
-            .translate(-NumCast(this.layoutDoc.xMargin), -NumCast(this.layoutDoc.yMargin))
-            .scale(this._props.NativeDimScaling?.() || 1);
+            .ScreenToLocalTransform() //
+            .translate(-NumCast(this.layoutDoc.xMargin) / this.nativeScaling(), -NumCast(this.layoutDoc.yMargin) / this.nativeScaling());
     isChildContentActive = () =>
         this._props.isContentActive?.() === false
             ? false
-            : this._props.isDocumentActive?.() && (this._props.childDocumentsActive?.() || BoolCast(this.Document.childDocumentsActive))
+            : this._props.isContentActive()
               ? true
               : this._props.childDocumentsActive?.() === false || this.Document.childDocumentsActive === false
                 ? false
-                : undefined;
+                : undefined; // prettier-ignore
     onPassiveWheel = (e: WheelEvent) => e.stopPropagation();
     renderDoc = (doc: Doc, showCaptions: boolean, overlayFunc?: (r: DocumentView | null) => void) => {
         return (
@@ -202,6 +195,8 @@ export class CollectionCarouselView extends CollectionSubView() {
         );
     }
 
+    nativeScaling = () => this._props.NativeDimScaling?.() || 1;
+
     docViewProps = () => ({
         ...this._props, //
         isDocumentActive: this._props.childDocumentsActive?.() ? this._props.isDocumentActive : this._props.isContentActive,
@@ -212,20 +207,25 @@ export class CollectionCarouselView extends CollectionSubView() {
 
     render() {
         return (
-            <div
-                className="collectionCarouselView-outer"
-                ref={this.createDashEventsTarget}
-                style={{
-                    background: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.BackgroundColor) as string,
-                    color: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.Color) as string,
-                    width: `calc(100% - ${NumCast(this.layoutDoc._xMargin)}px)`,
-                    height: `calc(100% - ${NumCast(this.layoutDoc._yMargin)}px)`,
-                    left: NumCast(this.layoutDoc._xMargin),
-                    top: NumCast(this.layoutDoc._yMargin),
-                }}>
-                {this.content}
-                {this.flashCardUI(this.curDoc, this.docViewProps, this.answered)}
-                {this.navButtons}
+            <div>
+                <div
+                    className="collectionCarouselView-outer"
+                    ref={this.createDashEventsTarget}
+                    style={{
+                        background: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.BackgroundColor) as string,
+                        color: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.Color) as string,
+                        left: NumCast(this.layoutDoc._xMargin),
+                        top: NumCast(this.layoutDoc._yMargin),
+                        transformOrigin: 'top left',
+                        transform: `scale(${this.nativeScaling()})`,
+                        width: `calc(${100 / this.nativeScaling()}% - ${(2 * NumCast(this.layoutDoc._xMargin)) / this.nativeScaling()}px)`,
+                        height: `calc(${100 / this.nativeScaling()}% - ${(2 * NumCast(this.layoutDoc._yMargin)) / this.nativeScaling()}px)`,
+                        position: 'relative',
+                    }}>
+                    {this.content}
+                    {this.flashCardUI(this.curDoc, this.docViewProps, this.answered)}
+                    {this.navButtons}
+                </div>
             </div>
         );
     }
diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx
index f85b0b433..ab5b70a85 100644
--- a/src/client/views/collections/CollectionSubView.tsx
+++ b/src/client/views/collections/CollectionSubView.tsx
@@ -523,7 +523,7 @@ export function CollectionSubView<X>() {
         /**
          * How much the content of the collection is being scaled based on its nesting and its fit-to-width settings
          */
-        @computed get contentScaling() { return this.ScreenToLocalBoxXf().Scale * (this._props.NativeDimScaling?.() ?? 1); } // prettier-ignore
+        @computed get contentScaling() { return this.ScreenToLocalBoxXf().Scale; } // prettier-ignore
         /**
          * The maximum size a UI widget can be in collection coordinates based on not wanting the widget to visually obscure too much of the collection
          * This takes the desired screen space size and converts into collection coordinates.  It then returns the smaller of the converted
diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx
index 7418d4360..6f0833a22 100644
--- a/src/client/views/collections/CollectionView.tsx
+++ b/src/client/views/collections/CollectionView.tsx
@@ -83,7 +83,7 @@ export class CollectionView extends ViewBoxAnnotatableComponent<CollectionViewPr
         return viewField;
     }
 
-    screenToLocalTransform = () => (this._props.renderDepth ? this.ScreenToLocalBoxXf() : this.ScreenToLocalBoxXf().scale(this._props.PanelWidth() / this.bodyPanelWidth()));
+    screenToLocalTransform = this.ScreenToLocalBoxXf;
     // prettier-ignore
     private renderSubView = (type: CollectionViewType | undefined, props: SubCollectionViewProps) => {
         TraceMobx();
@@ -202,8 +202,6 @@ export class CollectionView extends ViewBoxAnnotatableComponent<CollectionViewPr
         }
     };
 
-    bodyPanelWidth = () => this._props.PanelWidth();
-
     childLayoutTemplate = () => this._props.childLayoutTemplate?.() || Cast(this.Document.childLayoutTemplate, Doc, null);
     isContentActive = () => this._isContentActive;
 
@@ -221,7 +219,7 @@ export class CollectionView extends ViewBoxAnnotatableComponent<CollectionViewPr
             removeDocument: this.removeDocument,
             isContentActive: this.isContentActive,
             isAnyChildContentActive: this.isAnyChildContentActive,
-            PanelWidth: this.bodyPanelWidth,
+            PanelWidth: this._props.PanelWidth,
             PanelHeight: this._props.PanelHeight,
             ScreenToLocalTransform: this.screenToLocalTransform,
             childLayoutTemplate: this.childLayoutTemplate,
diff --git a/src/client/views/collections/FlashcardPracticeUI.tsx b/src/client/views/collections/FlashcardPracticeUI.tsx
index 45e040653..79eb7f107 100644
--- a/src/client/views/collections/FlashcardPracticeUI.tsx
+++ b/src/client/views/collections/FlashcardPracticeUI.tsx
@@ -1,7 +1,7 @@
 import { IconProp } from '@fortawesome/fontawesome-svg-core';
 import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
 import { Tooltip } from '@mui/material';
-import { IconButton, MultiToggle, Type } from 'browndash-components';
+import { MultiToggle, Type } from 'browndash-components';
 import { computed, makeObservable } from 'mobx';
 import { observer } from 'mobx-react';
 import * as React from 'react';
@@ -25,8 +25,8 @@ enum practiceVal {
 }
 
 export enum flashcardRevealOp {
-    HOVER = 'hover',
     FLIP = 'flip',
+    SLIDE = 'slide',
 }
 
 interface PracticeUIProps {
@@ -153,20 +153,28 @@ export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProp
                     selectedItems={this.practiceMode}
                     onSelectionChange={(val: (string | number) | (string | number)[]) => togglePracticeMode(val as practiceMode)}
                 />
-                <IconButton
-                    tooltip="hover over card to reveal answer"
-                    type={Type.TERT}
-                    text={StrCast(this._props.layoutDoc.revealOp)}
+                <MultiToggle
+                    tooltip="How to reveal flashcard answer"
+                    type={Type.PRIM}
                     color={SnappingManager.userColor}
                     background={SnappingManager.userVariantColor}
-                    icon={<FontAwesomeIcon color={SnappingManager.userColor} icon={this._props.layoutDoc.revealOp === flashcardRevealOp.HOVER ? 'hand-point-up' : 'question'} size="sm" />}
-                    label={StrCast(this._props.layoutDoc.revealOp)}
-                    onPointerDown={e =>
-                        setupMoveUpEvents(this, e, returnFalse, emptyFunction, () => {
-                            this._props.layoutDoc.revealOp = this._props.layoutDoc.revealOp === flashcardRevealOp.HOVER ? flashcardRevealOp.FLIP : flashcardRevealOp.HOVER;
-                            this._props.layoutDoc.childDocumentsActive = this._props.layoutDoc.revealOp === 'hover' ? true : undefined;
-                        })
-                    }
+                    multiSelect={false}
+                    isToggle={false}
+                    toggleStatus={!!this.practiceMode}
+                    label={StrCast(this._props.layoutDoc.revealOp, flashcardRevealOp.FLIP)}
+                    items={[
+                        ['reveal', StrCast(this._props.layoutDoc.revealOp) === flashcardRevealOp.SLIDE ? 'expand' : 'question', StrCast(this._props.layoutDoc.revealOp, flashcardRevealOp.FLIP)],
+                        ['trigger', this._props.layoutDoc.revealOp_hover ? 'hand-point-up' : 'hand', this._props.layoutDoc.revealOp_hover ? 'show on hover' : 'show on click'],
+                    ].map(([item, icon, tooltip]) => ({
+                        icon: <FontAwesomeIcon className={`FlashcardPracticeUI-${item}`} color={setColor(item as practiceMode)} icon={icon as IconProp} size="sm" />,
+                        tooltip: tooltip,
+                        val: item,
+                    }))}
+                    selectedItems={this._props.layoutDoc.revealOp_hover ? ['reveal', 'trigger'] : 'reveal'}
+                    onSelectionChange={(val: (string | number) | (string | number)[]) => {
+                        if (val === 'reveal') this._props.layoutDoc.revealOp = this._props.layoutDoc.revealOp === flashcardRevealOp.SLIDE ? flashcardRevealOp.FLIP : flashcardRevealOp.SLIDE;
+                        if (val === 'trigger') this._props.layoutDoc.revealOp_hover = !this._props.layoutDoc.revealOp_hover;
+                    }}
                 />
             </div>
         );
diff --git a/src/client/views/nodes/ComparisonBox.scss b/src/client/views/nodes/ComparisonBox.scss
index c328ef4bf..d1cc48051 100644
--- a/src/client/views/nodes/ComparisonBox.scss
+++ b/src/client/views/nodes/ComparisonBox.scss
@@ -246,8 +246,7 @@
     pointer-events: none;
 }
 
-.comparisonBox-interactive {
-    pointer-events: unset;
+.comparisonBox-slide {
     cursor: ew-resize;
 
     .slide-bar {
diff --git a/src/client/views/nodes/ComparisonBox.tsx b/src/client/views/nodes/ComparisonBox.tsx
index 80ef126dc..38ce5f2f7 100644
--- a/src/client/views/nodes/ComparisonBox.tsx
+++ b/src/client/views/nodes/ComparisonBox.tsx
@@ -35,22 +35,21 @@ import { FormattedTextBox } from './formattedText/FormattedTextBox';
 const API_URL = 'https://api.unsplash.com/search/photos';
 
 /**
- * This view serves three distinct functions depending on the metadata field layout_isFlashcard
- *     1) it provides a before/after animated sliding transition between two Docs
- *     2) it provides a question/answer switch between two Docs (flashcard)
- *     3) it provides a quiz view that displays a question and a user answer that can be "scored" by GPT
+ * This view serves two distinct functions depending on the revealOp field ('slide' or 'flip)
+ *     1) ('slide') - provides a before/after animated sliding transition between two Docs
+ *     2) ('flip') - provides a question/answer flip between two Docs
+ * And a third function that overrides the first two if the doc's container has its 'practiceMode' set to 'quiz'
+ *     3) ('quiz') - it provides a quiz view that displays a question and a user answer that can be "scored" by GPT
+ *     NOTE: this should probably be changed to passing down a prop to the flashcard telling it to render as a quiz.
  *
  * In each case, the two docs are stored in the <fieldKey>_front and <fieldKey>_back fields
  *
- * In the case of the flashcard, there is an icon that allows the user to choose between a
- * hover and a flip action to switch between cards.  The transition is stored in the 'revealOp' field.
- * In addition, if a flashcard is created without data in the front/back fields, this will
- * create Text documents with placeholder text indicating to the user how to fill in the cards.
- * One option is to allow the user to enter a topic and, by clicking on the flashcard stack button,
- * convert the comparision box into a stack of comparison boxes filled in by GPT about the topic.
+ * For 'flip' and 'slide', the trigger can either be clicking, or hovering as determined by the revealOp_hover field.
+ * For 'quiz' the data of both Docs are shown in a single-view quiz display.
  *
- * Quiz mode is activated when the parent collection has its 'quiz' field set when it renders a flashcard.
- * NOTE: this should probably be changed to passing down a prop to the flashcard telling it to render as a quiz.
+ * Users can create a stack of flashcards all at once (only) from an empty flashcard by entering a topic into the front card
+ * and clicking on the flashcard stack button.  This will convert the comparision box into a stack of comparison boxes
+ * filled in by GPT about the topic.
  *
  */
 
@@ -67,7 +66,6 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
      */
     public static createFlashcard(tuple: string, frontKey: string, backKey: string, useDoc?: Doc) {
         const [ktoken, atoken] = [ComparisonBox.ktoken, ComparisonBox.atoken];
-        const newDoc = useDoc ?? Docs.Create.ComparisonDocument('', { _layout_isFlashcard: true, _width: 300, _height: 300 });
         const question = (tuple.includes(ktoken) ? tuple.split(ktoken)[0] : tuple).split(atoken)[0];
         const rest = tuple.replace(question, '');
         // prettier-ignore
@@ -78,9 +76,14 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
                             rest.replace(atoken,""); // finally if there's no keyword, just get rid of answer token and take what's left
         const keyword = rest.replace(atoken, '').replace(answer, '').replace(ktoken, '').trim();
         const fillInFlashcard = (img?: Doc) => {
-            newDoc[DocData][frontKey] = FormattedTextBox.centeredTextCreator('question', question, img);
-            newDoc[DocData][backKey] = FormattedTextBox.centeredTextCreator('answer', answer);
-            return newDoc;
+            const front = Docs.Create.CenteredTextCreator('question', question, {}, img);
+            const back = Docs.Create.CenteredTextCreator('answer', answer, {});
+            if (useDoc) {
+                useDoc[DocData][frontKey] = front;
+                useDoc[DocData][backKey] = back;
+                return useDoc;
+            }
+            return Docs.Create.FlashcardDocument('flashcard', front, back, { _width: 300, _height: 300 });
         };
         return keyword && keyword.toLowerCase() !== 'none' ? ComparisonBox.fetchImages(keyword).then(img => fillInFlashcard(img)) : fillInFlashcard();
     }
@@ -98,6 +101,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
                 .map(tuple => ComparisonBox.createFlashcard(tuple, front, back))
         ).then(docs => {
             return Docs.Create.CarouselDocument(docs, {
+                title: 'flashcard deck',
                 _width: width,
                 _height: height,
                 _layout_fitWidth: false,
@@ -116,12 +120,11 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     private _sideBtnWidth = 35;
     private _closeRef = React.createRef<HTMLDivElement>();
     private _disposers: { [key: string]: DragManager.DragDropDisposer | undefined } = {};
-    private _reactDisposer: IReactionDisposer | undefined;
+    private _reactDisposer: { [key: string]: IReactionDisposer } = {};
 
     @observable private _inputValue = '';
     @observable private _outputValue = '';
     @observable private _loading = false;
-    @observable private _isEmpty = false;
     @observable private _childActive = false;
     @observable private _animating = '';
     @observable private _listening = false;
@@ -135,18 +138,28 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
 
     componentDidMount() {
         this._props.setContentViewBox?.(this);
-        this._reactDisposer = reaction(
-            () => this._props.isSelected(), // when this reaction should update
+        this._reactDisposer.select = reaction(
+            () => this._props.isSelected(),
             selected => {
-                if (selected && this.isFlashcard) this.activateContent();
+                if (selected && this.revealOp !== flashcardRevealOp.SLIDE) this.activateContent();
                 !selected && (this._childActive = false);
             }, // what it should update to
             { fireImmediately: true }
         );
+        this._reactDisposer.hover = reaction(
+            () => this._props.isContentActive(),
+            hover => {
+                if (!hover) {
+                    this.revealOp === flashcardRevealOp.FLIP && this.animateFlipping(this.frontKey);
+                    this.revealOp === flashcardRevealOp.SLIDE && this.animateSliding(this._props.PanelWidth() - 3);
+                }
+            }, // what it should update to
+            { fireImmediately: true }
+        );
     }
 
     componentWillUnmount() {
-        this._reactDisposer?.();
+        Object.values(this._reactDisposer).forEach(disposer => disposer?.());
     }
 
     protected createDropTarget = (ele: HTMLDivElement | null, fieldKey: string) => {
@@ -169,7 +182,8 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
         return undefined;
     }, 'internal drop');
 
-    @computed get isQuizMode()    { return DocCast(this.Document.embedContainer)?.practiceMode === practiceMode.QUIZ; } // prettier-ignore
+    @computed get containerDoc()  { return this._props.docViewPath().slice(-2)[0]?.Document; } // prettier-ignore
+    @computed get isQuizMode()    { return this.containerDoc?.practiceMode === practiceMode.QUIZ; } // prettier-ignore
     @computed get isFlashcard()   { return BoolCast(this.Document.layout_isFlashcard); } // prettier-ignore
     @computed get frontKey()      { return this._props.fieldKey + '_front'; } // prettier-ignore
     @computed get backKey()       { return this._props.fieldKey + '_back'; } // prettier-ignore
@@ -178,10 +192,10 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     @computed get revealOpKey()   { return `_${this._props.fieldKey}_revealOp`; } // prettier-ignore
     @computed get clipHeightKey() { return `_${this._props.fieldKey}_clipHeight`; } // prettier-ignore
     @computed get clipWidthKey()  { return `_${this._props.fieldKey}_clipWidth`;  } // prettier-ignore
-    @computed get clipWidth()     { return NumCast(this.layoutDoc[this.clipWidthKey], 50); } // prettier-ignore
+    @computed get clipWidth()     { return NumCast(this.layoutDoc[this.clipWidthKey], this.isFlashcard ? 100: 50); } // prettier-ignore
     @computed get clipHeight()    { return NumCast(this.layoutDoc[this.clipHeightKey], 200);  } // prettier-ignore
-    @computed get revealOp()      { return StrCast(this.layoutDoc[this.revealOpKey], StrCast(this._props.docViewPath().slice(-2)[0]?.Document.revealOp)); } // prettier-ignore
-    set revealOp(value:string)    { this.layoutDoc[this.revealOpKey] = value; } // prettier-ignore
+    @computed get revealOp()      { return StrCast(this.layoutDoc[this.revealOpKey], StrCast(this.containerDoc?.revealOp, this.isFlashcard ? flashcardRevealOp.FLIP : flashcardRevealOp.SLIDE)) as flashcardRevealOp; } // prettier-ignore
+    @computed get revealOpHover() { return BoolCast(this.layoutDoc[this.revealOpKey+"_hover"], BoolCast(this.containerDoc?.revealOp_hover)); } // prettier-ignore
     @computed get loading()       { return this._loading; } // prettier-ignore
     set loading(value)            { runInAction(() => { this._loading = value; })} // prettier-ignore
 
@@ -193,13 +207,13 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
                     onPointerDown={e =>
                         setupMoveUpEvents(e.target, e, returnFalse, emptyFunction, () => {
                             if (!this.revealOp || this.revealOp === flashcardRevealOp.FLIP) {
-                                this.flipFlashcard();
+                                this.animateFlipping();
                             }
                         })
                     }
                     style={{
-                        background: this.revealOp === flashcardRevealOp.HOVER ? 'gray' : this._renderSide === this.backKey ? 'white' : 'black',
-                        color: this.revealOp === flashcardRevealOp.HOVER ? 'black' : this._renderSide === this.backKey ? 'black' : 'white',
+                        background: this.revealOpHover ? 'gray' : this._renderSide === this.backKey ? 'white' : 'black',
+                        color: this.revealOpHover ? 'black' : this._renderSide === this.backKey ? 'black' : 'white',
                         display: 'inline-block',
                     }}>
                     <FontAwesomeIcon icon="turn-up" size="xl" />
@@ -223,7 +237,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     @computed get flashcardMenu() {
         return SnappingManager.HideDecorations ? null : (
             <div className="comparisonBox-bottomMenu" style={{ transform: `scale(${this.uiBtnScaling})` }}>
-                {this.revealOp === flashcardRevealOp.HOVER || !this._props.isSelected() ? null : this.overlayAlternateIcon}
+                {this.revealOpHover || !this._props.isSelected() ? null : this.overlayAlternateIcon}
                 {!this._props.isSelected() || this._renderSide === this.frontKey ? null : (
                     <Tooltip title={<div className="dash-tooltip">Ask GPT to create an answer for the question on the front</div>}>
                         <div className="comparisonBox-button" onPointerDown={() => this.askGPT(GPTCallType.CHATCARD)}>
@@ -296,13 +310,11 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
 
     moveDoc = (doc: Doc, addDocument: (document: Doc | Doc[]) => boolean, which: string) => this.remDoc(doc, which) && addDocument(doc);
     addDoc = (doc: Doc, which: string) => {
-        if (this.dataDoc[which] && !this._isEmpty) return false;
         this.dataDoc[which] = doc;
         return true;
     };
     remDoc = (doc: Doc, which: string) => {
         if (this.dataDoc[which] === doc) {
-            this._isEmpty = true;
             this.dataDoc[which] = undefined;
             return true;
         }
@@ -334,6 +346,26 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     moveDocBack = (docs: Doc | Doc[], targetCol: Doc | undefined, addDoc: (doc: Doc | Doc[]) => boolean) => toList(docs).reduce((res, doc: Doc) => res && this.moveDoc(doc, addDoc, this.backKey), true);
     remDocFront = (docs: Doc | Doc[]) => toList(docs).reduce((res, doc) => res && this.remDoc(doc, this.frontKey), true);
     remDocBack = (docs: Doc | Doc[]) => toList(docs).reduce((res, doc) => res && this.remDoc(doc, this.backKey), true);
+    animateSliding = action((targetWidth: number) => {
+        this._animating = `all ${this._slideTiming}ms`; // on click, animate slider movement to the targetWidth
+        this.layoutDoc[this.clipWidthKey] = (targetWidth * 100) / this._props.PanelWidth();
+        setTimeout(action(() => {this._animating = '';  }), this._slideTiming); // prettier-ignore
+    });
+
+    _flipAnim: NodeJS.Timeout | undefined;
+    animateFlipping = action((side?: string) => {
+        if (side !== this._renderSide) {
+            this._renderSide = side ?? (this._renderSide === this.frontKey ? this.backKey : this.frontKey); // switches to new front
+            this._animating = '0'; // reveals old front on the bottom layer by making top layer transparent
+            setTimeout(
+                action(() => {
+                    this._animating = `all ${this._slideTiming * 5}ms`; // makes new front fade in
+                    clearTimeout(this._flipAnim);
+                    this._flipAnim = setTimeout(  action(() => { this._animating = '';  }), this._slideTiming * 5 ); // prettier-ignore
+                })
+            );
+        }
+    });
 
     registerSliding = (e: React.PointerEvent<HTMLDivElement>, targetWidth: number) => {
         if (e.button !== 2) {
@@ -351,13 +383,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
                 }),
                 false,
                 undefined,
-                action(() => {
-                    if (!this._childActive) {
-                        this._animating = `all ${this._slideTiming}ms`; // on click, animate slider movement to the targetWidth
-                        this.layoutDoc[this.clipWidthKey] = (targetWidth * 100) / this._props.PanelWidth();
-                        setTimeout(  action(() => {this._animating = '';  }), this._slideTiming); // prettier-ignore
-                    }
-                })
+                action(() => !this._childActive && this.animateSliding(targetWidth))
             );
         }
     };
@@ -584,16 +610,6 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
         }
     };
 
-    @action
-    flipFlashcard = () => {
-        this._renderSide = this._renderSide === this.frontKey ? this.backKey : this.frontKey;
-    };
-
-    @action
-    hoverFlip = (side: string) => {
-        if (this.revealOp === flashcardRevealOp.HOVER) this._renderSide = side;
-    };
-
     flashcardContextMenu = () => {
         const appearance = ContextMenu.Instance.findByDescription('Appearance...');
         const appearanceItems = appearance?.subitems ?? [];
@@ -680,16 +696,8 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     };
 
     displayBox = (which: string, cover: number) => (
-        <div
-            className={`${which === this.frontKey ? 'before' : 'after'}Box-cont`}
-            key={which}
-            style={{ width: this._props.PanelWidth() }}
-            onPointerDown={e => {
-                this.registerSliding(e, cover);
-                this.isFlashcard && this.activateContent();
-            }}
-            ref={ele => this.createDropTarget(ele, which)}>
-            {!this._isEmpty ? this.displayDoc(which) : null}
+        <div className={`${which === this.frontKey ? 'before' : 'after'}Box-cont`} key={which} style={{ width: this._props.PanelWidth() }} onPointerDown={e => this.registerSliding(e, cover)} ref={ele => this.createDropTarget(ele, which)}>
+            {this.displayDoc(which)}
         </div>
     );
 
@@ -727,7 +735,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
                     <button className="submit-buttonpronunciation" onClick={this.evaluatePronunciation}>
                         Evaluate Pronunciation
                     </button>
-                    <button className="submit-buttonsubmit" type="button" onClick={this._renderSide === this.backKey ? this.flipFlashcard : this.handleRenderGPTClick}>
+                    <button className="submit-buttonsubmit" type="button" onClick={this._renderSide === this.backKey ? () => this.animateFlipping(this.frontKey) : this.handleRenderGPTClick}>
                         {this._renderSide === this.backKey ? 'Redo the Question' : 'Submit'}
                     </button>
                 </div>
@@ -736,40 +744,33 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     );
 
     // if flashcard is rendered that has no data, then add some placeholders for question and answer
-    addPlaceholdersForEmptyFlashcard = () => {
-        if (this.dataDoc.data) {
-            if (!this.dataDoc[this.backKey] || !this.dataDoc[this.frontKey]) ComparisonBox.createFlashcard(StrCast(this.dataDoc.data), this.frontKey, this.backKey, this.Document);
-        } else {
-            // add text box to each side when comparison box is first created
-            if (!this.dataDoc[this.backKey] && !this._isEmpty) {
-                this.dataDoc[this.backKey] = FormattedTextBox.centeredTextCreator('answer', 'answer here', undefined, true);
-            }
-
-            if (!this.dataDoc[this.frontKey] && !this._isEmpty) {
-                this.dataDoc[this.frontKey] = FormattedTextBox.centeredTextCreator('question', 'hint: Enter a topic, select this document and click the stack button to have GPT create a deck of cards', undefined, true);
-            }
-        }
-    };
-
-    renderAsFlashcard = () => (
+    // addPlaceholdersForEmptyFlashcard = () => {
+    //     if (this.dataDoc.data) {
+    //         if (!this.dataDoc[this.backKey] || !this.dataDoc[this.frontKey]) ComparisonBox.createFlashcard(StrCast(this.dataDoc.data), this.frontKey, this.backKey, this.Document);
+    //     }
+    // };
+
+    // render a button that flips between front and back
+    renderAsFlip = () => (
         <div
-            className={`comparisonBox${this._props.isContentActive() ? '-interactive' : ''}`} /* change className to easily disable/enable pointer events in CSS */
-            onContextMenu={this.flashcardContextMenu}
-            onMouseEnter={() => this.hoverFlip(this.backKey)}
-            onMouseLeave={() => this.hoverFlip(this.frontKey)}>
-            {this.displayBox(this._renderSide, this._props.PanelWidth() - 3)}
-            {this.loading ? (
-                <div className="loading-spinner">
-                    <ReactLoading type="spin" height={30} width={30} color="blue" />
-                </div>
-            ) : null}
+            style={{ display: 'flex', pointerEvents: this.revealOpHover && this._props.isContentActive() ? 'unset' : undefined }} //
+            onMouseEnter={() => this.revealOpHover && this.animateFlipping(this.backKey)}
+            onMouseLeave={() => this.revealOpHover && this.animateFlipping(this.frontKey)}>
+            <div style={{ position: 'absolute', width: '100%', height: '100%', transition: this._animating === '0' ? undefined : this._animating, opacity: this._animating === '0' ? 1 : 0 }}>
+                {this.displayBox(this._renderSide === this.backKey ? this.frontKey : this.backKey, 0)}
+            </div>
+            <div style={{ position: 'absolute', width: '100%', height: '100%', transition: this._animating === '0' ? undefined : this._animating, opacity: this._animating === '0' ? 0 : 1 }}>{this.displayBox(this._renderSide, 0)}</div>
             {this.flashcardMenu}
         </div>
     );
 
-    // render a comparison box that compares items side by side
+    // render a slider that reveals front and back as slider is dragged horizonally
     renderAsBeforeAfter = () => (
-        <div className={`comparisonBox${this._props.isContentActive() ? '-interactive' : ''}` /* change className to easily disable/enable pointer events in CSS */}>
+        <div
+            className="comparisonBox-slide"
+            style={{ display: 'flex', pointerEvents: this.revealOpHover && this._props.isContentActive() ? 'unset' : undefined }}
+            onMouseEnter={() => this.revealOpHover && this.animateSliding(0)}
+            onMouseLeave={() => this.revealOpHover && this.animateSliding(this._props.PanelWidth() - 3)}>
             {this.displayBox(this.backKey, this._props.PanelWidth() - 3)}
             <div className="clip-div" style={{ width: this.clipWidth + '%', transition: this._animating, background: StrCast(this.layoutDoc._backgroundColor, 'gray') }}>
                 {this.displayBox(this.frontKey, 0)}
@@ -789,11 +790,20 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     );
 
     render() {
-        this.isFlashcard && this.addPlaceholdersForEmptyFlashcard();
-        return this.isFlashcard ? 
-                    this.isQuizMode ? this.renderAsQuiz(this.frontText) :
-                                      this.renderAsFlashcard() : 
-                    this.renderAsBeforeAfter(); // prettier-ignore
+        const renderMode = new Map<flashcardRevealOp, () => JSX.Element>([
+            [flashcardRevealOp.FLIP, this.renderAsFlip],
+            [flashcardRevealOp.SLIDE, this.renderAsBeforeAfter]]); // prettier-ignore
+        if (this.isQuizMode) this.renderAsQuiz(this.frontText);
+        return (
+            <div className="comparisonBox" style={{ pointerEvents: this._props.isContentActive() ? 'unset' : undefined }} onContextMenu={this.flashcardContextMenu}>
+                {renderMode.get(this.revealOp)?.() ?? null}
+                {this.loading ? (
+                    <div className="loading-spinner">
+                        <ReactLoading type="spin" height={30} width={30} color="blue" />
+                    </div>
+                ) : null}
+            </div>
+        );
     }
 }
 
diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
index 9d3a899f5..29be8d285 100644
--- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx
+++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
@@ -76,26 +76,6 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FormattedTextB
     public static LayoutString(fieldStr: string) {
         return FieldView.LayoutString(FormattedTextBox, fieldStr);
     }
-    /**
-     * Creates a text box where the supplied text (and optional iimage) will be vertically
-     * and horizontally centered.  If text_placeholder is set to true, then the text will be
-     * treated as placeholder text and automatically selected when the text box is selected.
-     * @param title name of text box
-     * @param text text to display in textbox
-     * @param img optional image to add to text box
-     * @param text_placeholder makes the text automatially select
-     * @returns
-     */
-    public static centeredTextCreator(title: string, text: string, img?: Doc, text_placeholder?: boolean) {
-        return Docs.Create.TextDocument(RichTextField.textToRtf(text, img?.[Id]), {
-            title, //
-            _layout_autoHeight: true,
-            _layout_centered: true,
-            text_align: 'center',
-            text_placeholder,
-            _layout_fitWidth: true,
-        });
-    }
     public static MakeConfig(rules?: RichTextRules, props?: FormattedTextBoxProps) {
         return {
             schema,
diff --git a/src/fields/Doc.ts b/src/fields/Doc.ts
index 45dfe233f..6ec195910 100644
--- a/src/fields/Doc.ts
+++ b/src/fields/Doc.ts
@@ -1003,7 +1003,7 @@ export namespace Doc {
                     } else if (field instanceof ObjectField) {
                         const docAtKey = doc[key];
                         copy[key] =
-                            docAtKey instanceof Doc && key.includes('layout[')
+                            docAtKey instanceof Doc && (key.includes('layout[') || docAtKey.cloneOnCopy)
                                 ? new ProxyField(Doc.MakeCopy(docAtKey)) // copy the expanded render template
                                 : ObjectField.MakeCopy(field);
                     } else if (field instanceof Promise) {
-- 
cgit v1.2.3-70-g09d2


From 9779182e74e427d3a8a2004d0efd01fac8387d55 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Wed, 16 Oct 2024 17:31:12 -0400
Subject: major fixes to cardDeck view to simplify code and to make arch follow
 a true circle arc and to fix doc sizing when fitwidth/lightbox/etc.  fixes to
 flashcard UI for advancing to next Doc in cardView and carousel3D.

---
 src/client/documents/Documents.ts                  |   4 +-
 src/client/views/DocumentDecorations.tsx           |   4 +-
 .../views/collections/CollectionCardDeckView.scss  |  24 +-
 .../views/collections/CollectionCardDeckView.tsx   | 336 +++++++++++----------
 .../views/collections/CollectionCarousel3DView.tsx |   2 +-
 .../views/collections/CollectionCarouselView.tsx   |   2 +-
 .../views/collections/FlashcardPracticeUI.scss     |   6 +
 .../views/collections/FlashcardPracticeUI.tsx      |   6 +-
 src/client/views/global/globalScripts.ts           |  26 +-
 src/client/views/nodes/ComparisonBox.tsx           |  25 +-
 src/client/views/nodes/DocumentContentsView.tsx    |   1 -
 11 files changed, 230 insertions(+), 206 deletions(-)

(limited to 'src/client/views/collections/CollectionCarousel3DView.tsx')

diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts
index 99af1f1a9..e539e3c65 100644
--- a/src/client/documents/Documents.ts
+++ b/src/client/documents/Documents.ts
@@ -508,8 +508,8 @@ export class DocumentOptions {
     userBackgroundColor?: STRt = new StrInfo('background color associated with a Dash user (seen in header fields of shared documents)');
     userColor?: STRt = new StrInfo('color associated with a Dash user (seen in header fields of shared documents)');
 
-    cardSort?: STRt = new StrInfo('way cards are sorted in deck view');
-    cardSort_isDesc?: BOOLt = new BoolInfo('whether the cards are sorted ascending or descending');
+    card_sort?: STRt = new StrInfo('way cards are sorted in deck view');
+    card_sort_isDesc?: BOOLt = new BoolInfo('whether the cards are sorted ascending or descending');
 }
 
 export const DocOptions = new DocumentOptions();
diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx
index 62f2de776..5a48b6c62 100644
--- a/src/client/views/DocumentDecorations.tsx
+++ b/src/client/views/DocumentDecorations.tsx
@@ -10,7 +10,7 @@ import { lightOrDark, returnFalse, setupMoveUpEvents } from '../../ClientUtils';
 import { Utils, emptyFunction, numberValue } from '../../Utils';
 import { DateField } from '../../fields/DateField';
 import { Doc, DocListCast, Field, FieldType, HierarchyMapping, ReverseHierarchyMap } from '../../fields/Doc';
-import { AclAdmin, AclAugment, AclEdit, DocData } from '../../fields/DocSymbols';
+import { AclAdmin, AclAugment, AclEdit, Animation, DocData } from '../../fields/DocSymbols';
 import { Id } from '../../fields/FieldSymbols';
 import { InkField } from '../../fields/InkField';
 import { ScriptField } from '../../fields/ScriptField';
@@ -650,7 +650,7 @@ export class DocumentDecorations extends ObservableReactComponent<DocumentDecora
         this._forceRender;
         const { b, r, x, y } = this.Bounds;
         const seldocview = DocumentView.Selected().lastElement();
-        if (SnappingManager.IsDragging || r - x < 1 || x === Number.MAX_VALUE || !seldocview || SnappingManager.HideDecorations || isNaN(r) || isNaN(b) || isNaN(x) || isNaN(y)) {
+        if (SnappingManager.IsDragging || r - x < 1 || x === Number.MAX_VALUE || !seldocview || seldocview?.Document[Animation] || SnappingManager.HideDecorations || isNaN(r) || isNaN(b) || isNaN(x) || isNaN(y)) {
             setTimeout(
                 action(() => {
                     this._editingTitle = false;
diff --git a/src/client/views/collections/CollectionCardDeckView.scss b/src/client/views/collections/CollectionCardDeckView.scss
index 0637cd4e9..5283601bf 100644
--- a/src/client/views/collections/CollectionCardDeckView.scss
+++ b/src/client/views/collections/CollectionCardDeckView.scss
@@ -7,23 +7,31 @@
     background-color: white;
     overflow: hidden;
     display: flex;
+    .collectionCardView-inner {
+        display: flex;
+        transform-origin: top left;
+        align-items: center;
+    }
 
     button {
         border-radius: 50%;
     }
 }
 
-.card-wrapper {
-    display: grid;
-    grid-template-columns: repeat(10, 1fr);
+.collectionCardView-flashcardUI {
+    top: 0;
+    position: absolute;
+    width: 100%;
+    height: 100%;
     transform-origin: top left;
+}
 
-    position: absolute;
+.collectionCardView-cardwrapper {
+    display: grid;
+    grid-template-columns: repeat(10, 1fr);
+    transform-origin: left 50%;
     align-items: center;
-    justify-items: center;
-    justify-content: center;
-
-    transition: transform 0.3s cubic-bezier(0.455, 0.03, 0.515, 0.955);
+    z-index: 0; // so that setting z-index of active card doesn't make it land on top of things outside of the card-wrapper
 }
 
 .no-card-span {
diff --git a/src/client/views/collections/CollectionCardDeckView.tsx b/src/client/views/collections/CollectionCardDeckView.tsx
index 14ce9d2af..5faabacf4 100644
--- a/src/client/views/collections/CollectionCardDeckView.tsx
+++ b/src/client/views/collections/CollectionCardDeckView.tsx
@@ -5,7 +5,7 @@ import * as React from 'react';
 import { ClientUtils, DashColor, imageUrlToBase64, returnFalse, returnNever, returnZero } from '../../../ClientUtils';
 import { emptyFunction } from '../../../Utils';
 import { Doc } from '../../../fields/Doc';
-import { DocData } from '../../../fields/DocSymbols';
+import { Animation, DocData } from '../../../fields/DocSymbols';
 import { Id } from '../../../fields/FieldSymbols';
 import { List } from '../../../fields/List';
 import { ScriptField } from '../../../fields/ScriptField';
@@ -96,7 +96,7 @@ export class CollectionCardView extends CollectionSubView() {
                 if (isVis) {
                     this.openChatPopup();
                 } else {
-                    this.Document.cardSort = this.cardSort === cardSortings.Chat ? '' : this.Document.cardSort;
+                    this.Document.card_sort = this.cardSort === cardSortings.Chat ? '' : this.Document.card_sort;
                 }
             }
         );
@@ -119,7 +119,25 @@ export class CollectionCardView extends CollectionSubView() {
     }
 
     @computed get cardSort() {
-        return StrCast(this.Document.cardSort) as cardSortings;
+        return StrCast(this.Document.card_sort) as cardSortings;
+    }
+    /**
+     * Number of rows of cards to be rendered
+     */
+    @computed get numRows() {
+        return Math.ceil(this.sortedDocs.length / this._maxRowCount);
+    }
+    /**
+     * Circle arc size, in radians, to layout cards
+     */
+    @computed get archAngle() {
+        return NumCast(this.layoutDoc.card_arch, 90) * (Math.PI / 180) * (this.childCards.length < this._maxRowCount ? this.childCards.length / this._maxRowCount : 1);
+    }
+    /**
+     * Spacing card rows as a percent of Doc size.   100 means rows spread out to fill 100% of the Doc vertically.  Default is 60%
+     */
+    @computed get cardSpacing() {
+        return NumCast(this.layoutDoc.card_spacing, 60);
     }
 
     /**
@@ -137,6 +155,10 @@ export class CollectionCardView extends CollectionSubView() {
         return (this.childPanelWidth() * length) / this._props.PanelWidth();
     }
 
+    @computed get nativeScaling() {
+        return this._props.NativeDimScaling?.() || 1;
+    }
+
     /**
      * When in quiz mode, randomly selects a document
      */
@@ -145,70 +167,17 @@ export class CollectionCardView extends CollectionSubView() {
         this._curDoc = this.childDocs[randomIndex];
     });
 
-    /**
-     * Number of rows of cards to be rendered
-     */
-    @computed get numRows() {
-        return Math.ceil(this.sortedDocs.length / this._maxRowCount);
-    }
-
-    @action
-    setHoveredNodeIndex = (index: number) => {
+    setHoveredNodeIndex = action((index: number) => {
         if (!SnappingManager.IsDragging) this._hoveredNodeIndex = index;
-    };
+    });
 
     isSelected = (doc: Doc) => this._docRefs.get(doc)?.IsSelected;
-    childPanelWidth = () => NumCast(this.layoutDoc.childPanelWidth, this._props.PanelWidth() / 2);
+    childPanelWidth = () => NumCast(this.layoutDoc.childPanelWidth, Math.max(150, this._props.PanelWidth() / (this.childCards.length > this._maxRowCount ? this._maxRowCount : this.childCards.length) / this.nativeScaling));
     childPanelHeight = () => this._props.PanelHeight() * this.fitContentScale;
     onChildDoubleClick = () => ScriptCast(this.layoutDoc.onChildDoubleClick);
     isContentActive = () => this._props.isSelected() || this._props.isContentActive() || this.isAnyChildContentActive();
     isAnyChildContentActive = this._props.isAnyChildContentActive;
 
-    /**
-     * Returns the degree to rotate a card dependind on the amount of cards in their row and their index in said row
-     * @param amCards
-     * @param index
-     * @returns
-     */
-    rotate = (amCards: number, index: number) => {
-        if (amCards == 1) return 0;
-
-        const possRotate = -30 + index * (30 / ((amCards - (amCards % 2)) / 2));
-        if (amCards % 2 === 0) {
-            if (possRotate === 0) {
-                return possRotate + Math.abs(-30 + (index - 1) * (30 / (amCards / 2)));
-            }
-            if (index > (amCards + 1) / 2) {
-                const stepMag = Math.abs(-30 + (amCards / 2 - 1) * (30 / ((amCards - (amCards % 2)) / 2)));
-                return possRotate + stepMag;
-            }
-        }
-
-        return possRotate;
-    };
-    /**
-     * Returns the degree to which a card should be translated in the y direction for the arch effect
-     */
-    translateY = (amCards: number, index: number, realIndex: number) => {
-        const evenOdd = amCards % 2;
-        const apex = (amCards - evenOdd) / 2;
-        const Magnitude = this.childPanelWidth() / 2; // 400
-        const stepMag = Magnitude / 2 / ((amCards - evenOdd) / 2) + Math.abs((apex - index) * 25);
-
-        let rowOffset = 0;
-        if (realIndex > this._maxRowCount - 1) {
-            rowOffset = Magnitude * ((realIndex - (realIndex % this._maxRowCount)) / this._maxRowCount);
-        }
-        if (evenOdd === 1 || index < apex - 1) {
-            return Math.abs(stepMag * (apex - index)) - rowOffset;
-        }
-        if (index === apex || index === apex - 1) {
-            return 0 - rowOffset;
-        }
-
-        return Math.abs(stepMag * (apex - index - 1)) - rowOffset;
-    };
-
     /**
      * When dragging a card, determines the index the card should be set to if dropped
      * @param mouseX mouse's x location
@@ -216,28 +185,27 @@ export class CollectionCardView extends CollectionSubView() {
      * @returns the card's new index
      */
     findCardDropIndex = (mouseX: number, mouseY: number) => {
-        const amCardsTotal = this.sortedDocs.length;
+        const cardCount = this.sortedDocs.length;
         let index = 0;
-        const cardWidth = amCardsTotal < this._maxRowCount ? this._props.PanelWidth() / amCardsTotal : this._props.PanelWidth() / this._maxRowCount;
+        const cardWidth = cardCount < this._maxRowCount ? this._props.PanelWidth() / cardCount : this._props.PanelWidth() / this._maxRowCount;
 
         // Calculate the adjusted X position accounting for the initial offset
         let adjustedX = mouseX;
 
-        const amRows = Math.ceil(amCardsTotal / this._maxRowCount);
-        const rowHeight = this._props.PanelHeight() / amRows;
+        const rowHeight = this._props.PanelHeight() / this.numRows;
         const currRow = Math.floor((mouseY - 100) / rowHeight); //rows start at 0
 
         if (adjustedX < 0) {
             return 0; // Before the first column
         }
 
-        if (amCardsTotal < this._maxRowCount) {
+        if (cardCount < this._maxRowCount) {
             index = Math.floor(adjustedX / cardWidth);
-        } else if (currRow != amRows - 1) {
+        } else if (currRow != this.numRows - 1) {
             index = Math.floor(adjustedX / cardWidth) + currRow * this._maxRowCount;
         } else {
-            const rowAmCards = amCardsTotal - currRow * this._maxRowCount;
-            const offset = ((this._maxRowCount - rowAmCards) / 2) * cardWidth;
+            const cardsInRow = cardCount - currRow * this._maxRowCount;
+            const offset = ((this._maxRowCount - cardsInRow) / 2) * cardWidth;
             adjustedX = mouseX - offset;
 
             index = Math.floor(adjustedX / cardWidth) + currRow * this._maxRowCount;
@@ -246,11 +214,14 @@ export class CollectionCardView extends CollectionSubView() {
     };
 
     /**
-     * Checks to see if a card is being dragged and calls the appropriate methods if so
+     * if pointer moves over cardDeck while dragging a Doc that is in the Deck or that can be dropped in the deck,
+     * then this sets the card index where the dragged card would be added.
      */
     @action
     onPointerMove = (x: number, y: number) => {
-        this._docDraggedIndex = DragManager.docsBeingDragged.length ? this.findCardDropIndex(x, y) : -1;
+        if (DragManager.docsBeingDragged.some(doc => this.sortedDocs.includes(doc)) || SnappingManager.CanEmbed) {
+            this._docDraggedIndex = this.findCardDropIndex(x, y);
+        }
     };
 
     /**
@@ -269,7 +240,7 @@ export class CollectionCardView extends CollectionSubView() {
                     const sorted = this.sortedDocs;
                     const originalIndex = sorted.findIndex(doc => doc === draggedDoc);
 
-                    this.Document.cardSort = '';
+                    this.Document.card_sort = '';
                     originalIndex !== -1 && sorted.splice(originalIndex, 1);
                     sorted.splice(dragIndex, 0, draggedDoc);
                     if (de.complete.docDragData.removeDocument?.(draggedDoc)) {
@@ -285,15 +256,6 @@ export class CollectionCardView extends CollectionSubView() {
         ''
     );
 
-    @computed get sortedDocs() {
-        return this.sort(
-            this.childCards.map(card => card.layout),
-            this.cardSort,
-            BoolCast(this.Document.cardSort_isDesc),
-            this._docDraggedIndex
-        );
-    }
-
     /**
      * Used to determine how to sort cards based on tags. The leftmost tags are given lower values while cards to the right are
      * given higher values. Decimals are used to determine placement for cards with multiple tags
@@ -341,6 +303,15 @@ export class CollectionCardView extends CollectionSubView() {
         return docs;
     };
 
+    @computed get sortedDocs() {
+        return this.sort(
+            this.childCards.map(card => card.layout),
+            this.cardSort,
+            BoolCast(this.Document.card_sort_isDesc),
+            this._docDraggedIndex
+        );
+    }
+
     isChildContentActive = computedFn(
         (doc: Doc) => () =>
             this._props.isContentActive?.() === false
@@ -359,74 +330,99 @@ export class CollectionCardView extends CollectionSubView() {
             Document={doc}
             NativeWidth={returnZero}
             NativeHeight={returnZero}
-            fitWidth={returnFalse}
-            onDoubleClickScript={this.onChildDoubleClick}
+            PanelWidth={this.childPanelWidth}
+            PanelHeight={this.childPanelHeight}
             renderDepth={this._props.renderDepth + 1}
             LayoutTemplate={this._props.childLayoutTemplate}
             LayoutTemplateString={this._props.childLayoutString}
             containerViewPath={this.childContainerViewPath}
             ScreenToLocalTransform={screenToLocalTransform} // makes sure the box wrapper thing is in the right spot
             isDocumentActive={this._props.childDocumentsActive?.() || this.Document._childDocumentsActive ? this._props.isDocumentActive : this.isContentActive}
-            PanelWidth={this.childPanelWidth}
-            PanelHeight={this.childPanelHeight}
+            isContentActive={this.isChildContentActive(doc)}
+            fitWidth={returnFalse}
             waitForDoubleClickToClick={returnNever}
             scriptContext={this}
+            onDoubleClickScript={this.onChildDoubleClick}
             onClickScript={this._curDoc === doc ? undefined : this._clickScript}
             dontCenter="y" // Don't center it vertically, because the grid it's in is already doing that and we don't want to do it twice.
             dragAction={(this.Document.childDragAction ?? this._props.childDragAction) as dropActionType}
             showTags={BoolCast(this.layoutDoc.showChildTags)}
             whenChildContentsActiveChanged={this._props.whenChildContentsActiveChanged}
-            isContentActive={this.isChildContentActive(doc)}
             dontHideOnDrag
         />
     );
 
     /**
      * Determines how many cards are in the row of a card at a specific index
-     * @param index
-     * @returns
+     * @param index numerical index of card in total list of all cards
+     * @returns number of cards in row that contains index
      */
-    overflowAmCardsCalc = (index: number) => {
-        if (this.sortedDocs.length < this._maxRowCount) {
-            return this.sortedDocs.length;
+    cardsInRowThatIncludesCardIndex = (index: number) => {
+        if (this.childCards.length < this._maxRowCount) {
+            return this.childCards.length;
         }
-        const totalCards = this.sortedDocs.length;
-        // if 9 or less
+        const totalCards = this.childCards.length;
         if (index < totalCards - (totalCards % this._maxRowCount)) {
             return this._maxRowCount;
         }
         return totalCards % this._maxRowCount;
     };
     /**
-     * Determines the index a card is in in a row
-     * @param realIndex
-     * @returns
+     * Determines the index a card is in in a row.  If the row is not full, then the cards
+     * are centered within the row (as if unrendered cards had been added to the start and end
+     * of the row) and the retuned index is the index the card in this virtual full row.
+     * @param index numerical index of card in total list of all cards
+     * @returns index of card in its row, normalized to a full size row
      */
-    overflowIndexCalc = (realIndex: number) => realIndex % this._maxRowCount;
+    centeredIndexOfCardInRow = (index: number) => {
+        const cardsInRow = this.cardsInRowThatIncludesCardIndex(index);
+        const lineIndex = index % this._maxRowCount;
+        if (cardsInRow === this._maxRowCount) return lineIndex;
+        return lineIndex + (this._maxRowCount - cardsInRow) / 2;
+    };
     /**
-     * Translates the cards in the second rows and beyond over to the right
-     * @param realIndex
-     * @param calcIndex
-     * @param calcRowCards
-     * @returns
+     * Returns the rotation of a card in radians based on its horizontal location (and thus m apping to a circle arc).
+     * The amount of rotation is goverend by the Doc's card_arch field which specifies, in degrees, the range of a circle
+     * arc that cards should cover -- by default, -45 to 45 degrees.
+     * @param index numerical index of card in total list of all cards
+     * @returns angle of rotation in radians
+     */
+    rotate = (index: number) => {
+        const cardsInRow = this.cardsInRowThatIncludesCardIndex(index);
+        const centeredIndexInRow = (cardsInRow < this._maxRowCount ? index + (this._maxRowCount - cardsInRow) / 2 : index) % this._maxRowCount;
+        const rowIndexMax = this._maxRowCount - 1;
+        return ((this.archAngle / 2) * (centeredIndexInRow - rowIndexMax / 2)) / (rowIndexMax / 2);
+    };
+    /**
+     * Provides a vertical adjustment to a card's grid position so that it will lie along an arch.
+     * @param index numerical index of card in total list of all cards
+     */
+    translateY = (index: number) => {
+        const Magnitude = ((this._props.PanelHeight() * this.fitContentScale) / 2) * Math.sqrt(((this.archAngle * (180 / Math.PI)) / 60) * 4);
+        return Magnitude * (1 - Math.sin(this.rotate(index) + Math.PI / 2) - (1 - Math.sin(this.archAngle / 2 + Math.PI / 2)) / 2);
+    };
+    /**
+     * When the card index is for a row (not the first row) that is not full, this returns a horizontal adjustment that centers the row
+     * @param index index of card from start of deck
+     * @param cardsInRow number of cards in the row containing the indexed card
+     * @returns horizontal pixel translation
      */
-    translateOverflowX = (realIndex: number, calcRowCards: number) => (realIndex < this._maxRowCount ? 0 : (this._maxRowCount - calcRowCards) * (this.childPanelWidth() / 2));
+    horizontalAdjustmentForPartialRows = (index: number, cardsInRow: number) => (index < this._maxRowCount ? 0 : (this._maxRowCount - cardsInRow) * (this.childPanelWidth() / 2));
 
     /**
-     * Determines how far to translate a card in the y direction depending on its index and if it's selected
+     * Adjusts the vertical placement of the card from its grid position so that it will either line on a
+     * circular arc if the card isn't active, or so that it will be centered otherwise.
      * @param isActive whether the card is focused for interaction
-     * @param realIndex index of card from start of deck
-     * @param amCards ??
-     * @param calcRowIndex index of card from start of row
-     * @returns Y translation of card
+     * @param index index of card from start of deck
+     * @returns vertical pixel translation
      */
-    calculateTranslateY = (isActive: boolean, realIndex: number, amCards: number, calcRowIndex: number) => {
-        const rowHeight = (this._props.PanelHeight() * this.fitContentScale) / this.numRows;
-        const rowIndex = Math.trunc(realIndex / this._maxRowCount);
+    adjustCardYtoFitArch = (isActive: boolean, index: number) => {
+        const rowHeight = this._props.PanelHeight() / this.numRows;
+        const rowIndex = Math.floor(index / this._maxRowCount);
         const rowToCenterShift = this.numRows / 2 - rowIndex;
-        if (isActive) return rowToCenterShift * rowHeight - rowHeight / 2;
-        if (amCards == 1) return 50 * this.fitContentScale;
-        return this.translateY(amCards, calcRowIndex, realIndex);
+        return isActive
+            ? (rowToCenterShift * rowHeight - rowHeight / 2) * ((this.cardSpacing * this.fitContentScale) / 100) //
+            : this.translateY(index);
     };
 
     /**
@@ -493,7 +489,7 @@ export class CollectionCardView extends CollectionSubView() {
         }
 
         if (questionType === '6') {
-            this.Document.cardSort = 'chat';
+            this.Document.card_sort = 'chat';
         }
 
         listItems.forEach((item, index) => {
@@ -549,7 +545,7 @@ export class CollectionCardView extends CollectionSubView() {
         await this.childPairStringListAndUpdateSortDesc();
     };
 
-    childScreenToLocal = computedFn((doc: Doc, index: number, calcRowIndex: number, isSelected: boolean, amCards: number) => () => {
+    childScreenToLocal = computedFn((doc: Doc, index: number, isSelected: boolean) => () => {
         // need to explicitly trigger an invalidation since we're reading everything from the Dom
         this._forceChildXf;
         this._props.ScreenToLocalTransform();
@@ -560,24 +556,40 @@ export class CollectionCardView extends CollectionSubView() {
 
         return new Transform(-translateX + (dref?.centeringX || 0) * scale, 
                              -translateY + (dref?.centeringY || 0) * scale, 1)
-                  .scale(1 / scale).rotate(!isSelected ? -this.rotate(amCards, calcRowIndex) : 0); // prettier-ignore
+                  .scale(1 / scale).rotate(!isSelected ? -this.rotate(this.centeredIndexOfCardInRow(index)) : 0); // prettier-ignore
     });
 
+    /**
+     * Releases the currently focused Doc by deselecting it and returning it to its location on the arch, and selecting the
+     * cardDeck itself.
+     * This will also force the Doc to recompute its layout transform when the animation completes.
+     * In addition, this sets an animating flag on the Doc so that it will receive no poiner events when animating, such as hover
+     * events that would trigger a flashcard to flip.
+     * @param doc doc that will be animated away from center focus
+     */
+    releaseCurDoc = action(() => {
+        const selDoc = this._curDoc;
+        this._curDoc = undefined;
+        const cardDocView = DocumentView.getDocumentView(selDoc, this.DocumentView?.());
+        if (cardDocView && selDoc) {
+            DocumentView.DeselectView(cardDocView);
+            this._props.select(false);
+            selDoc[Animation] = selDoc; // turns off pointer events & doc decorations while animating - useful for flashcards that reveal back on hover
+            setTimeout(action(() => {
+                selDoc[Animation] = undefined;
+                this._forceChildXf++;
+            }), 350); // prettier-ignore
+        }
+    });
+
+    /**
+     * turns off the _dropped flag at the end of a drag/drop, or releases the focused Doc if a different Doc is clicked
+     */
     cardPointerUp = action((doc: Doc) => {
-        // if a card doc has just moved, or a card is selected and in front, then ignore this event
         if (this._curDoc === doc || this._dropped) {
             this._dropped = false;
         } else {
-            // otherwise, turn off documentDecorations becase we're in a selection transition and want to avoid artifacts.
-            // Turn them back on when the animation has completed and the render and backend structures are in synch
-            SnappingManager.SetHideDecorations(true);
-            setTimeout(
-                action(() => {
-                    SnappingManager.SetHideDecorations(false);
-                    this._forceChildXf++;
-                }),
-                1000
-            );
+            this.releaseCurDoc(); // NOTE: the onClick script for the card will select the new card (ie, 'doc')
         }
     });
 
@@ -585,25 +597,17 @@ export class CollectionCardView extends CollectionSubView() {
      * Actually renders all the cards
      */
     @computed get renderCards() {
-        if (!this.childCards.length) {
-            return null;
-        }
-
+        console.log('CHILDPw = ' + this.childPanelWidth());
         // Map sorted documents to their rendered components
         return this.sortedDocs.map((doc, index) => {
-            const calcRowIndex = this.overflowIndexCalc(index);
-            const amCards = this.overflowAmCardsCalc(index);
+            const cardsInRow = this.cardsInRowThatIncludesCardIndex(index);
+
+            const childScreenToLocal = this.childScreenToLocal(doc, index, doc === this._curDoc);
 
-            const childScreenToLocal = this.childScreenToLocal(doc, index, calcRowIndex, doc === this._curDoc, amCards);
+            const translateToCenterIfActive = () => (doc === this._curDoc ? (cardsInRow / 2 - (index % this._maxRowCount)) * 100 - 50 : 0);
 
-            const translateIfSelected = () => {
-                const indexInRow = index % this._maxRowCount;
-                const rowIndex = Math.trunc(index / this._maxRowCount);
-                const rowCenterIndex = Math.min(this._maxRowCount, this.sortedDocs.length - rowIndex * this._maxRowCount) / 2;
-                return (rowCenterIndex - indexInRow) * 100 - 50;
-            };
             const aspect = NumCast(doc.height) / NumCast(doc.width, 1);
-            const vscale = Math.max(1,Math.min((this._props.PanelHeight() * 0.95 * this.fitContentScale) / (aspect * this.childPanelWidth()), 
+            const vscale = Math.max(1,Math.min((this._props.PanelHeight() * 0.95 * this.fitContentScale * this.nativeScaling) / (aspect * this.childPanelWidth()), 
                                     (this._props.PanelHeight() - 80) / (aspect * (this._props.PanelWidth() / 10)))); // prettier-ignore
             const hscale = Math.min(this.sortedDocs.length, this._maxRowCount) / 2; // bcz: hack - the grid is divided evenly into maxRowCount cells, so the max scaling would be maxRowCount -- but making things that wide is ugly, so cap it off at half the window size
             return (
@@ -614,9 +618,9 @@ export class CollectionCardView extends CollectionSubView() {
                     style={{
                         width: this.childPanelWidth(),
                         height: 'max-content',
-                        transform: `translateY(${this.calculateTranslateY(doc === this._curDoc, index, amCards, calcRowIndex)}px)
-                                    translateX(calc(${doc === this._curDoc ? translateIfSelected() : 0}% + ${this.translateOverflowX(index, amCards)}px))
-                                    rotate(${doc !== this._curDoc ? this.rotate(amCards, calcRowIndex) : 0}deg)
+                        transform: `translateY(${this.adjustCardYtoFitArch(doc === this._curDoc, index)}px)
+                                    translateX(calc(${translateToCenterIfActive()}% + ${this.horizontalAdjustmentForPartialRows(index, cardsInRow)}px))
+                                    rotate(${doc !== this._curDoc ? this.rotate(index) : 0}rad)
                                     scale(${doc === this._curDoc ? `${Math.min(hscale, vscale) * 100}%` : this._hoveredNodeIndex === index ? 1.1 : 1})`,
                     }} // prettier-ignore
                     onPointerEnter={() => this.setHoveredNodeIndex(index)}
@@ -636,26 +640,19 @@ export class CollectionCardView extends CollectionSubView() {
         ScreenToLocalTransform: this.contentScreenToLocalXf,
     });
     answered = action(() => {
-        this._curDoc = this.curDoc ? this.filteredChildDocs()[(this.filteredChildDocs().findIndex(this.curDoc) + 1) % (this.filteredChildDocs().length || 1)] : undefined;
+        this._curDoc = this.curDoc ? this.filteredChildDocs()[(this.filteredChildDocs().findIndex(d => d === this.curDoc()) + 1) % (this.filteredChildDocs().length || 1)] : undefined;
     });
     curDoc = () => this._curDoc;
 
     render() {
-        const isEmpty = this.childCards.length === 0;
+        const fitContentScale = this.childCards.length === 0 ? 1 : this.fitContentScale;
         return (
             <div
                 className="collectionCardView-outer"
                 ref={(ele: HTMLDivElement | null) => this.createDashEventsTarget(ele)}
-                onPointerDown={action(() => {
-                    this._curDoc = undefined;
-                    SnappingManager.SetHideDecorations(true);
-                    setTimeout(
-                        action(() => {
-                            SnappingManager.SetHideDecorations(false);
-                            this._forceChildXf++;
-                        }),
-                        1000
-                    );
+                onPointerDown={action(e => {
+                    if (e.button === 2 || e.ctrlKey) return;
+                    this.releaseCurDoc();
                 })}
                 onPointerLeave={action(() => (this._docDraggedIndex = -1))}
                 onPointerMove={e => this.onPointerMove(...this._props.ScreenToLocalTransform().transformPoint(e.clientX, e.clientY))}
@@ -665,16 +662,31 @@ export class CollectionCardView extends CollectionSubView() {
                     color: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.Color) as string,
                 }}>
                 <div
-                    className="card-wrapper"
+                    className="collectionCardView-inner"
                     style={{
-                        ...(!isEmpty && { transform: `scale(${1 / this.fitContentScale})` }),
-                        ...{ height: `${100 * (isEmpty ? 1 : this.fitContentScale)}%` },
-                        ...{ width: `${100 * (isEmpty ? 1 : this.fitContentScale)}%` },
-                        gridAutoRows: `${100 / this.numRows}%`,
+                        transform: `scale(${1 / fitContentScale})`,
+                        height: `${100 * fitContentScale}%`,
+                        width: `${100 * fitContentScale}%`,
                     }}>
-                    {this.renderCards}
+                    <div
+                        className="collectionCardView-cardwrapper"
+                        style={{
+                            gridAutoRows: `${100 / this.numRows}%`,
+                            height: `${this.cardSpacing}%`,
+                        }}>
+                        {this.renderCards}
+                    </div>
+                    <div
+                        className="collectionCardView-flashcardUI"
+                        style={{
+                            pointerEvents: this.childCards.length === 0 ? undefined : 'none',
+                            height: `${100 / this.nativeScaling / fitContentScale}%`,
+                            width: `${100 / this.nativeScaling / fitContentScale}%`,
+                            transform: `scale(${this.nativeScaling * fitContentScale})`,
+                        }}>
+                        {this.flashCardUI(this.curDoc, this.docViewProps, this.answered)}
+                    </div>
                 </div>
-                {this.flashCardUI(this.curDoc, this.docViewProps, this.answered)}
             </div>
         );
     }
diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx
index e9ace733e..a71cc43ba 100644
--- a/src/client/views/collections/CollectionCarousel3DView.tsx
+++ b/src/client/views/collections/CollectionCarousel3DView.tsx
@@ -205,7 +205,7 @@ export class CollectionCarousel3DView extends CollectionSubView() {
 
     onPassiveWheel = (e: WheelEvent) => e.stopPropagation();
     curDoc = () => this.carouselItems[NumCast(this.layoutDoc._carousel_index)]?.layout;
-    answered = (correct: boolean) => (!correct || !this.curDoc()) && this.changeSlide(1);
+    answered = (correct: boolean) => (!correct || !this.curDoc() || NumCast(this.layoutDoc._carousel_index) === this.carouselItems.length - 1) && this.changeSlide(1);
     docViewProps = () => ({
         ...this._props, //
         isDocumentActive: this._props.childDocumentsActive?.() ? this._props.isDocumentActive : this._props.isContentActive,
diff --git a/src/client/views/collections/CollectionCarouselView.tsx b/src/client/views/collections/CollectionCarouselView.tsx
index ff587b199..1f2bc908f 100644
--- a/src/client/views/collections/CollectionCarouselView.tsx
+++ b/src/client/views/collections/CollectionCarouselView.tsx
@@ -203,7 +203,7 @@ export class CollectionCarouselView extends CollectionSubView() {
         isContentActive: this.isChildContentActive,
         ScreenToLocalTransform: this.contentScreenToLocalXf,
     });
-    answered = () => this.advance();
+    answered = (correct: boolean) => (!correct || !this.curDoc() || NumCast(this.layoutDoc._carousel_index) === this.carouselItems.length - 1) && this.advance();
 
     render() {
         return (
diff --git a/src/client/views/collections/FlashcardPracticeUI.scss b/src/client/views/collections/FlashcardPracticeUI.scss
index 4ed27793d..210c6798f 100644
--- a/src/client/views/collections/FlashcardPracticeUI.scss
+++ b/src/client/views/collections/FlashcardPracticeUI.scss
@@ -1,3 +1,9 @@
+.FlashcardPracticeUI {
+    width: 100%;
+    height: 100%;
+    display: flex;
+    align-items: center;
+}
 .FlashcardPracticeUI-remove,
 .FlashcardPracticeUI-check {
     position: absolute;
diff --git a/src/client/views/collections/FlashcardPracticeUI.tsx b/src/client/views/collections/FlashcardPracticeUI.tsx
index 79eb7f107..ec892ee3d 100644
--- a/src/client/views/collections/FlashcardPracticeUI.tsx
+++ b/src/client/views/collections/FlashcardPracticeUI.tsx
@@ -104,8 +104,8 @@ export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProp
         const setPracticeVal = (e: React.MouseEvent, val: string) => {
             e.stopPropagation();
             const curDoc = this._props.curDoc();
-            curDoc && (curDoc[this.practiceField] = val);
             this._props.advance?.(val === practiceVal.CORRECT);
+            curDoc && (curDoc[this.practiceField] = val);
         };
 
         return this.practiceMode == practiceMode.PRACTICE && this._props.curDoc() ? (
@@ -182,7 +182,7 @@ export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProp
     tryFilterOut = (doc: Doc) => (this.practiceMode && BoolCast(doc?._layout_isFlashcard) && doc[this.practiceField] === practiceVal.CORRECT ? true : false); // show only cards that aren't marked as correct
     render() {
         return (
-            <>
+            <div className="FlashcardPracticeUI">
                 {this.emptyMessage}
                 {this.practiceButtons}
                 {this._props.layoutDoc._chromeHidden ? null : (
@@ -208,7 +208,7 @@ export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProp
                         {this.practiceModesMenu}
                     </div>
                 )}
-            </>
+            </div>
         );
     }
 }
diff --git a/src/client/views/global/globalScripts.ts b/src/client/views/global/globalScripts.ts
index 903e04ad7..954c79f7d 100644
--- a/src/client/views/global/globalScripts.ts
+++ b/src/client/views/global/globalScripts.ts
@@ -189,38 +189,38 @@ ScriptingGlobals.add(function showFreeform(
             setDoc: (doc: Doc, dv: DocumentView) => { Doc.UserDoc().defaultToFlashcards = !Doc.UserDoc().defaultToFlashcards}, // prettier-ignore
         }],
         ['time', {
-            checkResult: (doc: Doc) => StrCast(doc?.cardSort) === "time",
-            setDoc: (doc: Doc, dv: DocumentView) => { doc.cardSort === "time" ? doc.cardSort = '' : doc.cardSort = 'time'}, // prettier-ignore
+            checkResult: (doc: Doc) => StrCast(doc?.card_sort) === "time",
+            setDoc: (doc: Doc, dv: DocumentView) => { doc.card_sort === "time" ? doc.card_sort = '' : doc.card_sort = 'time'}, // prettier-ignore
         }],
         ['docType', {
-            checkResult: (doc: Doc) => StrCast(doc?.cardSort) === "type",
-            setDoc: (doc: Doc, dv: DocumentView) => { doc.cardSort === "type" ? doc.cardSort = '' : doc.cardSort = 'type'}, // prettier-ignore
+            checkResult: (doc: Doc) => StrCast(doc?.card_sort) === "type",
+            setDoc: (doc: Doc, dv: DocumentView) => { doc.card_sort === "type" ? doc.card_sort = '' : doc.card_sort = 'type'}, // prettier-ignore
         }],
         ['color', {
-            checkResult: (doc: Doc) => StrCast(doc?.cardSort) === "color",
-            setDoc: (doc: Doc, dv: DocumentView) => { doc.cardSort === "color" ? doc.cardSort = '' : doc.cardSort = 'color'}, // prettier-ignore
+            checkResult: (doc: Doc) => StrCast(doc?.card_sort) === "color",
+            setDoc: (doc: Doc, dv: DocumentView) => { doc.card_sort === "color" ? doc.card_sort = '' : doc.card_sort = 'color'}, // prettier-ignore
         }],
         ['tag', {
-            checkResult: (doc: Doc) => StrCast(doc?.cardSort) === "tag",
-            setDoc: (doc: Doc, dv: DocumentView) => { doc.cardSort === "tag" ? doc.cardSort = '' : doc.cardSort = 'tag'}, // prettier-ignore
+            checkResult: (doc: Doc) => StrCast(doc?.card_sort) === "tag",
+            setDoc: (doc: Doc, dv: DocumentView) => { doc.card_sort === "tag" ? doc.card_sort = '' : doc.card_sort = 'tag'}, // prettier-ignore
         }],
         ['up', {
-            checkResult: (doc: Doc) => BoolCast(!doc?.cardSort_isDesc),
+            checkResult: (doc: Doc) => BoolCast(!doc?.card_sort_isDesc),
             setDoc: (doc: Doc, dv: DocumentView) => {
-                doc.cardSort_isDesc = false;
+                doc.card_sort_isDesc = false;
             },
         }],
         ['down', {
-            checkResult: (doc: Doc) => BoolCast(doc?.cardSort_isDesc),
+            checkResult: (doc: Doc) => BoolCast(doc?.card_sort_isDesc),
             setDoc: (doc: Doc, dv: DocumentView) => {
-                doc.cardSort_isDesc = true;
+                doc.card_sort_isDesc = true;
             },
         }],
         ['toggle-chat', {
             checkResult: (doc: Doc) => GPTPopup.Instance.visible,
             setDoc: (doc: Doc, dv: DocumentView) => {
                 if (GPTPopup.Instance.visible){
-                    doc.cardSort = ''
+                    doc.card_sort = ''
                     GPTPopup.Instance.setVisible(false);
    
                 } else {
diff --git a/src/client/views/nodes/ComparisonBox.tsx b/src/client/views/nodes/ComparisonBox.tsx
index 38ce5f2f7..3c126ea4a 100644
--- a/src/client/views/nodes/ComparisonBox.tsx
+++ b/src/client/views/nodes/ComparisonBox.tsx
@@ -8,7 +8,7 @@ import ReactLoading from 'react-loading';
 import { imageUrlToBase64, returnFalse, returnNone, returnTrue, returnZero, setupMoveUpEvents } from '../../../ClientUtils';
 import { emptyFunction } from '../../../Utils';
 import { Doc, Opt } from '../../../fields/Doc';
-import { DocData } from '../../../fields/DocSymbols';
+import { Animation, DocData } from '../../../fields/DocSymbols';
 import { RichTextField } from '../../../fields/RichTextField';
 import { BoolCast, DocCast, NumCast, RTFCast, StrCast, toList } from '../../../fields/Types';
 import { nullAudio } from '../../../fields/URLField';
@@ -18,7 +18,6 @@ import { DocumentType } from '../../documents/DocumentTypes';
 import { Docs } from '../../documents/Documents';
 import { DragManager } from '../../util/DragManager';
 import { dropActionType } from '../../util/DropActionTypes';
-import { SnappingManager } from '../../util/SnappingManager';
 import { undoable } from '../../util/UndoManager';
 import { ContextMenu } from '../ContextMenu';
 import { ViewBoxAnnotatableComponent } from '../DocComponent';
@@ -235,7 +234,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     @computed get uiBtnScaling() { return Math.max(this.maxWidgetSize / this._sideBtnWidth, 1) * Math.min(1, this.viewScaling)* (this._props.NativeDimScaling?.() ?? 1); } // prettier-ignore
 
     @computed get flashcardMenu() {
-        return SnappingManager.HideDecorations ? null : (
+        return (
             <div className="comparisonBox-bottomMenu" style={{ transform: `scale(${this.uiBtnScaling})` }}>
                 {this.revealOpHover || !this._props.isSelected() ? null : this.overlayAlternateIcon}
                 {!this._props.isSelected() || this._renderSide === this.frontKey ? null : (
@@ -666,20 +665,20 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
             <>
                 <DocumentView
                     {...this._props}
-                    showTags={undefined}
-                    fitWidth={undefined} // set to returnTrue to make images fill the comparisonBox-- should be a user option
-                    ignoreUsePath={layoutString ? true : undefined}
-                    renderDepth={this.props.renderDepth + 1}
-                    LayoutTemplateString={layoutString}
                     Document={layoutString ? this.Document : targetDoc}
-                    containerViewPath={this._props.docViewPath}
-                    moveDocument={whichSlot === this.frontKey ? this.moveDocFront : this.moveDocBack}
-                    removeDocument={whichSlot === this.frontKey ? this.remDocFront : this.remDocBack}
                     NativeWidth={returnZero}
                     NativeHeight={returnZero}
+                    renderDepth={this.props.renderDepth + 1}
+                    LayoutTemplateString={layoutString}
+                    containerViewPath={this._props.docViewPath}
                     ScreenToLocalTransform={this.contentScreenToLocalXf}
-                    isContentActive={this.childActiveFunc}
                     isDocumentActive={returnFalse}
+                    isContentActive={this.childActiveFunc}
+                    showTags={undefined}
+                    fitWidth={undefined} // set to returnTrue to make images fill the comparisonBox-- should be a user option
+                    ignoreUsePath={layoutString ? true : undefined}
+                    moveDocument={whichSlot === this.frontKey ? this.moveDocFront : this.moveDocBack}
+                    removeDocument={whichSlot === this.frontKey ? this.remDocFront : this.remDocBack}
                     dontSelect={returnTrue}
                     whenChildContentsActiveChanged={this.whenChildContentsActiveChanged}
                     styleProvider={this._childActive ? this._props.styleProvider : this.docStyleProvider}
@@ -795,7 +794,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
             [flashcardRevealOp.SLIDE, this.renderAsBeforeAfter]]); // prettier-ignore
         if (this.isQuizMode) this.renderAsQuiz(this.frontText);
         return (
-            <div className="comparisonBox" style={{ pointerEvents: this._props.isContentActive() ? 'unset' : undefined }} onContextMenu={this.flashcardContextMenu}>
+            <div className="comparisonBox" style={{ pointerEvents: this._props.isContentActive() && !this.Document[Animation] ? 'unset' : undefined }} onContextMenu={this.flashcardContextMenu}>
                 {renderMode.get(this.revealOp)?.() ?? null}
                 {this.loading ? (
                     <div className="loading-spinner">
diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx
index 9aa000ba7..aab8a183a 100644
--- a/src/client/views/nodes/DocumentContentsView.tsx
+++ b/src/client/views/nodes/DocumentContentsView.tsx
@@ -1,4 +1,3 @@
-/* eslint-disable react/require-default-props */
 import { computed, makeObservable } from 'mobx';
 import { observer } from 'mobx-react';
 import * as React from 'react';
-- 
cgit v1.2.3-70-g09d2


From 4b231bbaf21939144ed8639d35f022834a406e59 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Thu, 17 Oct 2024 22:02:19 -0400
Subject: changed layout_isFlashcard to layout_flashcardType with value of
 'flashcard' to make it easy to search for flashcards. made carousel views
 able to focus() on a Doc.  added ability for carousel and card views to have
 anchors so they can be pinned and linked.  fixed pinning collections to save
 filters

---
 src/client/apis/gpt/GPT.ts                         |  9 +++-
 src/client/documents/Documents.ts                  |  4 +-
 src/client/util/LinkFollower.ts                    |  2 -
 src/client/views/PinFuncs.ts                       | 13 ++++--
 .../views/collections/CollectionCardDeckView.tsx   | 32 +++++++++++++-
 .../views/collections/CollectionCarousel3DView.tsx | 32 +++++++++++++-
 .../views/collections/CollectionCarouselView.tsx   | 51 +++++++++++++++++++++-
 .../collections/CollectionStackedTimeline.tsx      |  5 +--
 .../views/collections/CollectionTimeView.tsx       |  2 -
 .../views/collections/FlashcardPracticeUI.tsx      |  6 +--
 .../collectionFreeForm/CollectionFreeFormView.tsx  |  2 +-
 src/client/views/nodes/ComparisonBox.tsx           | 21 +++++----
 src/client/views/nodes/DataVizBox/DataVizBox.tsx   |  2 +-
 src/client/views/nodes/MapBox/MapBox.tsx           |  2 +-
 .../views/nodes/MapboxMapBox/MapboxContainer.tsx   |  5 +--
 src/client/views/nodes/PDFBox.tsx                  |  2 +-
 .../views/nodes/formattedText/FormattedTextBox.tsx |  2 +-
 17 files changed, 151 insertions(+), 41 deletions(-)

(limited to 'src/client/views/collections/CollectionCarousel3DView.tsx')

diff --git a/src/client/apis/gpt/GPT.ts b/src/client/apis/gpt/GPT.ts
index 8a2c91269..03380e4d6 100644
--- a/src/client/apis/gpt/GPT.ts
+++ b/src/client/apis/gpt/GPT.ts
@@ -42,7 +42,7 @@ const callTypeMap: { [type: string]: GPTCallOpts } = {
         model: 'gpt-4o',
         maxTokens: 2048,
         temp: 0.7,
-        prompt: 'Create a stack of flashcards out of this text with each question and answer labeled as question and answer. For some questions, ask "what is this image of" but tailored to stacks theme and the image and write a keyword that represents the image and label it "keyword". Otherwise, write none. Do not label each flashcard and do not include asterisks.',
+        prompt: 'Create a stack of flashcards out of this text with each question and answer labeled as question and answer. Create a title that represents the question in just a few words and label it "title". For some questions, ask "what is this image of" but tailored to stacks theme and the image and write a keyword that represents the image and label it "keyword". Otherwise, write none. Do not label each flashcard and do not include asterisks.',
     },
 
     completion: { model: 'gpt-4-turbo', maxTokens: 256, temp: 0.5, prompt: "You are a helpful assistant. Answer the user's prompt." },
@@ -65,7 +65,12 @@ const callTypeMap: { [type: string]: GPTCallOpts } = {
         prompt: "The user is going to give you a list of descriptions. Each one is separated by `======` on either side. Descriptions will vary in length, so make sure to only separate when you see `======`. Sort them by the user's specifications. Make sure each description is only in the list once. Each item should be separated by `======`. Immediately afterward, surrounded by `------` on BOTH SIDES, provide some insight into your reasoning for the way you sorted (and mention nothing about the formatting details given in this description). It is VERY important that you format it exactly as described, ensuring the proper number of `=` and `-` (6 of each) and NO commas",
     },
     describe: { model: 'gpt-4-vision-preview', maxTokens: 2048, temp: 0, prompt: 'Describe these images in 3-5 words' },
-    flashcard: { model: 'gpt-4-turbo', maxTokens: 512, temp: 0.5, prompt: 'Make flashcards out of this text with each question and answer labeled as question and answer. Do not label each flashcard and do not include asterisks: ' },
+    flashcard: {
+        model: 'gpt-4-turbo',
+        maxTokens: 512,
+        temp: 0.5,
+        prompt: 'Make flashcards out of this text with each question and answer labeled as question and answer. Create a title for each question and asnwer that is labeled as "title".  Do not label each flashcard and do not include asterisks: ',
+    },
     chatcard: { model: 'gpt-4-turbo', maxTokens: 512, temp: 0.5, prompt: 'Answer the following question as a short flashcard response. Do not include a label.' },
     quiz: {
         model: 'gpt-4-turbo',
diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts
index e539e3c65..f2e85cf7a 100644
--- a/src/client/documents/Documents.ts
+++ b/src/client/documents/Documents.ts
@@ -281,7 +281,7 @@ export class DocumentOptions {
     _layout_fitWidth?: BOOLt = new BoolInfo('whether document should scale its contents to fit its rendered width or not (e.g., for PDFviews)');
     _layout_fieldKey?: STRt = new StrInfo('the field key containing the current layout definition', false);
     _layout_enableAltContentUI?: BOOLt = new BoolInfo('whether to show alternate content button');
-    _layout_isFlashcard?: BOOLt = new BoolInfo('whether comparison node should be displayed as a flashcard');
+    _layout_flashcardType?: STRt = new StrInfo('flashcard style to render in ComparisonBox.  currently just "flashcard".');
     _layout_showTitle?: string; // field name to display in header (:hover is an optional suffix)
     _layout_showSidebar?: BOOLt = new BoolInfo('whether an annotationsidebar should be displayed for text docuemnts');
     _layout_showCaption?: string; // which field to display in the caption area.  leave empty to have no caption
@@ -821,7 +821,7 @@ export namespace Docs {
                 data_front: front ?? CenteredTextCreator('question', 'hint: Enter a topic, select this document and click the stack button to have GPT create a deck of cards', { text_placeholder: true, cloneOnCopy: true }, undefined),
                 data_back: back ?? CenteredTextCreator('answer', 'answer here', { text_placeholder: true, cloneOnCopy: true }, undefined),
                 _layout_fitWidth: true,
-                _layout_isFlashcard: true,
+                _layout_flashcardType: 'flashcard',
                 title,
                 ...options,
             });
diff --git a/src/client/util/LinkFollower.ts b/src/client/util/LinkFollower.ts
index 0a3a0ba49..0e67dcfaa 100644
--- a/src/client/util/LinkFollower.ts
+++ b/src/client/util/LinkFollower.ts
@@ -113,12 +113,10 @@ export class LinkFollower {
                 }
                 const moveTo = [NumCast(sourceDoc.x) + NumCast(sourceDoc.followLinkXoffset), NumCast(sourceDoc.y) + NumCast(sourceDoc.followLinkYoffset)];
                 if (srcAnchor.followLinkXoffset !== undefined && moveTo[0] !== target.x) {
-                    // eslint-disable-next-line prefer-destructuring
                     target.x = moveTo[0];
                     movedTarget = true;
                 }
                 if (srcAnchor.followLinkYoffset !== undefined && moveTo[1] !== target.y) {
-                    // eslint-disable-next-line prefer-destructuring
                     target.y = moveTo[1];
                     movedTarget = true;
                 }
diff --git a/src/client/views/PinFuncs.ts b/src/client/views/PinFuncs.ts
index 430455644..5b57cd624 100644
--- a/src/client/views/PinFuncs.ts
+++ b/src/client/views/PinFuncs.ts
@@ -39,9 +39,14 @@ export interface PinProps {
     pinData?: pinDataTypes;
 }
 
-/// copies values from the targetDoc (which is the prototype of the pinDoc) to
-/// reserved fields on the pinDoc so that those values can be restored to the
-/// target doc when navigating to it.
+/**
+ * copies values from the targetDoc (which is the prototype of the pinDoc) to
+ * reserved fields on the pinDoc so that those values can be restored to the
+ * target doc when navigating to it.
+ * @param pinDoc Doc that will store pinned metadata
+ * @param pinProps description of props to pin
+ * @param targetDoc Doc that is being pinned
+ */
 export function PinDocView(pinDocIn: Doc, pinProps: PinProps, targetDoc: Doc) {
     const pinDoc = pinDocIn;
     pinDoc.presentation = true;
@@ -114,7 +119,7 @@ export function PinDocView(pinDocIn: Doc, pinProps: PinProps, targetDoc: Doc) {
                 )
             );
         if (pinProps.pinData.type_collection) pinDoc.config_viewType = targetDoc._type_collection;
-        if (pinProps.pinData.filters) pinDoc.config_docFilters = ObjectField.MakeCopy(targetDoc.childFilters as ObjectField);
+        if (pinProps.pinData.filters) pinDoc.config_docFilters = ObjectField.MakeCopy(targetDoc.childFilters as ObjectField) ?? new List<string>();
         if (pinProps.pinData.pivot) pinDoc.config_pivotField = targetDoc._pivotField;
         if (pinProps.pinData.pannable) {
             pinDoc.config_panX = NumCast(targetDoc._freeform_panX);
diff --git a/src/client/views/collections/CollectionCardDeckView.tsx b/src/client/views/collections/CollectionCardDeckView.tsx
index b86dad9d7..60305244c 100644
--- a/src/client/views/collections/CollectionCardDeckView.tsx
+++ b/src/client/views/collections/CollectionCardDeckView.tsx
@@ -9,7 +9,7 @@ import { Animation, DocData } from '../../../fields/DocSymbols';
 import { Id } from '../../../fields/FieldSymbols';
 import { List } from '../../../fields/List';
 import { ScriptField } from '../../../fields/ScriptField';
-import { BoolCast, DateCast, DocCast, NumCast, RTFCast, ScriptCast, StrCast } from '../../../fields/Types';
+import { BoolCast, DateCast, DocCast, NumCast, RTFCast, ScriptCast, StrCast, toList } from '../../../fields/Types';
 import { URLField } from '../../../fields/URLField';
 import { gptImageLabel } from '../../apis/gpt/GPT';
 import { DocumentType } from '../../documents/DocumentTypes';
@@ -25,6 +25,9 @@ import { GPTPopup, GPTPopupMode } from '../pdf/GPTPopup/GPTPopup';
 import './CollectionCardDeckView.scss';
 import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView';
 import { FocusViewOptions } from '../nodes/FocusViewOptions';
+import { Docs } from '../../documents/Documents';
+import { PinDocView } from '../PinFuncs';
+import { OpenWhere, OpenWhereMod } from '../nodes/OpenWhere';
 
 enum cardSortings {
     Time = 'time',
@@ -604,6 +607,33 @@ export class CollectionCardView extends CollectionSubView() {
         index !== -1 && (this._curDoc = target);
         return undefined;
     });
+    getAnchor = (addAsAnnotation: boolean) => {
+        const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document });
+        anchor.config_curDoc = this.curDoc();
+        PinDocView(anchor, { pinData: { type_collection: true, filters: true } }, this.Document);
+        if (addAsAnnotation) {
+            // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
+            Doc.AddDocToList(this.dataDoc, this._props.fieldKey + '_annotations', anchor);
+        }
+        return anchor;
+    };
+    // pinned / linked anchor doc includes selected rows, graph titles, and graph colors
+    restoreView = (viewData: Doc) => {
+        if (viewData.config_curDoc !== undefined && this.curDoc() !== viewData.config_curDoc) {
+            this._curDoc = DocCast(viewData.config_curDoc);
+            return true;
+        }
+        return false;
+    };
+    addDocTab = (docsIn: Doc | Doc[], location: OpenWhere) => {
+        const doc = toList(docsIn).lastElement();
+        const where = location.split(':')[0];
+        if (where === OpenWhere.lightbox && (this.childDocList?.includes(doc) || this.childLayoutPairs.map(pair => pair.layout)?.includes(doc))) {
+            if (doc.hidden) doc.hidden = false;
+            if (!location.includes(OpenWhereMod.always)) return true;
+        }
+        return this._props.addDocTab(docsIn, location);
+    };
 
     /**
      * Actually renders all the cards
diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx
index a71cc43ba..2be3ef48f 100644
--- a/src/client/views/collections/CollectionCarousel3DView.tsx
+++ b/src/client/views/collections/CollectionCarousel3DView.tsx
@@ -6,7 +6,7 @@ import { returnZero } from '../../../ClientUtils';
 import { Utils } from '../../../Utils';
 import { Doc, DocListCast, Opt } from '../../../fields/Doc';
 import { Id } from '../../../fields/FieldSymbols';
-import { BoolCast, DocCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
+import { BoolCast, DocCast, NumCast, ScriptCast, StrCast, toList } from '../../../fields/Types';
 import { DocumentType } from '../../documents/DocumentTypes';
 import { DragManager } from '../../util/DragManager';
 import { Transform } from '../../util/Transform';
@@ -16,6 +16,9 @@ import { FocusViewOptions } from '../nodes/FocusViewOptions';
 import './CollectionCarousel3DView.scss';
 import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView';
 import { computedFn } from 'mobx-utils';
+import { Docs } from '../../documents/Documents';
+import { PinDocView } from '../PinFuncs';
+import { OpenWhere, OpenWhereMod } from '../nodes/OpenWhere';
 
 // eslint-disable-next-line @typescript-eslint/no-require-imports
 const { CAROUSEL3D_CENTER_SCALE, CAROUSEL3D_SIDE_SCALE, CAROUSEL3D_TOP } = require('../global/globalCssVariables.module.scss');
@@ -96,6 +99,33 @@ export class CollectionCarousel3DView extends CollectionSubView() {
         index !== -1 && (this.layoutDoc._carousel_index = index);
         return undefined;
     };
+    getAnchor = (addAsAnnotation: boolean) => {
+        const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document });
+        anchor.config_carousel_index = this.layoutDoc._carousel_index;
+        PinDocView(anchor, { pinData: { type_collection: true, filters: true } }, this.Document);
+        if (addAsAnnotation) {
+            // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
+            Doc.AddDocToList(this.dataDoc, this._props.fieldKey + '_annotations', anchor);
+        }
+        return anchor;
+    };
+    // pinned / linked anchor doc includes selected rows, graph titles, and graph colors
+    restoreView = (viewData: Doc) => {
+        if (viewData.config_carousel_index !== undefined && this.layoutDoc._carousel_index !== viewData.config_carousel_index) {
+            this.layoutDoc._carousel_index = viewData.config_carousel_index;
+            return true;
+        }
+        return false;
+    };
+    addDocTab = (docsIn: Doc | Doc[], location: OpenWhere) => {
+        const doc = toList(docsIn).lastElement();
+        const where = location.split(':')[0];
+        if (where === OpenWhere.lightbox && (this.childDocList?.includes(doc) || this.childLayoutPairs.map(pair => pair.layout)?.includes(doc))) {
+            if (doc.hidden) doc.hidden = false;
+            if (!location.includes(OpenWhereMod.always)) return true;
+        }
+        return this._props.addDocTab(docsIn, location);
+    };
 
     @computed get content() {
         const currentIndex = NumCast(this.layoutDoc._carousel_index);
diff --git a/src/client/views/collections/CollectionCarouselView.tsx b/src/client/views/collections/CollectionCarouselView.tsx
index 1f2bc908f..b043706fd 100644
--- a/src/client/views/collections/CollectionCarouselView.tsx
+++ b/src/client/views/collections/CollectionCarouselView.tsx
@@ -3,12 +3,17 @@ import { action, computed, makeObservable, observable } from 'mobx';
 import { observer } from 'mobx-react';
 import * as React from 'react';
 import { StopEvent, returnOne, returnZero } from '../../../ClientUtils';
-import { Doc, Opt } from '../../../fields/Doc';
-import { BoolCast, DocCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
+import { Doc, DocListCast, Opt } from '../../../fields/Doc';
+import { BoolCast, DocCast, NumCast, ScriptCast, StrCast, toList } from '../../../fields/Types';
+import { DocumentType } from '../../documents/DocumentTypes';
+import { Docs } from '../../documents/Documents';
 import { DragManager } from '../../util/DragManager';
+import { PinDocView } from '../PinFuncs';
 import { StyleProp } from '../StyleProp';
 import { DocumentView } from '../nodes/DocumentView';
 import { FieldViewProps } from '../nodes/FieldView';
+import { FocusViewOptions } from '../nodes/FocusViewOptions';
+import { OpenWhere, OpenWhereMod } from '../nodes/OpenWhere';
 import { FormattedTextBox } from '../nodes/formattedText/FormattedTextBox';
 import './CollectionCarouselView.scss';
 import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView';
@@ -27,6 +32,9 @@ export class CollectionCarouselView extends CollectionSubView() {
         makeObservable(this);
     }
 
+    componentDidMount(): void {
+        this._props.setContentViewBox?.(this);
+    }
     componentWillUnmount() {
         this._dropDisposer?.();
     }
@@ -67,6 +75,44 @@ export class CollectionCarouselView extends CollectionSubView() {
 
     curDoc = () => this.carouselItems[this.carouselIndex]?.layout;
 
+    focus = (anchor: Doc, options: FocusViewOptions): Opt<number> => {
+        const docs = DocListCast(this.Document[this.fieldKey ?? Doc.LayoutFieldKey(this.Document)]);
+        if (anchor.type !== DocumentType.CONFIG && !docs.includes(anchor)) return undefined;
+        options.didMove = true;
+        const target = DocCast(anchor.annotationOn) ?? anchor;
+        const index = docs.indexOf(target);
+        index !== -1 && (this.layoutDoc._carousel_index = index);
+        return undefined;
+    };
+
+    getAnchor = (addAsAnnotation: boolean) => {
+        const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document });
+        anchor.config_carousel_index = this.carouselIndex;
+        PinDocView(anchor, { pinData: { type_collection: true, filters: true } }, this.Document);
+        if (addAsAnnotation) {
+            // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
+            Doc.AddDocToList(this.dataDoc, this._props.fieldKey + '_annotations', anchor);
+        }
+        return anchor;
+    };
+    // pinned / linked anchor doc includes selected rows, graph titles, and graph colors
+    restoreView = (viewData: Doc) => {
+        if (viewData.config_carousel_index !== undefined && this.layoutDoc._carousel_index !== viewData.config_carousel_index) {
+            this.layoutDoc._carousel_index = viewData.config_carousel_index;
+            return true;
+        }
+        return false;
+    };
+    addDocTab = (docsIn: Doc | Doc[], location: OpenWhere) => {
+        const doc = toList(docsIn).lastElement();
+        const where = location.split(':')[0];
+        if (where === OpenWhere.lightbox && (this.childDocList?.includes(doc) || this.childLayoutPairs.map(pair => pair.layout)?.includes(doc))) {
+            if (doc.hidden) doc.hidden = false;
+            if (!location.includes(OpenWhereMod.always)) return true;
+        }
+        return this._props.addDocTab(docsIn, location);
+    };
+
     captionStyleProvider = (doc: Doc | undefined, captionProps: Opt<FieldViewProps>, property: string) => {
         // first look for properties on the document in the carousel, then fallback to properties on the container
         const childValue = doc?.['caption_' + property] ? this._props.styleProvider?.(doc, captionProps, property) : undefined;
@@ -113,6 +159,7 @@ export class CollectionCarouselView extends CollectionSubView() {
                 LayoutTemplateString={this._props.childLayoutString}
                 TemplateDataDocument={DocCast(Doc.Layout(doc).resolvedDataDoc)}
                 childFilters={this.childDocFilters}
+                focus={this.focus}
                 hideDecorations={BoolCast(this.layoutDoc.layout_hideDecorations)}
                 addDocument={this._props.addDocument}
                 ScreenToLocalTransform={this.contentScreenToLocalXf}
diff --git a/src/client/views/collections/CollectionStackedTimeline.tsx b/src/client/views/collections/CollectionStackedTimeline.tsx
index 486c826b6..c3047e5fb 100644
--- a/src/client/views/collections/CollectionStackedTimeline.tsx
+++ b/src/client/views/collections/CollectionStackedTimeline.tsx
@@ -1,4 +1,3 @@
-/* eslint-disable react/jsx-props-no-spreading */
 /* eslint-disable no-use-before-define */
 import { action, computed, IReactionDisposer, makeObservable, observable, reaction, runInAction } from 'mobx';
 import { observer } from 'mobx-react';
@@ -59,7 +58,6 @@ export enum TrimScope {
 
 @observer
 export class CollectionStackedTimeline extends CollectionSubView<CollectionStackedTimelineProps>() {
-    // eslint-disable-next-line no-use-before-define
     public static SelectingRegions: Set<CollectionStackedTimeline> = new Set();
     public static StopSelecting() {
         this.SelectingRegions.forEach(
@@ -171,7 +169,7 @@ export class CollectionStackedTimeline extends CollectionSubView<CollectionStack
 
     makeDocUnfiltered = (doc: Doc) => this.childDocList?.some(item => item === doc);
 
-    getView = async (doc: Doc, options: FocusViewOptions): Promise<Opt<DocumentView>> =>
+    getView = (doc: Doc, options: FocusViewOptions): Promise<Opt<DocumentView>> =>
         new Promise<Opt<DocumentView>>(res => {
             if (doc.hidden) options.didMove = !(doc.hidden = false);
             const findDoc = (finish: (dv: DocumentView) => void) => DocumentView.addViewRenderedCb(doc, dv => finish(dv));
@@ -600,7 +598,6 @@ export class CollectionStackedTimeline extends CollectionSubView<CollectionStack
                                         pointerEvents: 'none',
                                     }}>
                                     <StackedTimelineAnchor
-                                        // eslint-disable-next-line react/jsx-props-no-spreading
                                         {...this._props}
                                         mark={d.anchor}
                                         containerViewPath={this._props.containerViewPath}
diff --git a/src/client/views/collections/CollectionTimeView.tsx b/src/client/views/collections/CollectionTimeView.tsx
index 8a24db330..5738e7ce3 100644
--- a/src/client/views/collections/CollectionTimeView.tsx
+++ b/src/client/views/collections/CollectionTimeView.tsx
@@ -147,7 +147,6 @@ export class CollectionTimeView extends CollectionSubView() {
         return (
             <div className="collectionTimeView-innards" key="timeline" style={{ pointerEvents: this._props.isContentActive() ? undefined : 'none' }} onClick={this.contentsDown}>
                 <CollectionFreeFormView
-                    // eslint-disable-next-line react/jsx-props-no-spreading
                     {...this._props}
                     engineProps={{ pivotField: this.pivotField, childFilters: this.childDocFilters, childFiltersByRanges: this.childDocRangeFilters }}
                     fitContentsToBox={returnTrue}
@@ -257,7 +256,6 @@ ScriptingGlobals.add(function pivotColumnClick(pivotDoc: Doc, bounds: ViewDefBou
             const pivotView = DocumentView.getDocumentView(pivotDoc);
             if (pivotDoc && pivotView?.ComponentView instanceof CollectionTimeView && filterVals.length === 1) {
                 if (pivotView?.ComponentView.childDocs.length && pivotView.ComponentView.childDocs[0][filterVals[0]]) {
-                    // eslint-disable-next-line prefer-destructuring
                     pivotDoc._pivotField = filterVals[0];
                 }
             }
diff --git a/src/client/views/collections/FlashcardPracticeUI.tsx b/src/client/views/collections/FlashcardPracticeUI.tsx
index 9e9318c0a..c298bff22 100644
--- a/src/client/views/collections/FlashcardPracticeUI.tsx
+++ b/src/client/views/collections/FlashcardPracticeUI.tsx
@@ -58,7 +58,7 @@ export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProp
     get practiceField() { return this._props.fieldKey + "_practice"; } // prettier-ignore
 
     @computed get filterDoc() { return DocListCast(Doc.MyContextMenuBtns.data).find(doc => doc.title === 'Filter'); } // prettier-ignore
-    @computed get practiceMode() {  return this._props.allChildDocs().some(doc => doc._layout_isFlashcard) ? StrCast(this._props.layoutDoc.practiceMode) : ''; } // prettier-ignore
+    @computed get practiceMode() {  return this._props.allChildDocs().some(doc => doc._flashcardType) ? StrCast(this._props.layoutDoc.practiceMode) : ''; } // prettier-ignore
 
     btnHeight = () => NumCast(this.filterDoc?.height) * Math.min(1, this._props.ScreenToLocalBoxXf().Scale);
     btnWidth = () => (!this.filterDoc ? 1 : (this.btnHeight() * NumCast(this.filterDoc._width)) / NumCast(this.filterDoc._height));
@@ -127,7 +127,7 @@ export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProp
         const setColor = (mode: practiceMode) => (StrCast(this.practiceMode) === mode ? 'white' : 'lightgray');
         const togglePracticeMode = (mode: practiceMode) => this.setPracticeMode(mode === this.practiceMode ? undefined : mode);
 
-        return !this._props.allChildDocs().some(doc => doc._layout_isFlashcard) ? null : (
+        return !this._props.allChildDocs().some(doc => doc._layout_flashcardType) ? null : (
             <div
                 className="FlashcardPracticeUI-practiceModes"
                 style={{
@@ -179,7 +179,7 @@ export class FlashcardPracticeUI extends ObservableReactComponent<PracticeUIProp
             </div>
         );
     }
-    tryFilterOut = (doc: Doc) => (this.practiceMode && BoolCast(doc?._layout_isFlashcard) && doc[this.practiceField] === practiceVal.CORRECT ? true : false); // show only cards that aren't marked as correct
+    tryFilterOut = (doc: Doc) => (this.practiceMode && BoolCast(doc?._flashcardType) && doc[this.practiceField] === practiceVal.CORRECT ? true : false); // show only cards that aren't marked as correct
     render() {
         return (
             <div className="FlashcardPracticeUI">
diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
index d2bc8f2c2..afd662b22 100644
--- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
+++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
@@ -389,7 +389,7 @@ export class CollectionFreeFormView extends CollectionSubView<Partial<collection
         return undefined;
     };
 
-    getView = async (doc: Doc, options: FocusViewOptions): Promise<Opt<DocumentView>> =>
+    getView = (doc: Doc, options: FocusViewOptions): Promise<Opt<DocumentView>> =>
         new Promise<Opt<DocumentView>>(res => {
             if (doc.hidden && this._lightboxDoc !== doc) options.didMove = !(doc.hidden = false);
             if (doc === this.Document) {
diff --git a/src/client/views/nodes/ComparisonBox.tsx b/src/client/views/nodes/ComparisonBox.tsx
index f6c33d6ba..672c189ba 100644
--- a/src/client/views/nodes/ComparisonBox.tsx
+++ b/src/client/views/nodes/ComparisonBox.tsx
@@ -63,8 +63,9 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
      * @param useDoc doc to fill in instead of creating a Doc
      * @returns the resulting flashcard Doc
      */
-    public static createFlashcard(tuple: string, frontKey: string, backKey: string, useDoc?: Doc) {
-        const [ktoken, atoken] = [ComparisonBox.ktoken, ComparisonBox.atoken];
+    public static createFlashcard(tuple3: string, frontKey: string, backKey: string, useDoc?: Doc) {
+        const [qtoken, ktoken, atoken] = [ComparisonBox.qtoken, ComparisonBox.ktoken, ComparisonBox.atoken];
+        const [title, tuple] = tuple3.split(qtoken);
         const question = (tuple.includes(ktoken) ? tuple.split(ktoken)[0] : tuple).split(atoken)[0];
         const rest = tuple.replace(question, '');
         // prettier-ignore
@@ -82,7 +83,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
                 useDoc[DocData][backKey] = back;
                 return useDoc;
             }
-            return Docs.Create.FlashcardDocument('flashcard', front, back, { _width: 300, _height: 300 });
+            return Docs.Create.FlashcardDocument(title, front, back, { _width: 300, _height: 300 });
         };
         return keyword && keyword.toLowerCase() !== 'none' ? ComparisonBox.fetchImages(keyword).then(img => fillInFlashcard(img)) : fillInFlashcard();
     }
@@ -95,12 +96,13 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     public static createFlashcardDeck(text: string, width: number, height: number, front: string, back: string) {
         return Promise.all(
             text
-                .split(ComparisonBox.qtoken)
+                .toLowerCase()
+                .split(ComparisonBox.ttoken)
                 .filter(t => t)
                 .map(tuple => ComparisonBox.createFlashcard(tuple, front, back))
         ).then(docs => {
             return Docs.Create.CarouselDocument(docs, {
-                title: 'flashcard deck',
+                title: text,
                 _width: width,
                 _height: height,
                 _layout_fitWidth: false,
@@ -112,9 +114,10 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
     }
     private SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
 
-    static qtoken = 'Question: ';
-    static ktoken = 'Keyword: ';
-    static atoken = 'Answer: ';
+    static qtoken = 'question: ';
+    static ktoken = 'keyword: ';
+    static atoken = 'answer: ';
+    static ttoken = 'title: ';
     private _slideTiming = 200;
     private _sideBtnWidth = 35;
     private _closeRef = React.createRef<HTMLDivElement>();
@@ -183,7 +186,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>()
 
     @computed get containerDoc()  { return this._props.docViewPath().slice(-2)[0]?.Document; } // prettier-ignore
     @computed get isQuizMode()    { return this.containerDoc?.practiceMode === practiceMode.QUIZ; } // prettier-ignore
-    @computed get isFlashcard()   { return BoolCast(this.Document.layout_isFlashcard); } // prettier-ignore
+    @computed get isFlashcard()   { return StrCast(this.Document.layout_flashcardType); } // prettier-ignore
     @computed get frontKey()      { return this._props.fieldKey + '_front'; } // prettier-ignore
     @computed get backKey()       { return this._props.fieldKey + '_back'; } // prettier-ignore
     @computed get frontText()     { return RTFCast(DocCast(this.dataDoc[this.frontKey]).text)?.Text; } // prettier-ignore
diff --git a/src/client/views/nodes/DataVizBox/DataVizBox.tsx b/src/client/views/nodes/DataVizBox/DataVizBox.tsx
index 896048ab3..d79a37181 100644
--- a/src/client/views/nodes/DataVizBox/DataVizBox.tsx
+++ b/src/client/views/nodes/DataVizBox/DataVizBox.tsx
@@ -323,7 +323,7 @@ export class DataVizBox extends ViewBoxAnnotatableComponent<FieldViewProps>() {
             () => UndoManager.RunInBatch(this.toggleSidebar, 'toggle sidebar')
         );
     };
-    getView = async (doc: Doc, options: FocusViewOptions) => {
+    getView = (doc: Doc, options: FocusViewOptions) => {
         if (this._sidebarRef?.current?.makeDocUnfiltered(doc) && !this.SidebarShown) {
             options.didMove = true;
             this.toggleSidebar();
diff --git a/src/client/views/nodes/MapBox/MapBox.tsx b/src/client/views/nodes/MapBox/MapBox.tsx
index c66f7c726..4a436319b 100644
--- a/src/client/views/nodes/MapBox/MapBox.tsx
+++ b/src/client/views/nodes/MapBox/MapBox.tsx
@@ -428,7 +428,7 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() {
         }
     };
 
-    getView = async (doc: Doc, options: FocusViewOptions) => {
+    getView = (doc: Doc, options: FocusViewOptions) => {
         if (this._sidebarRef?.current?.makeDocUnfiltered(doc) && !this.SidebarShown) {
             this.toggleSidebar();
             options.didMove = true;
diff --git a/src/client/views/nodes/MapboxMapBox/MapboxContainer.tsx b/src/client/views/nodes/MapboxMapBox/MapboxContainer.tsx
index a4557196e..d5d8f8afa 100644
--- a/src/client/views/nodes/MapboxMapBox/MapboxContainer.tsx
+++ b/src/client/views/nodes/MapboxMapBox/MapboxContainer.tsx
@@ -383,7 +383,7 @@ export class MapBoxContainer extends ViewBoxAnnotatableComponent<FieldViewProps>
         }
     };
 
-    getView = async (doc: Doc, options: FocusViewOptions) => {
+    getView = (doc: Doc, options: FocusViewOptions) => {
         if (this._sidebarRef?.current?.makeDocUnfiltered(doc) && !this.SidebarShown) {
             this.toggleSidebar();
             options.didMove = true;
@@ -732,7 +732,6 @@ export class MapBoxContainer extends ViewBoxAnnotatableComponent<FieldViewProps>
                         MapBoxContainer._rerenderDelay = 0;
                     }
                     this._rerenderTimeout = undefined;
-                    // eslint-disable-next-line operator-assignment
                     this.Document[DocCss] = this.Document[DocCss] + 1;
                 }), MapBoxContainer._rerenderDelay);
             return null;
@@ -792,7 +791,6 @@ export class MapBoxContainer extends ViewBoxAnnotatableComponent<FieldViewProps>
                                   .map(pushpin => (
                                       <DocumentView
                                           key={pushpin[Id]}
-                                          // eslint-disable-next-line react/jsx-props-no-spreading
                                           {...this._props}
                                           renderDepth={this._props.renderDepth + 1}
                                           Document={pushpin}
@@ -830,7 +828,6 @@ export class MapBoxContainer extends ViewBoxAnnotatableComponent<FieldViewProps>
                 <div className="mapBox-sidebar" style={{ width: `${this.sidebarWidthPercent}`, backgroundColor: `${this.sidebarColor}` }}>
                     <SidebarAnnos
                         ref={this._sidebarRef}
-                        // eslint-disable-next-line react/jsx-props-no-spreading
                         {...this._props}
                         fieldKey={this.fieldKey}
                         Document={this.Document}
diff --git a/src/client/views/nodes/PDFBox.tsx b/src/client/views/nodes/PDFBox.tsx
index 816d4a3b0..2e4c87d38 100644
--- a/src/client/views/nodes/PDFBox.tsx
+++ b/src/client/views/nodes/PDFBox.tsx
@@ -233,7 +233,7 @@ export class PDFBox extends ViewBoxAnnotatableComponent<FieldViewProps>() {
         return this._pdfViewer?.scrollFocus(anchor, NumCast(anchor.y, NumCast(anchor.config_scrollTop)), options);
     };
 
-    getView = async (doc: Doc, options: FocusViewOptions) => {
+    getView = (doc: Doc, options: FocusViewOptions) => {
         if (this._sidebarRef?.current?.makeDocUnfiltered(doc) && !this.SidebarShown) {
             options.didMove = true;
             this.toggleSidebar(false);
diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
index 29be8d285..2aee7b6b3 100644
--- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx
+++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
@@ -1156,7 +1156,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FormattedTextB
         return anchorDoc ?? this.Document;
     }
 
-    getView = async (doc: Doc, options: FocusViewOptions) => {
+    getView = (doc: Doc, options: FocusViewOptions) => {
         if (DocListCast(this.dataDoc[this.sidebarKey]).find(anno => Doc.AreProtosEqual(doc.layout_unrendered ? DocCast(doc.annotationOn) : doc, anno))) {
             if (!this.SidebarShown) {
                 this.toggleSidebar(false);
-- 
cgit v1.2.3-70-g09d2


From 7b29d9c14cb1ea786e64655b33b245ed14bd2d9e Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Thu, 17 Oct 2024 22:20:45 -0400
Subject: from last

---
 src/client/views/collections/CollectionCarousel3DView.tsx | 3 +++
 1 file changed, 3 insertions(+)

(limited to 'src/client/views/collections/CollectionCarousel3DView.tsx')

diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx
index 2be3ef48f..81e921724 100644
--- a/src/client/views/collections/CollectionCarousel3DView.tsx
+++ b/src/client/views/collections/CollectionCarousel3DView.tsx
@@ -33,6 +33,9 @@ export class CollectionCarousel3DView extends CollectionSubView() {
         makeObservable(this);
     }
 
+    componentDidMount(): void {
+        this._props.setContentViewBox?.(this);
+    }
     componentWillUnmount() {
         this._dropDisposer?.();
     }
-- 
cgit v1.2.3-70-g09d2


From 0728e918e6d075c0eda738b7d2fdbf6095c714ae Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Fri, 18 Oct 2024 00:28:55 -0400
Subject: fixed following links/show document of items in tabs/carousel/card
 view to set options.didMove correctly so that toggleTarget works.

---
 src/client/documents/Documents.ts                  |  2 ++
 .../views/collections/CollectionCardDeckView.tsx   | 42 +++++++++-------------
 .../views/collections/CollectionCarousel3DView.tsx | 40 +++++++--------------
 .../views/collections/CollectionCarouselView.tsx   | 33 ++++++-----------
 src/client/views/collections/CollectionSubView.tsx | 14 +++++++-
 src/client/views/collections/TabDocView.tsx        |  1 +
 .../collectionFreeForm/CollectionFreeFormView.tsx  | 19 ++++------
 src/client/views/nodes/trails/PresBox.tsx          |  3 +-
 src/extensions/ExtensionsTypings.ts                |  8 +++++
 src/extensions/Extensions_Array.ts                 | 10 ++++--
 10 files changed, 78 insertions(+), 94 deletions(-)

(limited to 'src/client/views/collections/CollectionCarousel3DView.tsx')

diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts
index f2e85cf7a..be3b9c3bb 100644
--- a/src/client/documents/Documents.ts
+++ b/src/client/documents/Documents.ts
@@ -372,6 +372,8 @@ export class DocumentOptions {
     config_panX?: NUMt = new NumInfo('panX saved as a view spec', false);
     config_panY?: NUMt = new NumInfo('panY saved as a view spec', false);
     config_zoom?: NUMt = new NumInfo('zoom saved as a view spec', false);
+    config_carousel_index?: NUMt = new NumInfo('saved carousel index', false);
+    config_curDoc?: DOCt = new DocInfo('current doc in a collection view, e.g., cardView');
     config_viewScale?: NUMt = new NumInfo('viewScale saved as a view Spec', false);
     presentation_transition?: NUMt = new NumInfo('the time taken for the transition TO a document', false);
     presentation_duration?: NUMt = new NumInfo('the duration of the slide in presentation view', false);
diff --git a/src/client/views/collections/CollectionCardDeckView.tsx b/src/client/views/collections/CollectionCardDeckView.tsx
index 60305244c..729a1585a 100644
--- a/src/client/views/collections/CollectionCardDeckView.tsx
+++ b/src/client/views/collections/CollectionCardDeckView.tsx
@@ -9,25 +9,24 @@ import { Animation, DocData } from '../../../fields/DocSymbols';
 import { Id } from '../../../fields/FieldSymbols';
 import { List } from '../../../fields/List';
 import { ScriptField } from '../../../fields/ScriptField';
-import { BoolCast, DateCast, DocCast, NumCast, RTFCast, ScriptCast, StrCast, toList } from '../../../fields/Types';
+import { BoolCast, DateCast, DocCast, NumCast, RTFCast, ScriptCast, StrCast } from '../../../fields/Types';
 import { URLField } from '../../../fields/URLField';
 import { gptImageLabel } from '../../apis/gpt/GPT';
 import { DocumentType } from '../../documents/DocumentTypes';
+import { Docs } from '../../documents/Documents';
 import { DragManager } from '../../util/DragManager';
 import { dropActionType } from '../../util/DropActionTypes';
 import { SnappingManager } from '../../util/SnappingManager';
 import { Transform } from '../../util/Transform';
 import { undoable } from '../../util/UndoManager';
+import { PinDocView } from '../PinFuncs';
 import { StyleProp } from '../StyleProp';
 import { TagItem } from '../TagsView';
 import { DocumentView, DocumentViewProps } from '../nodes/DocumentView';
+import { FocusViewOptions } from '../nodes/FocusViewOptions';
 import { GPTPopup, GPTPopupMode } from '../pdf/GPTPopup/GPTPopup';
 import './CollectionCardDeckView.scss';
 import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView';
-import { FocusViewOptions } from '../nodes/FocusViewOptions';
-import { Docs } from '../../documents/Documents';
-import { PinDocView } from '../PinFuncs';
-import { OpenWhere, OpenWhereMod } from '../nodes/OpenWhere';
 
 enum cardSortings {
     Time = 'time',
@@ -599,22 +598,21 @@ export class CollectionCardView extends CollectionSubView() {
     });
 
     focus = action((anchor: Doc, options: FocusViewOptions): Opt<number> => {
-        const docs = DocListCast(this.Document[this.fieldKey ?? Doc.LayoutFieldKey(this.Document)]);
-        if (anchor.type !== DocumentType.CONFIG && !docs.includes(anchor)) return undefined;
-        options.didMove = true;
-        const target = DocCast(anchor.annotationOn) ?? anchor;
-        const index = docs.indexOf(target);
-        index !== -1 && (this._curDoc = target);
+        const docs = DocListCast(this.Document[this.fieldKey]);
+        if (anchor.type === DocumentType.CONFIG || docs.includes(anchor)) {
+            const foundDoc = DocCast(
+                anchor.config_curDoc,
+                docs.find(doc => doc === DocCast(anchor.annotationOn, anchor))
+            );
+            options.didMove = foundDoc !== this.curDoc() ? true : false;
+            options.didMove && (this._curDoc = foundDoc);
+        }
         return undefined;
     });
     getAnchor = (addAsAnnotation: boolean) => {
-        const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document });
-        anchor.config_curDoc = this.curDoc();
+        const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document, config_curDoc: this.curDoc() });
         PinDocView(anchor, { pinData: { type_collection: true, filters: true } }, this.Document);
-        if (addAsAnnotation) {
-            // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
-            Doc.AddDocToList(this.dataDoc, this._props.fieldKey + '_annotations', anchor);
-        }
+        addAsAnnotation && Doc.AddDocToList(this.dataDoc, this.fieldKey + '_annotations', anchor); // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
         return anchor;
     };
     // pinned / linked anchor doc includes selected rows, graph titles, and graph colors
@@ -625,15 +623,7 @@ export class CollectionCardView extends CollectionSubView() {
         }
         return false;
     };
-    addDocTab = (docsIn: Doc | Doc[], location: OpenWhere) => {
-        const doc = toList(docsIn).lastElement();
-        const where = location.split(':')[0];
-        if (where === OpenWhere.lightbox && (this.childDocList?.includes(doc) || this.childLayoutPairs.map(pair => pair.layout)?.includes(doc))) {
-            if (doc.hidden) doc.hidden = false;
-            if (!location.includes(OpenWhereMod.always)) return true;
-        }
-        return this._props.addDocTab(docsIn, location);
-    };
+    addDocTab = this.addLinkedDocTab;
 
     /**
      * Actually renders all the cards
diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx
index 81e921724..081e2fe5a 100644
--- a/src/client/views/collections/CollectionCarousel3DView.tsx
+++ b/src/client/views/collections/CollectionCarousel3DView.tsx
@@ -1,24 +1,23 @@
 import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
 import { computed, makeObservable } from 'mobx';
 import { observer } from 'mobx-react';
+import { computedFn } from 'mobx-utils';
 import * as React from 'react';
 import { returnZero } from '../../../ClientUtils';
 import { Utils } from '../../../Utils';
 import { Doc, DocListCast, Opt } from '../../../fields/Doc';
 import { Id } from '../../../fields/FieldSymbols';
-import { BoolCast, DocCast, NumCast, ScriptCast, StrCast, toList } from '../../../fields/Types';
+import { BoolCast, DocCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
 import { DocumentType } from '../../documents/DocumentTypes';
+import { Docs } from '../../documents/Documents';
 import { DragManager } from '../../util/DragManager';
 import { Transform } from '../../util/Transform';
+import { PinDocView } from '../PinFuncs';
 import { StyleProp } from '../StyleProp';
 import { DocumentView } from '../nodes/DocumentView';
 import { FocusViewOptions } from '../nodes/FocusViewOptions';
 import './CollectionCarousel3DView.scss';
 import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView';
-import { computedFn } from 'mobx-utils';
-import { Docs } from '../../documents/Documents';
-import { PinDocView } from '../PinFuncs';
-import { OpenWhere, OpenWhereMod } from '../nodes/OpenWhere';
 
 // eslint-disable-next-line @typescript-eslint/no-require-imports
 const { CAROUSEL3D_CENTER_SCALE, CAROUSEL3D_SIDE_SCALE, CAROUSEL3D_TOP } = require('../global/globalCssVariables.module.scss');
@@ -94,22 +93,18 @@ export class CollectionCarousel3DView extends CollectionSubView() {
             .scale(1 / this.centerScale);
 
     focus = (anchor: Doc, options: FocusViewOptions): Opt<number> => {
-        const docs = DocListCast(this.Document[this.fieldKey ?? Doc.LayoutFieldKey(this.Document)]);
-        if (anchor.type !== DocumentType.CONFIG && !docs.includes(anchor)) return undefined;
-        options.didMove = true;
-        const target = DocCast(anchor.annotationOn) ?? anchor;
-        const index = docs.indexOf(target);
-        index !== -1 && (this.layoutDoc._carousel_index = index);
+        const docs = DocListCast(this.Document[this.fieldKey]);
+        if (anchor.type === DocumentType.CONFIG || docs.includes(anchor)) {
+            const newIndex = anchor.config_carousel_index ?? docs.getIndex(DocCast(anchor.annotationOn, anchor));
+            options.didMove = newIndex !== this.layoutDoc._carousel_index;
+            options.didMove && (this.layoutDoc._carousel_index = newIndex);
+        }
         return undefined;
     };
     getAnchor = (addAsAnnotation: boolean) => {
-        const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document });
-        anchor.config_carousel_index = this.layoutDoc._carousel_index;
+        const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document, config_carousel_index: this.layoutDoc._carousel_index as number });
         PinDocView(anchor, { pinData: { type_collection: true, filters: true } }, this.Document);
-        if (addAsAnnotation) {
-            // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
-            Doc.AddDocToList(this.dataDoc, this._props.fieldKey + '_annotations', anchor);
-        }
+        addAsAnnotation && Doc.AddDocToList(this.dataDoc, this.fieldKey + '_annotations', anchor); // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
         return anchor;
     };
     // pinned / linked anchor doc includes selected rows, graph titles, and graph colors
@@ -120,16 +115,7 @@ export class CollectionCarousel3DView extends CollectionSubView() {
         }
         return false;
     };
-    addDocTab = (docsIn: Doc | Doc[], location: OpenWhere) => {
-        const doc = toList(docsIn).lastElement();
-        const where = location.split(':')[0];
-        if (where === OpenWhere.lightbox && (this.childDocList?.includes(doc) || this.childLayoutPairs.map(pair => pair.layout)?.includes(doc))) {
-            if (doc.hidden) doc.hidden = false;
-            if (!location.includes(OpenWhereMod.always)) return true;
-        }
-        return this._props.addDocTab(docsIn, location);
-    };
-
+    addDocTab = this.addLinkedDocTab;
     @computed get content() {
         const currentIndex = NumCast(this.layoutDoc._carousel_index);
         const displayDoc = (child: Doc, dxf: () => Transform) => (
diff --git a/src/client/views/collections/CollectionCarouselView.tsx b/src/client/views/collections/CollectionCarouselView.tsx
index b043706fd..bfb58733d 100644
--- a/src/client/views/collections/CollectionCarouselView.tsx
+++ b/src/client/views/collections/CollectionCarouselView.tsx
@@ -4,7 +4,7 @@ import { observer } from 'mobx-react';
 import * as React from 'react';
 import { StopEvent, returnOne, returnZero } from '../../../ClientUtils';
 import { Doc, DocListCast, Opt } from '../../../fields/Doc';
-import { BoolCast, DocCast, NumCast, ScriptCast, StrCast, toList } from '../../../fields/Types';
+import { BoolCast, DocCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
 import { DocumentType } from '../../documents/DocumentTypes';
 import { Docs } from '../../documents/Documents';
 import { DragManager } from '../../util/DragManager';
@@ -13,7 +13,6 @@ import { StyleProp } from '../StyleProp';
 import { DocumentView } from '../nodes/DocumentView';
 import { FieldViewProps } from '../nodes/FieldView';
 import { FocusViewOptions } from '../nodes/FocusViewOptions';
-import { OpenWhere, OpenWhereMod } from '../nodes/OpenWhere';
 import { FormattedTextBox } from '../nodes/formattedText/FormattedTextBox';
 import './CollectionCarouselView.scss';
 import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView';
@@ -76,23 +75,19 @@ export class CollectionCarouselView extends CollectionSubView() {
     curDoc = () => this.carouselItems[this.carouselIndex]?.layout;
 
     focus = (anchor: Doc, options: FocusViewOptions): Opt<number> => {
-        const docs = DocListCast(this.Document[this.fieldKey ?? Doc.LayoutFieldKey(this.Document)]);
-        if (anchor.type !== DocumentType.CONFIG && !docs.includes(anchor)) return undefined;
-        options.didMove = true;
-        const target = DocCast(anchor.annotationOn) ?? anchor;
-        const index = docs.indexOf(target);
-        index !== -1 && (this.layoutDoc._carousel_index = index);
+        const docs = DocListCast(this.Document[this.fieldKey]);
+        if (anchor.type === DocumentType.CONFIG || docs.includes(anchor)) {
+            const newIndex = anchor.config_carousel_index ?? docs.getIndex(DocCast(anchor.annotationOn, anchor));
+            options.didMove = newIndex !== this.layoutDoc._carousel_index;
+            options.didMove && (this.layoutDoc._carousel_index = newIndex);
+        }
         return undefined;
     };
 
     getAnchor = (addAsAnnotation: boolean) => {
-        const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document });
-        anchor.config_carousel_index = this.carouselIndex;
+        const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document, config_carousel_index: this.carouselIndex });
         PinDocView(anchor, { pinData: { type_collection: true, filters: true } }, this.Document);
-        if (addAsAnnotation) {
-            // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
-            Doc.AddDocToList(this.dataDoc, this._props.fieldKey + '_annotations', anchor);
-        }
+        addAsAnnotation && Doc.AddDocToList(this.dataDoc, this.fieldKey + '_annotations', anchor); // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
         return anchor;
     };
     // pinned / linked anchor doc includes selected rows, graph titles, and graph colors
@@ -103,15 +98,7 @@ export class CollectionCarouselView extends CollectionSubView() {
         }
         return false;
     };
-    addDocTab = (docsIn: Doc | Doc[], location: OpenWhere) => {
-        const doc = toList(docsIn).lastElement();
-        const where = location.split(':')[0];
-        if (where === OpenWhere.lightbox && (this.childDocList?.includes(doc) || this.childLayoutPairs.map(pair => pair.layout)?.includes(doc))) {
-            if (doc.hidden) doc.hidden = false;
-            if (!location.includes(OpenWhereMod.always)) return true;
-        }
-        return this._props.addDocTab(docsIn, location);
-    };
+    addDocTab = this.addLinkedDocTab;
 
     captionStyleProvider = (doc: Doc | undefined, captionProps: Opt<FieldViewProps>, property: string) => {
         // first look for properties on the document in the carousel, then fallback to properties on the container
diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx
index 48aac3a68..9952863d7 100644
--- a/src/client/views/collections/CollectionSubView.tsx
+++ b/src/client/views/collections/CollectionSubView.tsx
@@ -9,7 +9,7 @@ import { Id } from '../../../fields/FieldSymbols';
 import { List } from '../../../fields/List';
 import { listSpec } from '../../../fields/Schema';
 import { ScriptField } from '../../../fields/ScriptField';
-import { BoolCast, Cast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
+import { BoolCast, Cast, NumCast, ScriptCast, StrCast, toList } from '../../../fields/Types';
 import { WebField } from '../../../fields/URLField';
 import { GetEffectiveAcl, TraceMobx } from '../../../fields/util';
 import { GestureUtils } from '../../../pen-gestures/GestureUtils';
@@ -27,6 +27,7 @@ import { ViewBoxBaseComponent } from '../DocComponent';
 import { FieldViewProps } from '../nodes/FieldView';
 import { DocumentView, DocumentViewProps } from '../nodes/DocumentView';
 import { FlashcardPracticeUI } from './FlashcardPracticeUI';
+import { OpenWhere, OpenWhereMod } from '../nodes/OpenWhere';
 
 export interface CollectionViewProps extends React.PropsWithChildren<FieldViewProps> {
     isAnnotationOverlay?: boolean; // is the collection an annotation overlay (eg an overlay on an image/video/etc)
@@ -130,6 +131,17 @@ export function CollectionSubView<X>() {
         @computed get childDocList() {
             return Cast(this.dataField, listSpec(Doc));
         }
+
+        addLinkedDocTab = (docsIn: Doc | Doc[], location: OpenWhere) => {
+            const doc = toList(docsIn).lastElement();
+            const where = location.split(':')[0];
+            if (where === OpenWhere.lightbox && (this.childDocList?.includes(doc) || this.childLayoutPairs.map(pair => pair.layout)?.includes(doc))) {
+                if (doc.hidden) doc.hidden = false;
+                if (!location.includes(OpenWhereMod.always)) return true;
+            }
+            return this._props.addDocTab(docsIn, location);
+        };
+
         collectionFilters = () => this._focusFilters ?? StrListCast(this.Document._childFilters);
         collectionRangeDocFilters = () => this._focusRangeFilters ?? Cast(this.Document._childFiltersByRanges, listSpec('string'), []);
         // child filters apply to the descendants of the documents in this collection
diff --git a/src/client/views/collections/TabDocView.tsx b/src/client/views/collections/TabDocView.tsx
index 5bfdee1f5..1c5722217 100644
--- a/src/client/views/collections/TabDocView.tsx
+++ b/src/client/views/collections/TabDocView.tsx
@@ -285,6 +285,7 @@ export class TabDocView extends ObservableReactComponent<TabDocViewProps> {
 
     static Activate = (tabDoc: Doc) => {
         const tab = Array.from(CollectionDockingView.Instance?.tabMap ?? []).find(findTab => findTab.DashDoc === tabDoc && !findTab.contentItem.config.props.keyValue);
+        if (tab.header.parent._activeContentItem === tab.contentItem) return false;
         tab?.header.parent.setActiveContentItem(tab.contentItem); // glr: Panning does not work when this is set - (this line is for trying to make a tab that is not topmost become topmost)
         return tab !== undefined;
     };
diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
index afd662b22..0241fc2dd 100644
--- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
+++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
@@ -40,7 +40,7 @@ import { ActiveArrowEnd, ActiveArrowStart, ActiveDash, ActiveEraserWidth, Active
 import { FieldViewProps } from '../../nodes/FieldView';
 import { FocusViewOptions } from '../../nodes/FocusViewOptions';
 import { FormattedTextBox } from '../../nodes/formattedText/FormattedTextBox';
-import { OpenWhere, OpenWhereMod } from '../../nodes/OpenWhere';
+import { OpenWhere } from '../../nodes/OpenWhere';
 import { PinDocView, PinProps } from '../../PinFuncs';
 import { AnnotationPalette } from '../../smartdraw/AnnotationPalette';
 import { DrawingOptions, SmartDrawHandler } from '../../smartdraw/SmartDrawHandler';
@@ -1596,21 +1596,14 @@ export class CollectionFreeFormView extends CollectionSubView<Partial<collection
             }
             case undefined:
             case OpenWhere.lightbox:
-                {
-                    const firstDoc = docs[0];
-                    if (this.layoutDoc._isLightbox) {
-                        this._lightboxDoc = firstDoc;
-                        return true;
-                    }
-                    if (firstDoc === this.Document || this.childDocList?.includes(firstDoc) || this.childLayoutPairs.map(pair => pair.layout)?.includes(firstDoc)) {
-                        if (firstDoc.hidden) firstDoc.hidden = false;
-                        if (!location.includes(OpenWhereMod.always)) return true;
-                    }
+                if (this.layoutDoc._isLightbox) {
+                    this._lightboxDoc = docs[0];
+                    return true;
                 }
-                break;
+                return this.addLinkedDocTab(docsIn, location);
             default:
         }
-        return this._props.addDocTab(docs, location);
+        return this._props.addDocTab(docsIn, location);
     });
     getCalculatedPositions(pair: { layout: Doc; data?: Doc }): PoolData {
         const random = (min: number, max: number, x: number, y: number) => /* min should not be equal to max */ min + (((Math.abs(x * y) * 9301 + 49297) % 233280) / 233280) * (max - min);
diff --git a/src/client/views/nodes/trails/PresBox.tsx b/src/client/views/nodes/trails/PresBox.tsx
index 7448fa898..53d72e946 100644
--- a/src/client/views/nodes/trails/PresBox.tsx
+++ b/src/client/views/nodes/trails/PresBox.tsx
@@ -48,6 +48,7 @@ import './PresBox.scss';
 import { PresEffect, PresEffectDirection, PresMovement, PresStatus } from './PresEnums';
 import SlideEffect from './SlideEffect';
 import { AnimationSettings, SpringSettings, SpringType, easeItems, effectItems, effectTimings, movementItems, presEffectDefaultTimings, springMappings, springPreviewColors } from './SpringUtils';
+import _ from 'lodash';
 
 @observer
 export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
@@ -708,7 +709,7 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
         }
 
         if ((pinDataTypes?.filters && activeItem.config_docFilters !== undefined) || (!pinDataTypes && activeItem.config_docFilters !== undefined)) {
-            if (bestTarget.childFilters !== activeItem.config_docFilters) {
+            if (!_.isEqual(Array.from(StrListCast(bestTarget.childFilters)), Array.from(StrListCast(activeItem.config_docFilters)))) {
                 bestTarget.childFilters = ObjectField.MakeCopy(activeItem.config_docFilters as ObjectField) || new List<string>([]);
                 changed = true;
             }
diff --git a/src/extensions/ExtensionsTypings.ts b/src/extensions/ExtensionsTypings.ts
index d6ffd3be3..fa8851bb3 100644
--- a/src/extensions/ExtensionsTypings.ts
+++ b/src/extensions/ExtensionsTypings.ts
@@ -1,6 +1,14 @@
 /* eslint-disable @typescript-eslint/no-unused-vars */
 interface Array<T> {
+    /**
+     * returns the last element of the array or undefined
+     */
     lastElement(): T;
+    /**
+     * if val is in the list, it returns its index, otherwise undefined;
+     * @param val
+     */
+    getIndex(val: T): number | undefined;
 }
 
 interface String {
diff --git a/src/extensions/Extensions_Array.ts b/src/extensions/Extensions_Array.ts
index a50fb330f..d61585e28 100644
--- a/src/extensions/Extensions_Array.ts
+++ b/src/extensions/Extensions_Array.ts
@@ -1,14 +1,13 @@
 export default class ArrayExtension {
     private readonly property: string;
-    private readonly body: <T>(this: Array<T>) => any;
+    private readonly body: <T>(this: Array<T>, args: unknown) => unknown;
 
-    constructor(property: string, body: <T>(this: Array<T>) => any) {
+    constructor(property: string, body: <T>(this: Array<T>, args: unknown) => unknown) {
         this.property = property;
         this.body = body;
     }
 
     assign() {
-        // eslint-disable-next-line no-extend-native
         Object.defineProperty(Array.prototype, this.property, {
             value: this.body,
             enumerable: false,
@@ -28,6 +27,11 @@ const extensions = [
         }
         return this[this.length - 1];
     }),
+    // eslint-disable-next-line @typescript-eslint/no-explicit-any
+    new ArrayExtension('getIndex', function (val: any) {
+        const index = this.indexOf(val);
+        return index === -1 ? undefined : index;
+    }),
 ];
 
 function Assign() {
-- 
cgit v1.2.3-70-g09d2


From 6d5b80adf8c0d1f93dce30401e1f90d11b838de3 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Fri, 18 Oct 2024 10:00:01 -0400
Subject: fixed following anchors to collection card/carousel to set the
 current/selected Doc

---
 src/client/documents/Documents.ts                  |  2 +-
 src/client/views/PinFuncs.ts                       |  6 +--
 src/client/views/ViewBoxInterface.ts               |  2 +-
 .../views/collections/CollectionCardDeckView.tsx   | 55 +++++++++-------------
 .../views/collections/CollectionCarousel3DView.tsx | 10 +---
 .../views/collections/CollectionCarouselView.tsx   | 10 +---
 .../views/collections/CollectionTimeView.tsx       |  2 +-
 .../collectionFreeForm/CollectionFreeFormView.tsx  |  2 +-
 src/client/views/nodes/trails/PresBox.tsx          | 36 +++++++-------
 src/fields/ScriptField.ts                          |  6 +--
 10 files changed, 53 insertions(+), 78 deletions(-)

(limited to 'src/client/views/collections/CollectionCarousel3DView.tsx')

diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts
index be3b9c3bb..98e8bc932 100644
--- a/src/client/documents/Documents.ts
+++ b/src/client/documents/Documents.ts
@@ -373,7 +373,7 @@ export class DocumentOptions {
     config_panY?: NUMt = new NumInfo('panY saved as a view spec', false);
     config_zoom?: NUMt = new NumInfo('zoom saved as a view spec', false);
     config_carousel_index?: NUMt = new NumInfo('saved carousel index', false);
-    config_curDoc?: DOCt = new DocInfo('current doc in a collection view, e.g., cardView');
+    config_card_curDoc?: DOCt = new DocInfo('current doc in a collection view, e.g., cardView');
     config_viewScale?: NUMt = new NumInfo('viewScale saved as a view Spec', false);
     presentation_transition?: NUMt = new NumInfo('the time taken for the transition TO a document', false);
     presentation_duration?: NUMt = new NumInfo('the duration of the slide in presentation view', false);
diff --git a/src/client/views/PinFuncs.ts b/src/client/views/PinFuncs.ts
index 17964c656..bed473eec 100644
--- a/src/client/views/PinFuncs.ts
+++ b/src/client/views/PinFuncs.ts
@@ -16,7 +16,7 @@ export interface pinDataTypes {
     scrollable?: boolean;
     dataviz?: number[];
     pannable?: boolean;
-    type_collection?: boolean;
+    collectionType?: boolean;
     inkable?: boolean;
     filters?: boolean;
     pivot?: boolean;
@@ -65,7 +65,7 @@ export function PinDocView(pinDocIn: Doc, pinProps: PinProps, targetDoc: Doc) {
             pinProps.pinData.scrollable ||
             pinProps.pinData.temporal ||
             pinProps.pinData.pannable ||
-            pinProps.pinData.type_collection ||
+            pinProps.pinData.collectionType ||
             pinProps.pinData.clippable ||
             pinProps.pinData.datarange ||
             pinProps.pinData.dataview ||
@@ -118,7 +118,7 @@ export function PinDocView(pinDocIn: Doc, pinProps: PinProps, targetDoc: Doc) {
                     })
                 )
             );
-        if (pinProps.pinData.type_collection) pinDoc.config_type_collection = targetDoc._type_collection;
+        if (pinProps.pinData.collectionType) pinDoc.config_type_collection = targetDoc._type_collection;
         if (pinProps.pinData.filters) pinDoc.config_docFilters = ObjectField.MakeCopy(targetDoc.childFilters as ObjectField) ?? new List<string>();
         if (pinProps.pinData.pivot) pinDoc.config_pivotField = targetDoc._pivotField;
         if (pinProps.pinData.pannable) {
diff --git a/src/client/views/ViewBoxInterface.ts b/src/client/views/ViewBoxInterface.ts
index f66f6062e..b7980d74e 100644
--- a/src/client/views/ViewBoxInterface.ts
+++ b/src/client/views/ViewBoxInterface.ts
@@ -24,7 +24,7 @@ export abstract class ViewBoxInterface<P> extends ObservableReactComponent<React
     promoteCollection?: () => void; // moves contents of collection to parent
     updateIcon?: (usePanelDimensions?: boolean) => Promise<void>; // updates the icon representation of the document
     getAnchor?: (addAsAnnotation: boolean, pinData?: PinProps) => Doc; // returns an Anchor Doc that represents the current state of the doc's componentview (e.g., the current playhead location of a an audio/video box)
-    restoreView?: (viewSpec: Doc) => boolean;
+    restoreView?: (viewSpec: Doc) => boolean; // DEPRECATED: do not use, it will go away.  see PresBox.restoreTargetDocView
     scrollPreview?: (docView: DocumentView, doc: Doc, focusSpeed: number, options: FocusViewOptions) => Opt<number>; // returns the duration of the focus
     brushView?: (view: { width: number; height: number; panX: number; panY: number }, transTime: number, holdTime: number) => void; // highlight a region of a view (used by freeforms)
     getView?: (doc: Doc, options: FocusViewOptions) => Promise<Opt<DocumentView>>; // returns a nested DocumentView for the specified doc or undefined
diff --git a/src/client/views/collections/CollectionCardDeckView.tsx b/src/client/views/collections/CollectionCardDeckView.tsx
index 729a1585a..beb45f326 100644
--- a/src/client/views/collections/CollectionCardDeckView.tsx
+++ b/src/client/views/collections/CollectionCardDeckView.tsx
@@ -51,14 +51,13 @@ export class CollectionCardView extends CollectionSubView() {
     private _textToDoc = new Map<string, Doc>();
     private _oldWheel: HTMLElement | null = null;
     private _dropped = false; // set when a card doc has just moved and the drop method has been called - prevents the pointerUp method from hiding doc decorations (which needs to be done when clicking on a card to animate it to front/center)
-    private _clickScript = () => ScriptField.MakeScript('scriptContext._curDoc=this', { scriptContext: 'any' })!;
+    private _setCurDocScript = () => ScriptField.MakeScript('scriptContext.layoutDoc._card_curDoc=this', { scriptContext: 'any' })!;
 
     @observable _forceChildXf = 0;
     @observable _hoveredNodeIndex = -1;
     @observable _docRefs = new ObservableMap<Doc, DocumentView>();
     @observable _maxRowCount = 10;
     @observable _docDraggedIndex: number = -1;
-    @observable _curDoc: Doc | undefined = undefined;
 
     constructor(props: SubCollectionViewProps) {
         super(props);
@@ -165,10 +164,10 @@ export class CollectionCardView extends CollectionSubView() {
     /**
      * When in quiz mode, randomly selects a document
      */
-    quizMode = action(() => {
+    quizMode = () => {
         const randomIndex = Math.floor(Math.random() * this.childDocs.length);
-        this._curDoc = this.childDocs[randomIndex];
-    });
+        this.layoutDoc._card_curDoc = this.childDocs[randomIndex];
+    };
 
     setHoveredNodeIndex = action((index: number) => {
         if (!SnappingManager.IsDragging) this._hoveredNodeIndex = index;
@@ -319,7 +318,7 @@ export class CollectionCardView extends CollectionSubView() {
         (doc: Doc) => () =>
             this._props.isContentActive?.() === false
                 ? false
-                : this._props.isDocumentActive?.() && this._curDoc === doc
+                : this._props.isDocumentActive?.() && this.curDoc() === doc
                   ? true
                   : this._props.childDocumentsActive?.() === false || this.Document.childDocumentsActive === false
                     ? false
@@ -347,7 +346,7 @@ export class CollectionCardView extends CollectionSubView() {
             scriptContext={this}
             focus={this.focus}
             onDoubleClickScript={this.onChildDoubleClick}
-            onClickScript={this._curDoc === doc ? undefined : this._clickScript}
+            onClickScript={this.curDoc() === doc ? undefined : this._setCurDocScript}
             dontCenter="y" // Don't center it vertically, because the grid it's in is already doing that and we don't want to do it twice.
             dragAction={(this.Document.childDragAction ?? this._props.childDragAction) as dropActionType}
             showTags={BoolCast(this.layoutDoc.showChildTags)}
@@ -572,8 +571,8 @@ export class CollectionCardView extends CollectionSubView() {
      * @param doc doc that will be animated away from center focus
      */
     releaseCurDoc = action(() => {
-        const selDoc = this._curDoc;
-        this._curDoc = undefined;
+        const selDoc = this.curDoc();
+        this.layoutDoc._card_curDoc = undefined;
         const cardDocView = DocumentView.getDocumentView(selDoc, this.DocumentView?.());
         if (cardDocView && selDoc) {
             DocumentView.DeselectView(cardDocView);
@@ -590,7 +589,7 @@ export class CollectionCardView extends CollectionSubView() {
      * turns off the _dropped flag at the end of a drag/drop, or releases the focused Doc if a different Doc is clicked
      */
     cardPointerUp = action((doc: Doc) => {
-        if (this._curDoc === doc || this._dropped) {
+        if (this.curDoc() === doc || this._dropped) {
             this._dropped = false;
         } else {
             this.releaseCurDoc(); // NOTE: the onClick script for the card will select the new card (ie, 'doc')
@@ -601,28 +600,20 @@ export class CollectionCardView extends CollectionSubView() {
         const docs = DocListCast(this.Document[this.fieldKey]);
         if (anchor.type === DocumentType.CONFIG || docs.includes(anchor)) {
             const foundDoc = DocCast(
-                anchor.config_curDoc,
+                anchor.config_card_curDoc,
                 docs.find(doc => doc === DocCast(anchor.annotationOn, anchor))
             );
             options.didMove = foundDoc !== this.curDoc() ? true : false;
-            options.didMove && (this._curDoc = foundDoc);
+            options.didMove && (this.layoutDoc._card_curDoc = foundDoc);
         }
         return undefined;
     });
     getAnchor = (addAsAnnotation: boolean) => {
-        const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document, config_curDoc: this.curDoc() });
-        PinDocView(anchor, { pinData: { type_collection: true, filters: true } }, this.Document);
+        const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document, config_card_curDoc: this.curDoc() });
+        PinDocView(anchor, { pinData: { collectionType: true, filters: true } }, this.Document);
         addAsAnnotation && Doc.AddDocToList(this.dataDoc, this.fieldKey + '_annotations', anchor); // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
         return anchor;
     };
-    // pinned / linked anchor doc includes selected rows, graph titles, and graph colors
-    restoreView = (viewData: Doc) => {
-        if (viewData.config_curDoc !== undefined && this.curDoc() !== viewData.config_curDoc) {
-            this._curDoc = DocCast(viewData.config_curDoc);
-            return true;
-        }
-        return false;
-    };
     addDocTab = this.addLinkedDocTab;
 
     /**
@@ -634,9 +625,9 @@ export class CollectionCardView extends CollectionSubView() {
         return this.sortedDocs.map((doc, index) => {
             const cardsInRow = this.cardsInRowThatIncludesCardIndex(index);
 
-            const childScreenToLocal = this.childScreenToLocal(doc, index, doc === this._curDoc);
+            const childScreenToLocal = this.childScreenToLocal(doc, index, doc === this.curDoc());
 
-            const translateToCenterIfActive = () => (doc === this._curDoc ? (cardsInRow / 2 - (index % this._maxRowCount)) * 100 - 50 : 0);
+            const translateToCenterIfActive = () => (doc === this.curDoc() ? (cardsInRow / 2 - (index % this._maxRowCount)) * 100 - 50 : 0);
 
             const aspect = NumCast(doc.height) / NumCast(doc.width, 1);
             const vscale = Math.max(1,Math.min((this._props.PanelHeight() * 0.95 * this.fitContentScale * this.nativeScaling) / (aspect * this.childPanelWidth()), 
@@ -645,15 +636,15 @@ export class CollectionCardView extends CollectionSubView() {
             return (
                 <div
                     key={doc[Id]}
-                    className={`card-item${doc === this._curDoc ? '-active' : this.isAnyChildContentActive() ? '-inactive' : ''}`}
+                    className={`card-item${doc === this.curDoc() ? '-active' : this.isAnyChildContentActive() ? '-inactive' : ''}`}
                     onPointerUp={() => this.cardPointerUp(doc)}
                     style={{
                         width: this.childPanelWidth(),
                         height: 'max-content',
-                        transform: `translateY(${this.adjustCardYtoFitArch(doc === this._curDoc, index)}px)
+                        transform: `translateY(${this.adjustCardYtoFitArch(doc === this.curDoc(), index)}px)
                                     translateX(calc(${translateToCenterIfActive()}% + ${this.horizontalAdjustmentForPartialRows(index, cardsInRow)}px))
-                                    rotate(${doc !== this._curDoc ? this.rotate(index) : 0}rad)
-                                    scale(${doc === this._curDoc ? `${Math.min(hscale, vscale) * 100}%` : this._hoveredNodeIndex === index ? 1.1 : 1})`,
+                                    rotate(${doc !== this.curDoc()? this.rotate(index) : 0}rad)
+                                    scale(${doc === this.curDoc()? `${Math.min(hscale, vscale) * 100}%` : this._hoveredNodeIndex === index ? 1.1 : 1})`,
                     }} // prettier-ignore
                     onPointerEnter={() => this.setHoveredNodeIndex(index)}
                     onPointerLeave={() => this.setHoveredNodeIndex(-1)}>
@@ -671,10 +662,10 @@ export class CollectionCardView extends CollectionSubView() {
         isContentActive: emptyFunction,
         ScreenToLocalTransform: this.contentScreenToLocalXf,
     });
-    answered = action(() => {
-        this._curDoc = this.curDoc ? this.filteredChildDocs()[(this.filteredChildDocs().findIndex(d => d === this.curDoc()) + 1) % (this.filteredChildDocs().length || 1)] : undefined;
-    });
-    curDoc = () => this._curDoc;
+    answered = () => {
+        this.layoutDoc._card_curDoc = this.curDoc() ? this.filteredChildDocs()[(this.filteredChildDocs().findIndex(d => d === this.curDoc()) + 1) % (this.filteredChildDocs().length || 1)] : undefined;
+    };
+    curDoc = () => DocCast(this.layoutDoc._card_curDoc);
 
     render() {
         const fitContentScale = this.childCards.length === 0 ? 1 : this.fitContentScale;
diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx
index 081e2fe5a..61a74dd7a 100644
--- a/src/client/views/collections/CollectionCarousel3DView.tsx
+++ b/src/client/views/collections/CollectionCarousel3DView.tsx
@@ -103,18 +103,10 @@ export class CollectionCarousel3DView extends CollectionSubView() {
     };
     getAnchor = (addAsAnnotation: boolean) => {
         const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document, config_carousel_index: this.layoutDoc._carousel_index as number });
-        PinDocView(anchor, { pinData: { type_collection: true, filters: true } }, this.Document);
+        PinDocView(anchor, { pinData: { collectionType: true, filters: true } }, this.Document);
         addAsAnnotation && Doc.AddDocToList(this.dataDoc, this.fieldKey + '_annotations', anchor); // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
         return anchor;
     };
-    // pinned / linked anchor doc includes selected rows, graph titles, and graph colors
-    restoreView = (viewData: Doc) => {
-        if (viewData.config_carousel_index !== undefined && this.layoutDoc._carousel_index !== viewData.config_carousel_index) {
-            this.layoutDoc._carousel_index = viewData.config_carousel_index;
-            return true;
-        }
-        return false;
-    };
     addDocTab = this.addLinkedDocTab;
     @computed get content() {
         const currentIndex = NumCast(this.layoutDoc._carousel_index);
diff --git a/src/client/views/collections/CollectionCarouselView.tsx b/src/client/views/collections/CollectionCarouselView.tsx
index bfb58733d..f714e2a00 100644
--- a/src/client/views/collections/CollectionCarouselView.tsx
+++ b/src/client/views/collections/CollectionCarouselView.tsx
@@ -86,18 +86,10 @@ export class CollectionCarouselView extends CollectionSubView() {
 
     getAnchor = (addAsAnnotation: boolean) => {
         const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document, config_carousel_index: this.carouselIndex });
-        PinDocView(anchor, { pinData: { type_collection: true, filters: true } }, this.Document);
+        PinDocView(anchor, { pinData: { collectionType: true, filters: true } }, this.Document);
         addAsAnnotation && Doc.AddDocToList(this.dataDoc, this.fieldKey + '_annotations', anchor); // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
         return anchor;
     };
-    // pinned / linked anchor doc includes selected rows, graph titles, and graph colors
-    restoreView = (viewData: Doc) => {
-        if (viewData.config_carousel_index !== undefined && this.layoutDoc._carousel_index !== viewData.config_carousel_index) {
-            this.layoutDoc._carousel_index = viewData.config_carousel_index;
-            return true;
-        }
-        return false;
-    };
     addDocTab = this.addLinkedDocTab;
 
     captionStyleProvider = (doc: Doc | undefined, captionProps: Opt<FieldViewProps>, property: string) => {
diff --git a/src/client/views/collections/CollectionTimeView.tsx b/src/client/views/collections/CollectionTimeView.tsx
index 5738e7ce3..d75c633ac 100644
--- a/src/client/views/collections/CollectionTimeView.tsx
+++ b/src/client/views/collections/CollectionTimeView.tsx
@@ -52,7 +52,7 @@ export class CollectionTimeView extends CollectionSubView() {
             title: ComputedField.MakeFunction(`"${this.pivotField}"])`) as unknown as string, // title can take a functiono or a string
             annotationOn: this.Document,
         });
-        PinDocView(anchor, { pinData: { type_collection: true, pivot: true, filters: true } }, this.Document);
+        PinDocView(anchor, { pinData: { collectionType: true, pivot: true, filters: true } }, this.Document);
 
         if (addAsAnnotation) {
             // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
index 0241fc2dd..ff711314b 100644
--- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
+++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
@@ -1743,7 +1743,7 @@ export class CollectionFreeFormView extends CollectionSubView<Partial<collection
         });
         PinDocView(
             anchor,
-            { pinDocLayout: pinProps?.pinDocLayout, pinData: { ...(pinProps?.pinData ? { ...pinProps.pinData, poslayoutview: pinProps.pinData.dataview } : {}), pannable: !this.Document.isGroup, type_collection: true, filters: true } },
+            { pinDocLayout: pinProps?.pinDocLayout, pinData: { ...(pinProps?.pinData ? { ...pinProps.pinData, poslayoutview: pinProps.pinData.dataview } : {}), pannable: !this.Document.isGroup, collectionType: true, filters: true } },
             this.Document
         );
 
diff --git a/src/client/views/nodes/trails/PresBox.tsx b/src/client/views/nodes/trails/PresBox.tsx
index 212dfec08..5d3672aee 100644
--- a/src/client/views/nodes/trails/PresBox.tsx
+++ b/src/client/views/nodes/trails/PresBox.tsx
@@ -14,7 +14,7 @@ import { StopEvent, lightOrDark, returnFalse, returnOne, setupMoveUpEvents } fro
 import { emptyFunction, stringHash } from '../../../../Utils';
 import { Doc, DocListCast, Field, FieldResult, FieldType, NumListCast, Opt, StrListCast } from '../../../../fields/Doc';
 import { Animation, DocData, TransitionTimer } from '../../../../fields/DocSymbols';
-import { Copy } from '../../../../fields/FieldSymbols';
+import { Copy, Id } from '../../../../fields/FieldSymbols';
 import { InkField } from '../../../../fields/InkField';
 import { List } from '../../../../fields/List';
 import { ObjectField } from '../../../../fields/ObjectField';
@@ -382,7 +382,6 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
             if (typeof res === 'string') {
                 const resObj = JSON.parse(res);
                 console.log('Parsed GPT Result ', resObj);
-                // eslint-disable-next-line no-restricted-syntax
                 for (const key in resObj) {
                     if (resObj[key]) {
                         console.log('typeof property', typeof resObj[key]);
@@ -563,11 +562,11 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
         const datarange = [DocumentType.FUNCPLOT].includes(targetType);
         const dataview = [DocumentType.INK, DocumentType.COL, DocumentType.IMG, DocumentType.RTF].includes(targetType) && target?.activeFrame === undefined;
         const poslayoutview = [DocumentType.COL].includes(targetType) && target?.activeFrame === undefined;
-        const typeCollection = targetType === DocumentType.COL;
+        const collectionType = targetType === DocumentType.COL;
         const filters = true;
         const pivot = true;
         const dataannos = false;
-        return { scrollable, pannable, inkable, type_collection: typeCollection, pivot, map, filters, temporal, clippable, dataview, datarange, poslayoutview, dataannos };
+        return { scrollable, pannable, inkable, collectionType, pivot, map, filters, temporal, clippable, dataview, datarange, poslayoutview, dataannos };
     }
 
     @action
@@ -575,7 +574,6 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
         /* empty */
     };
     @action
-    // eslint-disable-next-line default-param-last
     static restoreTargetDocView(bestTargetView: Opt<DocumentView>, activeItem: Doc, transTime: number, pinDocLayout: boolean = BoolCast(activeItem.config_pinLayout), pinDataTypes?: dataTypes, targetDoc?: Doc) {
         const bestTarget = bestTargetView?.Document ?? (targetDoc?.layout_unrendered ? DocCast(targetDoc?.annotationOn) : targetDoc);
         if (!bestTarget) return undefined;
@@ -701,7 +699,19 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
                 changed = true;
             }
         }
-        if ((pinDataTypes?.type_collection && activeItem.config_type_collection !== undefined) || (!pinDataTypes && activeItem.config_type_collection !== undefined)) {
+        if ((pinDataTypes?.collectionType && activeItem.config_card_curDoc !== undefined) || (!pinDataTypes && activeItem.config_card_curDoc !== undefined)) {
+            if (bestTarget._card_curDoc !== activeItem.config_card_curDoc) {
+                bestTarget._card_curDoc = activeItem.config_card_curDoc;
+                changed = true;
+            }
+        }
+        if ((pinDataTypes?.collectionType && activeItem.config_carousel_index !== undefined) || (!pinDataTypes && activeItem.config_carousel_index !== undefined)) {
+            if (bestTarget._carousel_index !== activeItem.config_carousel_index) {
+                bestTarget._carousel_index = activeItem.config_carousel_index;
+                changed = true;
+            }
+        }
+        if ((pinDataTypes?.collectionType && activeItem.config_type_collection !== undefined) || (!pinDataTypes && activeItem.config_type_collection !== undefined)) {
             if (bestTarget._type_collection !== activeItem.config_type_collection) {
                 bestTarget._type_collection = activeItem.config_type_collection;
                 changed = true;
@@ -1135,7 +1145,6 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
                     return false;
                 }
             } else if (doc.type !== DocumentType.PRES) {
-                // eslint-disable-next-line operator-assignment
                 if (!doc.presentation_targetDoc) doc.title = doc.title + ' - Slide';
                 doc.presentation_targetDoc = doc.createdFrom ?? doc; // dropped document will be a new embedding of an embedded document somewhere else.
                 doc.presentation_movement = PresMovement.Zoom;
@@ -1167,8 +1176,7 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
             const tagDoc = Cast(curDoc.presentation_targetDoc, Doc, null);
             if (curDoc && curDoc === this.activeItem)
                 return (
-                    // eslint-disable-next-line react/no-array-index-key
-                    <div key={index} className="selectedList-items">
+                    <div key={doc[Id]} className="selectedList-items">
                         <b>
                             {index + 1}. {StrCast(curDoc.title)})
                         </b>
@@ -1176,15 +1184,13 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
                 );
             if (tagDoc)
                 return (
-                    // eslint-disable-next-line react/no-array-index-key
-                    <div key={index} className="selectedList-items">
+                    <div key={doc[Id]} className="selectedList-items">
                         {index + 1}. {StrCast(curDoc.title)}
                     </div>
                 );
             if (curDoc)
                 return (
-                    // eslint-disable-next-line react/no-array-index-key
-                    <div key={index} className="selectedList-items">
+                    <div key={doc[Id]} className="selectedList-items">
                         {index + 1}. {StrCast(curDoc.title)}
                     </div>
                 );
@@ -1369,7 +1375,6 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
             const tagDoc = PresBox.targetRenderedDoc(doc);
             const srcContext = Cast(tagDoc.embedContainer, Doc, null);
             const labelCreator = (top: number, left: number, edge: number, fontSize: number) => (
-                // eslint-disable-next-line react/no-array-index-key
                 <div className="pathOrder" key={tagDoc.id + 'pres' + index} style={{ top, left, width: edge, height: edge, fontSize }} onClick={() => this.selectElement(doc)}>
                     <div className="pathOrder-frame">{index + 1}</div>
                 </div>
@@ -1620,7 +1625,6 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
         this.updateEffect(this.activeItem.presentation_effect as PresEffect, false, true);
         this.updateEffect(this.activeItem.presBulletEffect as PresEffect, true, true);
         this.updateEffectDirection(this.activeItem.presentation_effectDirection as PresEffectDirection, true);
-        // eslint-disable-next-line camelcase
         const { presentation_transition: pt, presentation_duration: pd, presentation_hideBefore: ph, presentation_hideAfter: pa } = this.activeItem;
         array.forEach(curDoc => {
             curDoc.presentation_transition = pt;
@@ -2018,7 +2022,6 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
                                 <div className="presBox-effects">
                                     {this.generatedAnimations.map((elem, i) => (
                                         <div
-                                            // eslint-disable-next-line react/no-array-index-key
                                             key={i}
                                             className="presBox-effect-container"
                                             onClick={() => {
@@ -3046,7 +3049,6 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
                     <div className="Slide">
                         {mode !== CollectionViewType.Invalid ? (
                             <CollectionView
-                                // eslint-disable-next-line react/jsx-props-no-spreading
                                 {...this._props}
                                 PanelWidth={this._props.PanelWidth}
                                 PanelHeight={this.panelHeight}
diff --git a/src/fields/ScriptField.ts b/src/fields/ScriptField.ts
index 582c09f29..0252961d3 100644
--- a/src/fields/ScriptField.ts
+++ b/src/fields/ScriptField.ts
@@ -85,6 +85,7 @@ async function deserializeScript(scriptIn: ScriptField) {
 }
 
 @scriptingGlobal
+// eslint-disable-next-line no-use-before-define
 @Deserializable('script', (obj: unknown) => deserializeScript(obj as ScriptField))
 export class ScriptField extends ObjectField {
     @serializable
@@ -137,7 +138,6 @@ export class ScriptField extends ObjectField {
     [ToString]() {
         return this.script.originalScript;
     }
-    // eslint-disable-next-line default-param-last
     public static CompileScript(script: string, params: object = {}, addReturn = false, capturedVariables?: { [name: string]: Doc | string | number | boolean }, transformer?: Transformer) {
         return CompileScript(script, {
             params: {
@@ -156,13 +156,11 @@ export class ScriptField extends ObjectField {
         });
     }
 
-    // eslint-disable-next-line default-param-last
     public static MakeFunction(script: string, params: object = {}, capturedVariables?: { [name: string]: Doc | string | number | boolean }) {
         const compiled = ScriptField.CompileScript(script, params, true, capturedVariables);
         return compiled.compiled ? new ScriptField(compiled) : undefined;
     }
 
-    // eslint-disable-next-line default-param-last
     public static MakeScript(script: string, params: object = {}, capturedVariables?: { [name: string]: Doc | string | number | boolean }) {
         const compiled = ScriptField.CompileScript(script, params, false, capturedVariables);
         return compiled.compiled ? new ScriptField(compiled) : undefined;
@@ -186,6 +184,7 @@ export class ScriptField extends ObjectField {
 }
 
 @scriptingGlobal
+// eslint-disable-next-line no-use-before-define
 @Deserializable('computed', (obj: unknown) => deserializeScript(obj as ComputedField))
 export class ComputedField extends ScriptField {
     static undefined = '__undefined';
@@ -229,7 +228,6 @@ export class ComputedField extends ScriptField {
     [ToValue](doc: Doc)   { return ComputedField.useComputed ? { value: this.value(doc) } : undefined; } // prettier-ignore
     [Copy](): ObjectField { return new ComputedField(this.script, this.setterscript, this.rawscript); } // prettier-ignore
 
-    // eslint-disable-next-line default-param-last
     public static MakeFunction(script: string, params: object = {}, capturedVariables?: { [name: string]: Doc | string | number | boolean }, setterscript?: string) {
         const compiled = ScriptField.CompileScript(script, params, true, { value: '', ...capturedVariables });
         const compiledsetter = setterscript ? ScriptField.CompileScript(setterscript, { ...params, value: 'any' }, false, capturedVariables) : undefined;
-- 
cgit v1.2.3-70-g09d2


From 050fe4fe0d9f9722a7a2a48ae3b446049f93775f Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Thu, 24 Oct 2024 11:06:27 -0400
Subject: fixed doc decorations for carousel docs.

---
 .../views/collections/CollectionCarousel3DView.tsx       | 16 +++++++++++-----
 src/client/views/collections/CollectionSubView.tsx       |  3 ++-
 2 files changed, 13 insertions(+), 6 deletions(-)

(limited to 'src/client/views/collections/CollectionCarousel3DView.tsx')

diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx
index 61a74dd7a..c080ba27e 100644
--- a/src/client/views/collections/CollectionCarousel3DView.tsx
+++ b/src/client/views/collections/CollectionCarousel3DView.tsx
@@ -75,21 +75,27 @@ export class CollectionCarousel3DView extends CollectionSubView() {
                       ? false
                       : undefined
     );
-    contentScreenToLocalXf = () => this._props.ScreenToLocalTransform().scale(this._props.NativeDimScaling?.() || 1);
+    contentScreenToLocalXf = () => this._props.ScreenToLocalTransform().translate(0, (-(Number(CAROUSEL3D_TOP) / 100) * this._props.PanelHeight()) / this.nativeScaling());
     childScreenLeftToLocal = () =>
         this.contentScreenToLocalXf()
-            .translate(-(this.panelWidth() - this.panelWidth() * this.sideScale) / 2, -(this.panelHeight() - this.panelHeight() * this.sideScale) / 2 - (Number(CAROUSEL3D_TOP) / 100) * this._props.PanelHeight())
+            .translate(
+                (-this.panelWidth() * (1 - this.sideScale)) / 2, //
+                (-this.panelHeight() * (1 - this.sideScale)) / 2
+            )
             .scale(1 / this.sideScale);
     childScreenRightToLocal = () =>
         this.contentScreenToLocalXf()
-            .translate(-2 * this.panelWidth() - (this.panelWidth() - this.panelWidth() * this.sideScale) / 2, -(this.panelHeight() - this.panelHeight() * this.sideScale) / 2 - (Number(CAROUSEL3D_TOP) / 100) * this._props.PanelHeight())
+            .translate(
+                -2 * this.panelWidth() - (this.panelWidth() * (1 - this.sideScale)) / 2, //
+                (-this.panelHeight() * (1 - this.sideScale)) / 2
+            )
             .scale(1 / this.sideScale);
     childCenterScreenToLocal = () =>
         this.contentScreenToLocalXf()
             .translate(
                 -this.panelWidth() + ((this.centerScale - 1) * this.panelWidth()) / 2, // Focused Doc is shifted right by 1/3 panel width then left by increased size percent of center * 1/2 * panel width / 3
-                -((Number(CAROUSEL3D_TOP) / 100) * this._props.PanelHeight()) + ((this.centerScale - 1) * this.panelHeight()) / 2
-            ) // top is top margin % of panelHeight - increased size percent of center * panelHeight / 2
+                ((this.centerScale - 1) * this.panelHeight()) / 2
+            )
             .scale(1 / this.centerScale);
 
     focus = (anchor: Doc, options: FocusViewOptions): Opt<number> => {
diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx
index 9952863d7..0c059f729 100644
--- a/src/client/views/collections/CollectionSubView.tsx
+++ b/src/client/views/collections/CollectionSubView.tsx
@@ -531,6 +531,7 @@ export function CollectionSubView<X>() {
         };
 
         protected _sideBtnWidth = 35;
+        protected _sideBtnMaxPanelPct = 0.15;
         @observable _filterFunc: ((doc: Doc) => boolean) | undefined = undefined;
         /**
          * How much the content of the collection is being scaled based on its nesting and its fit-to-width settings
@@ -541,7 +542,7 @@ export function CollectionSubView<X>() {
          * This takes the desired screen space size and converts into collection coordinates.  It then returns the smaller of the converted
          * size or a fraction of the collection view.
          */
-        @computed get maxWidgetSize() { return Math.min(this._sideBtnWidth * this.contentScaling, (this._props.fitWidth?.(this.Document) && this._props.PanelWidth() > NumCast(this.layoutDoc._width)? 1:  0.25) * NumCast(this.layoutDoc.width, 1));  } // prettier-ignore
+        @computed get maxWidgetSize() { return Math.min(this._sideBtnWidth * this.contentScaling, (this._props.fitWidth?.(this.Document) && this._props.PanelWidth() > NumCast(this.layoutDoc._width)? 1: this._sideBtnMaxPanelPct) * NumCast(this.layoutDoc.width, 1));  } // prettier-ignore
         /**
          * This computes a scale factor for UI elements so that they shrink and grow as the collection does in screen space.
          * Note, the scale factor does not allow for elements to grow larger than their native screen space size.
-- 
cgit v1.2.3-70-g09d2


From 6b070202843e1e2a11c09c4d29aee4ab8750f31f Mon Sep 17 00:00:00 2001
From: geireann <geireann.lindfield@gmail.com>
Date: Thu, 24 Oct 2024 12:01:21 -0400
Subject: fixed pinning of card and carousel views.

---
 src/client/views/collections/CollectionCardDeckView.tsx   | 6 +++---
 src/client/views/collections/CollectionCarousel3DView.tsx | 6 +++---
 src/client/views/collections/CollectionCarouselView.tsx   | 6 +++---
 3 files changed, 9 insertions(+), 9 deletions(-)

(limited to 'src/client/views/collections/CollectionCarousel3DView.tsx')

diff --git a/src/client/views/collections/CollectionCardDeckView.tsx b/src/client/views/collections/CollectionCardDeckView.tsx
index beb45f326..3a5cb5f37 100644
--- a/src/client/views/collections/CollectionCardDeckView.tsx
+++ b/src/client/views/collections/CollectionCardDeckView.tsx
@@ -19,7 +19,7 @@ import { dropActionType } from '../../util/DropActionTypes';
 import { SnappingManager } from '../../util/SnappingManager';
 import { Transform } from '../../util/Transform';
 import { undoable } from '../../util/UndoManager';
-import { PinDocView } from '../PinFuncs';
+import { PinDocView, PinProps } from '../PinFuncs';
 import { StyleProp } from '../StyleProp';
 import { TagItem } from '../TagsView';
 import { DocumentView, DocumentViewProps } from '../nodes/DocumentView';
@@ -608,9 +608,9 @@ export class CollectionCardView extends CollectionSubView() {
         }
         return undefined;
     });
-    getAnchor = (addAsAnnotation: boolean) => {
+    getAnchor = (addAsAnnotation: boolean, pinProps?: PinProps) => {
         const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document, config_card_curDoc: this.curDoc() });
-        PinDocView(anchor, { pinData: { collectionType: true, filters: true } }, this.Document);
+        PinDocView(anchor, { pinDocLayout: pinProps?.pinDocLayout, pinData: { collectionType: true, filters: true } }, this.Document);
         addAsAnnotation && Doc.AddDocToList(this.dataDoc, this.fieldKey + '_annotations', anchor); // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
         return anchor;
     };
diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx
index c080ba27e..b7ecf9a2f 100644
--- a/src/client/views/collections/CollectionCarousel3DView.tsx
+++ b/src/client/views/collections/CollectionCarousel3DView.tsx
@@ -12,7 +12,7 @@ import { DocumentType } from '../../documents/DocumentTypes';
 import { Docs } from '../../documents/Documents';
 import { DragManager } from '../../util/DragManager';
 import { Transform } from '../../util/Transform';
-import { PinDocView } from '../PinFuncs';
+import { PinDocView, PinProps } from '../PinFuncs';
 import { StyleProp } from '../StyleProp';
 import { DocumentView } from '../nodes/DocumentView';
 import { FocusViewOptions } from '../nodes/FocusViewOptions';
@@ -107,9 +107,9 @@ export class CollectionCarousel3DView extends CollectionSubView() {
         }
         return undefined;
     };
-    getAnchor = (addAsAnnotation: boolean) => {
+    getAnchor = (addAsAnnotation: boolean, pinProps?: PinProps) => {
         const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document, config_carousel_index: this.layoutDoc._carousel_index as number });
-        PinDocView(anchor, { pinData: { collectionType: true, filters: true } }, this.Document);
+        PinDocView(anchor, { pinDocLayout: pinProps?.pinDocLayout, pinData: { collectionType: true, filters: true } }, this.Document);
         addAsAnnotation && Doc.AddDocToList(this.dataDoc, this.fieldKey + '_annotations', anchor); // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
         return anchor;
     };
diff --git a/src/client/views/collections/CollectionCarouselView.tsx b/src/client/views/collections/CollectionCarouselView.tsx
index f714e2a00..87c6e3e5c 100644
--- a/src/client/views/collections/CollectionCarouselView.tsx
+++ b/src/client/views/collections/CollectionCarouselView.tsx
@@ -8,7 +8,7 @@ import { BoolCast, DocCast, NumCast, ScriptCast, StrCast } from '../../../fields
 import { DocumentType } from '../../documents/DocumentTypes';
 import { Docs } from '../../documents/Documents';
 import { DragManager } from '../../util/DragManager';
-import { PinDocView } from '../PinFuncs';
+import { PinDocView, PinProps } from '../PinFuncs';
 import { StyleProp } from '../StyleProp';
 import { DocumentView } from '../nodes/DocumentView';
 import { FieldViewProps } from '../nodes/FieldView';
@@ -84,9 +84,9 @@ export class CollectionCarouselView extends CollectionSubView() {
         return undefined;
     };
 
-    getAnchor = (addAsAnnotation: boolean) => {
+    getAnchor = (addAsAnnotation: boolean, pinProps?: PinProps) => {
         const anchor = Docs.Create.ConfigDocument({ annotationOn: this.Document, config_carousel_index: this.carouselIndex });
-        PinDocView(anchor, { pinData: { collectionType: true, filters: true } }, this.Document);
+        PinDocView(anchor, { pinDocLayout: pinProps?.pinDocLayout, pinData: { collectionType: true, filters: true } }, this.Document);
         addAsAnnotation && Doc.AddDocToList(this.dataDoc, this.fieldKey + '_annotations', anchor); // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered
         return anchor;
     };
-- 
cgit v1.2.3-70-g09d2


From 205fdacf9807be2691e13e1d9d04d6b98620391a Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Wed, 15 Jan 2025 13:03:59 -0500
Subject: fixed so that users are sentt to dropbox to authorized uploads once,
 and then a refresh token is used afterwards.  fixed up some collection views
 to work better with the tagsView.  fixed grid view to show entire image. 
 tweaked notetaking view to work better with tags, but it's incomplete.

---
 .../views/collections/CollectionCarousel3DView.tsx |  1 +
 .../views/collections/CollectionNoteTakingView.tsx | 11 +--
 .../views/collections/CollectionStackingView.tsx   | 13 ++-
 .../collectionGrid/CollectionGridView.tsx          | 12 +--
 src/client/views/smartdraw/DrawingFillHandler.tsx  | 28 +++++--
 src/server/ApiManagers/FireflyManager.ts           | 94 ++++++++++++++++++++--
 src/server/authentication/DashUserModel.ts         |  5 ++
 7 files changed, 141 insertions(+), 23 deletions(-)

(limited to 'src/client/views/collections/CollectionCarousel3DView.tsx')

diff --git a/src/client/views/collections/CollectionCarousel3DView.tsx b/src/client/views/collections/CollectionCarousel3DView.tsx
index b7ecf9a2f..9c8ef5519 100644
--- a/src/client/views/collections/CollectionCarousel3DView.tsx
+++ b/src/client/views/collections/CollectionCarousel3DView.tsx
@@ -136,6 +136,7 @@ export class CollectionCarousel3DView extends CollectionSubView() {
                 isDocumentActive={this._props.childDocumentsActive?.() || this.Document._childDocumentsActive ? this._props.isDocumentActive : this.isContentActive}
                 PanelWidth={this.panelWidth}
                 PanelHeight={this.panelHeight}
+                showTags={BoolCast(this.layoutDoc.showChildTags) || BoolCast(this.Document._layout_showTags)}
             />
         );
 
diff --git a/src/client/views/collections/CollectionNoteTakingView.tsx b/src/client/views/collections/CollectionNoteTakingView.tsx
index ac8e37358..323a679cc 100644
--- a/src/client/views/collections/CollectionNoteTakingView.tsx
+++ b/src/client/views/collections/CollectionNoteTakingView.tsx
@@ -2,7 +2,7 @@ import { action, computed, IReactionDisposer, makeObservable, observable, reacti
 import { observer } from 'mobx-react';
 import * as React from 'react';
 import { ClientUtils, DivHeight, lightOrDark, returnZero, smoothScroll } from '../../../ClientUtils';
-import { Doc, Field, FieldType, Opt } from '../../../fields/Doc';
+import { Doc, Field, FieldType, Opt, StrListCast } from '../../../fields/Doc';
 import { DocData } from '../../../fields/DocSymbols';
 import { Copy, Id } from '../../../fields/FieldSymbols';
 import { List } from '../../../fields/List';
@@ -48,6 +48,7 @@ export class CollectionNoteTakingView extends CollectionSubView() {
     @computed get notetakingCategoryField() {
         return StrCast(this.dataDoc.notetaking_column, StrCast(this.layoutDoc.pivotField, 'notetaking_column'));
     }
+    toHeader = (d: Doc) => (d[this.notetakingCategoryField] instanceof List ? StrListCast(d[this.notetakingCategoryField]).join('.') : (d[this.notetakingCategoryField] ?? 'unset'));
     public DividerWidth = 16;
     @observable docsDraggedRowCol: number[] = [];
     @observable _scroll = 0;
@@ -136,7 +137,7 @@ export class CollectionNoteTakingView extends CollectionSubView() {
         const rowCol = this.docsDraggedRowCol;
         // this will sort the docs into the correct columns (minus the ones you're currently dragging)
         docs.forEach(d => {
-            const sectionValue = (d[this.notetakingCategoryField] as object) ?? `unset`;
+            const sectionValue = this.toHeader(d);
             // look for if header exists already
             const existingHeader = columnHeaders.find(sh => sh.heading === sectionValue.toString());
             if (existingHeader) {
@@ -161,7 +162,7 @@ export class CollectionNoteTakingView extends CollectionSubView() {
     };
 
     @computed get allFieldValues() {
-        return new Set(this.childDocs.map(doc => StrCast(doc[this.notetakingCategoryField])));
+        return new Set(this.childDocs.map(doc => (doc[this.notetakingCategoryField] instanceof List ? StrListCast(doc[this.notetakingCategoryField]).join('.') : StrCast(doc[this.notetakingCategoryField]))));
     }
 
     componentDidMount() {
@@ -313,7 +314,7 @@ export class CollectionNoteTakingView extends CollectionSubView() {
     // how to get the width of a document. Currently returns the width of the column (minus margins)
     // if a note doc. Otherwise, returns the normal width (for graphs, images, etc...)
     getDocWidth = (d: Doc) => {
-        const heading = !d[this.notetakingCategoryField] ? 'unset' : Field.toString(d[this.notetakingCategoryField] as FieldType);
+        const heading = this.toHeader(d);
         const existingHeader = this.colHeaderData.find(sh => sh.heading === heading);
         const existingWidth = this.layoutDoc._notetaking_columns_autoSize ? 1 / (this.colHeaderData.length ?? 1) : existingHeader?.width ? existingHeader.width : 0;
         const maxWidth = existingWidth > 0 ? existingWidth * this.availableWidth : this.maxColWidth;
@@ -427,7 +428,7 @@ export class CollectionNoteTakingView extends CollectionSubView() {
         const colHeader = colIndex === undefined ? 'unset' : StrCast(this.colHeaderData[colIndex].heading);
         this.childDocs?.forEach(d => {
             if (d instanceof Promise) return;
-            const sectionValue = (d[this.notetakingCategoryField] as object) ?? 'unset';
+            const sectionValue = this.toHeader(d);
             if (sectionValue.toString() === colHeader) {
                 docsMatchingHeader.push(d);
             }
diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx
index 1ac0b6d70..a57256424 100644
--- a/src/client/views/collections/CollectionStackingView.tsx
+++ b/src/client/views/collections/CollectionStackingView.tsx
@@ -146,7 +146,17 @@ export class CollectionStackingView extends CollectionSubView<Partial<collection
             // assuming we need to get rowSpan because we might be dealing with many columns. Grid gap makes sense if multiple columns
             const rowSpan = Math.ceil((this.getDocHeight(d)() + this.gridGap) / this.gridGap);
             // just getting the style
-            const style = this.isStackingView ? { margin: undefined, transition: this.getDocTransition(d)(), width: this.columnWidth, marginTop: i ? this.gridGap : 0, height: this.getDocHeight(d)() } : { gridRowEnd: `span ${rowSpan}` };
+            const style = this.isStackingView
+                ? {
+                      //
+                      margin: undefined,
+                      transition: this.getDocTransition(d)(),
+                      width: this.columnWidth,
+                      marginTop: i ? this.gridGap : 0,
+                      height: this.getDocHeight(d)(),
+                      zIndex: DocumentView.getFirstDocumentView(d)?.IsSelected ? 1000 : 0,
+                  }
+                : { gridRowEnd: `span ${rowSpan}`, zIndex: DocumentView.getFirstDocumentView(d)?.IsSelected ? 1000 : 0 };
             // So we're choosing whether we're going to render a column or a masonry doc
             return (
                 <div className={`collectionStackingView-${this.isStackingView ? 'columnDoc' : 'masonryDoc'}`} key={d[Id]} style={style}>
@@ -344,6 +354,7 @@ export class CollectionStackingView extends CollectionSubView<Partial<collection
                 dontRegisterView={BoolCast(this.layoutDoc.childDontRegisterViews, this._props.dontRegisterView)} // used to be true if DataDoc existed, but template textboxes won't layout_autoHeight resize if dontRegisterView is set, but they need to.
                 rootSelected={this.rootSelected}
                 showTitle={this._props.childlayout_showTitle}
+                showTags={BoolCast(this.layoutDoc.showChildTags) || BoolCast(this.Document._layout_showTags)}
                 dragAction={(this.layoutDoc.childDragAction ?? this._props.childDragAction) as dropActionType}
                 onClickScript={this.onChildClickHandler}
                 onDoubleClickScript={this.onChildDoubleClickHandler}
diff --git a/src/client/views/collections/collectionGrid/CollectionGridView.tsx b/src/client/views/collections/collectionGrid/CollectionGridView.tsx
index 5c41fee37..6dffb80f1 100644
--- a/src/client/views/collections/collectionGrid/CollectionGridView.tsx
+++ b/src/client/views/collections/collectionGrid/CollectionGridView.tsx
@@ -186,21 +186,23 @@ export class CollectionGridView extends CollectionSubView() {
     getDisplayDoc(layout: Doc, dxf: () => Transform, width: () => number, height: () => number) {
         return (
             <DocumentView
-                // eslint-disable-next-line react/jsx-props-no-spreading
                 {...this._props}
-                NativeWidth={returnZero}
-                NativeHeight={returnZero}
-                setContentViewBox={emptyFunction}
                 Document={layout}
                 TemplateDataDocument={layout.resolvedDataDoc as Doc}
+                NativeWidth={returnZero}
+                NativeHeight={returnZero}
+                fitWidth={this._props.childLayoutFitWidth}
+                containerViewPath={this.childContainerViewPath}
+                renderDepth={this._props.renderDepth + 1}
                 isContentActive={this.isChildContentActive}
                 PanelWidth={width}
                 PanelHeight={height}
                 ScreenToLocalTransform={dxf}
+                setContentViewBox={emptyFunction}
                 whenChildContentsActiveChanged={this._props.whenChildContentsActiveChanged}
                 onClickScript={this.onChildClickHandler}
-                renderDepth={this._props.renderDepth + 1}
                 dontCenter={StrCast(this.layoutDoc.layout_dontCenter) as 'x' | 'y' | 'xy'}
+                showTags={BoolCast(this.layoutDoc.showChildTags) || BoolCast(this.Document._layout_showTags)}
             />
         );
     }
diff --git a/src/client/views/smartdraw/DrawingFillHandler.tsx b/src/client/views/smartdraw/DrawingFillHandler.tsx
index d9a01c436..bd8499806 100644
--- a/src/client/views/smartdraw/DrawingFillHandler.tsx
+++ b/src/client/views/smartdraw/DrawingFillHandler.tsx
@@ -10,6 +10,7 @@ import { DocumentView, DocumentViewInternal } from '../nodes/DocumentView';
 import { OpenWhere } from '../nodes/OpenWhere';
 import { AspectRatioLimits, FireflyDimensionsMap, FireflyImageDimensions, FireflyStylePresets } from './FireflyConstants';
 
+const DashDropboxId = '2m86iveqdr9vzsa';
 export class DrawingFillHandler {
     static drawingToImage = (drawing: Doc, strength: number, user_prompt: string) => {
         const docData = drawing[DocData];
@@ -33,14 +34,27 @@ export class DrawingFillHandler {
                 const structureUrl = `${hrefParts.slice(0, -1).join('.')}_o.${hrefParts.lastElement()}`;
                 return imageUrlToBase64(structureUrl)
                     .then(gptDescribeImage)
-                    .then(prompt => 
-                        Networking.PostToServer('/queryFireflyImageFromStructure', 
-                            { prompt: `${user_prompt || prompt}`, width: dims.width, height: dims.height, structureUrl, strength, styles })
+                    .then(prompt =>
+                        Networking.PostToServer('/queryFireflyImageFromStructure', { prompt: `${user_prompt || prompt}`, width: dims.width, height: dims.height, structureUrl, strength, styles })
                             .then((info: Upload.ImageInformation) =>
-                                DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(info.accessPaths.agnostic.client, 
-                                    { ai: 'firefly', title: user_prompt || prompt, ai_firefly_prompt: user_prompt || prompt, _width: 500, data_nativeWidth: info.nativeWidth, data_nativeHeight: info.nativeHeight }), OpenWhere.addRight)
-                        ).catch(e => alert("create image failed: " + e.toString())) 
-                    ); // prettier-ignore
+                                DocumentViewInternal.addDocTabFunc(
+                                    Docs.Create.ImageDocument(info.accessPaths.agnostic.client, {
+                                        ai: 'firefly',
+                                        title: user_prompt || prompt,
+                                        ai_firefly_prompt: user_prompt || prompt,
+                                        _width: 500,
+                                        data_nativeWidth: info.nativeWidth,
+                                        data_nativeHeight: info.nativeHeight,
+                                    }),
+                                    OpenWhere.addRight
+                                )
+                            )
+                            .catch(e => {
+                                if (e.toString().includes('Dropbox') && confirm('Create image failed. Try authorizing DropBox?\r\n' + e.toString().replace(/^[^"]*/, ''))) {
+                                    window.open(`https://www.dropbox.com/oauth2/authorize?client_id=${DashDropboxId}&response_type=code&token_access_type=offline&redirect_uri=http://localhost:1050/refreshDropbox`, '_blank')?.focus();
+                                }
+                            })
+                    ); // prettier-ignore:q
             }
         });
     };
diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts
index a1f8fab8d..6039f5675 100644
--- a/src/server/ApiManagers/FireflyManager.ts
+++ b/src/server/ApiManagers/FireflyManager.ts
@@ -1,7 +1,9 @@
+import axios from 'axios';
 import { Dropbox } from 'dropbox';
 import * as fs from 'fs';
 import * as multipart from 'parse-multipart-data';
 import * as path from 'path';
+import { DashUserModel } from '../authentication/DashUserModel';
 import { DashUploadUtils } from '../DashUploadUtils';
 import { _error, _invalid, _success, Method } from '../RouteManager';
 import { Directory, filesDirectory } from '../SocketData';
@@ -55,7 +57,7 @@ export default class FireflyManager extends ApiManager {
             )
         );
 
-    uploadImageToDropbox = (fileUrl: string, dbx = new Dropbox({ accessToken: process.env.DROPBOX_TOKEN })) =>
+    uploadImageToDropbox = (fileUrl: string, user: DashUserModel | undefined, dbx = new Dropbox({ accessToken: user?.dropboxToken || '' })) =>
         new Promise<string | Error>((res, rej) =>
             fs.readFile(path.join(filesDirectory, `${Directory.images}/${path.basename(fileUrl)}`), undefined, (err, contents) => {
                 if (err) {
@@ -69,8 +71,32 @@ export default class FireflyManager extends ApiManager {
                                 .catch(e => res(new Error(e.toString())));
                         })
                         .catch(e => {
-                            console.log('Dropbox error:', e);
-                            res(new Error(e.toString()));
+                            if (user?.dropboxRefresh) {
+                                console.log('*********** try refresh dropbox for: ' + user.email + ' ***********');
+                                this.refreshDropboxToken(user).then(token => {
+                                    if (!token) {
+                                        console.log('Dropbox error: cannot refresh token');
+                                        res(new Error(e.toString()));
+                                    } else {
+                                        const dbxNew = new Dropbox({ accessToken: user.dropboxToken || '' });
+                                        dbxNew
+                                            .filesUpload({ path: `/Apps/browndash/${path.basename(fileUrl)}`, contents })
+                                            .then(response => {
+                                                dbxNew
+                                                    .filesGetTemporaryLink({ path: response.result.path_display ?? '' })
+                                                    .then(link => res(link.result.link))
+                                                    .catch(linkErr => res(new Error(linkErr.toString())));
+                                            })
+                                            .catch(uploadErr => {
+                                                console.log('Dropbox error:', uploadErr);
+                                                res(new Error(uploadErr.toString()));
+                                            });
+                                    }
+                                });
+                            } else {
+                                console.log('Dropbox error:', e);
+                                res(new Error(e.toString()));
+                            }
                         });
                 }
             })
@@ -230,12 +256,35 @@ export default class FireflyManager extends ApiManager {
         );
         return fetched;
     };
+
+    refreshDropboxToken = (user: DashUserModel) =>
+        axios
+            .post(
+                'https://api.dropbox.com/oauth2/token',
+                new URLSearchParams({
+                    refresh_token: user.dropboxRefresh || '',
+                    grant_type: 'refresh_token',
+                    client_id: process.env._CLIENT_DROPBOX_CLIENT_ID || '',
+                    client_secret: process.env._CLIENT_DROPBOX_SECRET || '',
+                }).toString()
+            )
+            .then(refresh => {
+                console.log('***** dropbox token refreshed for ' + user?.email + ' ******* ');
+                user.dropboxToken = refresh.data.access_token;
+                user.save();
+                return user.dropboxToken;
+            })
+            .catch(e => {
+                console.log(e);
+                return undefined;
+            });
+
     protected initialize(register: Registration): void {
         register({
             method: Method.POST,
             subscription: '/queryFireflyImageFromStructure',
             secureHandler: async ({ req, res }) =>
-                this.uploadImageToDropbox(req.body.structureUrl).then(uploadUrl =>
+                this.uploadImageToDropbox(req.body.structureUrl, req.user as DashUserModel).then(uploadUrl =>
                     uploadUrl instanceof Error
                         ? _invalid(res, uploadUrl.message)
                         : this.generateImageFromStructure(req.body.prompt, req.body.width, req.body.height, uploadUrl, req.body.strength, req.body.styles).then(fire =>
@@ -275,7 +324,7 @@ export default class FireflyManager extends ApiManager {
             method: Method.POST,
             subscription: '/expandImage',
             secureHandler: ({ req, res }) =>
-                this.uploadImageToDropbox(req.body.file).then(uploadUrl =>
+                this.uploadImageToDropbox(req.body.file, req.user as DashUserModel).then(uploadUrl =>
                     uploadUrl instanceof Error
                         ? _invalid(res, uploadUrl.message)
                         : this.expandImage(uploadUrl, req.body.prompt).then(text => {
@@ -288,5 +337,40 @@ export default class FireflyManager extends ApiManager {
                           })
                 ),
         });
+
+        // construct this url and send user to it.  It will allow them to authorize their dropbox account and will send the resulting token to our endpoint /refreshDropbox
+        // https://www.dropbox.com/oauth2/authorize?client_id=DROPBOX_CLIENT_ID&response_type=code&token_access_type=offline&redirect_uri=http://localhost:1050/refreshDropbox
+        // see: https://dropbox.tech/developers/using-oauth-2-0-with-offline-access
+        //
+        register({
+            method: Method.GET,
+            subscription: '/refreshDropbox',
+            secureHandler: ({ req, res }) => {
+                const user = req.user as DashUserModel;
+                console.log(`******************* dropbox authorized for ${user?.email} ******************`);
+                _success(res, 'dropbox authorized for ' + user?.email);
+
+                const data = new URLSearchParams({
+                    code: req.query.code as string,
+                    grant_type: 'authorization_code',
+                    client_id: process.env._CLIENT_DROPBOX_CLIENT_ID ?? '',
+                    client_secret: process.env._CLIENT_DROPBOX_SECRET ?? '',
+                    redirect_uri: 'http://localhost:1050/refreshDropbox',
+                });
+                axios
+                    .post('https://api.dropbox.com/oauth2/token', data.toString())
+                    .then(response => {
+                        console.log('***** dropbox token (and refresh) received for ' + user?.email + ' ******* ');
+                        user.dropboxToken = response.data.access_token;
+                        user.dropboxRefresh = response.data.refresh_token;
+                        user.save();
+
+                        setTimeout(() => this.refreshDropboxToken(user), response.data.expires_in - 600);
+                    })
+                    .catch(e => {
+                        console.log(e);
+                    });
+            },
+        });
     }
 }
diff --git a/src/server/authentication/DashUserModel.ts b/src/server/authentication/DashUserModel.ts
index bfa6d7bdb..debeef60c 100644
--- a/src/server/authentication/DashUserModel.ts
+++ b/src/server/authentication/DashUserModel.ts
@@ -9,6 +9,9 @@ export type DashUserModel = mongoose.Document & {
     passwordResetToken?: string;
     passwordResetExpires?: Date;
 
+    dropboxRefresh?: string;
+    dropboxToken?: string;
+
     userDocumentId: string;
     sharingDocumentId: string;
     linkDatabaseId: string;
@@ -37,6 +40,8 @@ const userSchema = new mongoose.Schema(
         passwordResetToken: String,
         passwordResetExpires: Date,
 
+        dropboxRefresh: String,
+        dropboxToken: String,
         userDocumentId: String, // id that identifies a document which hosts all of a user's account data
         sharingDocumentId: String, // id that identifies a document that stores documents shared to a user, their user color, and any additional info needed to communicate between users
         linkDatabaseId: String,
-- 
cgit v1.2.3-70-g09d2

