From cea66bd846e886776bcb9d376f0aa7c88cf73504 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Tue, 13 Sep 2022 21:43:59 -0400
Subject: made overlayX/overlayY instead of re-using x/y in order that overlay
 docs can be dragged in playground mode (for shared mini-player presentations)
 without necessarily allowing regular docs to be dragged in playground mode.

---
 src/client/views/OverlayView.tsx | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

(limited to 'src/client/views/OverlayView.tsx')

diff --git a/src/client/views/OverlayView.tsx b/src/client/views/OverlayView.tsx
index 5242fabb8..2354e84ff 100644
--- a/src/client/views/OverlayView.tsx
+++ b/src/client/views/OverlayView.tsx
@@ -164,7 +164,7 @@ export class OverlayView extends React.Component {
 
     docScreenToLocalXf = computedFn(
         function docScreenToLocalXf(this: any, doc: Doc) {
-            return () => new Transform(-NumCast(doc.x), -NumCast(doc.y), 1);
+            return () => new Transform(-NumCast(doc.overlayX), -NumCast(doc.overlayY), 1);
         }.bind(this)
     );
 
@@ -175,8 +175,8 @@ export class OverlayView extends React.Component {
             const dref = React.createRef<HTMLDivElement>();
             const onPointerMove = action((e: PointerEvent, down: number[]) => {
                 if (e.buttons === 1) {
-                    d.x = e.clientX + offsetx;
-                    d.y = e.clientY + offsety;
+                    d.overlayX = e.clientX + offsetx;
+                    d.overlayY = e.clientY + offsety;
                 }
                 if (e.metaKey) {
                     const dragData = new DragManager.DocumentDragData([d]);
@@ -198,8 +198,8 @@ export class OverlayView extends React.Component {
 
             const onPointerDown = (e: React.PointerEvent) => {
                 setupMoveUpEvents(this, e, onPointerMove, emptyFunction, emptyFunction);
-                offsetx = NumCast(d.x) - e.clientX;
-                offsety = NumCast(d.y) - e.clientY;
+                offsetx = NumCast(d.overlayX) - e.clientX;
+                offsety = NumCast(d.overlayY) - e.clientY;
             };
             return (
                 <div
@@ -207,7 +207,7 @@ export class OverlayView extends React.Component {
                     ref={dref}
                     key={d[Id]}
                     onPointerDown={onPointerDown}
-                    style={{ top: d.type === 'presentation' ? 0 : undefined, width: NumCast(d._width), height: NumCast(d._height), transform: `translate(${d.x}px, ${d.y}px)` }}>
+                    style={{ top: d.type === 'presentation' ? 0 : undefined, width: NumCast(d._width), height: NumCast(d._height), transform: `translate(${d.overlayX}px, ${d.overlayY}px)` }}>
                     <DocumentView
                         Document={d}
                         rootSelected={returnTrue}
-- 
cgit v1.2.3-70-g09d2


From 8f21b2ef39afbe4723e0b23b1bd9f47c27e078fc Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Wed, 14 Sep 2022 00:56:52 -0400
Subject: turned off overlayView when lightboxDoc is active

---
 src/client/views/OverlayView.tsx | 135 ++++++++++++++++++++-------------------
 1 file changed, 69 insertions(+), 66 deletions(-)

(limited to 'src/client/views/OverlayView.tsx')

diff --git a/src/client/views/OverlayView.tsx b/src/client/views/OverlayView.tsx
index 2354e84ff..6d7f2c037 100644
--- a/src/client/views/OverlayView.tsx
+++ b/src/client/views/OverlayView.tsx
@@ -12,6 +12,7 @@ import { DragManager } from '../util/DragManager';
 import { ScriptingGlobals } from '../util/ScriptingGlobals';
 import { Transform } from '../util/Transform';
 import { CollectionFreeFormLinksView } from './collections/collectionFreeForm/CollectionFreeFormLinksView';
+import { LightboxView } from './LightboxView';
 import { DocumentView } from './nodes/DocumentView';
 import './OverlayView.scss';
 import { ScriptingRepl } from './ScriptingRepl';
@@ -90,7 +91,7 @@ export class OverlayWindow extends React.Component<OverlayWindowProps> {
     };
 
     render() {
-        return (
+        return LightboxView.LightboxDoc ? null : (
             <div className="overlayWindow-outerDiv" style={{ transform: `translate(${this.x}px, ${this.y}px)`, width: this.width, height: this.height }}>
                 <div className="overlayWindow-titleBar" onPointerDown={this.onPointerDown}>
                     {this.props.overlayOptions.title || 'Untitled'}
@@ -169,72 +170,74 @@ export class OverlayView extends React.Component {
     );
 
     @computed get overlayDocs() {
-        return DocListCast(Doc.MyOverlayDocs?.data).map(d => {
-            let offsetx = 0,
-                offsety = 0;
-            const dref = React.createRef<HTMLDivElement>();
-            const onPointerMove = action((e: PointerEvent, down: number[]) => {
-                if (e.buttons === 1) {
-                    d.overlayX = e.clientX + offsetx;
-                    d.overlayY = e.clientY + offsety;
-                }
-                if (e.metaKey) {
-                    const dragData = new DragManager.DocumentDragData([d]);
-                    dragData.offset = [-offsetx, -offsety];
-                    dragData.dropAction = 'move';
-                    dragData.removeDocument = (doc: Doc | Doc[]) => {
-                        const docs = doc instanceof Doc ? [doc] : doc;
-                        docs.forEach(d => Doc.RemoveDocFromList(Doc.MyOverlayDocs, undefined, d));
-                        return true;
-                    };
-                    dragData.moveDocument = (doc: Doc | Doc[], targetCollection: Doc | undefined, addDocument: (doc: Doc | Doc[]) => boolean): boolean => {
-                        return dragData.removeDocument!(doc) ? addDocument(doc) : false;
-                    };
-                    DragManager.StartDocumentDrag([dref.current!], dragData, down[0], down[1]);
-                    return true;
-                }
-                return false;
-            });
+        return LightboxView.LightboxDoc
+            ? null
+            : DocListCast(Doc.MyOverlayDocs?.data).map(d => {
+                  let offsetx = 0,
+                      offsety = 0;
+                  const dref = React.createRef<HTMLDivElement>();
+                  const onPointerMove = action((e: PointerEvent, down: number[]) => {
+                      if (e.buttons === 1) {
+                          d.overlayX = e.clientX + offsetx;
+                          d.overlayY = e.clientY + offsety;
+                      }
+                      if (e.metaKey) {
+                          const dragData = new DragManager.DocumentDragData([d]);
+                          dragData.offset = [-offsetx, -offsety];
+                          dragData.dropAction = 'move';
+                          dragData.removeDocument = (doc: Doc | Doc[]) => {
+                              const docs = doc instanceof Doc ? [doc] : doc;
+                              docs.forEach(d => Doc.RemoveDocFromList(Doc.MyOverlayDocs, undefined, d));
+                              return true;
+                          };
+                          dragData.moveDocument = (doc: Doc | Doc[], targetCollection: Doc | undefined, addDocument: (doc: Doc | Doc[]) => boolean): boolean => {
+                              return dragData.removeDocument!(doc) ? addDocument(doc) : false;
+                          };
+                          DragManager.StartDocumentDrag([dref.current!], dragData, down[0], down[1]);
+                          return true;
+                      }
+                      return false;
+                  });
 
-            const onPointerDown = (e: React.PointerEvent) => {
-                setupMoveUpEvents(this, e, onPointerMove, emptyFunction, emptyFunction);
-                offsetx = NumCast(d.overlayX) - e.clientX;
-                offsety = NumCast(d.overlayY) - e.clientY;
-            };
-            return (
-                <div
-                    className="overlayView-doc"
-                    ref={dref}
-                    key={d[Id]}
-                    onPointerDown={onPointerDown}
-                    style={{ top: d.type === 'presentation' ? 0 : undefined, width: NumCast(d._width), height: NumCast(d._height), transform: `translate(${d.overlayX}px, ${d.overlayY}px)` }}>
-                    <DocumentView
-                        Document={d}
-                        rootSelected={returnTrue}
-                        bringToFront={emptyFunction}
-                        addDocument={undefined}
-                        removeDocument={this.removeOverlayDoc}
-                        PanelWidth={d[WidthSym]}
-                        PanelHeight={d[HeightSym]}
-                        ScreenToLocalTransform={this.docScreenToLocalXf(d)}
-                        renderDepth={1}
-                        isDocumentActive={returnTrue}
-                        isContentActive={returnTrue}
-                        whenChildContentsActiveChanged={emptyFunction}
-                        focus={DocUtils.DefaultFocus}
-                        styleProvider={DefaultStyleProvider}
-                        docViewPath={returnEmptyDoclist}
-                        addDocTab={returnFalse}
-                        pinToPres={emptyFunction}
-                        docFilters={returnEmptyFilter}
-                        docRangeFilters={returnEmptyFilter}
-                        searchFilterDocs={returnEmptyDoclist}
-                        ContainingCollectionView={undefined}
-                        ContainingCollectionDoc={undefined}
-                    />
-                </div>
-            );
-        });
+                  const onPointerDown = (e: React.PointerEvent) => {
+                      setupMoveUpEvents(this, e, onPointerMove, emptyFunction, emptyFunction);
+                      offsetx = NumCast(d.overlayX) - e.clientX;
+                      offsety = NumCast(d.overlayY) - e.clientY;
+                  };
+                  return (
+                      <div
+                          className="overlayView-doc"
+                          ref={dref}
+                          key={d[Id]}
+                          onPointerDown={onPointerDown}
+                          style={{ top: d.type === 'presentation' ? 0 : undefined, width: NumCast(d._width), height: NumCast(d._height), transform: `translate(${d.overlayX}px, ${d.overlayY}px)` }}>
+                          <DocumentView
+                              Document={d}
+                              rootSelected={returnTrue}
+                              bringToFront={emptyFunction}
+                              addDocument={undefined}
+                              removeDocument={this.removeOverlayDoc}
+                              PanelWidth={d[WidthSym]}
+                              PanelHeight={d[HeightSym]}
+                              ScreenToLocalTransform={this.docScreenToLocalXf(d)}
+                              renderDepth={1}
+                              isDocumentActive={returnTrue}
+                              isContentActive={returnTrue}
+                              whenChildContentsActiveChanged={emptyFunction}
+                              focus={DocUtils.DefaultFocus}
+                              styleProvider={DefaultStyleProvider}
+                              docViewPath={returnEmptyDoclist}
+                              addDocTab={returnFalse}
+                              pinToPres={emptyFunction}
+                              docFilters={returnEmptyFilter}
+                              docRangeFilters={returnEmptyFilter}
+                              searchFilterDocs={returnEmptyDoclist}
+                              ContainingCollectionView={undefined}
+                              ContainingCollectionDoc={undefined}
+                          />
+                      </div>
+                  );
+              });
     }
 
     public static ShowSpinner() {
-- 
cgit v1.2.3-70-g09d2


From d5f796b433d7e72130d4109a3775347ccb10c454 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Tue, 17 Jan 2023 22:34:32 -0500
Subject: fixed linkint to trail to follow trail immediately in lightbox and
 show trail ui in minimized mode.  fixed overlay of pres box to not disappear
 when lightbox appears.   closing /ending trail hackily restores collecftion
 to prior pan/zoom.

---
 src/client/util/LinkFollower.ts                    |  19 +-
 src/client/views/MainView.tsx                      |  14 +-
 src/client/views/OverlayView.tsx                   | 136 ++++++-----
 .../CollectionFreeFormLinkView.tsx                 |   6 +-
 src/client/views/nodes/DocumentView.tsx            |   2 +-
 src/client/views/nodes/LinkDocPreview.tsx          |   3 +-
 .../views/nodes/formattedText/FormattedTextBox.tsx |   1 +
 src/client/views/nodes/trails/PresBox.scss         |  26 +-
 src/client/views/nodes/trails/PresBox.tsx          | 267 +++++++++++++--------
 src/client/views/nodes/trails/PresElementBox.tsx   |  12 +-
 src/fields/FieldLoader.scss                        |   9 +-
 src/fields/FieldLoader.tsx                         |  14 +-
 12 files changed, 298 insertions(+), 211 deletions(-)

(limited to 'src/client/views/OverlayView.tsx')

diff --git a/src/client/util/LinkFollower.ts b/src/client/util/LinkFollower.ts
index 807b54cd5..0f216e349 100644
--- a/src/client/util/LinkFollower.ts
+++ b/src/client/util/LinkFollower.ts
@@ -2,11 +2,14 @@ import { action, runInAction } from 'mobx';
 import { Doc, DocListCast, Opt } from '../../fields/Doc';
 import { BoolCast, Cast, DocCast, NumCast, StrCast } from '../../fields/Types';
 import { CollectionViewType, DocumentType } from '../documents/DocumentTypes';
+import { CollectionDockingView } from '../views/collections/CollectionDockingView';
 import { DocumentDecorations } from '../views/DocumentDecorations';
 import { LightboxView } from '../views/LightboxView';
-import { DocFocusOptions, DocumentViewSharedProps, OpenWhere, ViewAdjustment } from '../views/nodes/DocumentView';
+import { DocFocusOptions, DocumentViewSharedProps, OpenWhere, OpenWhereMod, ViewAdjustment } from '../views/nodes/DocumentView';
+import { PresBox } from '../views/nodes/trails';
 import { DocumentManager } from './DocumentManager';
 import { LinkManager } from './LinkManager';
+import { SelectionManager } from './SelectionManager';
 import { UndoManager } from './UndoManager';
 
 type CreateViewFunc = (doc: Doc, followLinkLocation: string, finished?: () => void) => void;
@@ -116,6 +119,20 @@ export class LinkFollower {
                         LightboxView.SetLightboxDoc(currentContext, undefined, tour);
                         setTimeout(LightboxView.Next);
                         allFinished();
+                    } else if (target.type === DocumentType.PRES) {
+                        const containerAnnoDoc = Cast(sourceDoc, Doc, null);
+                        const containerDoc = containerAnnoDoc || sourceDoc;
+                        var containerDocContext = containerDoc?.context ? [Cast(await containerDoc?.context, Doc, null)] : ([] as Doc[]);
+                        while (containerDocContext.length && containerDocContext[0]?.context && DocCast(containerDocContext[0].context)?.viewType !== CollectionViewType.Docking) {
+                            containerDocContext = [Cast(await containerDocContext[0].context, Doc, null), ...containerDocContext];
+                        }
+                        if (!DocumentManager.Instance.getDocumentView(containerDocContext[0])) {
+                            CollectionDockingView.AddSplit(containerDocContext[0], OpenWhereMod.right);
+                        }
+                        SelectionManager.DeselectAll();
+                        DocumentManager.Instance.AddViewRenderedCb(target, dv => containerDocContext.length && (dv.ComponentView as PresBox).PlayTrail(containerDocContext[0]));
+                        PresBox.OpenPresMinimized(target, [0, 0]);
+                        finished?.();
                     } else {
                         const containerAnnoDoc = Cast(target.annotationOn, Doc, null);
                         const containerDoc = containerAnnoDoc || target;
diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx
index 39cc9ba8e..4494166f2 100644
--- a/src/client/views/MainView.tsx
+++ b/src/client/views/MainView.tsx
@@ -574,7 +574,7 @@ export class MainView extends React.Component {
                     Document={this.headerBarDoc}
                     DataDoc={undefined}
                     addDocument={undefined}
-                    addDocTab={this.addDocTabFunc}
+                    addDocTab={MainView.addDocTabFunc}
                     pinToPres={emptyFunction}
                     docViewPath={returnEmptyDoclist}
                     styleProvider={DefaultStyleProvider}
@@ -611,7 +611,7 @@ export class MainView extends React.Component {
                     Document={this.mainContainer!}
                     DataDoc={undefined}
                     addDocument={undefined}
-                    addDocTab={this.addDocTabFunc}
+                    addDocTab={MainView.addDocTabFunc}
                     pinToPres={emptyFunction}
                     docViewPath={returnEmptyDoclist}
                     styleProvider={this._hideUI ? DefaultStyleProvider : undefined}
@@ -682,7 +682,7 @@ export class MainView extends React.Component {
 
     sidebarScreenToLocal = () => new Transform(0, -this.topOfSidebarDoc, 1);
     mainContainerXf = () => this.sidebarScreenToLocal().translate(-this.leftScreenOffsetOfMainDocView, 0);
-    addDocTabFunc = (doc: Doc, location: OpenWhere): boolean => {
+    static addDocTabFunc = (doc: Doc, location: OpenWhere): boolean => {
         const whereFields = doc._viewType === CollectionViewType.Docking ? [OpenWhere.dashboard] : location.split(':');
         const whereMods = whereFields.length > 1 ? (whereFields[1] as OpenWhereMod) : OpenWhereMod.none;
         if (doc.dockingConfig) return DashboardView.openDashboard(doc);
@@ -710,7 +710,7 @@ export class MainView extends React.Component {
                         Document={this._sidebarContent.proto || this._sidebarContent}
                         DataDoc={undefined}
                         addDocument={undefined}
-                        addDocTab={this.addDocTabFunc}
+                        addDocTab={MainView.addDocTabFunc}
                         pinToPres={emptyFunction}
                         docViewPath={returnEmptyDoclist}
                         styleProvider={this._sidebarContent.proto === Doc.MyDashboards || this._sidebarContent.proto === Doc.MyFilesystem ? DashboardStyleProvider : DefaultStyleProvider}
@@ -744,7 +744,7 @@ export class MainView extends React.Component {
                     Document={Doc.MyLeftSidebarMenu}
                     DataDoc={undefined}
                     addDocument={undefined}
-                    addDocTab={this.addDocTabFunc}
+                    addDocTab={MainView.addDocTabFunc}
                     pinToPres={emptyFunction}
                     rootSelected={returnTrue}
                     removeDocument={returnFalse}
@@ -808,7 +808,7 @@ export class MainView extends React.Component {
                             </div>
                         )}
                         <div className="properties-container" style={{ width: this.propertiesWidth() }}>
-                            {this.propertiesWidth() < 10 ? null : <PropertiesView styleProvider={DefaultStyleProvider} addDocTab={this.addDocTabFunc} width={this.propertiesWidth()} height={this.propertiesHeight()} />}
+                            {this.propertiesWidth() < 10 ? null : <PropertiesView styleProvider={DefaultStyleProvider} addDocTab={MainView.addDocTabFunc} width={this.propertiesWidth()} height={this.propertiesHeight()} />}
                         </div>
                     </div>
                 </div>
@@ -888,7 +888,7 @@ export class MainView extends React.Component {
                     moveDocument={this.moveButtonDoc}
                     CollectionView={undefined}
                     addDocument={this.addButtonDoc}
-                    addDocTab={this.addDocTabFunc}
+                    addDocTab={MainView.addDocTabFunc}
                     pinToPres={emptyFunction}
                     removeDocument={this.remButtonDoc}
                     ScreenToLocalTransform={this.buttonBarXf}
diff --git a/src/client/views/OverlayView.tsx b/src/client/views/OverlayView.tsx
index 6d7f2c037..08285ff0c 100644
--- a/src/client/views/OverlayView.tsx
+++ b/src/client/views/OverlayView.tsx
@@ -1,4 +1,4 @@
-import { action, computed, observable } from 'mobx';
+import { action, computed, observable, trace } from 'mobx';
 import { observer } from 'mobx-react';
 import { computedFn } from 'mobx-utils';
 import * as React from 'react';
@@ -8,15 +8,17 @@ import { Id } from '../../fields/FieldSymbols';
 import { NumCast } from '../../fields/Types';
 import { emptyFunction, returnEmptyDoclist, returnEmptyFilter, returnFalse, returnTrue, setupMoveUpEvents, Utils } from '../../Utils';
 import { DocUtils } from '../documents/Documents';
+import { DocumentType } from '../documents/DocumentTypes';
 import { DragManager } from '../util/DragManager';
 import { ScriptingGlobals } from '../util/ScriptingGlobals';
 import { Transform } from '../util/Transform';
 import { CollectionFreeFormLinksView } from './collections/collectionFreeForm/CollectionFreeFormLinksView';
 import { LightboxView } from './LightboxView';
+import { MainView } from './MainView';
 import { DocumentView } from './nodes/DocumentView';
 import './OverlayView.scss';
 import { ScriptingRepl } from './ScriptingRepl';
-import { DefaultStyleProvider } from './StyleProvider';
+import { DefaultStyleProvider, testDocProps } from './StyleProvider';
 
 export type OverlayDisposer = () => void;
 
@@ -170,74 +172,70 @@ export class OverlayView extends React.Component {
     );
 
     @computed get overlayDocs() {
-        return LightboxView.LightboxDoc
-            ? null
-            : DocListCast(Doc.MyOverlayDocs?.data).map(d => {
-                  let offsetx = 0,
-                      offsety = 0;
-                  const dref = React.createRef<HTMLDivElement>();
-                  const onPointerMove = action((e: PointerEvent, down: number[]) => {
-                      if (e.buttons === 1) {
-                          d.overlayX = e.clientX + offsetx;
-                          d.overlayY = e.clientY + offsety;
-                      }
-                      if (e.metaKey) {
-                          const dragData = new DragManager.DocumentDragData([d]);
-                          dragData.offset = [-offsetx, -offsety];
-                          dragData.dropAction = 'move';
-                          dragData.removeDocument = (doc: Doc | Doc[]) => {
-                              const docs = doc instanceof Doc ? [doc] : doc;
-                              docs.forEach(d => Doc.RemoveDocFromList(Doc.MyOverlayDocs, undefined, d));
-                              return true;
-                          };
-                          dragData.moveDocument = (doc: Doc | Doc[], targetCollection: Doc | undefined, addDocument: (doc: Doc | Doc[]) => boolean): boolean => {
-                              return dragData.removeDocument!(doc) ? addDocument(doc) : false;
-                          };
-                          DragManager.StartDocumentDrag([dref.current!], dragData, down[0], down[1]);
-                          return true;
-                      }
-                      return false;
-                  });
+        return DocListCast(Doc.MyOverlayDocs?.data)
+            .filter(d => !LightboxView.LightboxDoc || d.type === DocumentType.PRES)
+            .map(d => {
+                let offsetx = 0,
+                    offsety = 0;
+                const dref = React.createRef<HTMLDivElement>();
+                const onPointerMove = action((e: PointerEvent, down: number[]) => {
+                    if (e.buttons === 1) {
+                        d.overlayX = e.clientX + offsetx;
+                        d.overlayY = e.clientY + offsety;
+                    }
+                    if (e.metaKey) {
+                        const dragData = new DragManager.DocumentDragData([d]);
+                        dragData.offset = [-offsetx, -offsety];
+                        dragData.dropAction = 'move';
+                        dragData.removeDocument = this.removeOverlayDoc;
+                        dragData.moveDocument = (doc: Doc | Doc[], targetCollection: Doc | undefined, addDocument: (doc: Doc | Doc[]) => boolean): boolean => {
+                            return dragData.removeDocument!(doc) ? addDocument(doc) : false;
+                        };
+                        DragManager.StartDocumentDrag([dref.current!], dragData, down[0], down[1]);
+                        return true;
+                    }
+                    return false;
+                });
 
-                  const onPointerDown = (e: React.PointerEvent) => {
-                      setupMoveUpEvents(this, e, onPointerMove, emptyFunction, emptyFunction);
-                      offsetx = NumCast(d.overlayX) - e.clientX;
-                      offsety = NumCast(d.overlayY) - e.clientY;
-                  };
-                  return (
-                      <div
-                          className="overlayView-doc"
-                          ref={dref}
-                          key={d[Id]}
-                          onPointerDown={onPointerDown}
-                          style={{ top: d.type === 'presentation' ? 0 : undefined, width: NumCast(d._width), height: NumCast(d._height), transform: `translate(${d.overlayX}px, ${d.overlayY}px)` }}>
-                          <DocumentView
-                              Document={d}
-                              rootSelected={returnTrue}
-                              bringToFront={emptyFunction}
-                              addDocument={undefined}
-                              removeDocument={this.removeOverlayDoc}
-                              PanelWidth={d[WidthSym]}
-                              PanelHeight={d[HeightSym]}
-                              ScreenToLocalTransform={this.docScreenToLocalXf(d)}
-                              renderDepth={1}
-                              isDocumentActive={returnTrue}
-                              isContentActive={returnTrue}
-                              whenChildContentsActiveChanged={emptyFunction}
-                              focus={DocUtils.DefaultFocus}
-                              styleProvider={DefaultStyleProvider}
-                              docViewPath={returnEmptyDoclist}
-                              addDocTab={returnFalse}
-                              pinToPres={emptyFunction}
-                              docFilters={returnEmptyFilter}
-                              docRangeFilters={returnEmptyFilter}
-                              searchFilterDocs={returnEmptyDoclist}
-                              ContainingCollectionView={undefined}
-                              ContainingCollectionDoc={undefined}
-                          />
-                      </div>
-                  );
-              });
+                const onPointerDown = (e: React.PointerEvent) => {
+                    setupMoveUpEvents(this, e, onPointerMove, emptyFunction, emptyFunction);
+                    offsetx = NumCast(d.overlayX) - e.clientX;
+                    offsety = NumCast(d.overlayY) - e.clientY;
+                };
+                return (
+                    <div
+                        className="overlayView-doc"
+                        ref={dref}
+                        key={d[Id]}
+                        onPointerDown={onPointerDown}
+                        style={{ top: d.type === DocumentType.PRES ? 0 : undefined, width: NumCast(d._width), height: NumCast(d._height), transform: `translate(${d.overlayX}px, ${d.overlayY}px)` }}>
+                        <DocumentView
+                            Document={d}
+                            rootSelected={returnTrue}
+                            bringToFront={emptyFunction}
+                            addDocument={undefined}
+                            removeDocument={this.removeOverlayDoc}
+                            PanelWidth={d[WidthSym]}
+                            PanelHeight={d[HeightSym]}
+                            ScreenToLocalTransform={this.docScreenToLocalXf(d)}
+                            renderDepth={1}
+                            isDocumentActive={returnTrue}
+                            isContentActive={returnTrue}
+                            whenChildContentsActiveChanged={emptyFunction}
+                            focus={DocUtils.DefaultFocus}
+                            styleProvider={DefaultStyleProvider}
+                            docViewPath={returnEmptyDoclist}
+                            addDocTab={d.type === DocumentType.PRES ? MainView.addDocTabFunc : returnFalse}
+                            pinToPres={emptyFunction}
+                            docFilters={returnEmptyFilter}
+                            docRangeFilters={returnEmptyFilter}
+                            searchFilterDocs={returnEmptyDoclist}
+                            ContainingCollectionView={undefined}
+                            ContainingCollectionDoc={undefined}
+                        />
+                    </div>
+                );
+            });
     }
 
     public static ShowSpinner() {
diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx
index 4c8c65707..8919b1c01 100644
--- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx
+++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx
@@ -204,10 +204,12 @@ export class CollectionFreeFormLinkView extends React.Component<CollectionFreeFo
         const bclipped = bleft !== b.left || btop !== b.top;
         if (aclipped && bclipped) return undefined;
         const clipped = aclipped || bclipped;
+        const pt1inside = NumCast(LinkDocs[0].anchor1_x) % 100 !== 0 && NumCast(LinkDocs[0].anchor1_y) % 100 !== 0;
+        const pt2inside = NumCast(LinkDocs[0].anchor2_x) % 100 !== 0 && NumCast(LinkDocs[0].anchor2_y) % 100 !== 0;
         const pt1 = [aleft + a.width / 2, atop + a.height / 2];
         const pt2 = [bleft + b.width / 2, btop + b.width / 2];
-        const pt2vec = [(bDocBounds.left + bDocBounds.right) / 2 - pt2[0], (bDocBounds.top + bDocBounds.bottom) / 2 - pt2[1]];
-        const pt1vec = [(aDocBounds.left + aDocBounds.right) / 2 - pt1[0], (aDocBounds.top + aDocBounds.bottom) / 2 - pt1[1]];
+        const pt2vec = pt2inside ? [-0.7071, 0.7071] : [(bDocBounds.left + bDocBounds.right) / 2 - pt2[0], (bDocBounds.top + bDocBounds.bottom) / 2 - pt2[1]];
+        const pt1vec = pt1inside ? [-0.7071, 0.7071] : [(aDocBounds.left + aDocBounds.right) / 2 - pt1[0], (aDocBounds.top + aDocBounds.bottom) / 2 - pt1[1]];
         const pt1len = Math.sqrt(pt1vec[0] * pt1vec[0] + pt1vec[1] * pt1vec[1]);
         const pt2len = Math.sqrt(pt2vec[0] * pt2vec[0] + pt2vec[1] * pt2vec[1]);
         const ptlen = Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1])) / 2;
diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx
index 7fe74b876..1df46488b 100644
--- a/src/client/views/nodes/DocumentView.tsx
+++ b/src/client/views/nodes/DocumentView.tsx
@@ -1707,7 +1707,7 @@ export class DocumentView extends React.Component<DocumentViewProps> {
     toggleNativeDimensions = () => this.docView && Doc.toggleNativeDimensions(this.layoutDoc, this.docView.NativeDimScaling, this.props.PanelWidth(), this.props.PanelHeight());
     focus = (doc: Doc, options: DocFocusOptions) => this.docView?.focus(doc, options);
     getBounds = () => {
-        if (!this.docView || !this.docView.ContentDiv || this.props.Document.presBox || this.props.treeViewDoc || Doc.AreProtosEqual(this.props.Document, Doc.UserDoc())) {
+        if (!this.docView || !this.docView.ContentDiv || this.props.Document.type === DocumentType.PRES || this.props.treeViewDoc || Doc.AreProtosEqual(this.props.Document, Doc.UserDoc())) {
             return undefined;
         }
         const xf = this.docView?.props
diff --git a/src/client/views/nodes/LinkDocPreview.tsx b/src/client/views/nodes/LinkDocPreview.tsx
index b2fdd93fc..232c3459e 100644
--- a/src/client/views/nodes/LinkDocPreview.tsx
+++ b/src/client/views/nodes/LinkDocPreview.tsx
@@ -17,7 +17,6 @@ import { Transform } from '../../util/Transform';
 import { DocumentView, DocumentViewSharedProps, OpenWhere } from './DocumentView';
 import './LinkDocPreview.scss';
 import React = require('react');
-import { SelectionManager } from '../../util/SelectionManager';
 
 interface LinkDocPreviewProps {
     linkDoc?: Doc;
@@ -114,7 +113,7 @@ export class LinkDocPreview extends React.Component<LinkDocPreviewProps> {
                                     this._targetDoc = /*linkTarget?.type === DocumentType.MARKER &&*/ linkTarget?.annotationOn ? Cast(linkTarget.annotationOn, Doc, null) ?? linkTarget : linkTarget;
                                 }
                                 this._toolTipText = '';
-                                if (LinkDocPreview.LinkInfo?.noPreview) this.followLink();
+                                if (LinkDocPreview.LinkInfo?.noPreview || this._markerTargetDoc?.type === DocumentType.PRES) this.followLink();
                             }
                         })
                     );
diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
index b895043de..62e215521 100644
--- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx
+++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
@@ -1476,6 +1476,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
             let target = e.target as any; // hrefs are stored on the dataset of the <a> node that wraps the hyerlink <span>
             while (target && !target.dataset?.targethrefs) target = target.parentElement;
             FormattedTextBoxComment.update(this, editor, undefined, target?.dataset?.targethrefs, target?.dataset.linkdoc, target?.dataset.nopreview === 'true');
+            if (target) return;
         }
 
         if (e.button === 0 && this.props.isSelected(true) && !e.altKey) {
diff --git a/src/client/views/nodes/trails/PresBox.scss b/src/client/views/nodes/trails/PresBox.scss
index 4d60a02f1..fd202590e 100644
--- a/src/client/views/nodes/trails/PresBox.scss
+++ b/src/client/views/nodes/trails/PresBox.scss
@@ -938,14 +938,19 @@
         min-width: 15px;
         max-width: 100px;
         left: 8px;
+        margin: auto;
+        margin-left: unset;
+        height: 100%;
     }
 
     .presBox-presentPanel {
         display: flex;
         justify-self: end;
         width: 100%;
-        max-width: 300px;
-        min-width: 150px;
+        margin: auto;
+        margin-right: unset;
+        height: 100%;
+        position: relative;
     }
 
     select {
@@ -955,7 +960,7 @@
 
     .presBox-button {
         cursor: pointer;
-        height: 25px;
+        //height: 100%;
         border-radius: 5px;
         display: none;
         justify-content: center;
@@ -986,6 +991,9 @@
         width: max-content;
         position: absolute;
         right: 10px;
+        margin: auto;
+        margin-right: unset;
+        height: 100%;
 
         .present-icon {
             margin-right: 7px;
@@ -999,9 +1007,16 @@
         position: relative;
         display: inline-block;
         left: 8px;
+        margin: auto;
+        margin-left: unset;
     }
 }
 
+.presBox-buttons.inOverlay {
+    padding-top: unset;
+    padding-bottom: unset;
+}
+
 .presBox-backward,
 .presBox-forward {
     width: 25px;
@@ -1052,6 +1067,8 @@
             font-size: 30px;
             position: absolute;
             min-width: 50px;
+            margin: auto;
+            margin-left: unset;
         }
     }
 
@@ -1087,13 +1104,12 @@
     color: $white;
     border-radius: 5px;
     grid-template-rows: 100%;
-    height: 25;
+    height: 100%;
     width: max-content;
     min-width: max-content;
     justify-content: space-evenly;
     align-items: center;
     display: flex;
-    position: absolute;
     transition: all 0.2s;
 
     .presPanel-button-text {
diff --git a/src/client/views/nodes/trails/PresBox.tsx b/src/client/views/nodes/trails/PresBox.tsx
index a609b46e4..855a7f171 100644
--- a/src/client/views/nodes/trails/PresBox.tsx
+++ b/src/client/views/nodes/trails/PresBox.tsx
@@ -12,7 +12,7 @@ import { ObjectField } from '../../../../fields/ObjectField';
 import { listSpec } from '../../../../fields/Schema';
 import { BoolCast, Cast, DocCast, NumCast, StrCast } from '../../../../fields/Types';
 import { AudioField } from '../../../../fields/URLField';
-import { emptyPath, returnFalse, returnOne, setupMoveUpEvents, StopEvent } from '../../../../Utils';
+import { emptyFunction, emptyPath, returnFalse, returnOne, setupMoveUpEvents, StopEvent } from '../../../../Utils';
 import { DocServer } from '../../../DocServer';
 import { Docs } from '../../../documents/Documents';
 import { CollectionViewType, DocumentType } from '../../../documents/DocumentTypes';
@@ -136,6 +136,7 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
     @action
     componentWillUnmount() {
         this._unmounting = true;
+        if (this._presTimer) clearTimeout(this._presTimer);
         document.removeEventListener('keydown', PresBox.keyEventsWrapper, true);
         this.resetPresentation();
         // Turn of progressivize editors
@@ -143,7 +144,6 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
         Object.values(this._disposers).forEach(disposer => disposer?.());
     }
 
-    @action
     componentDidMount() {
         this._disposers.keyboard = reaction(
             () => this.selectedDoc,
@@ -167,10 +167,13 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
         );
         this.props.setContentView?.(this);
         this._unmounting = false;
-        this.rootDoc._forceRenderEngine = computeTimelineLayout.name;
-        this.layoutDoc.presStatus = PresStatus.Edit;
-        this.layoutDoc._gridGap = 0;
-        this.layoutDoc._yMargin = 0;
+        if (this.props.renderDepth > 0) {
+            runInAction(() => {
+                this.rootDoc._forceRenderEngine = computeTimelineLayout.name;
+                this.layoutDoc._gridGap = 0;
+                this.layoutDoc._yMargin = 0;
+            });
+        }
         this.turnOffEdit(true);
         this._disposers.selection = reaction(
             () => SelectionManager.Views(),
@@ -247,9 +250,12 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
             const slides = DocListCast(this.rootDoc[StrCast(this.presFieldKey, 'data')]);
             const curLast = this.selectedArray.size ? Math.max(...Array.from(this.selectedArray).map(d => slides.indexOf(DocCast(d)))) : this.itemIndex;
             this.nextSlide(curLast + 1 === this.childDocs.length ? (this.layoutDoc.presLoop ? 0 : curLast) : curLast + 1);
-        } else if (this.childDocs[this.itemIndex + 1] === undefined && (this.layoutDoc.presLoop || this.layoutDoc.presStatus === PresStatus.Edit)) {
-            // Case 2: Last slide and presLoop is toggled ON or it is in Edit mode
-            this.nextSlide(0);
+        } else {
+            if (this.childDocs[this.itemIndex + 1] === undefined && (this.layoutDoc.presLoop || this.layoutDoc.presStatus === PresStatus.Edit)) {
+                // Case 2: Last slide and presLoop is toggled ON or it is in Edit mode
+                this.nextSlide(0);
+            }
+            return 0;
         }
         return this.itemIndex;
     };
@@ -510,28 +516,28 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
         const srcContext = Cast(targetDoc.context, Doc, null) ?? Cast(Cast(targetDoc.annotationOn, Doc, null)?.context, Doc, null);
         const presCollection = Cast(this.layoutDoc.presCollection, Doc, null);
         const collectionDocView = presCollection ? DocumentManager.Instance.getDocumentView(presCollection) : undefined;
-        const includesDoc: boolean = DocumentManager.Instance.getDocumentView(targetDoc) ? true : false; //   DocListCast(presCollection?.data).includes(targetDoc);
+        const includesDoc = () => (DocumentManager.Instance.getDocumentView(targetDoc) ? true : false); //   DocListCast(presCollection?.data).includes(targetDoc);
         const tabMap = CollectionDockingView.Instance?.tabMap;
         const tab = tabMap && Array.from(tabMap).find(tab => tab.DashDoc === srcContext || tab.DashDoc === targetDoc);
         // Handles the setting of presCollection
-        if (includesDoc) {
+        if (includesDoc()) {
             //Case 1: Pres collection should not change as it is already the same
         } else if (tab !== undefined) {
             // Case 2: Pres collection should update
             this.layoutDoc.presCollection = srcContext;
         }
-        const presStatus = this.rootDoc.presStatus;
         const selViewCache = Array.from(this.selectedArray);
         const dragViewCache = Array.from(this._dragArray);
         const eleViewCache = Array.from(this._eleArray);
         const resetSelection = action(() => {
-            const presDocView = DocumentManager.Instance.getDocumentView(this.rootDoc);
-            if (presDocView) SelectionManager.SelectView(presDocView, false);
-            this.rootDoc.presStatus = presStatus;
-            this.clearSelectedArray();
-            selViewCache.forEach(doc => this.addToSelectedArray(doc));
-            this._dragArray.splice(0, this._dragArray.length, ...dragViewCache);
-            this._eleArray.splice(0, this._eleArray.length, ...eleViewCache);
+            if (!includesDoc()) {
+                const presDocView = DocumentManager.Instance.getDocumentView(this.rootDoc);
+                if (presDocView) SelectionManager.SelectView(presDocView, false);
+                this.clearSelectedArray();
+                selViewCache.forEach(doc => this.addToSelectedArray(doc));
+                this._dragArray.splice(0, this._dragArray.length, ...dragViewCache);
+                this._eleArray.splice(0, this._eleArray.length, ...eleViewCache);
+            }
             finished();
         });
         const createDocView = (doc: Doc, finished?: () => void) => {
@@ -539,7 +545,7 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
             (collectionDocView ?? this).props.addDocTab(doc, OpenWhere.lightbox);
             this.layoutDoc.presCollection = targetDoc;
         };
-        PresBox.NavigateToTarget(targetDoc, activeItem, createDocView, srcContext, includesDoc || tab ? finished : resetSelection);
+        PresBox.NavigateToTarget(targetDoc, activeItem, createDocView, srcContext, includesDoc() || tab ? finished : resetSelection);
     };
 
     static NavigateToTarget(targetDoc: Doc, activeItem: Doc, createDocView: any, srcContext: Doc, finished?: () => void) {
@@ -562,7 +568,6 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
             setTimeout(restoreLayout);
         } else {
             if (targetDoc) {
-                LightboxView.SetLightboxDoc(undefined);
                 const options: DocFocusOptions = {
                     willPan: activeItem.presMovement !== PresMovement.None,
                     willPanZoom: activeItem.presMovement === PresMovement.Zoom || activeItem.presMovement === PresMovement.Jump || activeItem.presMovement === PresMovement.Center,
@@ -579,10 +584,23 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
                 while (containerDocContext.length && !DocumentManager.Instance.getDocumentView(containerDocContext[0]) && containerDocContext[0].context) {
                     containerDocContext = [Cast(containerDocContext[0].context, Doc, null), ...containerDocContext];
                 }
-
+                const testTarget = containerDocContext.length ? containerDocContext[0] : targetDoc;
+                if (LightboxView.LightboxDoc && !DocumentManager.Instance.getLightboxDocumentView(testTarget)) {
+                    DocumentManager.Instance.AddViewRenderedCb(LightboxView.LightboxDoc, dv => {
+                        if (LightboxView.LightboxDoc && !DocumentManager.Instance.getLightboxDocumentView(LightboxView.LightboxDoc)) {
+                            DocumentManager.Instance.jumpToDocument(targetDoc, options, createDocView, containerDocContext, finished);
+                            restoreLayout();
+                        } else {
+                            LightboxView.SetLightboxDoc(undefined);
+                            DocumentManager.Instance.jumpToDocument(targetDoc, options, createDocView, containerDocContext, finished);
+                            restoreLayout();
+                        }
+                    });
+                    return;
+                }
                 DocumentManager.Instance.jumpToDocument(targetDoc, options, createDocView, containerDocContext, finished);
-            }
-            restoreLayout();
+                restoreLayout();
+            } else restoreLayout();
         }
     }
 
@@ -633,20 +651,19 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
         });
     };
 
-    //The function that starts or resets presentaton functionally, depending on presStatus of the layoutDoc
-    @action
-    startAutoPres = async (startSlide: number) => {
-        if (!this.childDocs.length) return;
-        this.layoutDoc.presStatus = PresStatus.Autoplay;
-        this.startPresentation(startSlide);
-        clearTimeout(this._presTimer);
-        const func = (itemIndex: number) => {
-            this._presTimer = setTimeout(() => {
-                if (itemIndex === this.next()) this.layoutDoc.presStatus = PresStatus.Manual;
-                this.layoutDoc.presStatus !== PresStatus.Manual && func(this.itemIndex);
-            }, NumCast(this.activeItem.presDuration, this.activeItem.type === DocumentType.SCRIPTING ? 0 : 2500) + NumCast(this.activeItem.presTransition));
+    _exitTrail: Opt<() => void>;
+    PlayTrail = (doc: Doc) => {
+        const savedState = { c: doc, x: NumCast(doc.panX), y: NumCast(doc.panY), s: NumCast(doc.viewScale) };
+        this.startPresentation(0);
+        this._exitTrail = () => {
+            const { x, y, s, c } = savedState;
+            c._panX = x;
+            c._panY = y;
+            c._viewScale = s;
+            LightboxView.SetLightboxDoc(undefined);
+            Doc.RemoveDocFromList(Doc.MyOverlayDocs, undefined, this.rootDoc);
+            return PresStatus.Edit;
         };
-        func(this.itemIndex);
     };
 
     // The function pauses the auto presentation
@@ -695,40 +712,54 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
      * @param startIndex: index that the presentation will start at
      */
     startPresentation = (startIndex: number) => {
-        this.childDocs.forEach(doc => {
-            const tagDoc = doc.presentationTargetDoc as Doc;
-            if (doc.presHideBefore && this.childDocs.indexOf(doc) > startIndex) {
-                tagDoc.opacity = 0;
-            }
-            if (doc.presHideAfter && this.childDocs.indexOf(doc) < startIndex) {
-                tagDoc.opacity = 0;
-            }
-        });
-        this.gotoDocument(startIndex, this.activeItem);
+        clearTimeout(this._presTimer);
+        if (this.childDocs.length) {
+            this.layoutDoc.presStatus = PresStatus.Autoplay;
+            this.childDocs.forEach(doc => {
+                const tagDoc = doc.presentationTargetDoc as Doc;
+                if (doc.presHideBefore && this.childDocs.indexOf(doc) > startIndex) tagDoc.opacity = 0;
+                if (doc.presHideAfter && this.childDocs.indexOf(doc) < startIndex) tagDoc.opacity = 0;
+                // if (doc.presHide && this.childDocs.indexOf(doc) === startIndex)  tagDoc.opacity = 0;
+            });
+            const func = () => {
+                const delay = NumCast(this.activeItem.presDuration, this.activeItem.type === DocumentType.SCRIPTING ? 0 : 2500) + NumCast(this.activeItem.presTransition);
+                this._presTimer = setTimeout(() => {
+                    if (!this.next()) this.layoutDoc.presStatus = this._exitTrail?.() ?? PresStatus.Manual;
+                    this.layoutDoc.presStatus === PresStatus.Autoplay && func();
+                }, delay);
+            };
+            this.gotoDocument(startIndex, this.activeItem, undefined, func);
+        }
     };
 
     /**
      * The method called to open the presentation as a minimized view
      */
     @action
-    updateMinimize = async () => {
+    enterMinimize = () => {
+        clearTimeout(this._presTimer);
+        const pt = this.props.ScreenToLocalTransform().inverse().transformPoint(0, 0);
+        this.props.removeDocument?.(this.layoutDoc);
+        return PresBox.OpenPresMinimized(this.rootDoc, [pt[0] + (this.props.PanelWidth() - 250), pt[1] + 10]);
+    };
+    exitMinimize = () => {
         if (DocListCast(Doc.MyOverlayDocs?.data).includes(this.layoutDoc)) {
-            this.layoutDoc.presStatus = PresStatus.Edit;
             Doc.RemoveDocFromList(Doc.MyOverlayDocs, undefined, this.rootDoc);
             CollectionDockingView.AddSplit(this.rootDoc, OpenWhereMod.right);
-        } else {
-            this.layoutDoc.presStatus = PresStatus.Edit;
-            clearTimeout(this._presTimer);
-            const pt = this.props.ScreenToLocalTransform().inverse().transformPoint(0, 0);
-            this.rootDoc.overlayX = pt[0] + (this.props.PanelWidth() - 250);
-            this.rootDoc.overlayY = pt[1] + 10;
-            this.rootDoc._height = 30;
-            this.rootDoc._width = 248;
-            Doc.AddDocToList(Doc.MyOverlayDocs, undefined, this.rootDoc);
-            this.props.removeDocument?.(this.layoutDoc);
         }
+        return PresStatus.Edit;
     };
 
+    public static minimizedWidth = 198;
+    public static OpenPresMinimized(doc: Doc, pt: number[]) {
+        doc.overlayX = pt[0];
+        doc.overlayY = pt[1];
+        doc._height = 30;
+        doc._width = PresBox.minimizedWidth;
+        Doc.AddDocToList(Doc.MyOverlayDocs, undefined, doc);
+        return (doc.presStatus = PresStatus.Manual);
+    }
+
     /**
      * Called when the user changes the view type
      * Either 'List' (stacking) or 'Slides' (carousel)
@@ -940,11 +971,13 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
                 break;
             case 'Escape':
                 if (DocListCast(Doc.MyOverlayDocs?.data).includes(this.layoutDoc)) {
-                    this.updateMinimize();
-                } else if (this.layoutDoc.presStatus === 'edit') {
+                    this.exitClicked();
+                } else if (this.layoutDoc.presStatus === PresStatus.Edit) {
                     this.clearSelectedArray();
                     this._eleArray.length = this._dragArray.length = 0;
-                } else this.layoutDoc.presStatus = 'edit';
+                } else {
+                    this.layoutDoc.presStatus = PresStatus.Edit;
+                }
                 if (this._presTimer) clearTimeout(this._presTimer);
                 handled = true;
                 break;
@@ -1797,7 +1830,7 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
                     className="dropdown-play-button"
                     onClick={undoBatch(
                         action(() => {
-                            this.updateMinimize();
+                            this.enterMinimize();
                             this.turnOffEdit(true);
                             this.gotoDocument(this.itemIndex, this.activeItem);
                         })
@@ -1820,8 +1853,8 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
     }
 
     scrollFocus = () => {
-        this.gotoDocument(0);
-        this.startOrPause(false);
+        // this.gotoDocument(0);
+        // this.startOrPause(false);
         return undefined;
     };
 
@@ -1951,8 +1984,9 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
     @computed get topPanel() {
         const mode = StrCast(this.rootDoc._viewType) as CollectionViewType;
         const isMini: boolean = this.toolbarWidth <= 100;
+        const inOverlay = DocListCast(Doc.MyOverlayDocs?.data).includes(this.layoutDoc);
         return (
-            <div className="presBox-buttons" style={{ background: Doc.ActivePresentation === this.rootDoc ? Colors.LIGHT_BLUE : undefined, display: !this.rootDoc._chromeHidden ? 'none' : undefined }}>
+            <div className={`presBox-buttons${inOverlay ? ' inOverlay' : ''}`} style={{ background: Doc.ActivePresentation === this.rootDoc ? Colors.LIGHT_BLUE : undefined, display: !this.rootDoc._chromeHidden ? 'none' : undefined }}>
                 {isMini ? null : (
                     <select className="presBox-viewPicker" style={{ display: this.layoutDoc.presStatus === 'edit' ? 'block' : 'none' }} onPointerDown={e => e.stopPropagation()} onChange={this.viewChanged} value={mode}>
                         <option onPointerDown={StopEvent} value={CollectionViewType.Stacking}>
@@ -1969,7 +2003,7 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
                     </select>
                 )}
                 <div className="presBox-presentPanel" style={{ opacity: this.childDocs.length ? 1 : 0.3 }}>
-                    <span className={`presBox-button ${this.layoutDoc.presStatus === 'edit' ? 'present' : ''}`}>
+                    <span className={`presBox-button ${this.layoutDoc.presStatus === PresStatus.Edit ? 'present' : ''}`}>
                         <div
                             className="presBox-button-left"
                             onClick={undoBatch(() => {
@@ -2001,11 +2035,15 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
     @computed get playButtons() {
         const presEnd: boolean = !this.layoutDoc.presLoop && this.itemIndex === this.childDocs.length - 1;
         const presStart: boolean = !this.layoutDoc.presLoop && this.itemIndex === 0;
+        const inOverlay = DocListCast(Doc.MyOverlayDocs?.data).includes(this.layoutDoc);
         // Case 1: There are still other frames and should go through all frames before going to next slide
         return (
             <div className="presPanelOverlay" style={{ display: this.layoutDoc.presStatus !== 'edit' ? 'inline-flex' : 'none' }}>
                 <Tooltip title={<div className="dash-tooltip">{'Loop'}</div>}>
-                    <div className="presPanel-button" style={{ color: this.layoutDoc.presLoop ? Colors.MEDIUM_BLUE : 'white' }} onClick={() => (this.layoutDoc.presLoop = !this.layoutDoc.presLoop)}>
+                    <div
+                        className="presPanel-button"
+                        style={{ color: this.layoutDoc.presLoop ? Colors.MEDIUM_BLUE : 'white' }}
+                        onPointerDown={e => setupMoveUpEvents(this, e, returnFalse, emptyFunction, () => (this.layoutDoc.presLoop = !this.layoutDoc.presLoop), false, false)}>
                         <FontAwesomeIcon icon={'redo-alt'} />
                     </div>
                 </Tooltip>
@@ -2013,42 +2051,77 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
                 <div
                     className="presPanel-button"
                     style={{ opacity: presStart ? 0.4 : 1 }}
-                    onClick={e => {
-                        this.back();
-                        if (this._presTimer) {
-                            clearTimeout(this._presTimer);
-                            this.layoutDoc.presStatus = PresStatus.Manual;
-                        }
-                        e.stopPropagation();
-                    }}>
+                    onPointerDown={e =>
+                        setupMoveUpEvents(
+                            this,
+                            e,
+                            returnFalse,
+                            emptyFunction,
+                            () => {
+                                this.back();
+                                if (this._presTimer) {
+                                    clearTimeout(this._presTimer);
+                                    this.layoutDoc.presStatus = PresStatus.Manual;
+                                }
+                                e.stopPropagation();
+                            },
+                            false,
+                            false
+                        )
+                    }>
                     <FontAwesomeIcon icon={'arrow-left'} />
                 </div>
                 <Tooltip title={<div className="dash-tooltip">{this.layoutDoc.presStatus === PresStatus.Autoplay ? 'Pause' : 'Autoplay'}</div>}>
-                    <div className="presPanel-button" onClick={e => this.startOrPause(true)}>
+                    <div className="presPanel-button" onPointerDown={e => setupMoveUpEvents(this, e, returnFalse, emptyFunction, () => this.startOrPause(true), false, false)}>
                         <FontAwesomeIcon icon={this.layoutDoc.presStatus === PresStatus.Autoplay ? 'pause' : 'play'} />
                     </div>
                 </Tooltip>
                 <div
                     className="presPanel-button"
                     style={{ opacity: presEnd ? 0.4 : 1 }}
-                    onClick={e => {
-                        this.next();
-                        if (this._presTimer) {
-                            clearTimeout(this._presTimer);
-                            this.layoutDoc.presStatus = PresStatus.Manual;
-                        }
-                        e.stopPropagation();
-                    }}>
+                    onPointerDown={e =>
+                        setupMoveUpEvents(
+                            this,
+                            e,
+                            returnFalse,
+                            emptyFunction,
+                            () => {
+                                this.next();
+                                if (this._presTimer) {
+                                    clearTimeout(this._presTimer);
+                                    this.layoutDoc.presStatus = PresStatus.Manual;
+                                }
+                                e.stopPropagation();
+                            },
+                            false,
+                            false
+                        )
+                    }>
                     <FontAwesomeIcon icon={'arrow-right'} />
                 </div>
                 <div className="presPanel-divider"></div>
                 <Tooltip title={<div className="dash-tooltip">{'Click to return to 1st slide'}</div>}>
-                    <div className="presPanel-button" style={{ border: 'solid 1px white' }} onClick={() => this.nextSlide(0)}>
+                    <div
+                        className="presPanel-button"
+                        style={{ border: 'solid 1px white' }}
+                        onPointerDown={e =>
+                            setupMoveUpEvents(
+                                this,
+                                e,
+                                returnFalse,
+                                emptyFunction,
+                                () => {
+                                    this.nextSlide(0);
+                                },
+                                false,
+                                false
+                            )
+                        }>
                         <b>1</b>
                     </div>
                 </Tooltip>
-                <div className="presPanel-button-text" onClick={() => this.gotoDocument(0, this.activeItem)} style={{ display: this.props.PanelWidth() > 250 ? 'inline-flex' : 'none' }}>
-                    Slide {this.itemIndex + 1} / {this.childDocs.length}
+                <div className="presPanel-button-text" onClick={() => this.gotoDocument(0, this.activeItem)} style={{ display: inOverlay || this.props.PanelWidth() > 250 ? 'inline-flex' : 'none' }}>
+                    {`${inOverlay ? '' : 'Slide'} ${this.itemIndex + 1} / ${this.childDocs.length}`}
                 </div>
                 <div className="presPanel-divider"></div>
                 {this.props.PanelWidth() > 250 ? (
@@ -2056,14 +2129,14 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
                         className="presPanel-button-text"
                         onClick={undoBatch(
                             action(() => {
-                                this.layoutDoc.presStatus = 'edit';
+                                this.layoutDoc.presStatus = PresStatus.Edit;
                                 clearTimeout(this._presTimer);
                             })
                         )}>
                         EXIT
                     </div>
                 ) : (
-                    <div className="presPanel-button" onClick={undoBatch(action(() => (this.layoutDoc.presStatus = 'edit')))}>
+                    <div className="presPanel-button" onPointerDown={e => setupMoveUpEvents(this, e, returnFalse, emptyFunction, this.exitClicked, false, false)}>
                         <FontAwesomeIcon icon={'times'} />
                     </div>
                 )}
@@ -2074,7 +2147,7 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
     @action
     startOrPause = (makeActive = true) => {
         makeActive && this.updateCurrentPresentation();
-        if (this.layoutDoc.presStatus === PresStatus.Manual || this.layoutDoc.presStatus === PresStatus.Edit) this.startAutoPres(this.itemIndex);
+        if (this.layoutDoc.presStatus === PresStatus.Manual || this.layoutDoc.presStatus === PresStatus.Edit) this.startPresentation(this.itemIndex);
         else this.pauseAutoPres();
     };
 
@@ -2097,9 +2170,8 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
     };
     @undoBatch
     @action
-    exitClicked = (e: PointerEvent) => {
-        this.updateMinimize();
-        this.layoutDoc.presStatus = PresStatus.Edit;
+    exitClicked = () => {
+        this.layoutDoc.presStatus = this._exitTrail?.() ?? this.exitMinimize();
         clearTimeout(this._presTimer);
     };
 
@@ -2134,8 +2206,9 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
         // needed to ensure that the childDocs are loaded for looking up fields
         this.childDocs.slice();
         const mode = StrCast(this.rootDoc._viewType) as CollectionViewType;
-        const presEnd: boolean = !this.layoutDoc.presLoop && this.itemIndex === this.childDocs.length - 1;
-        const presStart: boolean = !this.layoutDoc.presLoop && this.itemIndex === 0;
+        const presEnd = !this.layoutDoc.presLoop && this.itemIndex === this.childDocs.length - 1;
+        const presStart = !this.layoutDoc.presLoop && this.itemIndex === 0;
+        const inOverlay = DocListCast(Doc.MyOverlayDocs?.data).includes(this.layoutDoc);
         return this.props.addDocTab === returnFalse ? ( // bcz: hack!! - addDocTab === returnFalse only when this is being rendered by the OverlayView which means the doc is a mini player
             <div className="miniPres" onClick={e => e.stopPropagation()} onPointerEnter={action(e => (this._forceKeyEvents = true))}>
                 <div
@@ -2177,7 +2250,7 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
                 </div>
             </div>
         ) : (
-            <div className="presBox-cont" style={{ minWidth: DocListCast(Doc.MyOverlayDocs?.data).includes(this.layoutDoc) ? 240 : undefined }}>
+            <div className="presBox-cont" style={{ minWidth: inOverlay ? PresBox.minimizedWidth : undefined }}>
                 {this.topPanel}
                 {this.toolbar}
                 {this.newDocumentToolbarDropdown}
diff --git a/src/client/views/nodes/trails/PresElementBox.tsx b/src/client/views/nodes/trails/PresElementBox.tsx
index 5e1474b89..f1c97d26a 100644
--- a/src/client/views/nodes/trails/PresElementBox.tsx
+++ b/src/client/views/nodes/trails/PresElementBox.tsx
@@ -50,9 +50,6 @@ export class PresElementBox extends ViewBoxBaseComponent<FieldViewProps>() {
     @computed get collapsedHeight() {
         return 35;
     } // the collapsed height changes depending on the state of the presBox.  We could store this on the presentation element template if it's used by only one presentation - but if it's shared by multiple, then this value must be looked up
-    @computed get presStatus() {
-        return this.presBox.presStatus;
-    }
     @computed get selectedArray() {
         return this.presBoxView?.selectedArray;
     }
@@ -364,14 +361,7 @@ export class PresElementBox extends ViewBoxBaseComponent<FieldViewProps>() {
     };
 
     @computed get recordingIsInOverlay() {
-        let isInOverlay = false;
-        DocListCast(Doc.MyOverlayDocs.data).forEach(doc => {
-            if (doc.slides === this.rootDoc) {
-                isInOverlay = true;
-                // return
-            }
-        });
-        return isInOverlay;
+        return DocListCast(Doc.MyOverlayDocs.data).some(doc => doc.slides === this.rootDoc);
     }
 
     // a previously recorded video will have timecode defined
diff --git a/src/fields/FieldLoader.scss b/src/fields/FieldLoader.scss
index 123488c7d..9a23c3e4f 100644
--- a/src/fields/FieldLoader.scss
+++ b/src/fields/FieldLoader.scss
@@ -1,12 +1,15 @@
 .fieldLoader {
     z-index: 10000;
     width: 200px;
-    height: 50;
-    background: white;
+    height: 30;
+    background: lightblue;
     position: absolute;
     left: calc(50% - 99px);
-    top: calc(50% + 99px);
+    top: calc(50% + 110px);
     display: flex;
     align-items: center;
     padding: 20px;
+    margin: auto;
+    display: 'block';
+    box-shadow: darkslategrey 0.2vw 0.2vw 0.8vw;
 }
diff --git a/src/fields/FieldLoader.tsx b/src/fields/FieldLoader.tsx
index 36dca89f2..2a7b936f7 100644
--- a/src/fields/FieldLoader.tsx
+++ b/src/fields/FieldLoader.tsx
@@ -10,18 +10,6 @@ export class FieldLoader extends React.Component {
     public static active = false;
 
     render() {
-        return (
-            <div
-                className="fieldLoader"
-                style={{
-                    zIndex: 10000,
-                    margin: 'auto',
-                    width: 200,
-                    height: 75,
-                    background: 'lightblue',
-                    display: 'block',
-                    position: 'absolute',
-                }}>{`Requested: ${FieldLoader.ServerLoadStatus.requested} ... ${FieldLoader.ServerLoadStatus.retrieved} `}</div>
-        );
+        return <div className="fieldLoader">{`Requested: ${FieldLoader.ServerLoadStatus.requested} ... ${FieldLoader.ServerLoadStatus.retrieved} `}</div>;
     }
 }
-- 
cgit v1.2.3-70-g09d2


From 20c0190e820f2bd343693368b7ef55a91f19c880 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Tue, 14 Mar 2023 20:31:06 -0400
Subject: simplified Deserialize code.  streamlined currentUserUtils to need
 fewer compiled functions by parameterizing more functions.  .

---
 src/client/documents/Documents.ts                  |  13 +-
 src/client/util/CurrentUserUtils.ts                | 145 +++++------
 src/client/util/Scripting.ts                       |   4 +-
 src/client/util/SelectionManager.ts                |   7 +-
 src/client/util/SerializationHelper.ts             |  86 +------
 src/client/views/DashboardView.tsx                 |   1 -
 src/client/views/GestureOverlay.tsx                |   7 +-
 src/client/views/MainView.tsx                      |  20 --
 src/client/views/OverlayView.tsx                   |   1 +
 .../views/collections/CollectionDockingView.tsx    |  19 +-
 src/client/views/collections/CollectionView.tsx    |   2 +-
 src/client/views/collections/TreeView.tsx          |  10 +-
 src/client/views/nodes/DocumentView.tsx            |   2 +
 src/client/views/nodes/WebBox.tsx                  |   8 +-
 src/client/views/nodes/button/FontIconBox.tsx      | 272 +++++++--------------
 src/fields/Doc.ts                                  |  57 ++---
 src/fields/ScriptField.ts                          |  31 +--
 src/fields/util.ts                                 |  22 +-
 18 files changed, 253 insertions(+), 454 deletions(-)

(limited to 'src/client/views/OverlayView.tsx')

diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts
index 251e432ef..457811e26 100644
--- a/src/client/documents/Documents.ts
+++ b/src/client/documents/Documents.ts
@@ -200,6 +200,8 @@ export class DocumentOptions {
     'icon-nativeWidth'?: NUMt = new NumInfo('native width of icon view');
     'icon-nativeHeight'?: NUMt = new NumInfo('native height of icon view');
     'dragFactory-count'?: NUMt = new NumInfo('number of items created from a drag button (used for setting title with incrementing index)');
+    openFactoryLocation?: string; // an OpenWhere value to place the factory created document
+    openFactoryAsDelegate?: boolean; //
     lat?: number;
     lng?: number;
     infoWindowOpen?: boolean;
@@ -220,6 +222,8 @@ export class DocumentOptions {
     autoPlayAnchors?: boolean; // whether to play audio/video when an anchor is clicked in a stackedTimeline.
     dontPlayLinkOnSelect?: boolean; // whether an audio/video should start playing when a link is followed to it.
     toolTip?: string; // tooltip to display on hover
+    toolType?: string; // type of pen tool
+    expertMode?: boolean; // something available only in expert (not novice) mode
     contextMenuFilters?: List<ScriptField>;
     contextMenuScripts?: List<ScriptField>;
     contextMenuLabels?: List<string>;
@@ -1353,6 +1357,8 @@ export namespace DocUtils {
                 const script = scripts[key];
                 if (ScriptCast(doc[key])?.script.originalScript !== scripts[key] && script) {
                     doc[key] = ScriptField.MakeScript(script, {
+                        self: Doc.name,
+                        this: Doc.name,
                         dragData: DragManager.DocumentDragData.name,
                         value: 'any',
                         _readOnly_: 'boolean',
@@ -1862,11 +1868,8 @@ export namespace DocUtils {
 }
 
 ScriptingGlobals.add('Docs', Docs);
-ScriptingGlobals.add(function copyDragFactory(dragFactory: Doc) {
-    return DocUtils.copyDragFactory(dragFactory);
-});
-ScriptingGlobals.add(function delegateDragFactory(dragFactory: Doc) {
-    return DocUtils.delegateDragFactory(dragFactory);
+ScriptingGlobals.add(function copyDragFactory(dragFactory: Doc, asDelegate?: boolean) {
+    return dragFactory instanceof Doc ? (asDelegate ? DocUtils.delegateDragFactory(dragFactory) : DocUtils.copyDragFactory(dragFactory)) : dragFactory;
 });
 ScriptingGlobals.add(function makeDelegate(proto: any) {
     const d = Docs.Create.DelegateDocument(proto, { title: 'child of ' + proto.title });
diff --git a/src/client/util/CurrentUserUtils.ts b/src/client/util/CurrentUserUtils.ts
index c4fb4788c..2820c66ee 100644
--- a/src/client/util/CurrentUserUtils.ts
+++ b/src/client/util/CurrentUserUtils.ts
@@ -21,6 +21,7 @@ import { DashboardView } from "../views/DashboardView";
 import { Colors } from "../views/global/globalEnums";
 import { MainView } from "../views/MainView";
 import { ButtonType, NumButtonType } from "../views/nodes/button/FontIconBox";
+import { OpenWhere } from "../views/nodes/DocumentView";
 import { OverlayView } from "../views/OverlayView";
 import { DragManager } from "./DragManager";
 import { MakeTemplate } from "./DropConverter";
@@ -40,6 +41,8 @@ interface Button {
     numBtnMax?: number;
     switchToggle?: boolean;
     width?: number;
+    toolType?: string; // type of pen tool
+    expertMode?: boolean;// available only in expert mode
     btnList?: List<string>;
     ignoreClick?: boolean;
     buttonText?: string;
@@ -78,7 +81,7 @@ export class CurrentUserUtils {
         ];
         const requiredTypes = requiredTypeNameFields.map(({ btnOpts, template, templateOpts }) => {
             const tempBtn =  DocListCast(tempDocs?.data)?.find(doc => doc.title === btnOpts.title);
-            const reqdScripts = { onDragStart: '{ return copyDragFactory(this.dragFactory); }' };
+            const reqdScripts = { onDragStart:  '{ return copyDragFactory(this.dragFactory,this.openFactoryAsDelegate); }' };
             const assignBtnAndTempOpts = (templateBtn:Opt<Doc>, btnOpts:DocumentOptions, templateOptions:DocumentOptions) => {
                 if (templateBtn) {
                     DocUtils.AssignOpts(templateBtn,btnOpts);
@@ -105,7 +108,7 @@ export class CurrentUserUtils {
         const reqdClickOpts:DocumentOptions = {_width: 300, _height:200, system: true};
         const reqdTempOpts:{opts:DocumentOptions, script: string}[] = [
             { opts: { title: "Open In Target",        targetScriptKey: "onChildClick"},       script: "docCast(thisContainer.target).then((target) => target && (target.proto.data = new List([self])))"},
-            { opts: { title: "Open Detail On Right",  targetScriptKey: "onChildDoubleClick"}, script: "openOnRight(self.doubleClickView)"}];
+            { opts: { title: "Open Detail On Right",  targetScriptKey: "onChildDoubleClick"}, script: `openDoc(self.doubleClickView.${OpenWhere.addRight})`}];
         const reqdClickList = reqdTempOpts.map(opts => {
             const allOpts = {...reqdClickOpts, ...opts.opts};
             const clickDoc = tempClicks ? DocListCast(tempClicks.data).find(doc => doc.title === opts.opts.title): undefined;
@@ -121,11 +124,11 @@ export class CurrentUserUtils {
         const tempClicks = DocCast(doc[field]);
         const reqdClickOpts:DocumentOptions = { _width: 300, _height:200, system: true};
         const reqdTempOpts:{opts:DocumentOptions, script: string}[] = [
-            { opts: { title: "onClick"},             script: "console.log( 'click')"},
-            { opts: { title: "onDoubleClick"},       script: "console.log( 'double click')"},
-            { opts: { title: "onChildClick"},        script: "console.log( 'child click')"},
-            { opts: { title: "onChildDoubleClick"},  script: "console.log( 'child double click')"},
-            { opts: { title: "onCheckedClick"},      script: "console.log( heading, checked, containingTreeView)"},
+            { opts: { title: "onClick"},             script: "console.log('click')"},
+            { opts: { title: "onDoubleClick"},       script: "console.log('click')"},
+            { opts: { title: "onChildClick"},        script: "console.log('click')"},
+            { opts: { title: "onChildDoubleClick"},  script: "console.log('click')"},
+            { opts: { title: "onCheckedClick"},      script: "console.log(heading, checked, containingTreeView)"},
         ];
         const reqdClickList = reqdTempOpts.map(opts => {
             const allOpts = {...reqdClickOpts, ...opts.opts};
@@ -183,7 +186,7 @@ export class CurrentUserUtils {
             const allopts = {system: true, ...opts};
             return DocUtils.AssignScripts(  (curIcon?.iconTemplate === opts.iconTemplate ? 
                       DocUtils.AssignOpts(curIcon, allopts):undefined) ?? ((templateIconsDoc[iconFieldName] = MakeTemplate(creator(allopts), true, iconFieldName, templateField))),
-                {onClick:"deiconifyView(documentView)", onDoubleClick: "deiconifyViewToLightbox(documentView"});
+                {onClick:"deiconifyView(documentView)", onDoubleClick: "deiconifyViewToLightbox(documentView)"});
         };
         const labelBox = (opts: DocumentOptions, data?:string) => Docs.Create.LabelDocument({
             textTransform: "unset", letterSpacing: "unset", _singleLine: false, _minFontSize: 14, _maxFontSize: 24, borderRounding: "5px",  _width: 150, _height: 70, _xPadding: 10, _yPadding: 10, ...opts
@@ -211,7 +214,7 @@ export class CurrentUserUtils {
     /// initalizes the set of "empty<DocType>" versions of each document type with default fields.  e.g.,. emptyNote, emptyTrail
     static creatorBtnDescriptors(doc: Doc): {
         title: string, toolTip: string, icon: string,  ignoreClick?: boolean, dragFactory?: Doc, 
-        backgroundColor?: string,  clickFactory?: Doc, scripts?: { onClick?: string, onDragStart?: string}, funcs?: {onDragStart?:string, hidden?: string},
+        backgroundColor?: string, openFactoryAsDelegate?:boolean, openFactoryLocation?:string, clickFactory?: Doc, scripts?: { onClick?: string, onDragStart?: string}, funcs?: {onDragStart?:string, hidden?: string},
     }[] {
         const standardOps = (key:string) => ({ title : "Untitled "+ key, _fitWidth: false, system: true, "dragFactory-count": 0, cloneFieldFilter: new List<string>(["system"]) });
         const json = {
@@ -257,13 +260,13 @@ export class CurrentUserUtils {
                           creator:(opts:DocumentOptions)=> any // how to create the empty thing if it doesn't exist
               }[] = [
             {key: "Note",       creator: opts => Docs.Create.TextDocument("", opts),        opts: { _width: 200, _autoHeight: true }},
-            {key: "Noteboard",  creator: opts => Docs.Create.NoteTakingDocument([], opts),  opts: { _width: 250, _height: 200 }},
+            {key: "Noteboard",  creator: opts => Docs.Create.NoteTakingDocument([], opts),  opts: { _width: 250, _height: 200, _fitWidth: true}},
             {key: "Collection", creator: opts => Docs.Create.FreeformDocument([], opts),    opts: { _width: 150, _height: 100, _fitWidth: true }},
             {key: "Equation",   creator: opts => Docs.Create.EquationDocument(opts),        opts: { _width: 300, _height: 35, _backgroundGridShow: true, }},
             {key: "Webpage",    creator: opts => Docs.Create.WebDocument("",opts),          opts: { _width: 400, _height: 512, _nativeWidth: 850, useCors: true, }},
             {key: "Comparison", creator: Docs.Create.ComparisonDocument,                    opts: { _width: 300, _height: 300 }},
             {key: "Audio",      creator: opts => Docs.Create.AudioDocument(nullAudio, opts),opts: { _width: 200, _height: 100, }},
-            {key: "Map",        creator: opts => Docs.Create.MapDocument([], opts),         opts: { _width: 800, _height: 600, _showSidebar: true,  }},
+            {key: "Map",        creator: opts => Docs.Create.MapDocument([], opts),         opts: { _width: 800, _height: 600, _fitWidth: true, _showSidebar: true,  }},
             {key: "Screengrab", creator: Docs.Create.ScreenshotDocument,                    opts: { _width: 400, _height: 200 }},
             {key: "WebCam",     creator: opts => Docs.Create.WebCamDocument("", opts),      opts: { _width: 400, _height: 200, recording:true, system: true, cloneFieldFilter: new List<string>(["system"]) }},
             {key: "Button",     creator: Docs.Create.ButtonDocument,                        opts: { _width: 150, _height: 50, _xPadding: 10, _yPadding: 10, _isLinkButton: true }},
@@ -282,30 +285,34 @@ export class CurrentUserUtils {
         emptyThings.forEach(thing => DocUtils.AssignDocField(doc, "empty"+thing.key, (opts) => thing.creator(opts), {...standardOps(thing.key), ...thing.opts}, undefined, undefined, thing.funcs));
         
         return [
-            { toolTip: "Tap or drag to create a note",            title: "Note", icon: "sticky-note",   dragFactory: doc.emptyNote as Doc, },
-            { toolTip: "Tap or drag to create a note board",      title: "Notes", icon: "folder",       dragFactory: doc.emptyNoteboard as Doc, },
-            { toolTip: "Tap or drag to create a collection",      title: "Col", icon: "folder",         dragFactory: doc.emptyCollection as Doc, clickFactory: DocCast(doc.emptyTab),  scripts: { onClick: 'openOnRight(copyDragFactory(this.clickFactory))', onDragStart: '{ return copyDragFactory(this.dragFactory);}'}, },
-            { toolTip: "Tap or drag to create an equation",       title: "Math", icon: "calculator",    dragFactory: doc.emptyEquation as Doc, },
-            { toolTip: "Tap or drag to create a webpage",         title: "Web", icon: "globe-asia",     dragFactory: doc.emptyWebpage as Doc, },
-            { toolTip: "Tap or drag to create a comparison box",  title: "Compare", icon: "columns",    dragFactory: doc.emptyComparison as Doc, },
-            { toolTip: "Tap or drag to create an audio recorder", title: "Audio", icon: "microphone",   dragFactory: doc.emptyAudio as Doc,       scripts: { onClick: 'openInOverlay(copyDragFactory(this.dragFactory))', onDragStart: '{ return copyDragFactory(this.dragFactory);}'}, },
-            { toolTip: "Tap or drag to create a map",             title: "Map", icon: "map-marker-alt", dragFactory: doc.emptyMap as Doc, },
-            { toolTip: "Tap or drag to create a screen grabber",  title: "Grab", icon: "photo-video",   dragFactory: doc.emptyScreengrab as Doc,  scripts: { onClick: 'openInOverlay(copyDragFactory(this.dragFactory))', onDragStart: '{ return copyDragFactory(this.dragFactory);}'},funcs: { hidden: 'IsNoviceMode()'} },
-            { toolTip: "Tap or drag to create a WebCam recorder", title: "WebCam", icon: "photo-video", dragFactory: doc.emptyWebCam as Doc,      scripts: { onClick: 'openInOverlay(copyDragFactory(this.dragFactory))', onDragStart: '{ return copyDragFactory(this.dragFactory);}'},funcs: { hidden: 'IsNoviceMode()'}},
-            { toolTip: "Tap or drag to create a button",          title: "Button", icon: "bolt",        dragFactory: doc.emptyButton as Doc,      funcs:   { hidden: 'IsNoviceMode()'} },
-            { toolTip: "Tap or drag to create a scripting box",   title: "Script", icon: "terminal",    dragFactory: doc.emptyScript as Doc,      funcs:   { hidden: 'IsNoviceMode()'}},
-            { toolTip: "Tap or drag to create a data viz node",   title: "DataViz", icon: "file",       dragFactory: doc.emptyDataViz as Doc, },
-            { toolTip: "Tap or drag to create a bullet slide",    title: "PPT Slide", icon: "file",     dragFactory: doc.emptySlide as Doc,       funcs:   { hidden: 'IsNoviceMode()'}},
-            { toolTip: "Tap or drag to create a data note",       title: "DataNote", icon: "window-maximize", dragFactory: doc.emptyHeader as Doc,scripts: { onClick: 'openOnRight(delegateDragFactory(this.dragFactory))', onDragStart: '{ return delegateDragFactory(this.dragFactory);}'},  },
-            { toolTip: "Toggle a Calculator REPL",                title: "repl", icon: "calculator",                                              scripts: { onClick: 'addOverlayWindow("ScriptingRepl", { x: 300, y: 100, width: 200, height: 200, title: "Scripting REPL" })' } },
-          ].map(tuple => ({scripts: {onClick: 'openOnRight(copyDragFactory(this.dragFactory))', onDragStart: '{ return copyDragFactory(this.dragFactory);}'}, ...tuple, }))
+            { toolTip: "Tap or drag to create a note",            title: "Note", icon: "sticky-note",   dragFactory: doc.emptyNote as Doc,      clickFactory: DocCast(doc.emptyNote)},
+            { toolTip: "Tap or drag to create a note board",      title: "Notes", icon: "folder",       dragFactory: doc.emptyNoteboard as Doc, clickFactory: DocCast(doc.emptyNoteboard)},
+            { toolTip: "Tap or drag to create a collection",      title: "Col", icon: "folder",         dragFactory: doc.emptyCollection as Doc,clickFactory: DocCast(doc.emptyTab)},
+            { toolTip: "Tap or drag to create an equation",       title: "Math", icon: "calculator",    dragFactory: doc.emptyEquation as Doc,  clickFactory: DocCast(doc.emptyEquation)},
+            { toolTip: "Tap or drag to create a webpage",         title: "Web", icon: "globe-asia",     dragFactory: doc.emptyWebpage as Doc,   clickFactory: DocCast(doc.emptyWebpage)},
+            { toolTip: "Tap or drag to create a comparison box",  title: "Compare", icon: "columns",    dragFactory: doc.emptyComparison as Doc,clickFactory: DocCast(doc.emptyComparison)},
+            { toolTip: "Tap or drag to create an audio recorder", title: "Audio", icon: "microphone",   dragFactory: doc.emptyAudio as Doc,     clickFactory: DocCast(doc.emptyAudio),      openFactoryLocation: OpenWhere.overlay},
+            { toolTip: "Tap or drag to create a map",             title: "Map", icon: "map-marker-alt", dragFactory: doc.emptyMap as Doc,       clickFactory: DocCast(doc.emptyMap)},
+            { toolTip: "Tap or drag to create a screen grabber",  title: "Grab", icon: "photo-video",   dragFactory: doc.emptyScreengrab as Doc,clickFactory: DocCast(doc.emptyScreengrab), openFactoryLocation: OpenWhere.overlay},
+            { toolTip: "Tap or drag to create a WebCam recorder", title: "WebCam", icon: "photo-video", dragFactory: doc.emptyWebCam as Doc,    clickFactory: DocCast(doc.emptyWebCam),     openFactoryLocation: OpenWhere.overlay},
+            { toolTip: "Tap or drag to create a button",          title: "Button", icon: "bolt",        dragFactory: doc.emptyButton as Doc,    clickFactory: DocCast(doc.emptyButton)},
+            { toolTip: "Tap or drag to create a scripting box",   title: "Script", icon: "terminal",    dragFactory: doc.emptyScript as Doc,    clickFactory: DocCast(doc.emptyScript)},
+            { toolTip: "Tap or drag to create a data viz node",   title: "DataViz", icon: "file",       dragFactory: doc.emptyDataViz as Doc,   clickFactory: DocCast(doc.emptyDataViz)},
+            { toolTip: "Tap or drag to create a bullet slide",    title: "PPT Slide", icon: "file",     dragFactory: doc.emptySlide as Doc,     clickFactory: DocCast(doc.emptySlide),      openFactoryLocation: OpenWhere.overlay},
+            { toolTip: "Tap or drag to create a data note", title: "DataNote", icon: "window-maximize", dragFactory: doc.emptyHeader as Doc,    clickFactory: DocCast(doc.emptyHeader),     openFactoryAsDelegate: true },
+            { toolTip: "Toggle a Calculator REPL",                title: "repl", icon: "calculator",                                            clickFactory: "repl" as any,                openFactoryLocation: OpenWhere.overlay},
+          ].map(tuple => (
+              { openFactoryLocation: OpenWhere.addRight, 
+                scripts: { onClick:     'openDoc(copyDragFactory(this.clickFactory,this.openFactoryAsDelegate), this.openFactoryLocation)', 
+                           onDragStart: '{ return copyDragFactory(this.dragFactory,this.openFactoryAsDelegate); }'}, 
+                ...tuple, }))
     }
 
     /// Initalizes the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools
     static setupCreatorButtons(doc: Doc, dragCreatorDoc?:Doc):Doc {
         const creatorBtns = CurrentUserUtils.creatorBtnDescriptors(doc).map((reqdOpts) => {
             const btn = dragCreatorDoc ? DocListCast(dragCreatorDoc.data).find(doc => doc.title === reqdOpts.title): undefined;
-            const opts:DocumentOptions = {...OmitKeys(reqdOpts, ["funcs", "scripts", "backgroundColor"]).omit,
+            const opts:DocumentOptions = {...OmitKeys(reqdOpts, ["funcs", "scripts", "backgroundColor"]).omit, 
                 _nativeWidth: 50, _nativeHeight: 50, _width: 35, _height: 35, _hideContextMenu: true, _stayInCollection: true, 
                 btnType: ButtonType.ToolButton, backgroundColor: reqdOpts.backgroundColor ?? Colors.DARK_GRAY, color: Colors.WHITE, system: true,
                 _removeDropProperties: new List<string>(["_stayInCollection"]),
@@ -603,53 +610,50 @@ export class CurrentUserUtils {
 
     static textTools():Button[] {
         return [
-            { title: "Font",    toolTip: "Font", width: 100,     btnType: ButtonType.DropdownList,               ignoreClick: true, scripts: {script: 'setFont(value, _readOnly_)'},
+            { title: "Font",    toolTip: "Font", width: 100,     btnType: ButtonType.DropdownList,                      toolType:"font",     ignoreClick: true,   scripts: {script:  '{ return setFontAttr(self.toolType, value, _readOnly_);}'},
               btnList: new List<string>(["Roboto", "Roboto Mono", "Nunito", "Times New Roman", "Arial", "Georgia", "Comic Sans MS", "Tahoma", "Impact", "Crimson Text"]) },
-            { title: "Size",    toolTip: "Font size", width: 75, btnType: ButtonType.NumberButton,               ignoreClick: true, scripts: {script:  '{ return setFontSize(value, _readOnly_);}'}, numBtnMax: 200, numBtnMin: 0, numBtnType: NumButtonType.DropdownOptions },
-            { title: "Color",   toolTip: "Font color",           btnType: ButtonType.ColorButton,  icon: "font", ignoreClick: true, scripts: {script:  '{ return setFontColor(value, _readOnly_);}'}},
-            { title: "Highlight",toolTip:"Font highlight",       btnType: ButtonType.ColorButton,  icon: "highlighter", ignoreClick: true, scripts: {script:  '{ return setFontHighlight(value, _readOnly_);}'},funcs: {hidden: "IsNoviceMode()"} },
-            { title: "Bold",    toolTip: "Bold (Ctrl+B)",        btnType: ButtonType.ToggleButton, icon: "bold",                    scripts: {onClick: '{ return toggleBold(_readOnly_); }'} },
-            { title: "Italic",  toolTip: "Italic (Ctrl+I)",      btnType: ButtonType.ToggleButton, icon: "italic",                  scripts: {onClick: '{ return toggleItalic(_readOnly_);}'} },
-            { title: "Under",   toolTip: "Underline (Ctrl+U)",   btnType: ButtonType.ToggleButton, icon: "underline",               scripts: {onClick: '{ return toggleUnderline(_readOnly_);}'} },
-            { title: "Bullets", toolTip: "Bullet List",          btnType: ButtonType.ToggleButton, icon: "list",                    scripts: {onClick: '{ return setBulletList("bullet", _readOnly_);}'} },
-            { title: "#",       toolTip: "Number List",          btnType: ButtonType.ToggleButton, icon: "list-ol",                 scripts: {onClick: '{ return setBulletList("decimal", _readOnly_);}'} },
-
+            { title: "Size",    toolTip: "Font size", width: 75, btnType: ButtonType.NumberButton,                      toolType:"fontSize", ignoreClick: true,   scripts: {script:  '{ return setFontAttr(self.toolType, value, _readOnly_);}'}, numBtnMax: 200, numBtnMin: 0, numBtnType: NumButtonType.DropdownOptions },
+            { title: "Color",   toolTip: "Font color",           btnType: ButtonType.ColorButton,  icon: "font",        toolType:"fontColor",ignoreClick: true,   scripts: {script:  '{ return setFontAttr(self.toolType, value, _readOnly_);}'}},
+            { title: "Highlight",toolTip:"Font highlight",       btnType: ButtonType.ColorButton,  icon: "highlighter", toolType:"highlight",ignoreClick: true,   scripts: {script:  '{ return setFontAttr(self.toolType, value, _readOnly_);}'},funcs: {hidden: "IsNoviceMode()"} },
+            { title: "Bold",    toolTip: "Bold (Ctrl+B)",        btnType: ButtonType.ToggleButton, icon: "bold",        toolType:"bold",                          scripts: {onClick: '{ return toggleCharStyle(self.toolType, _readOnly_);}'} },
+            { title: "Italic",  toolTip: "Italic (Ctrl+I)",      btnType: ButtonType.ToggleButton, icon: "italic",      toolType:"italics",                       scripts: {onClick: '{ return toggleCharStyle(self.toolType, _readOnly_);}'} },
+            { title: "Under",   toolTip: "Underline (Ctrl+U)",   btnType: ButtonType.ToggleButton, icon: "underline",   toolType:"underline",                     scripts: {onClick: '{ return toggleCharStyle(self.toolType, _readOnly_);}'} },
+            { title: "Bullets", toolTip: "Bullet List",          btnType: ButtonType.ToggleButton, icon: "list",        toolType:"bullet",                        scripts: {onClick: '{ return toggleCharStyle(self.toolType, _readOnly_);}'} },
+            { title: "#",       toolTip: "Number List",          btnType: ButtonType.ToggleButton, icon: "list-ol",     toolType:"decimal",                       scripts: {onClick: '{ return toggleCharStyle(self.toolType, _readOnly_);}'} },
+            { title: "Left",    toolTip: "Left align",           btnType: ButtonType.ToggleButton, icon: "align-left",  toolType:"left",                          scripts: {onClick: '{ return toggleCharStyle(self.toolType, _readOnly_);}' }},
+            { title: "Center",  toolTip: "Center align",         btnType: ButtonType.ToggleButton, icon: "align-center",toolType:"center",                        scripts: {onClick: '{ return toggleCharStyle(self.toolType, _readOnly_);}'} },
+            { title: "Right",   toolTip: "Right align",          btnType: ButtonType.ToggleButton, icon: "align-right", toolType:"right",                         scripts: {onClick: '{ return toggleCharStyle(self.toolType, _readOnly_);}'} },
+            { title: "Dictate", toolTip: "Dictate",              btnType: ButtonType.ToggleButton, icon: "microphone",  toolType:"dictation",                     scripts: {onClick: '{ return toggleCharStyle(self.toolType, _readOnly_);}'}},
+            { title: "NoLink",  toolTip: "Auto Link",            btnType: ButtonType.ToggleButton, icon: "link",        toolType:"noAutoLink", expertMode:true,   scripts: {onClick: '{ return toggleCharStyle(self.toolType, _readOnly_);}'}, funcs: {hidden: 'IsNoviceMode()'}},
             // { title: "Strikethrough", tooltip: "Strikethrough", btnType: ButtonType.ToggleButton, icon: "strikethrough", scripts: {onClick:: 'toggleStrikethrough()'}},
             // { title: "Superscript", tooltip: "Superscript", btnType: ButtonType.ToggleButton, icon: "superscript", scripts: {onClick:: 'toggleSuperscript()'}},
             // { title: "Subscript", tooltip: "Subscript", btnType: ButtonType.ToggleButton, icon: "subscript", scripts: {onClick:: 'toggleSubscript()'}},
-            { title: "Left",   toolTip: "Left align",   btnType: ButtonType.ToggleButton, icon: "align-left",   scripts: {onClick:'{ return setAlignment("left", _readOnly_);}' }},
-            { title: "Center", toolTip: "Center align", btnType: ButtonType.ToggleButton, icon: "align-center", scripts: {onClick:'{ return setAlignment("center", _readOnly_);}'} },
-            { title: "Right",  toolTip: "Right align",  btnType: ButtonType.ToggleButton, icon: "align-right",  scripts: {onClick:'{ return setAlignment("right", _readOnly_);}'} },
-            { title: "NoLink", toolTip: "Auto Link",    btnType: ButtonType.ToggleButton, icon: "link",         scripts: {onClick:'{ return toggleNoAutoLinkAnchor(_readOnly_);}'}, funcs: {hidden: '!SelectionManager_selectedDocType(undefined, "freeform") || IsNoviceMode()'}},
-            { title: "Dictate",toolTip: "Dictate",      btnType: ButtonType.ToggleButton, icon: "microphone",   scripts: {onClick:'{ return toggleDictation(_readOnly_);}'}},
-        ];
+             ];
     }
 
     static inkTools():Button[] {
         return [
-            { title: "Pen",    toolTip: "Pen (Ctrl+P)",          btnType: ButtonType.ToggleButton, icon: "pen-nib",                     scripts: {onClick:'{ return setActiveTool("pen", false, _readOnly_);}' }},
-            { title: "Write",  toolTip: "Write (Ctrl+Shift+P)",  btnType: ButtonType.ToggleButton, icon: "pen",                         scripts: {onClick:'{ return setActiveTool("write", false, _readOnly_);}'} },
-            { title: "Eraser", toolTip: "Eraser (Ctrl+E)",       btnType: ButtonType.ToggleButton, icon: "eraser",                      scripts: {onClick:'{ return setActiveTool("eraser", false, _readOnly_);}' }},
-            // { title: "Highlighter", toolTip: "Highlighter (Ctrl+H)", btnType: ButtonType.ToggleButton, icon: "highlighter", scripts:{onClick: 'setActiveTool("highlighter")'} },
-            { title: "Circle", toolTip: "Circle (double tap to lock mode)", btnType: ButtonType.ToggleButton, icon: "circle",           scripts: {onClick:`{ return setActiveTool("${GestureUtils.Gestures.Circle}", false, _readOnly_);}`, onDoubleClick:`{ return setActiveTool("${GestureUtils.Gestures.Circle}", true, _readOnly_);}`} },
-            { title: "Square", toolTip: "Square (double tap to lock mode)", btnType: ButtonType.ToggleButton, icon: "square",           scripts: {onClick:`{ return setActiveTool("${GestureUtils.Gestures.Rectangle}", false, _readOnly_);}`, onDoubleClick:`{ return setActiveTool("${GestureUtils.Gestures.Rectangle}", true, _readOnly_);}`} },
-            { title: "Line",   toolTip: "Line (double tap to lock mode)",   btnType: ButtonType.ToggleButton, icon: "minus",            scripts: {onClick:`{ return setActiveTool("${GestureUtils.Gestures.Line}", false, _readOnly_);}`, onDoubleClick:`{ return setActiveTool("${GestureUtils.Gestures.Line}", true, _readOnly_);}`} },
-            { title: "Mask",   toolTip: "Mask",                  btnType: ButtonType.ToggleButton, icon: "user-circle",                 scripts: {onClick:'{ return setIsInkMask(_readOnly_);}'} },
-            { title: "Fill",   toolTip: "Fill color",            btnType: ButtonType.ColorButton,  icon: "fill-drip",ignoreClick: true, scripts: {script: '{ return setFillColor(value, _readOnly_);}'} },
-            { title: "Width",  toolTip: "Stroke width",          btnType: ButtonType.NumberButton,                   ignoreClick: true, scripts: {script: '{ return setStrokeWidth(value, _readOnly_);}'}, numBtnType: NumButtonType.Slider, numBtnMin: 1},
-            { title: "Color",  toolTip: "Stroke color",          btnType: ButtonType.ColorButton,  icon: "pen",      ignoreClick: true, scripts: {script: '{ return setStrokeColor(value, _readOnly_);}'} },
+            { title: "Pen",    toolTip: "Pen (Ctrl+P)",                     btnType: ButtonType.ToggleButton, icon: "pen-nib",    toolType: "pen",                            scripts: {onClick:'{ return setActiveTool(self.toolType, false, _readOnly_);}' }},
+            { title: "Write",  toolTip: "Write (Ctrl+Shift+P)",             btnType: ButtonType.ToggleButton, icon: "pen",        toolType: "write",                          scripts: {onClick:'{ return setActiveTool(self.toolType, false, _readOnly_);}'} },
+            { title: "Eraser", toolTip: "Eraser (Ctrl+E)",                  btnType: ButtonType.ToggleButton, icon: "eraser",     toolType: "eraser",                         scripts: {onClick:'{ return setActiveTool(self.toolType, false, _readOnly_);}' }},
+            { title: "Circle", toolTip: "Circle (double tap to lock mode)", btnType: ButtonType.ToggleButton, icon: "circle",     toolType:GestureUtils.Gestures.Circle,      scripts: {onClick:`{ return setActiveTool(self.toolType, false, _readOnly_);}`, onDoubleClick:`{ return setActiveTool(self.toolType, true, _readOnly_);}`} },
+            { title: "Square", toolTip: "Square (double tap to lock mode)", btnType: ButtonType.ToggleButton, icon: "square",     toolType:GestureUtils.Gestures.Rectangle,   scripts: {onClick:`{ return setActiveTool(self.toolType, false, _readOnly_);}`, onDoubleClick:`{ return setActiveTool(self.toolType, true, _readOnly_);}`} },
+            { title: "Line",   toolTip: "Line (double tap to lock mode)",   btnType: ButtonType.ToggleButton, icon: "minus",      toolType:GestureUtils.Gestures.Line,        scripts: {onClick:`{ return setActiveTool(self.toolType, false, _readOnly_);}`, onDoubleClick:`{ return setActiveTool(self.toolType, true, _readOnly_);}`} },
+            { title: "Mask",   toolTip: "Mask",                             btnType: ButtonType.ToggleButton, icon: "user-circle",toolType: "inkMask",                        scripts: {onClick:'{ return setInkProperty(self.toolType, value, _readOnly_);}'} },
+            { title: "Fill",   toolTip: "Fill color",                       btnType: ButtonType.ColorButton,  icon: "fill-drip",  toolType: "fillColor",   ignoreClick: true, scripts: {script: '{ return setInkProperty(self.toolType, value, _readOnly_);}'} },
+            { title: "Width",  toolTip: "Stroke width",                     btnType: ButtonType.NumberButton,                     toolType: "strokeWidth", ignoreClick: true, scripts: {script: '{ return setInkProperty(self.toolType, value, _readOnly_);}'}, numBtnType: NumButtonType.Slider, numBtnMin: 1},
+            { title: "Color",  toolTip: "Stroke color",                     btnType: ButtonType.ColorButton,  icon: "pen",        toolType: "strokeColor", ignoreClick: true, scripts: {script: '{ return setInkProperty(self.toolType, value, _readOnly_);}'} },
         ];
     }
 
     static schemaTools():Button[] {
-        return [{ title: "Show preview", toolTip: "Show preview of selected document", btnType: ButtonType.ToggleButton, buttonText: "Show Preview", icon: "eye", scripts:{ onClick: '{return toggleSchemaPreview(_readOnly_);}'}, }];
+        return [{ title: "Show preview", toolTip: "Show selection preview", btnType: ButtonType.ToggleButton, buttonText: "Show Preview", icon: "eye", scripts:{ onClick: '{ return toggleSchemaPreview(_readOnly_); }'}, }];
     }
 
     static webTools() {
         return [
             { title: "Back",    toolTip: "Go back",         btnType: ButtonType.ClickButton,  icon: "arrow-left",              scripts: { onClick: '{ return webBack(_readOnly_); }' }},
             { title: "Forward", toolTip: "Go forward",      btnType: ButtonType.ClickButton,  icon: "arrow-right",             scripts: { onClick: '{ return webForward(_readOnly_); }'}},
-            //{ title: "Reload", toolTip: "Reload webpage", btnType: ButtonType.ClickButton, icon: "redo-alt", click: 'webReload()' },
             { title: "URL",     toolTip: "URL", width: 250, btnType: ButtonType.EditableText, icon: "lock", ignoreClick: true, scripts: { script: '{ return webSetURL(value, _readOnly_); }'} },
         ];
     }
@@ -661,18 +665,18 @@ export class CurrentUserUtils {
                     CollectionViewType.Multirow, CollectionViewType.Time, CollectionViewType.Carousel,
                     CollectionViewType.Carousel3D, CollectionViewType.Linear, CollectionViewType.Map,
                     CollectionViewType.Grid, CollectionViewType.NoteTaking]),
-              title: "Perspective",                    toolTip: "View",                 btnType: ButtonType.DropdownList,                                                                                    ignoreClick: true, width: 100, scripts: { script: 'setView(value, _readOnly_)'}},
-            { title: "Pin",     icon: "map-pin",       toolTip: "Pin View to Trail",    btnType: ButtonType.ClickButton,         funcs: {hidden: '!SelectionManager_selectedDocType(undefined, "tab")'},                        width: 20,  scripts: { onClick: 'pinWithView(_readOnly_, altKey)'}},
-            { title: "Back",    icon: "chevron-left",  toolTip: "Prev Animation Frame", btnType: ButtonType.ClickButton,         funcs: {hidden: '!SelectionManager_selectedDocType(undefined, "freeform") || IsNoviceMode()'}, width: 20,  scripts: { onClick: 'prevKeyFrame(_readOnly_)'}},
-            { title: "Num",icon: "",toolTip: "Frame Number (click to toggle edit mode)",btnType: ButtonType.TextButton,          funcs: {hidden: '!SelectionManager_selectedDocType(undefined, "freeform") || IsNoviceMode()', buttonText: 'selectedDocs()?.lastElement()?.currentFrame?.toString()'}, width: 20, scripts: { onClick: '{ return curKeyFrame(_readOnly_);}'}},
-            { title: "Fwd",     icon: "chevron-right", toolTip: "Next Animation Frame", btnType: ButtonType.ClickButton,         funcs: {hidden: '!SelectionManager_selectedDocType(undefined, "freeform") || IsNoviceMode()'}, width: 20,  scripts: { onClick: 'nextKeyFrame(_readOnly_)'}},
-            { title: "Fill",    icon: "fill-drip",     toolTip: "Background Fill Color",btnType: ButtonType.ColorButton,         funcs: {hidden: '!SelectionManager_selectedDocType()'},                     ignoreClick: true, width: 20,  scripts: { script:  'return setBackgroundColor(value, _readOnly_)'}}, // Only when a document is selected
-            { title: "Header",  icon: "heading",       toolTip: "Header Color",         btnType: ButtonType.ColorButton,         funcs: {hidden: '!SelectionManager_selectedDocType()'},                     ignoreClick: true,             scripts: { script:  'return setHeaderColor(value, _readOnly_)'}},
-            { title: "Overlay", icon: "layer-group",   toolTip: "Overlay",              btnType: ButtonType.ToggleButton,        funcs: {hidden: '!SelectionManager_selectedDocType(undefined, "freeform", true)'},                         scripts: { onClick: 'toggleOverlay(_readOnly_)'}}, // Only when floating document is selected in freeform
-            { title: "Text",    icon: "Text",          toolTip: "Text functions",       subMenu: CurrentUserUtils.textTools(),   funcs: {hidden: 'false',                                                                        linearViewIsExpanded: `SelectionManager_selectedDocType("${DocumentType.RTF}")`} }, // Always available
-            { title: "Ink",     icon: "Ink",           toolTip: "Ink functions",        subMenu: CurrentUserUtils.inkTools(),    funcs: {hidden: 'false',                                                                        linearViewIsExpanded: `SelectionManager_selectedDocType("${DocumentType.INK}")`}, scripts: { onClick: 'setInkToolDefaults()'} }, // Always available
-            { title: "Web",     icon: "Web",           toolTip: "Web functions",        subMenu: CurrentUserUtils.webTools(),    funcs: {hidden: `!SelectionManager_selectedDocType("${DocumentType.WEB}")`,                     linearViewIsExpanded: `SelectionManager_selectedDocType("${DocumentType.WEB}")`,                     } }, // Only when Web is selected
-            { title: "Schema",  icon: "Schema",        toolTip: "Schema functions",     subMenu: CurrentUserUtils.schemaTools(), funcs: {hidden: `!SelectionManager_selectedDocType(undefined, "${CollectionViewType.Schema}")`, linearViewIsExpanded: `SelectionManager_selectedDocType(undefined, "${CollectionViewType.Schema}")`} } // Only when Schema is selected
+              title: "Perspective",                    toolTip: "View",                 btnType: ButtonType.DropdownList,                                                                                                                                    ignoreClick: true, width: 100, scripts: { script: 'setView(value, _readOnly_)'}},
+            { title: "Pin",     icon: "map-pin",       toolTip: "Pin View to Trail",    btnType: ButtonType.ClickButton,         expertMode: false, toolType:"tab",                       funcs: {hidden: `!SelectionManager_selectedDocType(self.toolType, self.expertMode)`}, width: 20,  scripts: { onClick: 'pinWithView(_readOnly_, altKey)'}},
+            { title: "Fill",    icon: "fill-drip",     toolTip: "Background Fill Color",btnType: ButtonType.ColorButton,         expertMode: false, toolType:"tab",                                                                                          ignoreClick: true, width: 20,  scripts: { script:  'return setBackgroundColor(value, _readOnly_)'}}, // Only when a document is selected
+            { title: "Header",  icon: "heading",       toolTip: "Header Color",         btnType: ButtonType.ColorButton,         expertMode: false, toolType:"tab",                                                                                          ignoreClick: true,             scripts: { script:  'return setHeaderColor(value, _readOnly_)'}},
+            { title: "Overlay", icon: "layer-group",   toolTip: "Overlay",              btnType: ButtonType.ToggleButton,        expertMode: false, toolType:CollectionViewType.Freeform, funcs: {hidden: '!SelectionManager_selectedDocType(self.toolType, self.expertMode, true)'},       scripts: { onClick: 'toggleOverlay(_readOnly_)'}}, // Only when floating document is selected in freeform
+            { title: "Back",    icon: "chevron-left",  toolTip: "Prev Animation Frame", btnType: ButtonType.ClickButton,         expertMode: true,  toolType:CollectionViewType.Freeform, funcs: {hidden: '!SelectionManager_selectedDocType(self.toolType, self.expertMode)'}, width: 20,  scripts: { onClick: 'prevKeyFrame(_readOnly_)'}},
+            { title: "Num", icon:"",toolTip: "Frame Number (click to toggle edit mode)",btnType: ButtonType.TextButton,          expertMode: true,  toolType:CollectionViewType.Freeform, funcs: {hidden: '!SelectionManager_selectedDocType(self.toolType, self.expertMode)', buttonText: 'selectedDocs()?.lastElement()?.currentFrame?.toString()'}, width: 20, scripts: { onClick: '{ return curKeyFrame(_readOnly_);}'}},
+            { title: "Fwd",     icon: "chevron-right", toolTip: "Next Animation Frame", btnType: ButtonType.ClickButton,         expertMode: true,  toolType:CollectionViewType.Freeform, funcs: {hidden: '!SelectionManager_selectedDocType(self.toolType, self.expertMode)'}, width: 20,  scripts: { onClick: 'nextKeyFrame(_readOnly_)'}},
+            { title: "Text",    icon: "Text",          toolTip: "Text functions",       subMenu: CurrentUserUtils.textTools(),   expertMode: false, toolType:DocumentType.RTF,            funcs: {                                                                             linearViewIsExpanded: `SelectionManager_selectedDocType(self.toolType, self.expertMode)`} }, // Always available
+            { title: "Ink",     icon: "Ink",           toolTip: "Ink functions",        subMenu: CurrentUserUtils.inkTools(),    expertMode: false, toolType:DocumentType.INK,            funcs: {                                                                             linearViewIsExpanded: `SelectionManager_selectedDocType(self.toolType, self.expertMode)`}, scripts: { onClick: 'setInkToolDefaults()'} }, // Always available
+            { title: "Web",     icon: "Web",           toolTip: "Web functions",        subMenu: CurrentUserUtils.webTools(),    expertMode: false, toolType:DocumentType.WEB,            funcs: {hidden: `!SelectionManager_selectedDocType(self.toolType, self.expertMode)`, linearViewIsExpanded: `SelectionManager_selectedDocType(self.toolType, self.expertMode)`} }, // Only when Web is selected
+            { title: "Schema",  icon: "Schema",        toolTip: "Schema functions",     subMenu: CurrentUserUtils.schemaTools(), expertMode: false, toolType:CollectionViewType.Schema,   funcs: {hidden: `!SelectionManager_selectedDocType(self.toolType, self.expertMode)`, linearViewIsExpanded: `SelectionManager_selectedDocType(self.toolType, self.expertMode)`} } // Only when Schema is selected
         ];
     }
 
@@ -684,6 +688,7 @@ export class CurrentUserUtils {
             color: Colors.WHITE, system: true, dontUndo: true, 
             _nativeWidth: params.width ?? 30, _width: params.width ?? 30,
             _height: 30, _nativeHeight: 30, 
+            toolType: params.toolType, expertMode: params.expertMode,
             _stayInCollection: true, _hideContextMenu: true, _lockedPosition: true,
             _removeDropProperties: new List<string>([ "_stayInCollection"]),
         };
diff --git a/src/client/util/Scripting.ts b/src/client/util/Scripting.ts
index 6dcdcb71b..d32298c83 100644
--- a/src/client/util/Scripting.ts
+++ b/src/client/util/Scripting.ts
@@ -248,8 +248,10 @@ export function CompileScript(script: string, options: ScriptOptions = {}): Comp
         ScriptingGlobals.resetScriptingGlobals();
     }
     !signature.includes('XXX') && ScriptField._scriptFieldCache.set(script + ':' + signature, result as CompiledScript);
-    //console.log('COMPILED: ' + script + ':' + signature);
     return result;
 }
 
 ScriptingGlobals.add(CompileScript);
+ScriptingGlobals.add(function runScript(self: Doc, script: ScriptField) {
+    return script?.script.run({ this: self, self: self }).result;
+});
diff --git a/src/client/util/SelectionManager.ts b/src/client/util/SelectionManager.ts
index c0fc25376..0f4f77588 100644
--- a/src/client/util/SelectionManager.ts
+++ b/src/client/util/SelectionManager.ts
@@ -104,10 +104,11 @@ export namespace SelectionManager {
         return Array.from(manager.SelectedViews.values()).filter(doc => doc?._viewType !== CollectionViewType.Docking);
     }
 }
-ScriptingGlobals.add(function SelectionManager_selectedDocType(docType?: DocumentType, colType?: CollectionViewType, checkContext?: boolean) {
-    if (colType === ('tab' as any)) {
+ScriptingGlobals.add(function SelectionManager_selectedDocType(type: string, expertMode: boolean, checkContext?: boolean) {
+    if (Doc.noviceMode && expertMode) return false;
+    if (type === 'tab') {
         return SelectionManager.Views().lastElement()?.props.renderDepth === 0;
     }
     let selected = (sel => (checkContext ? DocCast(sel?.context) : sel))(SelectionManager.SelectedSchemaDoc() ?? SelectionManager.Docs().lastElement());
-    return docType ? selected?.type === docType : colType ? selected?.viewType === colType : true;
+    return selected?.type === type || selected?.viewType === type || !type;
 });
diff --git a/src/client/util/SerializationHelper.ts b/src/client/util/SerializationHelper.ts
index 2d1f61cfb..76037a7e9 100644
--- a/src/client/util/SerializationHelper.ts
+++ b/src/client/util/SerializationHelper.ts
@@ -44,12 +44,8 @@ export namespace SerializationHelper {
         }
 
         if (!obj.__type) {
-            if (true || ClientUtils.RELEASE) {
-                console.warn("No property 'type' found in JSON.");
-                return undefined;
-            } else {
-                throw Error("No property 'type' found in JSON.");
-            }
+            console.warn("No property 'type' found in JSON.");
+            return undefined;
         }
 
         if (!(obj.__type in serializationTypes)) {
@@ -58,9 +54,8 @@ export namespace SerializationHelper {
 
         const type = serializationTypes[obj.__type];
         const value = await new Promise(res => deserialize(type.ctor, obj, (err, result) => res(result)));
-        if (type.afterDeserialize) {
-            type.afterDeserialize(value);
-        }
+        type.afterDeserialize?.(value);
+
         return value;
     }
 }
@@ -68,75 +63,20 @@ export namespace SerializationHelper {
 const serializationTypes: { [name: string]: { ctor: { new (): any }; afterDeserialize?: (obj: any) => void | Promise<any> } } = {};
 const reverseMap: { [ctor: string]: string } = {};
 
-export interface DeserializableOpts {
-    (constructor: { new (...args: any[]): any }): void;
-    withFields(fields: string[]): Function;
-}
-
-export function Deserializable(name: string, afterDeserialize?: (obj: any) => void | Promise<any>): DeserializableOpts;
-export function Deserializable(constructor: { new (...args: any[]): any }): void;
-export function Deserializable(constructor: { new (...args: any[]): any } | string, afterDeserialize?: (obj: any) => void): DeserializableOpts | void {
-    function addToMap(name: string, ctor: { new (...args: any[]): any }) {
+export function Deserializable(className: string, afterDeserialize?: (obj: any) => void | Promise<any>, constructorArgs?: [string]): (constructor: { new (...args: any[]): any }) => void {
+    function addToMap(className: string, ctor: { new (...args: any[]): any }) {
         const schema = getDefaultModelSchema(ctor) as any;
-        if (schema.targetClass !== ctor) {
-            const newSchema = { ...schema, factory: () => new ctor() };
-            setDefaultModelSchema(ctor, newSchema);
+        if (schema.targetClass !== ctor || constructorArgs) {
+            setDefaultModelSchema(ctor, { ...schema, factory: (context: any) => new ctor(...(constructorArgs ?? [])?.map(arg => context.json[arg])) });
         }
-        if (!(name in serializationTypes)) {
-            serializationTypes[name] = { ctor, afterDeserialize };
-            reverseMap[ctor.name] = name;
+        if (!(className in serializationTypes)) {
+            serializationTypes[className] = { ctor, afterDeserialize };
+            reverseMap[ctor.name] = className;
         } else {
-            throw new Error(`Name ${name} has already been registered as deserializable`);
+            throw new Error(`Name ${className} has already been registered as deserializable`);
         }
     }
-    if (typeof constructor === 'string') {
-        return Object.assign(
-            (ctor: { new (...args: any[]): any }) => {
-                addToMap(constructor, ctor);
-            },
-            { withFields: (fields: string[]) => Deserializable.withFields(fields, constructor, afterDeserialize) }
-        );
-    }
-    addToMap(constructor.name, constructor);
-}
-
-export namespace Deserializable {
-    export function withFields(fields: string[], name?: string, afterDeserialize?: (obj: any) => void | Promise<any>) {
-        return function (constructor: { new (...fields: any[]): any }) {
-            Deserializable(name || constructor.name, afterDeserialize)(constructor);
-            let schema = getDefaultModelSchema(constructor);
-            if (schema) {
-                schema.factory = context => {
-                    const args = fields.map(key => context.json[key]);
-                    return new constructor(...args);
-                };
-                // TODO A modified version of this would let us not reassign fields that we're passing into the constructor later on in deserializing
-                // fields.forEach(field => {
-                //     if (field in schema.props) {
-                //         let propSchema = schema.props[field];
-                //         if (propSchema === false) {
-                //             return;
-                //         } else if (propSchema === true) {
-                //             propSchema = primitive();
-                //         }
-                //         schema.props[field] = custom(propSchema.serializer,
-                //             () => {
-                //                 return SKIP;
-                //             });
-                //     }
-                // });
-            } else {
-                schema = {
-                    props: {},
-                    factory: context => {
-                        const args = fields.map(key => context.json[key]);
-                        return new constructor(...args);
-                    },
-                };
-                setDefaultModelSchema(constructor, schema);
-            }
-        };
-    }
+    return (ctor: { new (...args: any[]): any }) => addToMap(className, ctor);
 }
 
 export function autoObject(): PropSchema {
diff --git a/src/client/views/DashboardView.tsx b/src/client/views/DashboardView.tsx
index 7ebe8d0e3..2b586b0e2 100644
--- a/src/client/views/DashboardView.tsx
+++ b/src/client/views/DashboardView.tsx
@@ -233,7 +233,6 @@ export class DashboardView extends React.Component {
     /// this also sets the readonly state of the dashboard based on the current mode of dash (from its url)
     public static openDashboard = (doc: Doc | undefined, fromHistory = false) => {
         if (!doc) return false;
-        Doc.MainDocId = doc[Id];
         Doc.AddDocToList(Doc.MyDashboards, 'data', doc);
 
         // this has the side-effect of setting the main container since we're assigning the active/guest dashboard
diff --git a/src/client/views/GestureOverlay.tsx b/src/client/views/GestureOverlay.tsx
index 6058eaaf9..0feccb742 100644
--- a/src/client/views/GestureOverlay.tsx
+++ b/src/client/views/GestureOverlay.tsx
@@ -94,7 +94,7 @@ export class GestureOverlay extends Touchable<GestureOverlayProps> {
     }
 
     static setupThumbButtons(doc: Doc) {
-        const docProtoData: { title: string; icon: string; drag?: string; ignoreClick?: boolean; pointerDown?: string; pointerUp?: string; clipboard?: Doc; backgroundColor?: string; dragFactory?: Doc }[] = [
+        const docProtoData: { title: string; icon: string; drag?: string; toolType?: string; ignoreClick?: boolean; pointerDown?: string; pointerUp?: string; clipboard?: Doc; backgroundColor?: string; dragFactory?: Doc }[] = [
             { title: 'use pen', icon: 'pen-nib', pointerUp: 'resetPen()', pointerDown: 'setPen(2, this.backgroundColor)', backgroundColor: 'blue' },
             { title: 'use highlighter', icon: 'highlighter', pointerUp: 'resetPen()', pointerDown: 'setPen(20, this.backgroundColor)', backgroundColor: 'yellow' },
             {
@@ -105,8 +105,8 @@ export class GestureOverlay extends Touchable<GestureOverlayProps> {
                 clipboard: Docs.Create.FreeformDocument([], { _width: 300, _height: 300, system: true }),
                 backgroundColor: 'orange',
             },
-            { title: 'interpret text', icon: 'font', pointerUp: "setToolglass('none')", pointerDown: "setToolglass('inktotext')", backgroundColor: 'orange' },
-            { title: 'ignore gestures', icon: 'signature', pointerUp: "setToolglass('none')", pointerDown: "setToolglass('ignoregesture')", backgroundColor: 'green' },
+            { title: 'interpret text', icon: 'font', toolType: 'inktotext', pointerUp: "setToolglass('none')", pointerDown: 'setToolglass(self.toolType)', backgroundColor: 'orange' },
+            { title: 'ignore gestures', icon: 'signature', toolType: 'ignoregesture', pointerUp: "setToolglass('none')", pointerDown: 'setToolglass(self.toolType)', backgroundColor: 'green' },
         ];
         return docProtoData.map(data =>
             Docs.Create.FontIconDocument({
@@ -116,6 +116,7 @@ export class GestureOverlay extends Touchable<GestureOverlayProps> {
                 _height: 10,
                 title: data.title,
                 icon: data.icon,
+                toolType: data.toolType,
                 _dropAction: data.pointerDown ? 'copy' : undefined,
                 ignoreClick: data.ignoreClick,
                 onDragStart: data.drag ? ScriptField.MakeFunction(data.drag) : undefined,
diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx
index 945cd61db..2e04ca3dd 100644
--- a/src/client/views/MainView.tsx
+++ b/src/client/views/MainView.tsx
@@ -230,8 +230,6 @@ export class MainView extends React.Component {
         if (window.location.pathname !== '/home') {
             const pathname = window.location.pathname.substr(1).split('/');
             if (pathname.length > 1 && pathname[0] === 'doc') {
-                Doc.MainDocId = pathname[1];
-                //!this.userDoc &&
                 DocServer.GetRefField(pathname[1]).then(
                     action(field => {
                         if (field instanceof Doc && field._viewType !== CollectionViewType.Docking) {
@@ -482,7 +480,6 @@ export class MainView extends React.Component {
                 fa.faHandPointUp,
             ]
         );
-        this.initAuthenticationRouters();
     }
 
     globalPointerDown = action((e: PointerEvent) => {
@@ -521,23 +518,6 @@ export class MainView extends React.Component {
         document.oncontextmenu = () => false;
     };
 
-    initAuthenticationRouters = async () => {
-        const received = Doc.MainDocId;
-        if (received && !this.userDoc) {
-            reaction(
-                () => Doc.GuestTarget,
-                target => target && DashboardView.createNewDashboard(),
-                { fireImmediately: true }
-            );
-        }
-        // else {
-        //     PromiseValue(this.userDoc.activeDashboard).then(dash => {
-        //         if (dash instanceof Doc) DashboardView.openDashboard(dash);
-        //         else Doc.createNewDashboard();
-        //     });
-        // }
-    };
-
     @action
     createNewPresentation = () => {
         const pres = Doc.MakeCopy(Doc.UserDoc().emptyTrail as Doc, true);
diff --git a/src/client/views/OverlayView.tsx b/src/client/views/OverlayView.tsx
index 08285ff0c..34e8cd6dd 100644
--- a/src/client/views/OverlayView.tsx
+++ b/src/client/views/OverlayView.tsx
@@ -255,4 +255,5 @@ export class OverlayView extends React.Component {
 // bcz: ugh ... want to be able to pass ScriptingRepl as tag argument, but that doesn't seem to work.. runtime error
 ScriptingGlobals.add(function addOverlayWindow(type: string, options: OverlayElementOptions) {
     OverlayView.Instance.addWindow(<ScriptingRepl />, options);
+    addOverlayWindow('ScriptingRepl', { x: 300, y: 100, width: 200, height: 200, title: 'Scripting REPL' });
 });
diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx
index 1ead80bd0..9b6554d67 100644
--- a/src/client/views/collections/CollectionDockingView.tsx
+++ b/src/client/views/collections/CollectionDockingView.tsx
@@ -26,6 +26,9 @@ import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView';
 import { TabDocView } from './TabDocView';
 import React = require('react');
 import { OpenWhere, OpenWhereMod } from '../nodes/DocumentView';
+import { OverlayView } from '../OverlayView';
+import { ScriptingRepl } from '../ScriptingRepl';
+import { ScriptField } from '../../../fields/ScriptField';
 const _global = (window /* browser */ || global) /* node */ as any;
 
 @observer
@@ -580,15 +583,21 @@ ScriptingGlobals.add(
     '(doc: any)'
 );
 ScriptingGlobals.add(
-    function openOnRight(doc: any) {
-        return CollectionDockingView.AddSplit(doc, OpenWhereMod.right);
+    function openDoc(doc: any, where: OpenWhere) {
+        switch (where) {
+            case OpenWhere.addRight:
+                return CollectionDockingView.AddSplit(doc, OpenWhereMod.right);
+            case OpenWhere.overlay:
+                if (doc === 'repl') OverlayView.Instance.addWindow(<ScriptingRepl />, { x: 300, y: 100, width: 200, height: 200, title: 'Scripting REPL' });
+                else Doc.AddDocToList(Doc.MyOverlayDocs, undefined, doc);
+        }
     },
-    'opens up document in tab on right side of the screen',
+    'opens up document in location specified',
     '(doc: any)'
 );
 ScriptingGlobals.add(
-    function openInOverlay(doc: any) {
-        return Doc.AddDocToList(Doc.MyOverlayDocs, undefined, doc);
+    function openRepl() {
+        return 'openRepl';
     },
     'opens up document in screen overlay layer',
     '(doc: any)'
diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx
index 48e5748a0..aed88aa1a 100644
--- a/src/client/views/collections/CollectionView.tsx
+++ b/src/client/views/collections/CollectionView.tsx
@@ -169,7 +169,7 @@ export class CollectionView extends ViewBoxAnnotatableComponent<ViewBoxAnnotatab
 
     onContextMenu = (e: React.MouseEvent): void => {
         const cm = ContextMenu.Instance;
-        if (cm && !e.isPropagationStopped() && this.rootDoc[Id] !== Doc.MainDocId) {
+        if (cm && !e.isPropagationStopped()) {
             // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7
             this.setupViewTypes(
                 'UI Controls...',
diff --git a/src/client/views/collections/TreeView.tsx b/src/client/views/collections/TreeView.tsx
index 2bdcf472f..af2d148e0 100644
--- a/src/client/views/collections/TreeView.tsx
+++ b/src/client/views/collections/TreeView.tsx
@@ -2,7 +2,7 @@ import { IconProp } from '@fortawesome/fontawesome-svg-core';
 import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
 import { action, computed, IReactionDisposer, observable, reaction } from 'mobx';
 import { observer } from 'mobx-react';
-import { DataSym, Doc, DocListCast, DocListCastOrNull, Field, HeightSym, Opt, StrListCast, WidthSym } from '../../../fields/Doc';
+import { DataSym, Doc, DocListCast, Field, HeightSym, Opt, StrListCast, WidthSym } from '../../../fields/Doc';
 import { Id } from '../../../fields/FieldSymbols';
 import { List } from '../../../fields/List';
 import { RichTextField } from '../../../fields/RichTextField';
@@ -172,11 +172,7 @@ export class TreeView extends React.Component<TreeViewProps> {
 
     childDocList(field: string) {
         const layout = Cast(Doc.LayoutField(this.doc), Doc, null);
-        return (
-            (this.props.dataDoc ? DocListCastOrNull(this.props.dataDoc[field]) : undefined) || // if there's a data doc for an expanded template, use it's data field
-            (layout ? DocListCastOrNull(layout[field]) : undefined) || // else if there's a layout doc, display it's fields
-            DocListCastOrNull(this.doc[field])
-        ); // otherwise use the document's data field
+        return DocListCast(this.props.dataDoc?.[field], DocListCast(layout?.[field], DocListCast(this.doc[field])));
     }
     moving: boolean = false;
     @undoBatch move = (doc: Doc | Doc[], target: Doc | undefined, addDoc: (doc: Doc | Doc[]) => boolean) => {
@@ -759,7 +755,7 @@ export class TreeView extends React.Component<TreeViewProps> {
         const makeFolder = { script: ScriptField.MakeFunction(`scriptContext.makeFolder()`, { scriptContext: 'any' })!, icon: 'folder-plus', label: 'New Folder' };
         const deleteItem = { script: ScriptField.MakeFunction(`scriptContext.deleteItem()`, { scriptContext: 'any' })!, icon: 'folder-plus', label: 'Delete' };
         const folderOp = this.childDocs?.length ? [makeFolder] : [];
-        const openAlias = { script: ScriptField.MakeFunction(`openOnRight(getAlias(self))`)!, icon: 'copy', label: 'Open Alias' };
+        const openAlias = { script: ScriptField.MakeFunction(`openDoc(getAlias(self), ${OpenWhere.addRight})`)!, icon: 'copy', label: 'Open Alias' };
         const focusDoc = { script: ScriptField.MakeFunction(`DocFocusOrOpen(self)`)!, icon: 'eye', label: 'Focus or Open' };
         return [
             ...(this.props.contextMenuItems ?? []).filter(mi => (!mi.filter ? true : mi.filter.script.run({ doc: this.doc })?.result)),
diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx
index 964231e9d..02af30d0c 100644
--- a/src/client/views/nodes/DocumentView.tsx
+++ b/src/client/views/nodes/DocumentView.tsx
@@ -80,6 +80,7 @@ export enum OpenWhere {
     replaceLeft = 'replace:left',
     inParent = 'inParent',
     inParentFromScreen = 'inParentFromScreen',
+    overlay = 'overlay',
 }
 export enum OpenWhereMod {
     none = '',
@@ -612,6 +613,7 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
                                 altKey,
                                 shiftKey,
                                 ctrlKey,
+                                value: undefined,
                             },
                             console.log
                         );
diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx
index b1acef44a..f7425b26a 100644
--- a/src/client/views/nodes/WebBox.tsx
+++ b/src/client/views/nodes/WebBox.tsx
@@ -145,6 +145,9 @@ export class WebBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatableProps
         const nativeWidth = NumCast(this.layoutDoc.nativeWidth);
         const nativeHeight = (nativeWidth * this.props.PanelHeight()) / this.props.PanelWidth();
         if (
+            !this.props.isSelected(true) &&
+            !Doc.IsBrushedDegree(this.rootDoc) &&
+            !this.isAnyChildContentActive() &&
             !this.rootDoc.thumbLockout &&
             !this.props.dontRegisterView &&
             this._iframe &&
@@ -181,6 +184,7 @@ export class WebBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatableProps
                 });
         }
     };
+    _thumbTimer: any;
     async componentDidMount() {
         this.props.setContentView?.(this); // this tells the DocumentView that this WebBox is the "content" of the document.  this allows the DocumentView to call WebBox relevant methods to configure the UI (eg, show back/forward buttons)
 
@@ -197,6 +201,7 @@ export class WebBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatableProps
             () => this.props.isSelected(true) || this.isAnyChildContentActive() || Doc.isBrushedHighlightedDegree(this.props.Document),
             async selected => {
                 if (selected) {
+                    this._thumbTimer && clearTimeout(this._thumbTimer);
                     this._webPageHasBeenRendered = true;
                 } else if (
                     (!this.props.isContentActive(true) || SnappingManager.GetIsDragging()) && // update thumnail when unselected AND (no child annotation is active OR we've started dragging the document in which case no additional deselect will occur so this is the only chance to update the thumbnail)
@@ -204,7 +209,8 @@ export class WebBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatableProps
                     LightboxView.LightboxDoc !== this.rootDoc
                 ) {
                     // don't create a thumbnail if entering Lightbox from maximize either, since thumb will be empty.
-                    this.updateThumb();
+                    this._thumbTimer && clearTimeout(this._thumbTimer);
+                    this._thumbTimer = setTimeout(this.updateThumb, 2000);
                 }
             },
             { fireImmediately: this.props.isSelected(true) || this.isAnyChildContentActive() || (Doc.isBrushedHighlightedDegreeUnmemoized(this.props.Document) ? true : false) }
diff --git a/src/client/views/nodes/button/FontIconBox.tsx b/src/client/views/nodes/button/FontIconBox.tsx
index 0468d1c47..b3a3c3ae4 100644
--- a/src/client/views/nodes/button/FontIconBox.tsx
+++ b/src/client/views/nodes/button/FontIconBox.tsx
@@ -1,4 +1,5 @@
 import { IconProp } from '@fortawesome/fontawesome-svg-core';
+import { faAlignRight } from '@fortawesome/free-solid-svg-icons';
 import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
 import { Tooltip } from '@material-ui/core';
 import { action, computed, observable, runInAction } from 'mobx';
@@ -11,7 +12,7 @@ import { ScriptField } from '../../../../fields/ScriptField';
 import { BoolCast, Cast, NumCast, ScriptCast, StrCast } from '../../../../fields/Types';
 import { WebField } from '../../../../fields/URLField';
 import { GestureUtils } from '../../../../pen-gestures/GestureUtils';
-import { aggregateBounds, StopEvent, Utils } from '../../../../Utils';
+import { aggregateBounds, Utils } from '../../../../Utils';
 import { CollectionViewType, DocumentType } from '../../../documents/DocumentTypes';
 import { LinkManager } from '../../../util/LinkManager';
 import { ScriptingGlobals } from '../../../util/ScriptingGlobals';
@@ -134,10 +135,10 @@ export class FontIconBox extends DocComponent<ButtonProps>() {
     @computed get numberButton() {
         const numBtnType: string = StrCast(this.rootDoc.numBtnType);
         const numScript = ScriptCast(this.rootDoc.script);
-        const setValue = (value: number) => UndoManager.RunInBatch(() => numScript?.script.run({ value, _readOnly_: false }), 'set num value');
+        const setValue = (value: number) => UndoManager.RunInBatch(() => numScript?.script.run({ self: this.rootDoc, value, _readOnly_: false }), 'set num value');
 
         // Script for checking the outcome of the toggle
-        const checkResult = Number(numScript?.script.run({ value: 0, _readOnly_: true }).result ?? 0).toPrecision(NumCast(this.dataDoc.numPrecision, 3));
+        const checkResult = Number(numScript?.script.run({ self: this.rootDoc, value: 0, _readOnly_: true }).result ?? 0).toPrecision(NumCast(this.dataDoc.numPrecision, 3));
 
         const label = !FontIconBox.GetShowLabels() ? null : <div className="fontIconBox-label">{this.label}</div>;
 
@@ -150,7 +151,7 @@ export class FontIconBox extends DocComponent<ButtonProps>() {
                         min={NumCast(this.rootDoc.numBtnMin, 0)}
                         max={NumCast(this.rootDoc.numBtnMax, 100)}
                         value={checkResult}
-                        className={'menu-slider'}
+                        className="menu-slider"
                         onPointerDown={() => (this._batch = UndoManager.StartBatch('presDuration'))}
                         onPointerUp={() => this._batch?.end()}
                         onChange={e => {
@@ -284,27 +285,23 @@ export class FontIconBox extends DocComponent<ButtonProps>() {
                     text = 'User Default';
                 }
                 noviceList = [CollectionViewType.Freeform, CollectionViewType.Schema, CollectionViewType.Stacking, CollectionViewType.NoteTaking];
-            } else if (script?.script.originalScript.startsWith('setFont')) {
-                const editorView = RichTextMenu.Instance?.TextView?.EditorView;
-                text = StrCast((editorView ? RichTextMenu.Instance : Doc.UserDoc()).fontFamily);
-                noviceList = ['Roboto', 'Times New Roman', 'Arial', 'Georgia', 'Comic Sans MS', 'Tahoma', 'Impact', 'Crimson Text'];
-            }
+            } else text = StrCast((RichTextMenu.Instance?.TextView?.EditorView ? RichTextMenu.Instance : Doc.UserDoc()).fontFamily);
         } catch (e) {
             console.log(e);
         }
 
         // Get items to place into the list
         const list = this.buttonList
-            .filter(value => !Doc.noviceMode || noviceList.includes(value))
+            .filter(value => !Doc.noviceMode || !noviceList.length || noviceList.includes(value))
             .map(value => (
                 <div
                     className="list-item"
                     key={`${value}`}
                     style={{
-                        fontFamily: script.script.originalScript.startsWith('setFont') ? value : undefined,
+                        fontFamily: script.script.originalScript.startsWith('{ return setFont') ? value : undefined,
                         backgroundColor: value === text ? Colors.LIGHT_BLUE : undefined,
                     }}
-                    onClick={undoBatch(() => script.script.run({ value }))}>
+                    onClick={undoBatch(() => script.script.run({ self: this.rootDoc, value }))}>
                     {value[0].toUpperCase() + value.slice(1)}
                 </div>
             ));
@@ -357,7 +354,7 @@ export class FontIconBox extends DocComponent<ButtonProps>() {
             ev.preventDefault();
             ev.stopPropagation();
             const s = this.colorScript;
-            s && undoBatch(() => s.script.run({ value: Utils.colorString(value), _readOnly_: false }).result)();
+            s && undoBatch(() => s.script.run({ self: this.rootDoc, value: Utils.colorString(value), _readOnly_: false }).result)();
         };
         const presets = ['#D0021B', '#F5A623', '#F8E71C', '#8B572A', '#7ED321', '#417505', '#9013FE', '#4A90E2', '#50E3C2', '#B8E986', '#000000', '#4A4A4A', '#9B9B9B', '#FFFFFF', '#f1efeb', 'transparent'];
         return <SketchPicker onChange={change as any /* SketchPicker passes the mouse event to the callback, but the type system doesn't know that */} color={curColor} presetColors={presets} />;
@@ -368,7 +365,7 @@ export class FontIconBox extends DocComponent<ButtonProps>() {
     @computed get colorButton() {
         const color = this.props.styleProvider?.(this.rootDoc, this.props, StyleProp.Color);
         const backgroundColor = this.props.styleProvider?.(this.rootDoc, this.props, StyleProp.BackgroundColor);
-        const curColor = this.colorScript?.script.run({ value: undefined, _readOnly_: true }).result ?? 'transparent';
+        const curColor = this.colorScript?.script.run({ self: this.rootDoc, value: undefined, _readOnly_: true }).result ?? 'transparent';
 
         const label =
             !this.label || !FontIconBox.GetShowLabels() ? null : (
@@ -377,13 +374,6 @@ export class FontIconBox extends DocComponent<ButtonProps>() {
                 </div>
             );
 
-        // dropdown caret seems superfluous since clicking the color button does the same thing
-        // const dropdownCaret = <div
-        //     className="menuButton-dropDown"
-        //     style={{ borderBottomRightRadius: this.dropdown ? 0 : undefined }}>
-        //     <FontAwesomeIcon icon={'caret-down'} color={color} size="sm" />
-        // </div>;
-        //setTimeout(() => this.colorPicker(curColor)); // cause an update to the color picker rendered in MainView
         return (
             <div
                 className={`menuButton ${this.type + (FontIconBox.GetShowLabels() ? 'Label' : '')} ${this.colorPickerClosed}`}
@@ -598,121 +588,70 @@ ScriptingGlobals.add(function toggleOverlay(checkResult?: boolean) {
     selected ? selected.props.CollectionFreeFormDocumentView?.().float() : console.log('[FontIconBox.tsx] toggleOverlay failed');
 });
 
-/** TEXT
- *      setFont
- *      setFontSize
- *      toggleBold
- *      toggleUnderline
- *      toggleItalic
- *      setAlignment
- *      toggleBold
- *      toggleItalic
- *      toggleUnderline
- **/
-
-// toggle: Set overlay status of selected document
-ScriptingGlobals.add(function setFont(font: string, checkResult?: boolean) {
-    if (checkResult) return RichTextMenu.Instance?.fontFamily;
-    font && RichTextMenu.Instance.setFontFamily(font);
-});
-
-ScriptingGlobals.add(function getActiveTextInfo(info: 'family' | 'size' | 'color' | 'highlight') {
-    const editorView = RichTextMenu.Instance.TextView?.EditorView;
-    const style = editorView?.state && RichTextMenu.Instance.getActiveFontStylesOnSelection();
-    // prettier-ignore
-    switch (info) {
-        case 'family':    return style?.activeFamilies[0];
-        case 'size':      return style?.activeSizes[0];
-        case 'color':     return style?.activeColors[0];
-        case 'highlight': return style?.activeHighlights[0];
-    }
-});
-
-ScriptingGlobals.add(function setAlignment(align: 'left' | 'right' | 'center', checkResult?: boolean) {
-    const editorView = RichTextMenu.Instance?.TextView?.EditorView;
-    if (checkResult) {
-        return (editorView ? RichTextMenu.Instance.textAlign : Doc.UserDoc().textAlign) === align ? Colors.MEDIUM_BLUE : 'transparent';
-    }
-    if (editorView?.state) RichTextMenu.Instance.align(editorView, editorView.dispatch, align);
-    else Doc.UserDoc().textAlign = align;
-});
-
-ScriptingGlobals.add(function setBulletList(mapStyle: 'bullet' | 'decimal', checkResult?: boolean) {
+ScriptingGlobals.add(function setFontAttr(attr: 'font' | 'fontColor' | 'highlight' | 'fontSize', value: any, checkResult?: boolean) {
     const editorView = RichTextMenu.Instance?.TextView?.EditorView;
-    if (checkResult) {
-        const active = editorView?.state && RichTextMenu.Instance.getActiveListStyle();
-        if (active === mapStyle) return Colors.MEDIUM_BLUE;
-        return 'transparent';
-    }
-    editorView?.state && RichTextMenu.Instance.changeListType(mapStyle);
-});
-
-// toggle: Set overlay status of selected document
-ScriptingGlobals.add(function setFontColor(color?: string, checkResult?: boolean) {
-    if (checkResult) return RichTextMenu.Instance.fontColor;
-    color && RichTextMenu.Instance.setColor(color);
-});
-
-// toggle: Set overlay status of selected document
-ScriptingGlobals.add(function setFontHighlight(color?: string, checkResult?: boolean) {
     const selected = SelectionManager.Docs().lastElement();
-    const editorView = RichTextMenu.Instance.TextView?.EditorView;
+    // prettier-ignore
+    const map: Map<'font'|'fontColor'|'highlight'|'fontSize', { checkResult: () => any; setDoc: () => void; setMode?: () => void }> = new Map([
+        ['font', {
+            checkResult: () => RichTextMenu.Instance?.fontFamily,
+            setDoc: () => value && RichTextMenu.Instance.setFontFamily(value),
+            setMode: () => Doc.UserDoc().textAlign = value,
+        }],
+        ['highlight', {
+            checkResult: () =>(selected ?? Doc.UserDoc())._fontHighlight,
+            setDoc: () => value  && RichTextMenu.Instance.setHighlight(value),
+        }],
+        ['fontColor', {
+            checkResult: () => RichTextMenu.Instance?.fontColor,
+            setDoc: () => value && RichTextMenu.Instance.setColor(value),
+        }],
+        ['fontSize', {
+            checkResult: () => RichTextMenu.Instance?.fontSize.replace('px', ''),
+            setDoc: () => {
+                if (typeof value === 'number') value = value.toString();
+                if (value && Number(value).toString() === value) value += 'px';
+                RichTextMenu.Instance.setFontSize(value);
+            },
+        }],
+    ]);
 
     if (checkResult) {
-        return (selected ?? Doc.UserDoc())._fontHighlight;
+        return map.get(attr)?.checkResult();
     }
-    color && RichTextMenu.Instance.setHighlight(color);
+    if (editorView?.state) map.get(attr)?.setDoc();
+    else map.get(attr)?.setMode?.();
 });
 
-// toggle: Set overlay status of selected document
-ScriptingGlobals.add(function setFontSize(size: string | number, checkResult?: boolean) {
-    if (checkResult) {
-        return RichTextMenu.Instance?.fontSize.replace('px', '');
-    }
-    if (typeof size === 'number') size = size.toString();
-    if (size && Number(size).toString() === size) size += 'px';
-    RichTextMenu.Instance.setFontSize(size);
-});
-ScriptingGlobals.add(function toggleNoAutoLinkAnchor(checkResult?: boolean) {
-    const editorView = RichTextMenu.Instance?.TextView?.EditorView;
-    if (checkResult) {
-        return (editorView ? RichTextMenu.Instance.noAutoLink : false) ? Colors.MEDIUM_BLUE : 'transparent';
-    }
-    if (editorView) RichTextMenu.Instance?.toggleNoAutoLinkAnchor();
-});
-ScriptingGlobals.add(function toggleDictation(checkResult?: boolean) {
+type attrname = 'noAutoLink' | 'dictation' | 'bold' | 'italics' | 'underline' | 'left' | 'center' | 'right' | 'bullet' | 'decimal';
+type attrfuncs = [attrname, { checkResult: () => boolean; toggle: () => any }];
+ScriptingGlobals.add(function toggleCharStyle(charStyle: attrname, checkResult?: boolean) {
     const textView = RichTextMenu.Instance?.TextView;
-    if (checkResult) {
-        return textView?._recording ? Colors.MEDIUM_BLUE : 'transparent';
-    }
-    if (textView) runInAction(() => (textView._recording = !textView._recording));
-});
-
-ScriptingGlobals.add(function toggleBold(checkResult?: boolean) {
-    const editorView = RichTextMenu.Instance?.TextView?.EditorView;
-    if (checkResult) {
-        return (editorView ? RichTextMenu.Instance.bold : Doc.UserDoc().fontWeight === 'bold') ? Colors.MEDIUM_BLUE : 'transparent';
-    }
-    if (editorView) RichTextMenu.Instance?.toggleBold();
-    else Doc.UserDoc().fontWeight = Doc.UserDoc().fontWeight === 'bold' ? undefined : 'bold';
-});
-
-ScriptingGlobals.add(function toggleUnderline(checkResult?: boolean) {
-    const editorView = RichTextMenu.Instance?.TextView?.EditorView;
-    if (checkResult) {
-        return (editorView ? RichTextMenu.Instance.underline : Doc.UserDoc().textDecoration === 'underline') ? Colors.MEDIUM_BLUE : 'transparent';
-    }
-    if (editorView) RichTextMenu.Instance?.toggleUnderline();
-    else Doc.UserDoc().textDecoration = Doc.UserDoc().textDecoration === 'underline' ? undefined : 'underline';
-});
-
-ScriptingGlobals.add(function toggleItalic(checkResult?: boolean) {
-    const editorView = RichTextMenu.Instance?.TextView?.EditorView;
-    if (checkResult) {
-        return (editorView ? RichTextMenu.Instance.italics : Doc.UserDoc().fontStyle === 'italics') ? Colors.MEDIUM_BLUE : 'transparent';
-    }
-    if (editorView) RichTextMenu.Instance?.toggleItalics();
-    else Doc.UserDoc().fontStyle = Doc.UserDoc().fontStyle === 'italics' ? undefined : 'italics';
+    const editorView = textView?.EditorView;
+    // prettier-ignore
+    const alignments:attrfuncs[] = (['left','right','center'] as ("left"|"center"|"right")[]).map((where) =>
+        [ where, {      checkResult: () =>(editorView ? (RichTextMenu.Instance.textAlign ===where): (Doc.UserDoc().textAlign ===where) ? true:false),
+                        toggle: () => (editorView?.state ? RichTextMenu.Instance.align(editorView, editorView.dispatch, where):(Doc.UserDoc().textAlign = where))}]);
+    // prettier-ignore
+    const listings:attrfuncs[] = (['bullet','decimal'] as attrname[]).map(list =>
+        [ list, {       checkResult: () => (editorView ? RichTextMenu.Instance.getActiveListStyle() === list:false),
+                        toggle: () => editorView?.state && RichTextMenu.Instance.changeListType(list) }]);
+    // prettier-ignore
+    const attrs:attrfuncs[] = [
+        ['dictation', { checkResult: () => textView?._recording ? true:false,
+                        toggle: () => textView && runInAction(() => (textView._recording = !textView._recording)) }],
+        ['noAutoLink',{ checkResult: () => (editorView ? RichTextMenu.Instance.noAutoLink : false),
+                        toggle: () => editorView && RichTextMenu.Instance?.toggleNoAutoLinkAnchor()}],
+        ['bold',      { checkResult: () => (editorView ? RichTextMenu.Instance.bold : (Doc.UserDoc().fontWeight === 'bold') ? true:false),
+                        toggle: editorView ? RichTextMenu.Instance.toggleBold : () => (Doc.UserDoc().fontWeight = Doc.UserDoc().fontWeight === 'bold' ? undefined : 'bold')}],
+        ['italics',   { checkResult: () => (editorView ? RichTextMenu.Instance.italics : (Doc.UserDoc().fontStyle === 'italics') ? true:false),
+                        toggle: editorView ? RichTextMenu.Instance.toggleItalics : () => (Doc.UserDoc().fontStyle = Doc.UserDoc().fontStyle === 'italics' ? undefined : 'italics')}],
+        ['underline', { checkResult: () => (editorView ? RichTextMenu.Instance.underline : (Doc.UserDoc().textDecoration === 'underline') ? true:false),
+                        toggle: editorView ? RichTextMenu.Instance.toggleUnderline : () => (Doc.UserDoc().textDecoration = Doc.UserDoc().textDecoration === 'underline' ? undefined : 'underline') }]]
+
+    const map = new Map(attrs.concat(alignments).concat(listings));
+    if (checkResult) return map.get(charStyle)?.checkResult() ? Colors.MEDIUM_BLUE : 'transparent';
+    map.get(charStyle)?.toggle();
 });
 
 export function checkInksToGroup() {
@@ -832,62 +771,39 @@ function setActiveTool(tool: InkTool | GestureUtils.Gestures, keepPrim: boolean,
 ScriptingGlobals.add(setActiveTool, 'sets the active ink tool mode');
 
 // toggle: Set overlay status of selected document
-ScriptingGlobals.add(function setIsInkMask(checkResult?: boolean) {
-    const selected = SelectionManager.Docs().lastElement();
-    if (checkResult) {
-        if (selected?.type === DocumentType.INK) {
-            return BoolCast(selected.isInkMask) ? Colors.MEDIUM_BLUE : 'transparent';
-        }
-        return ActiveIsInkMask() ? Colors.MEDIUM_BLUE : 'transparent';
-    }
-    SetActiveIsInkMask(!ActiveIsInkMask());
-    SelectionManager.Docs()
-        .filter(doc => doc.type === DocumentType.INK)
-        .map(doc => (doc.isInkMask = !doc.isInkMask));
-});
-
-// toggle: Set overlay status of selected document
-ScriptingGlobals.add(function setFillColor(color?: string, checkResult?: boolean) {
+ScriptingGlobals.add(function setInkProperty(option: 'inkMask' | 'fillColor' | 'strokeWidth' | 'strokeColor', value: any, checkResult?: boolean) {
     const selected = SelectionManager.Docs().lastElement();
-    if (checkResult) {
-        if (selected?.type === DocumentType.INK) {
-            return StrCast(selected.fillColor);
-        }
-        return ActiveFillColor();
-    }
-    SetActiveFillColor(StrCast(color));
-    SelectionManager.Docs()
-        .filter(doc => doc.type === DocumentType.INK)
-        .map(doc => (doc.fillColor = color));
-});
-
-ScriptingGlobals.add(function setStrokeWidth(width: number, checkResult?: boolean) {
-    if (checkResult) {
-        const selected = SelectionManager.Docs().lastElement();
-        if (selected?.type === DocumentType.INK) {
-            return NumCast(selected.strokeWidth);
-        }
-        return ActiveInkWidth();
-    }
-    SetActiveInkWidth(width.toString());
-    SelectionManager.Docs()
-        .filter(doc => doc.type === DocumentType.INK)
-        .map(doc => (doc.strokeWidth = Number(width)));
-});
+    // prettier-ignore
+    const map: Map<'inkMask' | 'fillColor' | 'strokeWidth' | 'strokeColor', { checkResult: () => any; setInk: (doc: Doc) => void; setMode: () => void }> = new Map([
+        ['inkMask', {
+            checkResult: () => ((selected?.type === DocumentType.INK ? BoolCast(selected.isInkMask) : ActiveIsInkMask()) ? Colors.MEDIUM_BLUE : 'transparent'),
+            setInk: (doc: Doc) => (doc.isInkMask = !doc.isInkMask),
+            setMode: () => selected?.type !== DocumentType.INK && SetActiveIsInkMask(!ActiveIsInkMask()),
+        }],
+        ['fillColor', {
+            checkResult: () => (selected?.type === DocumentType.INK ? StrCast(selected.fillColor) : ActiveFillColor() ? Colors.MEDIUM_BLUE : 'transparent'),
+            setInk: (doc: Doc) => (doc.fillColor = StrCast(value)),
+            setMode: () => SetActiveFillColor(StrCast(value)),
+        }],
+        [ 'strokeWidth', {
+            checkResult: () => (selected?.type === DocumentType.INK ? NumCast(selected.strokeWidth) : ActiveInkWidth()),
+            setInk: (doc: Doc) => (doc.strokeWidth = NumCast(value)),
+            setMode: () => SetActiveInkWidth(value.toString()),
+        }],
+        ['strokeColor', {
+            checkResult: () => (selected?.type === DocumentType.INK ? NumCast(selected.color) : ActiveInkColor()),
+            setInk: (doc: Doc) => (doc.color = String(value)),
+            setMode: () => SetActiveInkColor(StrCast(value)),
+        }],
+    ]);
 
-// toggle: Set overlay status of selected document
-ScriptingGlobals.add(function setStrokeColor(color?: string, checkResult?: boolean) {
     if (checkResult) {
-        const selected = SelectionManager.Docs().lastElement();
-        if (selected?.type === DocumentType.INK) {
-            return StrCast(selected.color);
-        }
-        return ActiveInkColor();
+        return map.get(option)?.checkResult();
     }
-    SetActiveInkColor(StrCast(color));
+    map.get(option)?.setMode();
     SelectionManager.Docs()
         .filter(doc => doc.type === DocumentType.INK)
-        .map(doc => (doc.color = String(color)));
+        .map(doc => map.get(option)?.setInk(doc));
 });
 
 /** WEB
diff --git a/src/fields/Doc.ts b/src/fields/Doc.ts
index ee164ab31..de94ed5db 100644
--- a/src/fields/Doc.ts
+++ b/src/fields/Doc.ts
@@ -33,20 +33,19 @@ export namespace Field {
         return !Field.IsField(field) ? '' : (onDelegate ? '=' : '') + (field instanceof ComputedField ? `:=${field.script.originalScript}` : Field.toScriptString(field));
     }
     export function toScriptString(field: Field): string {
-        if (typeof field === 'string') {
-            if (field.startsWith('{"')) return `'${field}'`; // bcz: hack ... want to quote the string the right way. if there are nested "'s, then use ' instead of ".  In this case, test for the start of a JSON string of the format {"property": ... } and use outer 's instead of "s
-            return `"${field}"`;
+        switch (typeof field) {
+            case 'string':
+                if (field.startsWith('{"')) return `'${field}'`; // bcz: hack ... want to quote the string the right way. if there are nested "'s, then use ' instead of ".  In this case, test for the start of a JSON string of the format {"property": ... } and use outer 's instead of "s
+                return `"${field}"`;
+            case 'number':
+            case 'boolean':
+                return String(field);
         }
-        if (typeof field === 'number' || typeof field === 'boolean') return String(field);
-        if (field === undefined || field === null) return 'null';
-        return field[ToScriptString]();
+        return field?.[ToScriptString]?.() ?? 'null';
     }
     export function toString(field: Field): string {
-        if (typeof field === 'string') return field;
-        if (typeof field === 'number' || typeof field === 'boolean') return String(field);
-        if (field instanceof ObjectField) return field[ToString]();
-        if (field instanceof RefField) return field[ToString]();
-        return '';
+        if (typeof field === 'string' || typeof field === 'number' || typeof field === 'boolean') return String(field);
+        return field?.[ToString]?.() || '';
     }
     export function IsField(field: any): field is Field;
     export function IsField(field: any, includeUndefined: true): field is Field | undefined;
@@ -79,17 +78,14 @@ export async function DocCastAsync(field: FieldResult): Promise<Opt<Doc>> {
     return Cast(field, Doc);
 }
 
-export function NumListCast(field: FieldResult) {
-    return Cast(field, listSpec('number'), []);
+export function NumListCast(field: FieldResult, defaultVal: number[] = []) {
+    return Cast(field, listSpec('number'), defaultVal);
 }
-export function StrListCast(field: FieldResult) {
-    return Cast(field, listSpec('string'), []);
+export function StrListCast(field: FieldResult, defaultVal: string[] = []) {
+    return Cast(field, listSpec('string'), defaultVal);
 }
-export function DocListCast(field: FieldResult) {
-    return Cast(field, listSpec(Doc), []).filter(d => d instanceof Doc) as Doc[];
-}
-export function DocListCastOrNull(field: FieldResult) {
-    return Cast(field, listSpec(Doc), null)?.filter(d => d instanceof Doc) as Doc[] | undefined;
+export function DocListCast(field: FieldResult, defaultVal: Doc[] = []) {
+    return Cast(field, listSpec(Doc), defaultVal).filter(d => d instanceof Doc) as Doc[];
 }
 
 export const WidthSym = Symbol('Width');
@@ -153,17 +149,8 @@ export function updateCachedAcls(doc: Doc) {
 }
 
 @scriptingGlobal
-@Deserializable('Doc', updateCachedAcls).withFields(['id'])
+@Deserializable('Doc', updateCachedAcls, ['id'])
 export class Doc extends RefField {
-    //TODO tfs: these should be temporary...
-    private static mainDocId: string | undefined;
-    public static get MainDocId() {
-        return this.mainDocId;
-    }
-    public static set MainDocId(id: string | undefined) {
-        this.mainDocId = id;
-    }
-
     @observable public static CurrentlyLoading: Doc[];
     // removes from currently loading display
     @action
@@ -582,21 +569,13 @@ export namespace Doc {
 
     // compare whether documents or their protos match
     export function AreProtosEqual(doc?: Doc, other?: Doc) {
-        if (!doc || !other) return false;
-        const r = doc === other;
-        const r2 = Doc.GetProto(doc) === other;
-        const r3 = Doc.GetProto(other) === doc;
-        const r4 = Doc.GetProto(doc) === Doc.GetProto(other) && Doc.GetProto(other) !== undefined;
-        return r || r2 || r3 || r4;
+        return doc && other && Doc.GetProto(doc) === Doc.GetProto(other);
     }
 
     // Gets the data document for the document.  Note: this is mis-named -- it does not specifically
     // return the doc's proto, but rather recursively searches through the proto inheritance chain
     // and returns the document who's proto is undefined or whose proto is marked as a base prototype ('isPrototype').
     export function GetProto(doc: Doc): Doc {
-        if (doc instanceof Promise) {
-            // console.log("GetProto: warning: got Promise insead of Doc");
-        }
         const proto = doc && (Doc.GetT(doc, 'isPrototype', 'boolean', true) ? doc : doc.proto || doc);
         return proto === doc ? proto : Doc.GetProto(proto);
     }
diff --git a/src/fields/ScriptField.ts b/src/fields/ScriptField.ts
index b5eca78dd..feb419597 100644
--- a/src/fields/ScriptField.ts
+++ b/src/fields/ScriptField.ts
@@ -103,30 +103,9 @@ export class ScriptField extends ObjectField {
         }
         this.rawscript = rawscript;
         this.setterscript = setterscript;
-        this.script = script ?? (CompileScript('false', { addReturn: true }) as CompiledScript);
+        this.script = script ?? ScriptField.GetScriptFieldCache('false:') ?? (CompileScript('false', { addReturn: true }) as CompiledScript);
     }
 
-    //     init(callback: (res: Field) => any) {
-    //         const options = this.options!;
-    //         const keys = Object.keys(options.options.capturedIds);
-    //         Server.GetFields(keys).then(fields => {
-    //             let captured: { [name: string]: Field } = {};
-    //             keys.forEach(key => captured[options.options.capturedIds[key]] = fields[key]);
-    //             const opts: ScriptOptions = {
-    //                 addReturn: options.options.addReturn,
-    //                 params: options.options.params,
-    //                 requiredType: options.options.requiredType,
-    //                 capturedVariables: captured
-    //             };
-    //             const script = CompileScript(options.script, opts);
-    //             if (!script.compiled) {
-    //                 throw new Error("Can't compile script");
-    //             }
-    //             this._script = script;
-    //             callback(this);
-    //         });
-    //     }
-
     [Copy](): ObjectField {
         return new ScriptField(this.script, this.setterscript, this.rawscript);
     }
@@ -172,7 +151,7 @@ export class ComputedField extends ScriptField {
     _lastComputedResult: any;
     //TODO maybe add an observable cache based on what is passed in for doc, considering there shouldn't really be that many possible values for doc
     value = computedFn((doc: Doc) => this._valueOutsideReaction(doc));
-    _valueOutsideReaction = (doc: Doc) => (this._lastComputedResult = this.script.run({ this: doc, self: Cast(doc.rootDocument, Doc, null) || doc, _last_: this._lastComputedResult, _readOnly_: true }, console.log).result);
+    _valueOutsideReaction = (doc: Doc) => (this._lastComputedResult = this.script.run({ this: doc, self: Cast(doc.rootDocument, Doc, null) ?? doc, value: '', _last_: this._lastComputedResult, _readOnly_: true }, console.log).result);
 
     [ToValue](doc: Doc) {
         return ComputedField.toValue(doc, this);
@@ -181,12 +160,8 @@ export class ComputedField extends ScriptField {
         return new ComputedField(this.script, this.setterscript, this.rawscript);
     }
 
-    public static MakeScript(script: string, params: object = {}) {
-        const compiled = ScriptField.CompileScript(script, params, false);
-        return compiled.compiled ? new ComputedField(compiled) : undefined;
-    }
     public static MakeFunction(script: string, params: object = {}, capturedVariables?: { [name: string]: Doc | string | number | boolean }, setterscript?: string) {
-        const compiled = ScriptField.CompileScript(script, params, true, capturedVariables);
+        const compiled = ScriptField.CompileScript(script, params, true, { value: '', ...capturedVariables });
         const compiledsetter = setterscript ? ScriptField.CompileScript(setterscript, { ...params, value: 'any' }, false, capturedVariables) : undefined;
         const compiledsetscript = compiledsetter?.compiled ? compiledsetter : undefined;
         return compiled.compiled ? new ComputedField(compiled, compiledsetscript) : undefined;
diff --git a/src/fields/util.ts b/src/fields/util.ts
index 6ff13d5d3..70d9ed61f 100644
--- a/src/fields/util.ts
+++ b/src/fields/util.ts
@@ -48,15 +48,11 @@ export function TraceMobx() {
 }
 
 const _setterImpl = action(function (target: any, prop: string | symbol | number, value: any, receiver: any): boolean {
-    if (SerializationHelper.IsSerializing()) {
+    if (SerializationHelper.IsSerializing() || typeof prop === 'symbol') {
         target[prop] = value;
         return true;
     }
 
-    if (typeof prop === 'symbol') {
-        target[prop] = value;
-        return true;
-    }
     if (value !== undefined) {
         value = value[SelfProxy] || value;
     }
@@ -95,12 +91,8 @@ const _setterImpl = action(function (target: any, prop: string | symbol | number
             delete target.__fields[prop];
         } else {
             target.__fieldKeys && (target.__fieldKeys[prop] = true);
-            // if (target.__fields[prop] !== value) {
-            //     console.log("ASSIGN " + prop + " " + value);
-            // }
             target.__fields[prop] = value;
         }
-        //if (typeof value === "object" && !(value instanceof ObjectField)) debugger;
 
         if (writeToServer) {
             if (value === undefined) target[Update]({ $unset: { ['fields.' + prop]: '' } });
@@ -143,13 +135,6 @@ export function denormalizeEmail(email: string) {
     return email.replace(/__/g, '.');
 }
 
-// playground mode allows the user to add/delete documents or make layout changes without them saving to the server
-// let playgroundMode = false;
-
-// export function togglePlaygroundMode() {
-//     playgroundMode = !playgroundMode;
-// }
-
 /**
  * Copies parent's acl fields to the child
  */
@@ -317,7 +302,6 @@ export function setter(target: any, in_prop: string | symbol | number, value: an
     if (effectiveAcl !== AclEdit && effectiveAcl !== AclAdmin && !(effectiveAcl === AclSelfEdit && value instanceof RichTextField)) return true;
     // if you're trying to change an acl but don't have Admin access / you're trying to change it to something that isn't an acceptable acl, you can't
     if (typeof prop === 'string' && prop.startsWith('acl') && (effectiveAcl !== AclAdmin || ![...Object.values(SharingPermissions), undefined].includes(value))) return true;
-    // if (typeof prop === "string" && prop.startsWith("acl") && !["Can Edit", "Can Augment", "Can View", "Not Shared", undefined].includes(value)) return true;
 
     if (typeof prop === 'string' && prop !== '__id' && prop !== '__fields' && prop.startsWith('_')) {
         if (!prop.startsWith('__')) prop = prop.substring(1);
@@ -377,9 +361,9 @@ export function getField(target: any, prop: string | number, ignoreProto: boolea
 export function deleteProperty(target: any, prop: string | number | symbol) {
     if (typeof prop === 'symbol') {
         delete target[prop];
-        return true;
+    } else {
+        target[SelfProxy][prop] = undefined;
     }
-    target[SelfProxy][prop] = undefined;
     return true;
 }
 
-- 
cgit v1.2.3-70-g09d2


From 0d899471be676f6619244350982630b151bb4b41 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Tue, 28 Mar 2023 19:53:49 -0400
Subject: mostly code cleaning.  small bugs

---
 src/client/documents/Documents.ts                  |  4 +-
 src/client/util/CurrentUserUtils.ts                |  2 +-
 src/client/views/OverlayView.tsx                   |  6 +-
 src/client/views/StyleProvider.tsx                 | 12 +--
 .../views/collections/CollectionTimeView.tsx       |  2 +-
 src/client/views/collections/TabDocView.tsx        |  1 +
 .../collections/collectionFreeForm/MarqueeView.tsx |  2 +-
 src/client/views/nodes/DocumentView.scss           |  6 +-
 src/client/views/nodes/DocumentView.tsx            | 93 ++++++++++------------
 src/client/views/nodes/LinkAnchorBox.tsx           | 32 +++-----
 src/client/views/nodes/trails/PresBox.tsx          |  5 +-
 11 files changed, 76 insertions(+), 89 deletions(-)

(limited to 'src/client/views/OverlayView.tsx')

diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts
index c484db0db..a110782b2 100644
--- a/src/client/documents/Documents.ts
+++ b/src/client/documents/Documents.ts
@@ -263,6 +263,7 @@ export class DocumentOptions {
     defaultBackgroundColor?: string;
     _isLinkButton?: boolean; // marks a document as a button that will follow its primary link when clicked
     _linkAutoMove?: boolean; // whether link endpoint should move around the edges of a document to make shortest path to other link endpoint
+    hideLinkAnchors?: boolean; // suppresses link anchor dots from being displayed
     isFolder?: boolean;
     lastFrame?: number; // the last frame of a frame-based collection (e.g., progressive slide)
     activeFrame?: number; // the active frame of a document in a frame base collection
@@ -505,6 +506,7 @@ export namespace Docs {
                     options: {
                         childDontRegisterViews: true,
                         _isLinkButton: true,
+                        hideLinkAnchors: true,
                         _height: 150,
                         description: '',
                         showCaption: 'description',
@@ -581,7 +583,7 @@ export namespace Docs {
                 DocumentType.PRES,
                 {
                     layout: { view: PresBox, dataField: defaultDataKey },
-                    options: { defaultDoubleClick: 'ignore' },
+                    options: { defaultDoubleClick: 'ignore', hideLinkAnchors: true },
                 },
             ],
             [
diff --git a/src/client/util/CurrentUserUtils.ts b/src/client/util/CurrentUserUtils.ts
index b21f53221..753cd1cb7 100644
--- a/src/client/util/CurrentUserUtils.ts
+++ b/src/client/util/CurrentUserUtils.ts
@@ -301,7 +301,7 @@ export class CurrentUserUtils {
             { toolTip: "Tap or drag to create a data viz node",   title: "DataViz", icon: "file",       dragFactory: doc.emptyDataViz as Doc,   clickFactory: DocCast(doc.emptyDataViz)},
             { toolTip: "Tap or drag to create a bullet slide",    title: "PPT Slide", icon: "file",     dragFactory: doc.emptySlide as Doc,     clickFactory: DocCast(doc.emptySlide),      openFactoryLocation: OpenWhere.overlay},
             { toolTip: "Tap or drag to create a data note", title: "DataNote", icon: "window-maximize", dragFactory: doc.emptyHeader as Doc,    clickFactory: DocCast(doc.emptyHeader),     openFactoryAsDelegate: true },
-            { toolTip: "Toggle a Calculator REPL",                title: "repl", icon: "calculator",                                            clickFactory: "repl" as any,                openFactoryLocation: OpenWhere.overlay},
+            { toolTip: "Toggle a Calculator REPL",                title: "repl", icon: "calculator",                                            clickFactory: 'repl' as any,                openFactoryLocation: OpenWhere.overlay},
           ].map(tuple => (
               { openFactoryLocation: OpenWhere.addRight, 
                 scripts: { onClick:     'openDoc(copyDragFactory(this.clickFactory,this.openFactoryAsDelegate), this.openFactoryLocation)', 
diff --git a/src/client/views/OverlayView.tsx b/src/client/views/OverlayView.tsx
index 34e8cd6dd..ec22128d4 100644
--- a/src/client/views/OverlayView.tsx
+++ b/src/client/views/OverlayView.tsx
@@ -219,6 +219,7 @@ export class OverlayView extends React.Component {
                             PanelHeight={d[HeightSym]}
                             ScreenToLocalTransform={this.docScreenToLocalXf(d)}
                             renderDepth={1}
+                            hideDecorations={true}
                             isDocumentActive={returnTrue}
                             isContentActive={returnTrue}
                             whenChildContentsActiveChanged={emptyFunction}
@@ -252,8 +253,3 @@ export class OverlayView extends React.Component {
         );
     }
 }
-// bcz: ugh ... want to be able to pass ScriptingRepl as tag argument, but that doesn't seem to work.. runtime error
-ScriptingGlobals.add(function addOverlayWindow(type: string, options: OverlayElementOptions) {
-    OverlayView.Instance.addWindow(<ScriptingRepl />, options);
-    addOverlayWindow('ScriptingRepl', { x: 300, y: 100, width: 200, height: 200, title: 'Scripting REPL' });
-});
diff --git a/src/client/views/StyleProvider.tsx b/src/client/views/StyleProvider.tsx
index faaa4e1f9..bd0539069 100644
--- a/src/client/views/StyleProvider.tsx
+++ b/src/client/views/StyleProvider.tsx
@@ -36,10 +36,10 @@ export enum StyleProp {
     FillColor = 'fillColor', // fill color of an ink stroke or shape
     WidgetColor = 'widgetColor', // color to display UI widgets on a document view -- used for the sidebar divider dragger on a text note
     HideLinkButton = 'hideLinkButton', // hides the blue-dot link button.  used when a document acts like a button
-    LinkSource = 'linkSource', // source document of a link -- used by LinkAnchorBox
     PointerEvents = 'pointerEvents', // pointer events for DocumentView -- inherits pointer events if not specified
     Decorations = 'decorations', // additional decoration to display above a DocumentView -- currently only used to display a Lock for making things background
     HeaderMargin = 'headerMargin', // margin at top of documentview, typically for displaying a title -- doc contents will start below that
+    ShowCaption = 'showCaption',
     TitleHeight = 'titleHeight', // Height of Title area
     ShowTitle = 'showTitle', // whether to display a title on a Document (optional :hover suffix)
     JitterRotation = 'jitterRotation', // whether documents should be randomly rotated
@@ -182,6 +182,8 @@ export function DefaultStyleProvider(doc: Opt<Doc>, props: Opt<DocumentViewProps
                 : { path: undefined, width: 0 };
         case StyleProp.JitterRotation:
             return Doc.IsComicStyle(doc) ? random(-1, 1, NumCast(doc?.x), NumCast(doc?.y)) * ((props?.PanelWidth() || 0) > (props?.PanelHeight() || 0) ? 5 : 10) : 0;
+        case StyleProp.ShowCaption:
+            return doc?._viewType === CollectionViewType.Carousel || props?.hideCaptions ? undefined : StrCast(doc?._showCaption);
         case StyleProp.HeaderMargin:
             return ([CollectionViewType.Stacking, CollectionViewType.NoteTaking, CollectionViewType.Masonry, CollectionViewType.Tree].includes(doc?._viewType as any) ||
                 (doc?.type === DocumentType.RTF && !showTitle()?.includes('noMargin')) ||
@@ -299,12 +301,12 @@ export function DefaultStyleProvider(doc: Opt<Doc>, props: Opt<DocumentViewProps
             if (props?.isDocumentActive?.()) return isInk ? 'visiblePainted' : 'all';
             return undefined; // fixes problem with tree view elements getting pointer events when the tree view is not active
         case StyleProp.Decorations:
-            if (props?.ContainingCollectionDoc?._viewType === CollectionViewType.Freeform || doc?.x !== undefined || doc?.y !== undefined) {
-                return doc && doc.pointerEvents === 'none' && lockedPosition() && !Doc.IsSystem(doc) && (props?.renderDepth || 0) > 0 ? (
+            if (props?.ContainingCollectionDoc?._viewType === CollectionViewType.Freeform) {
+                return doc?.pointerEvents !== 'none' ? null : (
                     <div className="styleProvider-lock" onClick={() => toggleLockedPosition(doc)}>
-                        <FontAwesomeIcon icon={lockedPosition() ? 'lock' : 'unlock'} style={{ color: lockedPosition() ? 'red' : undefined }} size="lg" />
+                        <FontAwesomeIcon icon={'lock'} style={{ color: 'red' }} size="lg" />
                     </div>
-                ) : null;
+                );
             }
     }
 }
diff --git a/src/client/views/collections/CollectionTimeView.tsx b/src/client/views/collections/CollectionTimeView.tsx
index 89b2fbfe3..4d5978548 100644
--- a/src/client/views/collections/CollectionTimeView.tsx
+++ b/src/client/views/collections/CollectionTimeView.tsx
@@ -150,7 +150,7 @@ export class CollectionTimeView extends CollectionSubView() {
                     engineProps={{ pivotField: this.pivotField, docFilters: this.childDocFilters, docRangeFilters: this.childDocRangeFilters }}
                     fitContentsToBox={returnTrue}
                     childClickScript={this._childClickedScript}
-                    viewDefDivClick={this._viewDefDivClick}
+                    viewDefDivClick={this.layoutEngine() === computeTimelineLayout.name ? undefined : this._viewDefDivClick}
                     //dontScaleFilter={this.dontScaleFilter}
                     layoutEngine={this.layoutEngine}
                 />
diff --git a/src/client/views/collections/TabDocView.tsx b/src/client/views/collections/TabDocView.tsx
index 93b816581..4ad09628f 100644
--- a/src/client/views/collections/TabDocView.tsx
+++ b/src/client/views/collections/TabDocView.tsx
@@ -422,6 +422,7 @@ export class TabDocView extends React.Component<TabDocViewProps> {
                     })}
                     renderDepth={0}
                     LayoutTemplateString={this.props.keyValue ? KeyValueBox.LayoutString() : undefined}
+                    hideTitle={this.props.keyValue}
                     Document={this._document}
                     DataDoc={!Doc.AreProtosEqual(this._document[DataSym], this._document) ? this._document[DataSym] : undefined}
                     ContainingCollectionView={undefined}
diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx
index 0714bffbc..f16371592 100644
--- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx
+++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx
@@ -609,7 +609,7 @@ export class MarqueeView extends React.Component<SubCollectionViewProps & Marque
         return false;
     }
 
-    marqueeSelect(selectBackgrounds: boolean = true) {
+    marqueeSelect(selectBackgrounds: boolean = false) {
         const selection: Doc[] = [];
         const selectFunc = (doc: Doc) => {
             const layoutDoc = Doc.Layout(doc);
diff --git a/src/client/views/nodes/DocumentView.scss b/src/client/views/nodes/DocumentView.scss
index e5913d997..1265651ad 100644
--- a/src/client/views/nodes/DocumentView.scss
+++ b/src/client/views/nodes/DocumentView.scss
@@ -17,8 +17,7 @@
     top: 0;
 }
 
-.documentView-node,
-.documentView-node-topmost {
+.documentView-node {
     position: inherit;
     top: 0;
     left: 0;
@@ -209,8 +208,7 @@
     }
 }
 
-.documentView-node:hover,
-.documentView-node-topmost:hover {
+.documentView-node:hover {
     > .documentView-styleWrapper {
         > .documentView-titleWrapper-hover {
             display: inline-block;
diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx
index 9a3e77e6e..ab93ce87b 100644
--- a/src/client/views/nodes/DocumentView.tsx
+++ b/src/client/views/nodes/DocumentView.tsx
@@ -268,9 +268,6 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
     @observable _animateScaleTime: Opt<number>; // milliseconds for animating between views.  defaults to 300 if not uset
     @observable _animateScalingTo = 0;
 
-    private get topMost() {
-        return this.props.renderDepth === 0 && !LightboxView.LightboxDoc;
-    }
     public get animateScaleTime() {
         return this._animateScaleTime ?? 300;
     }
@@ -307,8 +304,9 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
     @computed get widgetDecorations() {
         return this.props.styleProvider?.(this.rootDoc, this.props, StyleProp.Decorations + (this.props.isSelected() ? ':selected' : ''));
     }
-    @computed get backgroundColor() {
-        return this.props.styleProvider?.(this.layoutDoc, this.props, StyleProp.BackgroundColor);
+    @computed get backgroundBoxColor() {
+        const thumb = ImageCast(this.layoutDoc['thumb-frozen'], ImageCast(this.layoutDoc.thumb));
+        return thumb ? undefined : this.props.styleProvider?.(this.layoutDoc, this.props, StyleProp.BackgroundColor + ':box');
     }
     @computed get docContents() {
         return this.props.styleProvider?.(this.rootDoc, this.props, StyleProp.DocContents);
@@ -316,6 +314,9 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
     @computed get headerMargin() {
         return this.props?.styleProvider?.(this.layoutDoc, this.props, StyleProp.HeaderMargin) || 0;
     }
+    @computed get showCaption() {
+        return this.props?.styleProvider?.(this.layoutDoc, this.props, StyleProp.ShowCaption) || 0;
+    }
     @computed get titleHeight() {
         return this.props?.styleProvider?.(this.layoutDoc, this.props, StyleProp.TitleHeight) || 0;
     }
@@ -389,7 +390,8 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
             RadialMenu.Instance.addItem({
                 description: 'Delete',
                 event: () => {
-                    this.props.ContainingCollectionView?.removeDocument(this.props.Document), RadialMenu.Instance.closeMenu();
+                    this.props.ContainingCollectionView?.removeDocument(this.props.Document);
+                    RadialMenu.Instance.closeMenu();
                 },
                 icon: 'external-link-square-alt',
                 selected: -1,
@@ -563,13 +565,11 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
 
     @action
     onPointerMove = (e: PointerEvent): void => {
-        if (InteractionUtils.IsType(e, InteractionUtils.PENTYPE) || [InkTool.Highlighter, InkTool.Pen, InkTool.Write].includes(Doc.ActiveTool)) return;
+        if (e.buttons !== 1 || [InkTool.Highlighter, InkTool.Pen, InkTool.Write].includes(Doc.ActiveTool)) return;
 
-        if (e.buttons === 1 || InteractionUtils.IsType(e, InteractionUtils.TOUCHTYPE)) {
-            if (Math.abs(this._downX - e.clientX) > 3 || Math.abs(this._downY - e.clientY) > 3) {
-                this.cleanupPointerEvents();
-                this.startDragging(this._downX, this._downY, ((e.ctrlKey || e.altKey) && 'alias') || ((this.Document.dropAction || this.props.dropAction || undefined) as dropActionType));
-            }
+        if (!Utils.isClick(e.clientX, e.clientY, this._downX, this._downY, Date.now())) {
+            this.cleanupPointerEvents();
+            this.startDragging(this._downX, this._downY, ((e.ctrlKey || e.altKey) && 'alias') || ((this.Document.dropAction || this.props.dropAction || undefined) as dropActionType));
         }
     };
 
@@ -888,7 +888,7 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
         }
         cm.addItem({ description: 'Help...', noexpand: true, subitems: helpItems, icon: 'question' });
 
-        if (!this.topMost) e?.stopPropagation(); // DocumentViews should stop propagation of this event
+        e?.stopPropagation(); // DocumentViews should stop propagation of this event
         cm.displayMenu((e?.pageX || pageX || 0) - 15, (e?.pageY || pageY || 0) - 15);
     };
 
@@ -1021,7 +1021,6 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
         switch (property.split(':')[0]) {
             case StyleProp.ShowTitle:     return '';
             case StyleProp.PointerEvents: return 'none';
-            case StyleProp.LinkSource:    return this.props.Document; // pass the LinkSource to the LinkAnchorBox
             case StyleProp.Highlighting:  return undefined;
         }
         return this.props.styleProvider?.(doc, props, property);
@@ -1049,9 +1048,7 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
     @computed get allLinkEndpoints() {
         // the small blue dots that mark the endpoints of links
         TraceMobx();
-        if (this.props.hideLinkAnchors) return null;
-        if (this.layoutDoc.unrendered || this.props.LayoutTemplateString?.includes(LinkAnchorBox.name)) return null;
-        if (this.rootDoc.type === DocumentType.PRES || this.rootDoc.type === DocumentType.LINK || this.props.dontRegisterView) return null;
+        if (this.props.hideLinkAnchors || this.layoutDoc.hideLinkAnchors || this.props.dontRegisterView || this.layoutDoc.unrendered) return null;
         const filtered = DocUtils.FilterDocs(this.directLinks, this.props.docFilters?.() ?? [], []).filter(d => d.linkDisplay);
         return filtered.map((link, i) => (
             <div className="documentView-anchorCont" key={link[Id]}>
@@ -1059,11 +1056,13 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
                     {...this.props}
                     isContentActive={returnFalse}
                     Document={link}
+                    docViewPath={this.props.viewPath}
                     PanelWidth={this.anchorPanelWidth}
                     PanelHeight={this.anchorPanelHeight}
                     dontRegisterView={false}
                     showTitle={returnEmptyString}
                     hideCaptions={true}
+                    hideLinkAnchors={true}
                     fitWidth={returnTrue}
                     styleProvider={this.anchorStyleProvider}
                     removeDocument={this.hideLinkAnchor}
@@ -1148,12 +1147,11 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
         const ffscale = () => this.props.DocumentView().props.CollectionFreeFormDocumentView?.().props.ScreenToLocalTransform().Scale || 1;
         const showTitle = this.ShowTitle?.split(':')[0];
         const showTitleHover = this.ShowTitle?.includes(':hover');
-        const showCaption = !this.props.hideCaptions && this.Document._viewType !== CollectionViewType.Carousel ? StrCast(this.layoutDoc._showCaption) : undefined;
-        const captionView = !showCaption ? null : (
+        const captionView = !this.showCaption ? null : (
             <div
                 className="documentView-captionWrapper"
                 style={{
-                    pointerEvents: (!this.disableClickScriptFunc && this.onClickHandler) || this.Document.ignoreClick ? 'none' : this.isContentActive() || this.props.isDocumentActive?.() ? 'all' : undefined,
+                    pointerEvents: this.Document.ignoreClick ? 'none' : this.isContentActive() || this.props.isDocumentActive?.() ? 'all' : undefined,
                     minWidth: 50 * ffscale(),
                     maxHeight: `max(100%, ${20 * ffscale()}px)`,
                 }}>
@@ -1161,12 +1159,13 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
                     {...OmitKeys(this.props, ['children']).omit}
                     yPadding={10}
                     xPadding={10}
-                    fieldKey={showCaption}
+                    fieldKey={this.showCaption}
                     fontSize={12 * Math.max(1, (2 * ffscale()) / 3)}
                     styleProvider={this.captionStyleProvider}
                     dontRegisterView={true}
                     noSidebar={true}
                     dontScale={true}
+                    renderDepth={this.props.renderDepth}
                     isContentActive={this.isContentActive}
                     onClick={this.onClickFunc}
                 />
@@ -1220,7 +1219,7 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
                 />
             </div>
         );
-        return this.props.hideTitle || (!showTitle && !showCaption) ? (
+        return this.props.hideTitle || (!showTitle && !this.showCaption) ? (
             this.contents
         ) : (
             <div className="documentView-styleWrapper">
@@ -1235,31 +1234,27 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
 
     renderDoc = (style: object) => {
         TraceMobx();
-        const thumb = ImageCast(this.layoutDoc['thumb-frozen'], ImageCast(this.layoutDoc.thumb))?.url?.href.replace('.png', '_m.png');
-        const background = this.props.styleProvider?.(this.layoutDoc, this.props, StyleProp.BackgroundColor + ':box');
-        if (!(this.props.Document instanceof Doc) || GetEffectiveAcl(this.props.Document[DataSym]) === AclPrivate || this.hidden) return null;
-        return (
-            this.docContents ?? (
-                <div
-                    className={`documentView-node${this.topMost ? '-topmost' : ''}`}
-                    id={this.props.Document[Id]}
-                    style={{
-                        ...style,
-                        background: thumb ? undefined : background,
-                        opacity: this.opacity,
-                        cursor: Doc.ActiveTool === InkTool.None ? 'grab' : 'crosshair',
-                        color: StrCast(this.layoutDoc.color, 'inherit'),
-                        fontFamily: StrCast(this.Document._fontFamily, 'inherit'),
-                        fontSize: Cast(this.Document._fontSize, 'string', null),
-                        transform: this._animateScalingTo ? `scale(${this._animateScalingTo})` : undefined,
-                        transition: !this._animateScalingTo ? StrCast(this.Document.dataTransition) : `transform ${this.animateScaleTime / 1000}s ease-${this._animateScalingTo < 1 ? 'in' : 'out'}`,
-                    }}>
-                    {this.innards}
-                    {!this.disableClickScriptFunc && this.onClickHandler && this.props.ContainingCollectionView?.props.Document._viewType === CollectionViewType.Time ? <div className="documentView-contentBlocker" /> : null}
-                    {this.widgetDecorations ?? null}
-                </div>
-            )
-        );
+        return !DocCast(this.Document) || GetEffectiveAcl(this.Document[DataSym]) === AclPrivate || this.hidden
+            ? null
+            : this.docContents ?? (
+                  <div
+                      className="documentView-node"
+                      id={this.Document[Id]}
+                      style={{
+                          ...style,
+                          background: this.backgroundBoxColor,
+                          opacity: this.opacity,
+                          cursor: Doc.ActiveTool === InkTool.None ? 'grab' : 'crosshair',
+                          color: StrCast(this.layoutDoc.color, 'inherit'),
+                          fontFamily: StrCast(this.Document._fontFamily, 'inherit'),
+                          fontSize: Cast(this.Document._fontSize, 'string', null),
+                          transform: this._animateScalingTo ? `scale(${this._animateScalingTo})` : undefined,
+                          transition: !this._animateScalingTo ? StrCast(this.Document.dataTransition) : `transform ${this.animateScaleTime / 1000}s ease-${this._animateScalingTo < 1 ? 'in' : 'out'}`,
+                      }}>
+                      {this.innards}
+                      {this.widgetDecorations ?? null}
+                  </div>
+              );
     };
 
     /**
@@ -1506,7 +1501,7 @@ export class DocumentView extends React.Component<DocumentViewProps> {
         return this.effectiveNativeWidth ? this.effectiveNativeWidth * this.nativeScaling : this.props.PanelWidth();
     }
     @computed get panelHeight() {
-        if (this.effectiveNativeHeight && !this.layoutDoc.nativeHeightUnfrozen) {
+        if (this.effectiveNativeHeight && (!this.fitWidth || !this.layoutDoc.nativeHeightUnfrozen)) {
             return Math.min(this.props.PanelHeight(), this.effectiveNativeHeight * this.nativeScaling);
         }
         return this.props.PanelHeight();
@@ -1528,7 +1523,7 @@ export class DocumentView extends React.Component<DocumentViewProps> {
 
     toggleNativeDimensions = () => this.docView && Doc.toggleNativeDimensions(this.layoutDoc, this.docView.NativeDimScaling, this.props.PanelWidth(), this.props.PanelHeight());
     getBounds = () => {
-        if (!this.docView || !this.docView.ContentDiv || this.props.Document.type === DocumentType.PRES || this.props.treeViewDoc || Doc.AreProtosEqual(this.props.Document, Doc.UserDoc())) {
+        if (!this.docView || !this.docView.ContentDiv || this.props.treeViewDoc || Doc.AreProtosEqual(this.props.Document, Doc.UserDoc())) {
             return undefined;
         }
         const xf = this.docView?.props
diff --git a/src/client/views/nodes/LinkAnchorBox.tsx b/src/client/views/nodes/LinkAnchorBox.tsx
index e12548f18..3feb95ce9 100644
--- a/src/client/views/nodes/LinkAnchorBox.tsx
+++ b/src/client/views/nodes/LinkAnchorBox.tsx
@@ -1,22 +1,19 @@
-import { action, observable } from 'mobx';
+import { action, computed, observable } from 'mobx';
 import { observer } from 'mobx-react';
 import { Doc } from '../../../fields/Doc';
-import { Cast, NumCast, StrCast } from '../../../fields/Types';
+import { NumCast, StrCast } from '../../../fields/Types';
 import { TraceMobx } from '../../../fields/util';
 import { emptyFunction, setupMoveUpEvents, Utils } from '../../../Utils';
 import { DragManager } from '../../util/DragManager';
 import { LinkFollower } from '../../util/LinkFollower';
-import { ContextMenu } from '../ContextMenu';
-import { ContextMenuProps } from '../ContextMenuItem';
+import { SelectionManager } from '../../util/SelectionManager';
 import { ViewBoxBaseComponent } from '../DocComponent';
 import { StyleProp } from '../StyleProvider';
 import { FieldView, FieldViewProps } from './FieldView';
 import './LinkAnchorBox.scss';
 import { LinkDocPreview } from './LinkDocPreview';
 import React = require('react');
-import { LinkManager } from '../../util/LinkManager';
 import globalCssVariables = require('../global/globalCssVariables.scss');
-import { SelectionManager } from '../../util/SelectionManager';
 
 @observer
 export class LinkAnchorBox extends ViewBoxBaseComponent<FieldViewProps>() {
@@ -31,19 +28,15 @@ export class LinkAnchorBox extends ViewBoxBaseComponent<FieldViewProps>() {
     @observable _x = 0;
     @observable _y = 0;
 
+    @computed get linkSource() {
+        return this.props.docViewPath()[this.props.docViewPath().length - 2].rootDoc; // this.props.styleProvider?.(this.dataDoc, this.props, StyleProp.LinkSource);
+    }
+
     onPointerDown = (e: React.PointerEvent) => {
-        const anchorContainerDoc = this.props.styleProvider?.(this.dataDoc, this.props, StyleProp.LinkSource);
-        setupMoveUpEvents(
-            this,
-            e,
-            this.onPointerMove,
-            emptyFunction,
-            (e, doubleTap) => {
-                if (doubleTap) LinkFollower.FollowLink(this.rootDoc, anchorContainerDoc, false);
-                else this.props.select(false);
-            },
-            false
-        );
+        setupMoveUpEvents(this, e, this.onPointerMove, emptyFunction, (e, doubleTap) => {
+            if (doubleTap) LinkFollower.FollowLink(this.rootDoc, this.linkSource, false);
+            else this.props.select(false);
+        });
     };
     onPointerMove = action((e: PointerEvent, down: number[], delta: number[]) => {
         const cdiv = this._ref?.current?.parentElement;
@@ -73,7 +66,6 @@ export class LinkAnchorBox extends ViewBoxBaseComponent<FieldViewProps>() {
         const small = this.props.PanelWidth() <= 1; // this happens when rendered in a treeView
         const x = NumCast(this.rootDoc[this.fieldKey + '_x'], 100);
         const y = NumCast(this.rootDoc[this.fieldKey + '_y'], 100);
-        const linkSource = this.props.styleProvider?.(this.dataDoc, this.props, StyleProp.LinkSource);
         const background = this.props.styleProvider?.(this.dataDoc, this.props, StyleProp.BackgroundColor + ':anchor');
         const anchor = this.fieldKey === 'anchor1' ? 'anchor2' : 'anchor1';
         const anchorScale = !this.dataDoc[this.fieldKey + '-useLinkSmallAnchor'] && (x === 0 || x === 100 || y === 0 || y === 100) ? 1 : 0.25;
@@ -87,7 +79,7 @@ export class LinkAnchorBox extends ViewBoxBaseComponent<FieldViewProps>() {
                 onPointerEnter={e =>
                     LinkDocPreview.SetLinkInfo({
                         docProps: this.props,
-                        linkSrc: linkSource,
+                        linkSrc: this.linkSource,
                         linkDoc: this.rootDoc,
                         showHeader: true,
                         location: [e.clientX, e.clientY + 20],
diff --git a/src/client/views/nodes/trails/PresBox.tsx b/src/client/views/nodes/trails/PresBox.tsx
index 3376c29a9..0afb36214 100644
--- a/src/client/views/nodes/trails/PresBox.tsx
+++ b/src/client/views/nodes/trails/PresBox.tsx
@@ -919,6 +919,7 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
      */
     @action
     enterMinimize = () => {
+        this.updateCurrentPresentation(this.rootDoc);
         clearTimeout(this._presTimer);
         const pt = this.props.ScreenToLocalTransform().inverse().transformPoint(0, 0);
         this.props.removeDocument?.(this.layoutDoc);
@@ -939,7 +940,7 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
         doc._height = 30;
         doc._width = PresBox.minimizedWidth;
         Doc.AddDocToList(Doc.MyOverlayDocs, undefined, doc);
-        PresBox.Instance.initializePresState(PresBox.Instance.itemIndex);
+        PresBox.Instance?.initializePresState(PresBox.Instance.itemIndex);
         return (doc.presStatus = PresStatus.Manual);
     }
 
@@ -2435,7 +2436,7 @@ export class PresBox extends ViewBoxBaseComponent<FieldViewProps>() {
                     </Tooltip>
                     <div className="presPanel-button-text">
                         Slide {this.itemIndex + 1}
-                        {this.activeItem.presIndexed !== undefined ? `(${this.activeItem.presIndexed}/${this.progressivizedItems(this.activeItem)?.length})` : ''} / {this.childDocs.length}
+                        {this.activeItem?.presIndexed !== undefined ? `(${this.activeItem.presIndexed}/${this.progressivizedItems(this.activeItem)?.length})` : ''} / {this.childDocs.length}
                     </div>
                     <div className="presPanel-divider" />
                     <div className="presPanel-button-text" onPointerDown={e => setupMoveUpEvents(this, e, returnFalse, returnFalse, this.exitClicked, false, false)}>
-- 
cgit v1.2.3-70-g09d2

