From 131408385d49fc8d5f360c2918737da4cecc13c1 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Fri, 29 Jul 2022 16:55:01 -0400
Subject: fixed autoHeight for texdtviews embedded in text views.   fixed doc
 decorations for sidebar items in lightbox view.  added 'tree' as sidebar type
 for text.  fixed text sidebar to show same annotations whether in stacking or
 tree view.   fixed linkDescription pop to go away on click outside of it.

---
 .../views/nodes/formattedText/FormattedTextBox.tsx | 64 ++++++++++++----------
 1 file changed, 35 insertions(+), 29 deletions(-)

(limited to 'src/client/views/nodes/formattedText/FormattedTextBox.tsx')

diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
index bbb7ddc85..eb87d11a4 100644
--- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx
+++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
@@ -20,7 +20,7 @@ import { RichTextUtils } from '../../../../fields/RichTextUtils';
 import { ComputedField } from '../../../../fields/ScriptField';
 import { BoolCast, Cast, FieldValue, NumCast, ScriptCast, StrCast } from '../../../../fields/Types';
 import { GetEffectiveAcl, TraceMobx } from '../../../../fields/util';
-import { addStyleSheet, addStyleSheetRule, clearStyleSheetRules, emptyFunction, numberRange, OmitKeys, returnZero, setupMoveUpEvents, smoothScroll, unimplementedFunction, Utils } from '../../../../Utils';
+import { addStyleSheet, addStyleSheetRule, clearStyleSheetRules, emptyFunction, numberRange, OmitKeys, returnFalse, returnZero, setupMoveUpEvents, smoothScroll, unimplementedFunction, Utils } from '../../../../Utils';
 import { GoogleApiClientUtils, Pulls, Pushes } from '../../../apis/google_docs/GoogleApiClientUtils';
 import { DocServer } from '../../../DocServer';
 import { Docs, DocUtils } from '../../../documents/Documents';
@@ -62,6 +62,7 @@ import { SummaryView } from './SummaryView';
 import applyDevTools = require('prosemirror-dev-tools');
 import React = require('react');
 import { text } from 'body-parser';
+import { CollectionTreeView } from '../../collections/CollectionTreeView';
 const translateGoogleApi = require('translate-google-api');
 
 export interface FormattedTextBoxProps {
@@ -1500,7 +1501,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
     onFocused = (e: React.FocusEvent): void => {
         //applyDevTools.applyDevTools(this._editorView);
         FormattedTextBox.Focused = this;
-        this._editorView && RichTextMenu.Instance?.updateMenu(this._editorView, undefined, this.props);
+        this.ProseRef?.children[0] === e.nativeEvent.target && this._editorView && RichTextMenu.Instance?.updateMenu(this._editorView, undefined, this.props);
     };
     @observable public static Focused: FormattedTextBox | undefined;
 
@@ -1588,6 +1589,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
 
     @action
     onBlur = (e: any) => {
+        if (this.ProseRef?.children[0] !== e.nativeEvent.target) return;
         this.autoLink();
         FormattedTextBox.Focused === this && (FormattedTextBox.Focused = undefined);
         if (RichTextMenu.Instance?.view === this._editorView && !this.props.isSelected(true)) {
@@ -1702,7 +1704,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
     };
     fitContentsToBox = () => this.props.Document._fitContentsToBox;
     sidebarContentScaling = () => (this.props.NativeDimScaling?.() || 1) * NumCast(this.layoutDoc._viewScale, 1);
-    sidebarAddDocument = (doc: Doc | Doc[], sidebarKey?: string) => {
+    sidebarAddDocument = (doc: Doc | Doc[], sidebarKey: string = this.SidebarKey) => {
         if (!this.layoutDoc._showSidebar) this.toggleSidebar();
         // console.log("printting allSideBarDocs");
         // console.log(this.allSidebarDocs);
@@ -1716,7 +1718,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
         this.props
             .ScreenToLocalTransform()
             .translate(-(this.props.PanelWidth() - this.sidebarWidth()) / (this.props.NativeDimScaling?.() || 1), 0)
-            .scale(1 / NumCast(this.layoutDoc._viewScale, 1));
+            .scale(1 / NumCast(this.layoutDoc._viewScale, 1) / (this.props.NativeDimScaling?.() || 1));
 
     @computed get audioHandle() {
         return (
@@ -1746,7 +1748,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
     }
     @computed get sidebarCollection() {
         const renderComponent = (tag: string) => {
-            const ComponentTag = tag === 'freeform' ? CollectionFreeFormView : tag === 'translation' ? FormattedTextBox : CollectionStackingView;
+            const ComponentTag = tag === 'freeform' ? CollectionFreeFormView : tag === 'tree' ? CollectionTreeView : tag === 'translation' ? FormattedTextBox : CollectionStackingView;
             return ComponentTag === CollectionStackingView ? (
                 <SidebarAnnos
                     ref={this._sidebarRef}
@@ -1755,6 +1757,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
                     rootDoc={this.rootDoc}
                     layoutDoc={this.layoutDoc}
                     dataDoc={this.dataDoc}
+                    ScreenToLocalTransform={this.sidebarScreenToLocal}
                     nativeWidth={NumCast(this.layoutDoc._nativeWidth)}
                     whenChildContentsActiveChanged={this.whenChildContentsActiveChanged}
                     showSidebar={this.SidebarShown}
@@ -1765,30 +1768,33 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
                     removeDocument={this.removeDocument}
                 />
             ) : (
-                <ComponentTag
-                    {...OmitKeys(this.props, ['NativeWidth', 'NativeHeight', 'setContentView']).omit}
-                    NativeWidth={returnZero}
-                    NativeHeight={returnZero}
-                    PanelHeight={this.props.PanelHeight}
-                    PanelWidth={this.sidebarWidth}
-                    xPadding={0}
-                    yPadding={0}
-                    scaleField={this.SidebarKey + '-scale'}
-                    isAnnotationOverlay={false}
-                    select={emptyFunction}
-                    NativeDimScaling={this.sidebarContentScaling}
-                    whenChildContentsActiveChanged={this.whenChildContentsActiveChanged}
-                    removeDocument={this.sidebarRemDocument}
-                    moveDocument={this.sidebarMoveDocument}
-                    addDocument={this.sidebarAddDocument}
-                    CollectionView={undefined}
-                    ScreenToLocalTransform={this.sidebarScreenToLocal}
-                    renderDepth={this.props.renderDepth + 1}
-                    setHeight={this.setSidebarHeight}
-                    fitContentsToBox={this.fitContentsToBox}
-                    noSidebar={true}
-                    fieldKey={this.layoutDoc.sidebarViewType === 'translation' ? `${this.fieldKey}-translation` : `${this.fieldKey}-annotations`}
-                />
+                <div onPointerDown={e => setupMoveUpEvents(this, e, returnFalse, emptyFunction, () => SelectionManager.SelectView(this.props.DocumentView?.()!), true)}>
+                    <ComponentTag
+                        {...OmitKeys(this.props, ['NativeWidth', 'NativeHeight', 'setContentView']).omit}
+                        NativeWidth={returnZero}
+                        NativeHeight={returnZero}
+                        PanelHeight={this.props.PanelHeight}
+                        PanelWidth={this.sidebarWidth}
+                        xPadding={0}
+                        yPadding={0}
+                        scaleField={this.SidebarKey + '-scale'}
+                        isAnnotationOverlay={false}
+                        select={emptyFunction}
+                        NativeDimScaling={this.sidebarContentScaling}
+                        whenChildContentsActiveChanged={this.whenChildContentsActiveChanged}
+                        removeDocument={this.sidebarRemDocument}
+                        moveDocument={this.sidebarMoveDocument}
+                        addDocument={this.sidebarAddDocument}
+                        CollectionView={undefined}
+                        ScreenToLocalTransform={this.sidebarScreenToLocal}
+                        renderDepth={this.props.renderDepth + 1}
+                        setHeight={this.setSidebarHeight}
+                        fitContentsToBox={this.fitContentsToBox}
+                        noSidebar={true}
+                        treeViewHideTitle={true}
+                        fieldKey={this.layoutDoc.sidebarViewType === 'translation' ? `${this.fieldKey}-translation` : `${this.fieldKey}-sidebar`}
+                    />
+                </div>
             );
         };
         return (
-- 
cgit v1.2.3-70-g09d2


From cfa31b87f1c2a6597ed3cfb6a777126c58ace665 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Tue, 2 Aug 2022 16:28:18 -0400
Subject: Adjusted ScriptFields to have a rawScript, and updated ScrptingBoxes
 to create a scriptField even for scripts that don't compile.  Updated
 CurrentUserUtils setup functions for clicks.   Fixed TemplateMenu to work
 again.

---
 src/client/documents/Documents.ts                  |  14 +--
 src/client/util/CurrentUserUtils.ts                |  88 +++++++-------
 src/client/views/DocumentButtonBar.tsx             |  15 ++-
 src/client/views/ScriptBox.tsx                     | 134 +++++++++++----------
 src/client/views/TemplateMenu.tsx                  |  98 ++++++---------
 .../views/collections/CollectionStackingView.tsx   |   2 +-
 src/client/views/nodes/DocumentView.scss           |  23 ++--
 src/client/views/nodes/DocumentView.tsx            |  22 +++-
 src/client/views/nodes/FieldView.tsx               |   5 +-
 src/client/views/nodes/ScriptingBox.tsx            |  85 +++++++------
 src/client/views/nodes/button/FontIconBox.tsx      |   6 +-
 .../views/nodes/formattedText/FormattedTextBox.tsx |   8 +-
 src/fields/ScriptField.ts                          |  11 +-
 13 files changed, 259 insertions(+), 252 deletions(-)

(limited to 'src/client/views/nodes/formattedText/FormattedTextBox.tsx')

diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts
index 51a9283f4..64d26e425 100644
--- a/src/client/documents/Documents.ts
+++ b/src/client/documents/Documents.ts
@@ -264,12 +264,6 @@ export class DocumentOptions {
     baseProto?: boolean; // is this a base prototoype
     dontRegisterView?: boolean;
     lookupField?: ScriptField; // script that returns the value of a field. This script is passed the rootDoc, layoutDoc, field, and container of the document.  see PresBox.
-    'onDoubleClick-rawScript'?: string; // onDoubleClick script in raw text form
-    'onChildDoubleClick-rawScript'?: string; // onChildDoubleClick script in raw text form
-    'onChildClick-rawScript'?: string; // on ChildClick script in raw text form
-    'onClick-rawScript'?: string; // onClick script in raw text form
-    'onCheckedClick-rawScript'?: string; // onChecked script in raw text form
-    'onCheckedClick-params'?: List<string>; // parameter list for onChecked treeview functions
     columnHeaders?: List<SchemaHeaderField>; // headers for stacking views
     schemaHeaders?: List<SchemaHeaderField>; // headers for schema view
     clipWidth?: number; // percent transition from before to after in comparisonBox
@@ -1065,7 +1059,7 @@ export namespace Docs {
         }
 
         export function ButtonDocument(options?: DocumentOptions) {
-            return InstanceFromProto(Prototypes.get(DocumentType.BUTTON), undefined, { ...(options || {}), 'onClick-rawScript': '-script-' });
+            return InstanceFromProto(Prototypes.get(DocumentType.BUTTON), undefined, { ...(options || {}) });
         }
 
         export function SliderDocument(options?: DocumentOptions) {
@@ -1356,7 +1350,11 @@ export namespace DocUtils {
         scripts &&
             Object.keys(scripts).map(key => {
                 if (ScriptCast(doc[key])?.script.originalScript !== scripts[key] && scripts[key]) {
-                    doc[key] = ScriptField.MakeScript(scripts[key], { dragData: DragManager.DocumentDragData.name, value: 'any', scriptContext: 'any', documentView: Doc.name }, { _readOnly_: true });
+                    doc[key] = ScriptField.MakeScript(
+                        scripts[key],
+                        { dragData: DragManager.DocumentDragData.name, value: 'any', scriptContext: 'any', thisContainer: Doc.name, documentView: Doc.name, heading: Doc.name, checked: 'boolean', containingTreeView: Doc.name },
+                        { _readOnly_: true }
+                    );
                 }
             });
         funcs &&
diff --git a/src/client/util/CurrentUserUtils.ts b/src/client/util/CurrentUserUtils.ts
index ce32595d4..f55ed6e72 100644
--- a/src/client/util/CurrentUserUtils.ts
+++ b/src/client/util/CurrentUserUtils.ts
@@ -97,6 +97,45 @@ export class CurrentUserUtils {
         return DocUtils.AssignScripts(DocUtils.AssignOpts(tempDocs, reqdOpts, requiredTypes) ?? Docs.Create.MasonryDocument(requiredTypes, reqdOpts), reqdScripts, reqdFuncs);
     }
 
+    /// Initializes templates for editing click funcs of a document 
+    static setupChildClickEditors(doc: Doc, field = "clickFuncs-child") {
+        const tempClicks = DocCast(doc[field]);
+        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)"}];
+        const reqdClickList = reqdTempOpts.map(opts => {
+            const allOpts = {...reqdClickOpts, ...opts.opts};
+            const clickDoc = tempClicks ? DocListCast(tempClicks.data).find(doc => doc.title === opts.opts.title): undefined;
+            return DocUtils.AssignOpts(clickDoc, allOpts) ?? Docs.Create.ScriptingDocument(ScriptField.MakeScript(opts.script,allOpts));
+        });
+
+        const reqdOpts:DocumentOptions = { title: "child click editors", _height:75, system: true};
+        return DocUtils.AssignOpts(tempClicks, reqdOpts, reqdClickList) ?? (doc[field] = Docs.Create.TreeDocument(reqdClickList, reqdOpts));
+    }
+
+    /// Initializes templates for editing click funcs of a document 
+    static setupClickEditorTemplates(doc: Doc, field = "template-clickFuncs") {
+        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)"},
+        ];
+        const reqdClickList = reqdTempOpts.map(opts => {
+            const allOpts = {...reqdClickOpts, ...opts.opts};
+            const clickDoc = tempClicks ? DocListCast(tempClicks.data).find(doc => doc.title === opts.opts.title): undefined;
+            return DocUtils.AssignOpts(clickDoc, allOpts) ?? MakeTemplate(Docs.Create.ScriptingDocument(ScriptField.MakeScript(opts.script, {heading:Doc.name, checked:"boolean", containingTreeView:Doc.name}), allOpts), true, opts.opts.title);
+        });
+
+        const reqdOpts:DocumentOptions = {title: "click editor templates", _height:75, system: true};
+        return DocUtils.AssignOpts(tempClicks, reqdOpts, reqdClickList) ?? (doc[field] = Docs.Create.TreeDocument(reqdClickList, reqdOpts));
+    }
+
+
     /// Initializes templates that can be applied to notes
     static setupNoteTemplates(doc: Doc, field="template-notes") {
         const tempNotes = DocCast(doc[field]);
@@ -105,7 +144,7 @@ export class CurrentUserUtils {
             { noteType: "Idea", backgroundColor: "pink", icon: "lightbulb" },
             { noteType: "Topic", backgroundColor: "lightblue", icon: "book-open" }];
         const reqdNoteList = reqdTempOpts.map(opts => {
-            const reqdOpts = {...opts, title: "text", system: true};
+            const reqdOpts = {...opts, title: "text", width:200, system: true};
             const noteType = tempNotes ? DocListCast(tempNotes.data).find(doc => doc.noteType === opts.noteType): undefined;
             return DocUtils.AssignOpts(noteType, reqdOpts) ?? MakeTemplate(Docs.Create.TextDocument("",reqdOpts), true, opts.noteType??"Note");
         });
@@ -118,10 +157,10 @@ export class CurrentUserUtils {
     static setupDocTemplates(doc: Doc, field="myTemplates") {
         DocUtils.AssignDocField(doc, "presElement", opts => Docs.Create.PresElementBoxDocument(opts), { title: "pres element template", type: DocumentType.PRESELEMENT, _fitWidth: true, _xMargin: 0, isTemplateDoc: true, isTemplateForField: "data"});
         const templates = [
-            DocCast(doc.presElement),
             CurrentUserUtils.setupNoteTemplates(doc),
             CurrentUserUtils.setupClickEditorTemplates(doc)
         ];
+        CurrentUserUtils.setupChildClickEditors(doc)
         const reqdOpts = { title: "template layouts", _xMargin: 0, system: true,  };
         const reqdScripts = {  dropConverter: "convertToButtons(dragData)"  };
         return DocUtils.AssignDocField(doc, field, (opts,items) => Docs.Create.TreeDocument(items??[], opts), reqdOpts, templates, reqdScripts);
@@ -748,51 +787,6 @@ export class CurrentUserUtils {
         DocUtils.AssignDocField(myImports, "buttonMenuDoc", (opts) => Docs.Create.FontIconDocument(opts), reqdBtnOpts, undefined, { onClick: "importDocument()" });
         return myImports;
     }
-
-    static setupClickEditorTemplates(doc: Doc) {
-        if (doc["clickFuncs-child"] === undefined) {
-            // to use this function, select it from the context menu of a collection.  then edit the onChildClick script.  Add two Doc variables: 'target' and 'thisContainer', then assign 'target' to some target collection.  After that, clicking on any document in the initial collection will open it in the target
-            const openInTarget = Docs.Create.ScriptingDocument(ScriptField.MakeScript(
-                "docCast(thisContainer.target).then((target) => target && (target.proto.data = new List([self]))) ",
-                { thisContainer: Doc.name }), {
-                title: "Click to open in target", _width: 300, _height: 200,
-                targetScriptKey: "onChildClick", system: true
-            });
-
-            const openDetail = Docs.Create.ScriptingDocument(ScriptField.MakeScript( "openOnRight(self.doubleClickView)",  {}), 
-                { title: "Double click to open doubleClickView", _width: 300, _height: 200, targetScriptKey: "onChildDoubleClick", system: true });
-
-            doc["clickFuncs-child"] = Docs.Create.TreeDocument([openInTarget, openDetail], { title: "on Child Click function templates", system: true });
-        }
-
-        if (doc.clickFuncs === undefined) {
-            const onClick = Docs.Create.ScriptingDocument(undefined, {
-                title: "onClick", "onClick-rawScript": "console.log('click')",
-                isTemplateDoc: true, isTemplateForField: "onClick", _width: 300, _height: 200, system: true
-            }, "onClick");
-            const onChildClick = Docs.Create.ScriptingDocument(undefined, {
-                title: "onChildClick", "onChildClick-rawScript": "console.log('child click')",
-                isTemplateDoc: true, isTemplateForField: "onChildClick", _width: 300, _height: 200, system: true
-            }, "onChildClick");
-            const onDoubleClick = Docs.Create.ScriptingDocument(undefined, {
-                title: "onDoubleClick", "onDoubleClick-rawScript": "console.log('double click')",
-                isTemplateDoc: true, isTemplateForField: "onDoubleClick", _width: 300, _height: 200, system: true
-            }, "onDoubleClick");
-            const onChildDoubleClick = Docs.Create.ScriptingDocument(undefined, {
-                title: "onChildDoubleClick", "onChildDoubleClick-rawScript": "console.log('child double click')",
-                isTemplateDoc: true, isTemplateForField: "onChildDoubleClick", _width: 300, _height: 200, system: true
-            }, "onChildDoubleClick");
-            const onCheckedClick = Docs.Create.ScriptingDocument(undefined, {
-                title: "onCheckedClick", "onCheckedClick-rawScript": "console.log(heading + checked + containingTreeView)",
-                "onCheckedClick-params": new List<string>(["heading", "checked", "containingTreeView"]), isTemplateDoc: true,
-                isTemplateForField: "onCheckedClick", _width: 300, _height: 200, system: true
-            }, "onCheckedClick");
-            doc.clickFuncs = Docs.Create.TreeDocument([onClick, onChildClick, onDoubleClick, onCheckedClick], { title: "onClick funcs", system: true });
-        }
-
-        return doc.clickFuncs as Doc;
-    }
-
     /// Updates the UserDoc to have all required fields, docs, etc.  No changes should need to be
     /// written to the server if the code hasn't changed.  However, choices need to be made for each Doc/field
     /// whether to revert to "default" values, or to leave them as the user/system last set them.
diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx
index bac51a11d..1d4056759 100644
--- a/src/client/views/DocumentButtonBar.tsx
+++ b/src/client/views/DocumentButtonBar.tsx
@@ -335,8 +335,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV
         );
     }
     @observable _aliasDown = false;
-    onAliasButtonDown = action((e: React.PointerEvent): void => {
-        this.props.views()[0]?.select(false);
+    onTemplateButton = action((e: React.PointerEvent): void => {
         this._tooltipOpen = false;
         setupMoveUpEvents(this, e, this.onAliasButtonMoved, emptyFunction, emptyFunction);
     });
@@ -374,7 +373,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV
                                 </div>
                             )
                         }>
-                        <div className={'documentButtonBar-linkButton-empty'} ref={this._dragRef} onPointerDown={this.onAliasButtonDown}>
+                        <div className={'documentButtonBar-linkButton-empty'} ref={this._dragRef} onPointerDown={this.onTemplateButton}>
                             {<FontAwesomeIcon className="documentdecorations-icon" icon="edit" size="sm" />}
                         </div>
                     </Flyout>
@@ -412,15 +411,15 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV
                         <DocumentLinksButton View={this.view0} AlwaysOn={true} InMenu={true} StartLink={false} />
                     </div>
                 ) : null}
-                {/*!Doc.UserDoc()["documentLinksButton-fullMenu"] ? (null) : <div className="documentButtonBar-button">
-                {this.templateButton}
-            </div>
-            /*<div className="documentButtonBar-button">
+                {
+                    Doc.noviceMode ? null : <div className="documentButtonBar-button">{this.templateButton}</div>
+                    /*<div className="documentButtonBar-button">
                 {this.metadataButton}
             </div>
             <div className="documentButtonBar-button">
                 {this.contextButton}
-            </div> */}
+            </div> */
+                }
                 {!SelectionManager.Views()?.some(v => v.allLinks.length) ? null : <div className="documentButtonBar-button">{this.followLinkButton}</div>}
                 <div className="documentButtonBar-button">{this.pinButton}</div>
                 {!Doc.UserDoc()['documentLinksButton-fullMenu'] ? null : <div className="documentButtonBar-button">{this.shareButton}</div>}
diff --git a/src/client/views/ScriptBox.tsx b/src/client/views/ScriptBox.tsx
index b7ea124b9..416162aeb 100644
--- a/src/client/views/ScriptBox.tsx
+++ b/src/client/views/ScriptBox.tsx
@@ -1,17 +1,16 @@
-import { action, observable } from "mobx";
-import { observer } from "mobx-react";
-import * as React from "react";
-import { Doc, Opt } from "../../fields/Doc";
-import { ScriptField } from "../../fields/ScriptField";
-import { ScriptCast } from "../../fields/Types";
-import { emptyFunction } from "../../Utils";
-import { DragManager } from "../util/DragManager";
-import { CompileScript } from "../util/Scripting";
-import { EditableView } from "./EditableView";
-import { DocumentIconContainer } from "./nodes/DocumentIcon";
-import { OverlayView } from "./OverlayView";
-import "./ScriptBox.scss";
-
+import { action, observable } from 'mobx';
+import { observer } from 'mobx-react';
+import * as React from 'react';
+import { Doc, Opt } from '../../fields/Doc';
+import { ScriptField } from '../../fields/ScriptField';
+import { ScriptCast } from '../../fields/Types';
+import { emptyFunction } from '../../Utils';
+import { DragManager } from '../util/DragManager';
+import { CompileScript } from '../util/Scripting';
+import { EditableView } from './EditableView';
+import { DocumentIconContainer } from './nodes/DocumentIcon';
+import { OverlayView } from './OverlayView';
+import './ScriptBox.scss';
 
 export interface ScriptBoxProps {
     onSave: (text: string, onError: (error: string) => void) => void;
@@ -28,53 +27,58 @@ export class ScriptBox extends React.Component<ScriptBoxProps> {
 
     constructor(props: ScriptBoxProps) {
         super(props);
-        this._scriptText = props.initialText || "";
+        this._scriptText = props.initialText || '';
     }
 
     @action
     onChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
         this._scriptText = e.target.value;
-    }
+    };
 
     @action
     onError = (error: string) => {
-        console.log("ScriptBox: " + error);
-    }
+        console.log('ScriptBox: ' + error);
+    };
 
     overlayDisposer?: () => void;
     onFocus = () => {
         this.overlayDisposer?.();
         this.overlayDisposer = OverlayView.Instance.addElement(<DocumentIconContainer />, { x: 0, y: 0 });
-    }
+    };
 
     onBlur = () => {
         this.overlayDisposer?.();
-    }
+    };
 
     render() {
-        let onFocus: Opt<() => void> = undefined, onBlur: Opt<() => void> = undefined;
+        let onFocus: Opt<() => void> = undefined,
+            onBlur: Opt<() => void> = undefined;
         if (this.props.showDocumentIcons) {
             onFocus = this.onFocus;
             onBlur = this.onBlur;
         }
-        const params = <EditableView
-            contents={""}
-            display={"block"}
-            maxHeight={72}
-            height={35}
-            fontSize={28}
-            GetValue={() => ""}
-            SetValue={(value: string) => this.props.setParams && this.props.setParams(value.split(" ").filter(s => s !== " ")) ? true : true}
-        />;
+        const params = <EditableView contents={''} display={'block'} maxHeight={72} height={35} fontSize={28} GetValue={() => ''} SetValue={(value: string) => (this.props.setParams?.(value.split(' ').filter(s => s !== ' ')) ? true : true)} />;
         return (
             <div className="scriptBox-outerDiv">
-                <div style={{ display: "flex", flexDirection: "column", height: "100%" }}>
+                <div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
                     <textarea className="scriptBox-textarea" onChange={this.onChange} value={this._scriptText} onFocus={onFocus} onBlur={onBlur}></textarea>
-                    <div style={{ background: "beige" }} >{params}</div>
+                    <div style={{ background: 'beige' }}>{params}</div>
                 </div>
                 <div className="scriptBox-toolbar">
-                    <button onClick={e => { this.props.onSave(this._scriptText, this.onError); e.stopPropagation(); }}>Save</button>
-                    <button onClick={e => { this.props.onCancel && this.props.onCancel(); e.stopPropagation(); }}>Cancel</button>
+                    <button
+                        onClick={e => {
+                            this.props.onSave(this._scriptText, this.onError);
+                            e.stopPropagation();
+                        }}>
+                        Save
+                    </button>
+                    <button
+                        onClick={e => {
+                            this.props.onCancel && this.props.onCancel();
+                            e.stopPropagation();
+                        }}>
+                        Cancel
+                    </button>
                 </div>
             </div>
         );
@@ -90,35 +94,43 @@ export class ScriptBox extends React.Component<ScriptBoxProps> {
         // tslint:disable-next-line: no-unnecessary-callback-wrapper
         const params: string[] = [];
         const setParams = (p: string[]) => params.splice(0, params.length, ...p);
-        const scriptingBox = <ScriptBox initialText={originalText} setParams={setParams} onCancel={overlayDisposer} onSave={(text, onError) => {
-            if (!text) {
-                Doc.GetProto(doc)[fieldKey] = undefined;
-            } else {
-                const script = CompileScript(text, {
-                    params: { this: Doc.name, ...contextParams },
-                    typecheck: false,
-                    editable: true,
-                    transformer: DocumentIconContainer.getTransformer()
-                });
-                if (!script.compiled) {
-                    onError(script.errors.map(error => error.messageText).join("\n"));
-                    return;
-                }
+        const scriptingBox = (
+            <ScriptBox
+                initialText={originalText}
+                setParams={setParams}
+                onCancel={overlayDisposer}
+                onSave={(text, onError) => {
+                    if (!text) {
+                        Doc.GetProto(doc)[fieldKey] = undefined;
+                    } else {
+                        const script = CompileScript(text, {
+                            params: { this: Doc.name, ...contextParams },
+                            typecheck: false,
+                            editable: true,
+                            transformer: DocumentIconContainer.getTransformer(),
+                        });
+                        if (!script.compiled) {
+                            onError(script.errors.map(error => error.messageText).join('\n'));
+                            return;
+                        }
 
-                const div = document.createElement("div");
-                div.style.width = "90";
-                div.style.height = "20";
-                div.style.background = "gray";
-                div.style.position = "absolute";
-                div.style.display = "inline-block";
-                div.style.transform = `translate(${clientX}px, ${clientY}px)`;
-                div.innerHTML = "button";
-                params.length && DragManager.StartButtonDrag([div], text, doc.title + "-instance", {}, params, (button: Doc) => { }, clientX, clientY);
+                        const div = document.createElement('div');
+                        div.style.width = '90';
+                        div.style.height = '20';
+                        div.style.background = 'gray';
+                        div.style.position = 'absolute';
+                        div.style.display = 'inline-block';
+                        div.style.transform = `translate(${clientX}px, ${clientY}px)`;
+                        div.innerHTML = 'button';
+                        params.length && DragManager.StartButtonDrag([div], text, doc.title + '-instance', {}, params, (button: Doc) => {}, clientX, clientY);
 
-                Doc.GetProto(doc)[fieldKey] = new ScriptField(script);
-                overlayDisposer();
-            }
-        }} showDocumentIcons />;
+                        Doc.GetProto(doc)[fieldKey] = new ScriptField(script);
+                        overlayDisposer();
+                    }
+                }}
+                showDocumentIcons
+            />
+        );
         overlayDisposer = OverlayView.Instance.addWindow(scriptingBox, { x: 400, y: 200, width: 500, height: 400, title });
     }
 }
diff --git a/src/client/views/TemplateMenu.tsx b/src/client/views/TemplateMenu.tsx
index 156513f47..863829a51 100644
--- a/src/client/views/TemplateMenu.tsx
+++ b/src/client/views/TemplateMenu.tsx
@@ -55,16 +55,12 @@ export class TemplateMenu extends React.Component<TemplateMenuProps> {
     @observable private _hidden: boolean = true;
 
     toggleLayout = (e: React.ChangeEvent<HTMLInputElement>, layout: string): void => {
-        this.props.docViews.map(dv => dv.switchViews(e.target.checked, layout));
+        this.props.docViews.map(dv => dv.switchViews(e.target.checked, layout, undefined, true));
     };
     toggleDefault = (e: React.ChangeEvent<HTMLInputElement>): void => {
         this.props.docViews.map(dv => dv.switchViews(false, 'layout'));
     };
 
-    toggleAudio = (e: React.ChangeEvent<HTMLInputElement>): void => {
-        this.props.docViews.map(dv => (dv.props.Document._showAudio = e.target.checked));
-    };
-
     @undoBatch
     @action
     toggleTemplate = (event: React.ChangeEvent<HTMLInputElement>, template: string): void => {
@@ -76,12 +72,6 @@ export class TemplateMenu extends React.Component<TemplateMenuProps> {
         this._hidden = !this._hidden;
     };
 
-    @undoBatch
-    @action
-    toggleChrome = (): void => {
-        this.props.docViews.map(dv => Doc.Layout(dv.layoutDoc)).forEach(layout => (layout._chromeHidden = !layout._chromeHidden));
-    };
-
     // todo: add brushes to brushMap to save with a style name
     onCustomKeypress = (e: React.KeyboardEvent) => {
         if (e.key === 'Enter') {
@@ -95,13 +85,9 @@ export class TemplateMenu extends React.Component<TemplateMenuProps> {
             .map(key => runInAction(() => this._addedKeys.add(key.replace('layout_', ''))));
     }
 
-    return100 = () => 100;
+    return100 = () => 300;
     @computed get scriptField() {
-        const script = ScriptField.MakeScript(
-            'docs.map(d => switchView(d, this))',
-            { this: Doc.name, heading: 'string', checked: 'string', containingTreeView: Doc.name, firstDoc: Doc.name },
-            { docs: new List<Doc>(this.props.docViews.map(dv => dv.props.Document)) }
-        );
+        const script = ScriptField.MakeScript('docs.map(d => switchView(d, this))', { this: Doc.name }, { docs: this.props.docViews.map(dv => dv.props.Document) as any });
         return script ? () => script : undefined;
     }
     templateIsUsed = (selDoc: Doc, templateDoc: Doc) => {
@@ -113,13 +99,10 @@ export class TemplateMenu extends React.Component<TemplateMenuProps> {
         const firstDoc = this.props.docViews[0].props.Document;
         const templateName = StrCast(firstDoc.layoutKey, 'layout').replace('layout_', '');
         const noteTypes = DocListCast(Cast(Doc.UserDoc()['template-notes'], Doc, null)?.data);
-        const addedTypes = Doc.noviceMode ? [] : DocListCast(Cast(Doc.UserDoc()['template-buttons'], Doc, null)?.data);
-        const layout = Doc.Layout(firstDoc);
+        const addedTypes = DocListCast(Cast(Doc.UserDoc()['template-clickFuncs'], Doc, null)?.data);
         const templateMenu: Array<JSX.Element> = [];
         this.props.templates?.forEach((checked, template) => templateMenu.push(<TemplateToggle key={template} template={template} checked={checked} toggle={this.toggleTemplate} />));
-        templateMenu.push(<OtherToggle key={'audio'} name={'Audio'} checked={firstDoc._showAudio ? true : false} toggle={this.toggleAudio} />);
         templateMenu.push(<OtherToggle key={'default'} name={'Default'} checked={templateName === 'layout'} toggle={this.toggleDefault} />);
-        !Doc.noviceMode && templateMenu.push(<OtherToggle key={'chrome'} name={'Chrome'} checked={!layout._chromeHidden} toggle={this.toggleChrome} />);
         addedTypes.concat(noteTypes).map(template => (template.treeViewChecked = this.templateIsUsed(firstDoc, template)));
         this._addedKeys &&
             Array.from(this._addedKeys)
@@ -129,43 +112,42 @@ export class TemplateMenu extends React.Component<TemplateMenuProps> {
             <ul className="template-list" style={{ display: 'block' }}>
                 {Doc.noviceMode ? null : <input placeholder="+ layout" ref={this._customRef} onKeyPress={this.onCustomKeypress} />}
                 {templateMenu}
-                {Doc.noviceMode ? null : (
-                    <CollectionTreeView
-                        Document={Doc.MyTemplates}
-                        CollectionView={undefined}
-                        ContainingCollectionDoc={undefined}
-                        ContainingCollectionView={undefined}
-                        styleProvider={DefaultStyleProvider}
-                        setHeight={returnFalse}
-                        docViewPath={returnEmptyDoclist}
-                        docFilters={returnEmptyFilter}
-                        docRangeFilters={returnEmptyFilter}
-                        searchFilterDocs={returnEmptyDoclist}
-                        rootSelected={returnFalse}
-                        onCheckedClick={this.scriptField}
-                        onChildClick={this.scriptField}
-                        dropAction={undefined}
-                        isAnyChildContentActive={returnFalse}
-                        isContentActive={returnTrue}
-                        bringToFront={emptyFunction}
-                        focus={emptyFunction}
-                        whenChildContentsActiveChanged={emptyFunction}
-                        ScreenToLocalTransform={Transform.Identity}
-                        isSelected={returnFalse}
-                        pinToPres={emptyFunction}
-                        select={emptyFunction}
-                        renderDepth={1}
-                        addDocTab={returnFalse}
-                        PanelWidth={this.return100}
-                        PanelHeight={this.return100}
-                        treeViewHideHeaderFields={true}
-                        dontRegisterView={true}
-                        fieldKey={'data'}
-                        moveDocument={returnFalse}
-                        removeDocument={returnFalse}
-                        addDocument={returnFalse}
-                    />
-                )}
+                <CollectionTreeView
+                    Document={Doc.MyTemplates}
+                    CollectionView={undefined}
+                    ContainingCollectionDoc={undefined}
+                    ContainingCollectionView={undefined}
+                    styleProvider={DefaultStyleProvider}
+                    setHeight={returnFalse}
+                    docViewPath={returnEmptyDoclist}
+                    docFilters={returnEmptyFilter}
+                    docRangeFilters={returnEmptyFilter}
+                    searchFilterDocs={returnEmptyDoclist}
+                    rootSelected={returnFalse}
+                    onCheckedClick={this.scriptField}
+                    onChildClick={this.scriptField}
+                    dropAction={undefined}
+                    isAnyChildContentActive={returnFalse}
+                    isContentActive={returnTrue}
+                    bringToFront={emptyFunction}
+                    focus={emptyFunction}
+                    whenChildContentsActiveChanged={emptyFunction}
+                    ScreenToLocalTransform={Transform.Identity}
+                    isSelected={returnFalse}
+                    pinToPres={emptyFunction}
+                    select={emptyFunction}
+                    renderDepth={1}
+                    addDocTab={returnFalse}
+                    PanelWidth={this.return100}
+                    PanelHeight={this.return100}
+                    treeViewHideHeaderFields={true}
+                    treeViewHideTitle={true}
+                    dontRegisterView={true}
+                    fieldKey={'data'}
+                    moveDocument={returnFalse}
+                    removeDocument={returnFalse}
+                    addDocument={returnFalse}
+                />
             </ul>
         );
     }
diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx
index 6850fb23a..a6c367ff7 100644
--- a/src/client/views/collections/CollectionStackingView.tsx
+++ b/src/client/views/collections/CollectionStackingView.tsx
@@ -296,7 +296,7 @@ export class CollectionStackingView extends CollectionSubView<Partial<collection
                 NativeWidth={this.props.childIgnoreNativeSize ? returnZero : this.props.childFitWidth?.(doc) || (doc._fitWidth && !Doc.NativeWidth(doc)) ? width : undefined} // explicitly ignore nativeWidth/height if childIgnoreNativeSize is set- used by PresBox
                 NativeHeight={this.props.childIgnoreNativeSize ? returnZero : this.props.childFitWidth?.(doc) || (doc._fitWidth && !Doc.NativeHeight(doc)) ? height : undefined}
                 dontCenter={this.props.childIgnoreNativeSize ? 'xy' : undefined}
-                dontRegisterView={dataDoc ? true : BoolCast(this.layoutDoc.childDontRegisterViews, this.props.dontRegisterView)}
+                dontRegisterView={BoolCast(this.layoutDoc.childDontRegisterViews, this.props.dontRegisterView)}
                 rootSelected={this.rootSelected}
                 showTitle={this.props.childShowTitle}
                 dropAction={StrCast(this.layoutDoc.childDropAction) as dropActionType}
diff --git a/src/client/views/nodes/DocumentView.scss b/src/client/views/nodes/DocumentView.scss
index 6a1bfa406..c02692bfb 100644
--- a/src/client/views/nodes/DocumentView.scss
+++ b/src/client/views/nodes/DocumentView.scss
@@ -1,4 +1,4 @@
-@import "../global/globalCssVariables";
+@import '../global/globalCssVariables';
 
 .documentView-effectsWrapper {
     border-radius: inherit;
@@ -24,7 +24,7 @@
     width: 100%;
     height: 100%;
     border-radius: inherit;
-    transition: outline .3s linear;
+    transition: outline 0.3s linear;
     cursor: grab;
 
     // background: $white; //overflow: hidden;
@@ -62,7 +62,7 @@
 
     .documentView-audioBackground {
         display: inline-block;
-        width: 10%;
+        width: 25px;
         height: 25;
         position: absolute;
         top: 10px;
@@ -88,7 +88,7 @@
         width: 100%;
         overflow: hidden;
 
-        >.documentView-node {
+        > .documentView-node {
             position: absolute;
         }
     }
@@ -158,7 +158,7 @@
             top: 0;
             width: 100%;
             height: 14;
-            background: rgba(0, 0, 0, .4);
+            background: rgba(0, 0, 0, 0.4);
             text-align: center;
             text-overflow: ellipsis;
             white-space: pre;
@@ -187,19 +187,18 @@
             transition: opacity 0.5s;
         }
     }
-
 }
 
 .documentView-node:hover,
 .documentView-node-topmost:hover {
-    >.documentView-styleWrapper {
-        >.documentView-titleWrapper-hover {
+    > .documentView-styleWrapper {
+        > .documentView-titleWrapper-hover {
             display: inline-block;
         }
     }
 
-    >.documentView-styleWrapper {
-        >.documentView-captionWrapper {
+    > .documentView-styleWrapper {
+        > .documentView-captionWrapper {
             opacity: 1;
         }
     }
@@ -225,6 +224,6 @@
 
     .documentView-node:first-child {
         position: relative;
-        background: "#B59B66"; //$white;
+        background: '#B59B66'; //$white;
     }
-}
\ No newline at end of file
+}
diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx
index 8847c0c6a..edaa40bad 100644
--- a/src/client/views/nodes/DocumentView.tsx
+++ b/src/client/views/nodes/DocumentView.tsx
@@ -177,6 +177,7 @@ export interface DocumentViewProps extends DocumentViewSharedProps {
     dontScaleFilter?: (doc: Doc) => boolean; // decides whether a document can be scaled to fit its container vs native size with scrolling
     NativeWidth?: () => number;
     NativeHeight?: () => number;
+    NativeDimScaling?: () => number; // scaling the DocumentView does to transform its contents into its panel & needed by ScreenToLocal NOTE: Must also be added to FieldViewProps
     LayoutTemplate?: () => Opt<Doc>;
     contextMenuItems?: () => { script: ScriptField; filter?: ScriptField; label: string; icon: string }[];
     onClick?: () => ScriptField;
@@ -191,7 +192,6 @@ export interface DocumentViewProps extends DocumentViewSharedProps {
 export interface DocumentViewInternalProps extends DocumentViewProps {
     NativeWidth: () => number;
     NativeHeight: () => number;
-    NativeDimScaling?: () => number; // scaling the DocumentView does to transform its contents into its panel & needed by ScreenToLocal NOTE: Must also be added to FieldViewProps
     isSelected: (outsideReaction?: boolean) => boolean;
     select: (ctrlPressed: boolean) => void;
     DocumentView: () => DocumentView;
@@ -716,7 +716,7 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
             this.Document.followLinkLocation = location;
         } else if (this.Document._isLinkButton && this.onClickHandler) {
             this.Document._isLinkButton = false;
-            this.Document['onClick-rawScript'] = this.dataDoc['onClick-rawScript'] = this.dataDoc.onClick = this.Document.onClick = this.layoutDoc.onClick = undefined;
+            this.dataDoc.onClick = this.Document.onClick = this.layoutDoc.onClick = undefined;
         }
     };
     @undoBatch
@@ -750,7 +750,13 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
     };
 
     @undoBatch deleteClicked = () => this.props.removeDocument?.(this.props.Document);
-    @undoBatch setToggleDetail = () => (this.Document.onClick = ScriptField.MakeScript(`toggleDetail(documentView, "${StrCast(this.Document.layoutKey).replace('layout_', '')}")`, { documentView: 'any' }));
+    @undoBatch setToggleDetail = () =>
+        (this.Document.onClick = ScriptField.MakeScript(
+            `toggleDetail(documentView, "${StrCast(this.Document.layoutKey)
+                .replace('layout_', '')
+                .replace(/^layout$/, 'detail')}")`,
+            { documentView: 'any' }
+        ));
 
     @undoBatch
     @action
@@ -1538,11 +1544,15 @@ export class DocumentView extends React.Component<DocumentViewProps> {
         Doc.setNativeView(this.props.Document);
         custom && DocUtils.makeCustomViewClicked(this.props.Document, Docs.Create.StackingDocument, layout, undefined);
     };
-    switchViews = action((custom: boolean, view: string, finished?: () => void) => {
+    switchViews = action((custom: boolean, view: string, finished?: () => void, useExistingLayout = false) => {
         this.docView && (this.docView._animateScalingTo = 0.1); // shrink doc
         setTimeout(
             action(() => {
-                this.setCustomView(custom, view);
+                if (useExistingLayout && custom && this.rootDoc['layout_' + view]) {
+                    this.rootDoc.layoutKey = 'layout_' + view;
+                } else {
+                    this.setCustomView(custom, view);
+                }
                 this.docView && (this.docView._animateScalingTo = 1); // expand it
                 setTimeout(
                     action(() => {
@@ -1646,7 +1656,7 @@ ScriptingGlobals.add(function deiconifyView(documentView: DocumentView) {
 
 ScriptingGlobals.add(function toggleDetail(dv: DocumentView, detailLayoutKeySuffix: string) {
     if (dv.Document.layoutKey === 'layout_' + detailLayoutKeySuffix) dv.switchViews(false, 'layout');
-    else dv.switchViews(true, detailLayoutKeySuffix);
+    else dv.switchViews(true, detailLayoutKeySuffix, undefined, true);
 });
 
 ScriptingGlobals.add(function updateLinkCollection(linkCollection: Doc) {
diff --git a/src/client/views/nodes/FieldView.tsx b/src/client/views/nodes/FieldView.tsx
index 5a6c49809..dd2c13391 100644
--- a/src/client/views/nodes/FieldView.tsx
+++ b/src/client/views/nodes/FieldView.tsx
@@ -4,10 +4,9 @@ import { observer } from 'mobx-react';
 import { DateField } from '../../../fields/DateField';
 import { Doc, Field, FieldResult, Opt } from '../../../fields/Doc';
 import { List } from '../../../fields/List';
-import { WebField } from '../../../fields/URLField';
-import { DocumentView, DocumentViewSharedProps } from './DocumentView';
 import { ScriptField } from '../../../fields/ScriptField';
-import { RecordingBox } from './RecordingBox';
+import { WebField } from '../../../fields/URLField';
+import { DocumentViewSharedProps } from './DocumentView';
 
 //
 // these properties get assigned through the render() method of the DocumentView when it creates this node.
diff --git a/src/client/views/nodes/ScriptingBox.tsx b/src/client/views/nodes/ScriptingBox.tsx
index 05ff40f22..1c9b0bc0e 100644
--- a/src/client/views/nodes/ScriptingBox.tsx
+++ b/src/client/views/nodes/ScriptingBox.tsx
@@ -6,7 +6,7 @@ import { Doc } from '../../../fields/Doc';
 import { List } from '../../../fields/List';
 import { listSpec } from '../../../fields/Schema';
 import { ScriptField } from '../../../fields/ScriptField';
-import { BoolCast, Cast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
+import { BoolCast, Cast, DocCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
 import { TraceMobx } from '../../../fields/util';
 import { returnEmptyString } from '../../../Utils';
 import { DragManager } from '../../util/DragManager';
@@ -60,6 +60,14 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
 
     constructor(props: any) {
         super(props);
+        if (!this.compileParams.length) {
+            const params = ScriptCast(this.rootDoc[this.props.fieldKey])?.script.options.params as { [key: string]: any };
+            if (params) {
+                this.compileParams = Array.from(Object.keys(params))
+                    .filter(p => !p.startsWith('_'))
+                    .map(key => key + ':' + params[key]);
+            }
+        }
     }
 
     // vars included in fields that store parameters types and names and the script itself
@@ -70,30 +78,30 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
         return this.compileParams.map(p => p.split(':')[1].trim());
     }
     @computed({ keepAlive: true }) get rawScript() {
-        return StrCast(this.dataDoc[this.props.fieldKey + '-rawScript'], '');
+        return ScriptCast(this.rootDoc[this.fieldKey])?.script.originalScript ?? '';
     }
     @computed({ keepAlive: true }) get functionName() {
-        return StrCast(this.dataDoc[this.props.fieldKey + '-functionName'], '');
+        return StrCast(this.rootDoc[this.props.fieldKey + '-functionName'], '');
     }
     @computed({ keepAlive: true }) get functionDescription() {
-        return StrCast(this.dataDoc[this.props.fieldKey + '-functionDescription'], '');
+        return StrCast(this.rootDoc[this.props.fieldKey + '-functionDescription'], '');
     }
     @computed({ keepAlive: true }) get compileParams() {
-        return Cast(this.dataDoc[this.props.fieldKey + '-params'], listSpec('string'), []);
+        return Cast(this.rootDoc[this.props.fieldKey + '-params'], listSpec('string'), []);
     }
 
     set rawScript(value) {
-        this.dataDoc[this.props.fieldKey + '-rawScript'] = value;
+        Doc.SetInPlace(this.rootDoc, this.props.fieldKey, new ScriptField(undefined, undefined, value), true);
     }
     set functionName(value) {
-        this.dataDoc[this.props.fieldKey + '-functionName'] = value;
+        Doc.SetInPlace(this.rootDoc, this.props.fieldKey + '-functionName', value, true);
     }
     set functionDescription(value) {
-        this.dataDoc[this.props.fieldKey + '-functionDescription'] = value;
+        Doc.SetInPlace(this.rootDoc, this.props.fieldKey + '-functionDescription', value, true);
     }
 
     set compileParams(value) {
-        this.dataDoc[this.props.fieldKey + '-params'] = new List<string>(value);
+        Doc.SetInPlace(this.rootDoc, this.props.fieldKey + '-params', new List<string>(value), true);
     }
 
     getValue(result: any, descrip: boolean) {
@@ -107,8 +115,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
 
     @action
     componentDidMount() {
-        this.rawScript = ScriptCast(this.dataDoc[this.props.fieldKey])?.script?.originalScript ?? this.rawScript;
-
+        this.rawText = this.rawScript;
         const observer = new _global.ResizeObserver(
             action((entries: any) => {
                 const area = document.querySelector('textarea');
@@ -171,13 +178,13 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
         const params: ScriptParam = {};
         this.compileParams.forEach(p => (params[p.split(':')[0].trim()] = p.split(':')[1].trim()));
 
-        const result = CompileScript(this.rawScript, {
+        const result = CompileScript(this.rawText, {
             editable: true,
             transformer: DocumentIconContainer.getTransformer(),
             params,
             typecheck: false,
         });
-        this.dataDoc[this.fieldKey] = result.compiled ? new ScriptField(result) : undefined;
+        Doc.SetInPlace(this.rootDoc, this.fieldKey, result.compiled ? new ScriptField(result, undefined, this.rawText) : new ScriptField(undefined, undefined, this.rawText), true);
         this.onError(result.compiled ? undefined : result.errors);
         return result.compiled;
     };
@@ -187,9 +194,9 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
     onRun = () => {
         if (this.onCompile()) {
             const bindings: { [name: string]: any } = {};
-            this.paramsNames.forEach(key => (bindings[key] = this.dataDoc[key]));
+            this.paramsNames.forEach(key => (bindings[key] = this.rootDoc[key]));
             // binds vars so user doesnt have to refer to everything as self.<var>
-            ScriptCast(this.dataDoc[this.fieldKey], null)?.script.run({ self: this.rootDoc, this: this.layoutDoc, ...bindings }, this.onError);
+            ScriptCast(this.rootDoc[this.fieldKey], null)?.script.run({ self: this.rootDoc, this: this.layoutDoc, ...bindings }, this.onError);
         }
     };
 
@@ -257,14 +264,14 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
     // sets field of the corresponding field key (param name) to be dropped document
     @action
     onDrop = (e: Event, de: DragManager.DropEvent, fieldKey: string) => {
-        this.dataDoc[fieldKey] = de.complete.docDragData?.droppedDocuments[0];
+        Doc.SetInPlace(this.rootDoc, fieldKey, de.complete.docDragData?.droppedDocuments[0], true);
         e.stopPropagation();
     };
 
     // deletes a param from all areas in which it is stored
     @action
     onDelete = (num: number) => {
-        this.dataDoc[this.paramsNames[num]] = undefined;
+        Doc.SetInPlace(this.rootDoc, this.paramsNames[num], undefined, true);
         this.compileParams.splice(num, 1);
         return true;
     };
@@ -274,7 +281,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
     viewChanged = (e: React.ChangeEvent, name: string) => {
         //@ts-ignore
         const val = e.target.selectedOptions[0].value;
-        this.dataDoc[name] = val[0] === 'S' ? val.substring(1) : val[0] === 'N' ? parseInt(val.substring(1)) : val.substring(1) === 'true';
+        Doc.SetInPlace(this.rootDoc, name, val[0] === 'S' ? val.substring(1) : val[0] === 'N' ? parseInt(val.substring(1)) : val.substring(1) === 'true', true);
     };
 
     // creates a copy of the script document
@@ -330,8 +337,8 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
                     maxHeight={72}
                     height={35}
                     fontSize={14}
-                    contents={this.dataDoc[parameter]?.title ?? 'undefined'}
-                    GetValue={() => this.dataDoc[parameter]?.title ?? 'undefined'}
+                    contents={StrCast(DocCast(this.rootDoc[parameter])?.title, 'undefined')}
+                    GetValue={() => StrCast(DocCast(this.rootDoc[parameter])?.title, 'undefined')}
                     SetValue={action((value: string) => {
                         const script = CompileScript(value, {
                             addReturn: true,
@@ -341,7 +348,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
                         const results = script.compiled && script.run();
                         if (results && results.success) {
                             this._errorMessage = '';
-                            this.dataDoc[parameter] = results.result;
+                            Doc.SetInPlace(this.rootDoc, parameter, results.result, true);
                             return true;
                         }
                         this._errorMessage = 'invalid document';
@@ -354,7 +361,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
 
     // rendering when a string's value can be set in applied UI
     renderBasicType(parameter: string, isNum: boolean) {
-        const strVal = isNum ? NumCast(this.dataDoc[parameter]).toString() : StrCast(this.dataDoc[parameter]);
+        const strVal = isNum ? NumCast(this.rootDoc[parameter]).toString() : StrCast(this.rootDoc[parameter]);
         return (
             <div className="scriptingBox-paramInputs" style={{ overflowY: 'hidden' }}>
                 <EditableView
@@ -368,7 +375,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
                         const setValue = isNum ? parseInt(value) : value;
                         if (setValue !== undefined && setValue !== ' ') {
                             this._errorMessage = '';
-                            this.dataDoc[parameter] = setValue;
+                            Doc.SetInPlace(this.rootDoc, parameter, setValue, true);
                             return true;
                         }
                         this._errorMessage = 'invalid input';
@@ -389,7 +396,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
                             className="scriptingBox-viewPicker"
                             onPointerDown={e => e.stopPropagation()}
                             onChange={e => this.viewChanged(e, parameter)}
-                            value={typeof this.dataDoc[parameter] === 'string' ? 'S' + StrCast(this.dataDoc[parameter]) : typeof this.dataDoc[parameter] === 'number' ? 'N' + NumCast(this.dataDoc[parameter]) : 'B' + BoolCast(this.dataDoc[parameter])}>
+                            value={typeof this.rootDoc[parameter] === 'string' ? 'S' + StrCast(this.rootDoc[parameter]) : typeof this.rootDoc[parameter] === 'number' ? 'N' + NumCast(this.rootDoc[parameter]) : 'B' + BoolCast(this.rootDoc[parameter])}>
                             {types.map(type => (
                                 <option className="scriptingBox-viewOption" value={(typeof type === 'string' ? 'S' : typeof type === 'number' ? 'N' : 'B') + type}>
                                     {' '}
@@ -442,7 +449,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
 
     @action
     handleFunc(pos: number) {
-        const scriptString = this.rawScript.slice(0, pos - 2);
+        const scriptString = this.rawText.slice(0, pos - 2);
         this._currWord = scriptString.split(' ')[scriptString.split(' ').length - 1];
         this._suggestions = [StrCast(this._scriptingParams[this._currWord])];
         return this._suggestions;
@@ -474,7 +481,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
     }
 
     getSuggestedParams(pos: number) {
-        const firstScript = this.rawScript.slice(0, pos);
+        const firstScript = this.rawText.slice(0, pos);
         const indexP = firstScript.lastIndexOf('.');
         const indexS = firstScript.lastIndexOf(' ');
         const func = firstScript.slice((indexP > indexS ? indexP : indexS) + 1, firstScript.length + 1);
@@ -494,8 +501,9 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
 
     @action
     keyHandler(e: any, pos: number) {
+        e.stopPropagation();
         if (this._lastChar === 'Enter') {
-            this.rawScript = this.rawScript + ' ';
+            this.rawText = this.rawText + ' ';
         }
         if (e.key === '(') {
             this.suggestionPos();
@@ -504,7 +512,7 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
             this._scriptSuggestedParams = this.getSuggestedParams(pos);
 
             if (this._scriptParamsText !== undefined && this._scriptParamsText.length > 0) {
-                if (this.rawScript[pos - 2] !== '(') {
+                if (this.rawText[pos - 2] !== '(') {
                     this._paramSuggestion = true;
                 }
             }
@@ -515,22 +523,22 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
                 if (this._lastChar === '(') {
                     this._paramSuggestion = false;
                 } else if (this._lastChar === ')') {
-                    if (this.rawScript.slice(0, this.rawScript.length - 1).split('(').length - 1 > this.rawScript.slice(0, this.rawScript.length - 1).split(')').length - 1) {
+                    if (this.rawText.slice(0, this.rawText.length - 1).split('(').length - 1 > this.rawText.slice(0, this.rawText.length - 1).split(')').length - 1) {
                         if (this._scriptParamsText.length > 0) {
                             this._paramSuggestion = true;
                         }
                     }
                 }
-            } else if (this.rawScript.split('(').length - 1 <= this.rawScript.split(')').length - 1) {
+            } else if (this.rawText.split('(').length - 1 <= this.rawText.split(')').length - 1) {
                 this._paramSuggestion = false;
             }
         }
-        this._lastChar = e.key === 'Backspace' ? this.rawScript[this.rawScript.length - 2] : e.key;
+        this._lastChar = e.key === 'Backspace' ? this.rawText[this.rawText.length - 2] : e.key;
 
         if (this._paramSuggestion) {
             const parameters = this._scriptParamsText.split(',');
-            const index = this.rawScript.lastIndexOf('(');
-            const enteredParams = this.rawScript.slice(index, this.rawScript.length);
+            const index = this.rawText.lastIndexOf('(');
+            const enteredParams = this.rawText.slice(index, this.rawText.length);
             const splitEntered = enteredParams.split(',');
             const numEntered = splitEntered.length;
 
@@ -564,15 +572,16 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
     handlePosChange(number: any) {
         this._caretPos = number;
         if (this._caretPos === 0) {
-            this.rawScript = ' ' + this.rawScript;
+            this.rawText = ' ' + this.rawText;
         } else if (this._spaced) {
             this._spaced = false;
-            if (this.rawScript[this._caretPos - 1] === ' ') {
-                this.rawScript = this.rawScript.slice(0, this._caretPos - 1) + this.rawScript.slice(this._caretPos, this.rawScript.length);
+            if (this.rawText[this._caretPos - 1] === ' ') {
+                this.rawText = this.rawText.slice(0, this._caretPos - 1) + this.rawText.slice(this._caretPos, this.rawText.length);
             }
         }
     }
 
+    @observable rawText: string = '';
     @computed({ keepAlive: true }) get renderScriptingBox() {
         TraceMobx();
         return (
@@ -583,8 +592,8 @@ export class ScriptingBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatable
                     placeholder="write your script here"
                     onFocus={this.onFocus}
                     onBlur={() => this._overlayDisposer?.()}
-                    onChange={(e: any) => (this.rawScript = e.target.value)}
-                    value={this.rawScript}
+                    onChange={action((e: any) => (this.rawText = e.target.value))}
+                    value={this.rawText}
                     movePopupAsYouType={true}
                     loadingComponent={() => <span>Loading</span>}
                     trigger={{
diff --git a/src/client/views/nodes/button/FontIconBox.tsx b/src/client/views/nodes/button/FontIconBox.tsx
index 5e279f984..78ef85ec2 100644
--- a/src/client/views/nodes/button/FontIconBox.tsx
+++ b/src/client/views/nodes/button/FontIconBox.tsx
@@ -579,11 +579,11 @@ ScriptingGlobals.add(function setView(view: string) {
 
 // toggle: Set overlay status of selected document
 ScriptingGlobals.add(function setBackgroundColor(color?: string, checkResult?: boolean) {
-    const selected = SelectionManager.Docs().lastElement();
+    const selected = SelectionManager.Views().lastElement();
     if (checkResult) {
-        return selected?._backgroundColor ?? 'transparent';
+        return selected?.props.Document._backgroundColor ?? 'transparent';
     }
-    if (selected) selected._backgroundColor = color;
+    if (selected) selected.props.Document._backgroundColor = color;
 });
 
 // toggle: Set overlay status of selected document
diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
index eb87d11a4..b8ee89ef2 100644
--- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx
+++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
@@ -398,7 +398,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
     };
 
     updateTitle = () => {
-        const title = StrCast(this.dataDoc.title);
+        const title = StrCast(this.dataDoc.title, Cast(this.dataDoc.title, RichTextField, null)?.Text);
         if (
             !this.props.dontRegisterView && // (this.props.Document.isTemplateForField === "text" || !this.props.Document.isTemplateForField) && // only update the title if the data document's data field is changing
             (title.startsWith('-') || title.startsWith('@')) &&
@@ -1000,7 +1000,8 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
             // set the document height when one of the component heights changes and autoHeight is on
             () => ({ sidebarHeight: this.sidebarHeight, textHeight: this.textHeight, autoHeight: this.autoHeight, marginsHeight: this.autoHeightMargins }),
             ({ sidebarHeight, textHeight, autoHeight, marginsHeight }) => {
-                autoHeight && this.props.setHeight?.(this.contentScaling * (marginsHeight + Math.max(sidebarHeight, textHeight)));
+                const newHeight = this.contentScaling * (marginsHeight + Math.max(sidebarHeight, textHeight));
+                autoHeight && newHeight && this.props.setHeight?.(newHeight);
             },
             { fireImmediately: true }
         );
@@ -1768,7 +1769,8 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
                     removeDocument={this.removeDocument}
                 />
             ) : (
-                <div onPointerDown={e => setupMoveUpEvents(this, e, returnFalse, emptyFunction, () => SelectionManager.SelectView(this.props.DocumentView?.()!), true)}>
+                <div onPointerDown={e => setupMoveUpEvents(this, e, returnFalse, emptyFunction, () => SelectionManager.SelectView(this.props.DocumentView?.()!, false), true)}>
+                    //@ts-ignore
                     <ComponentTag
                         {...OmitKeys(this.props, ['NativeWidth', 'NativeHeight', 'setContentView']).omit}
                         NativeWidth={returnZero}
diff --git a/src/fields/ScriptField.ts b/src/fields/ScriptField.ts
index 2b4b1ef4c..68fb45987 100644
--- a/src/fields/ScriptField.ts
+++ b/src/fields/ScriptField.ts
@@ -81,6 +81,8 @@ async function deserializeScript(script: ScriptField) {
 @scriptingGlobal
 @Deserializable('script', deserializeScript)
 export class ScriptField extends ObjectField {
+    @serializable
+    readonly rawscript: string | undefined;
     @serializable(object(scriptSchema))
     readonly script: CompiledScript;
     @serializable(object(scriptSchema))
@@ -94,15 +96,16 @@ export class ScriptField extends ObjectField {
         return this._scriptFieldCache.get(field);
     }
 
-    constructor(script: CompiledScript, setterscript?: CompiledScript) {
+    constructor(script: CompiledScript | undefined, setterscript?: CompiledScript, rawscript?: string) {
         super();
 
         const captured = script?.options.capturedVariables;
         if (captured) {
             this.captures = new List<string>(Object.keys(captured).map(key => key + ':' + (captured[key] instanceof Doc ? 'ID->' + (captured[key] as Doc)[Id] : captured[key].toString())));
         }
+        this.rawscript = rawscript;
         this.setterscript = setterscript;
-        this.script = script;
+        this.script = script ?? (CompileScript('false') as CompiledScript);
     }
 
     //     init(callback: (res: Field) => any) {
@@ -127,7 +130,7 @@ export class ScriptField extends ObjectField {
     //     }
 
     [Copy](): ObjectField {
-        return new ScriptField(this.script, this.setterscript);
+        return new ScriptField(this.script, this.setterscript, this.rawscript);
     }
     toString() {
         return `${this.script.originalScript} + ${this.setterscript?.originalScript}`;
@@ -175,7 +178,7 @@ export class ComputedField extends ScriptField {
     _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);
 
     [Copy](): ObjectField {
-        return new ComputedField(this.script, this.setterscript);
+        return new ComputedField(this.script, this.setterscript, this.rawscript);
     }
 
     public static MakeScript(script: string, params: object = {}) {
-- 
cgit v1.2.3-70-g09d2


From 55bac585fa0b8d6c3f513ccecb22456d1d361040 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Wed, 3 Aug 2022 13:33:38 -0400
Subject: fixes for dragging notes so that they highlight properly and go to
 the right place when embedded in freeform views.

---
 src/client/documents/Documents.ts                  |   9 +-
 src/client/util/CurrentUserUtils.ts                |   3 +-
 src/client/util/DragManager.ts                     |  12 +-
 src/client/views/DocumentDecorations.tsx           |   2 +-
 src/client/views/StyleProvider.tsx                 |   8 +-
 .../views/collections/CollectionNoteTakingView.tsx |  91 +++---
 .../collections/CollectionNoteTakingViewColumn.tsx | 358 +++++++++++----------
 .../CollectionNoteTakingViewDivider.tsx            | 112 +++----
 .../views/collections/CollectionStackingView.tsx   |   4 +-
 src/client/views/nodes/DocumentView.tsx            |  30 +-
 .../views/nodes/formattedText/FormattedTextBox.tsx |   6 +-
 11 files changed, 332 insertions(+), 303 deletions(-)

(limited to 'src/client/views/nodes/formattedText/FormattedTextBox.tsx')

diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts
index 32d7152fd..9d00664ad 100644
--- a/src/client/documents/Documents.ts
+++ b/src/client/documents/Documents.ts
@@ -1036,7 +1036,14 @@ export namespace Docs {
         }
 
         export function NoteTakingDocument(documents: Array<Doc>, options: DocumentOptions, id?: string, protoId?: string) {
-            return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { ...options, _viewType: CollectionViewType.NoteTaking }, id, undefined, protoId);
+            return InstanceFromProto(
+                Prototypes.get(DocumentType.COL),
+                new List(documents),
+                { columnHeaders: new List<SchemaHeaderField>([new SchemaHeaderField('Untitled')]), ...options, _viewType: CollectionViewType.NoteTaking },
+                id,
+                undefined,
+                protoId
+            );
         }
 
         export function MulticolumnDocument(documents: Array<Doc>, options: DocumentOptions) {
diff --git a/src/client/util/CurrentUserUtils.ts b/src/client/util/CurrentUserUtils.ts
index 28dc44c25..7856c913b 100644
--- a/src/client/util/CurrentUserUtils.ts
+++ b/src/client/util/CurrentUserUtils.ts
@@ -135,7 +135,6 @@ export class CurrentUserUtils {
         return DocUtils.AssignOpts(tempClicks, reqdOpts, reqdClickList) ?? (doc[field] = Docs.Create.TreeDocument(reqdClickList, reqdOpts));
     }
 
-
     /// Initializes templates that can be applied to notes
     static setupNoteTemplates(doc: Doc, field="template-notes") {
         const tempNotes = DocCast(doc[field]);
@@ -255,6 +254,7 @@ 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: "Collection", creator: opts => Docs.Create.FreeformDocument([], opts),    opts: { _width: 150, _height: 100 }},
             {key: "Equation",   creator: opts => Docs.Create.EquationDocument(opts),        opts: { _width: 300, _height: 35, _fitWidth:false, _backgroundGridShow: true, }},
             {key: "Webpage",    creator: opts => Docs.Create.WebDocument("",opts),          opts: { _width: 400, _height: 512, _nativeWidth: 850, useCors: true, }},
@@ -280,6 +280,7 @@ export class CurrentUserUtils {
         
         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, },
diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts
index 3a1bb1673..f4987cf34 100644
--- a/src/client/util/DragManager.ts
+++ b/src/client/util/DragManager.ts
@@ -1,4 +1,4 @@
-import { action } from 'mobx';
+import { action, observable, runInAction } from 'mobx';
 import { DateField } from '../../fields/DateField';
 import { Doc, Field, Opt } from '../../fields/Doc';
 import { List } from '../../fields/List';
@@ -320,7 +320,7 @@ export namespace DragManager {
             y: snapVal([yFromTop, yFromBottom], e.pageY, SnappingManager.horizSnapLines()),
         };
     }
-    export let docsBeingDragged: Doc[] = [];
+    export let docsBeingDragged: Doc[] = observable([] as Doc[]);
     export let CanEmbed = false;
     export let DocDragData: DocumentDragData | undefined;
     export function StartDrag(eles: HTMLElement[], dragData: { [id: string]: any }, downX: number, downY: number, options?: DragOptions, finishDrag?: (dropData: DragCompleteEvent) => void) {
@@ -349,13 +349,13 @@ export namespace DragManager {
             xs: number[] = [],
             ys: number[] = [];
 
-        docsBeingDragged = dragData instanceof DocumentDragData ? dragData.draggedDocuments : dragData instanceof AnchorAnnoDragData ? [dragData.dragDocument] : [];
         const elesCont = {
             left: Number.MAX_SAFE_INTEGER,
             right: Number.MIN_SAFE_INTEGER,
             top: Number.MAX_SAFE_INTEGER,
             bottom: Number.MIN_SAFE_INTEGER,
         };
+        const docsToDrag = dragData instanceof DocumentDragData ? dragData.draggedDocuments : dragData instanceof AnchorAnnoDragData ? [dragData.dragDocument] : [];
         const dragElements = eles.map(ele => {
             if (!ele.parentNode) dragDiv.appendChild(ele);
             const dragElement = ele.parentNode === dragDiv ? ele : (ele.cloneNode(true) as HTMLElement);
@@ -405,7 +405,7 @@ export namespace DragManager {
             });
             dragLabel.style.transform = `translate(${rect.left + (options?.offsetX || 0)}px, ${rect.top + (options?.offsetY || 0) - 20}px)`;
 
-            if (docsBeingDragged.length) {
+            if (docsToDrag.length) {
                 const pdfBox = dragElement.getElementsByTagName('canvas');
                 const pdfBoxSrc = ele.getElementsByTagName('canvas');
                 Array.from(pdfBox)
@@ -429,6 +429,8 @@ export namespace DragManager {
             return dragElement;
         });
 
+        runInAction(() => docsBeingDragged.push(...docsToDrag));
+
         const hideDragShowOriginalElements = (hide: boolean) => {
             dragLabel.style.display = hide ? '' : 'none';
             !hide && dragElements.map(dragElement => dragElement.parentNode === dragDiv && dragDiv.removeChild(dragElement));
@@ -456,7 +458,7 @@ export namespace DragManager {
             SnappingManager.SetIsDragging(false);
             SnappingManager.clearSnapLines();
             batch.end();
-            docsBeingDragged = [];
+            docsBeingDragged.length = 0;
         });
         var startWindowDragTimer: any;
         const moveHandler = (e: PointerEvent) => {
diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx
index c53e61699..0db9eab69 100644
--- a/src/client/views/DocumentDecorations.tsx
+++ b/src/client/views/DocumentDecorations.tsx
@@ -351,7 +351,7 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P
 
     @action
     onPointerDown = (e: React.PointerEvent): void => {
-        DragManager.docsBeingDragged = SelectionManager.Views().map(dv => dv.rootDoc);
+        DragManager.docsBeingDragged.push(...SelectionManager.Views().map(dv => dv.rootDoc));
         this._inkDragDocs = DragManager.docsBeingDragged
             .filter(doc => doc.type === DocumentType.INK)
             .map(doc => {
diff --git a/src/client/views/StyleProvider.tsx b/src/client/views/StyleProvider.tsx
index 692f7b98e..a83163eb0 100644
--- a/src/client/views/StyleProvider.tsx
+++ b/src/client/views/StyleProvider.tsx
@@ -110,8 +110,8 @@ export function DefaultStyleProvider(doc: Opt<Doc>, props: Opt<DocumentViewProps
             return undefined;
         case StyleProp.WidgetColor:
             return isAnnotated ? Colors.LIGHT_BLUE : darkScheme() ? 'lightgrey' : 'dimgrey';
-            // return doc = dragManager.dragDocument ? props.dragEffects.opacity??CastofOpacityonline94 : Cast())
-            // same idea for background Color
+        // return doc = dragManager.dragDocument ? props.dragEffects.opacity??CastofOpacityonline94 : Cast())
+        // same idea for background Color
         case StyleProp.Opacity:
             return Cast(doc?._opacity, 'number', Cast(doc?.opacity, 'number', null));
         case StyleProp.HideLinkButton:
@@ -156,7 +156,9 @@ export function DefaultStyleProvider(doc: Opt<Doc>, props: Opt<DocumentViewProps
         case StyleProp.JitterRotation:
             return comicStyle() ? random(-1, 1, NumCast(doc?.x), NumCast(doc?.y)) * ((props?.PanelWidth() || 0) > (props?.PanelHeight() || 0) ? 5 : 10) : 0;
         case StyleProp.HeaderMargin:
-            return ([CollectionViewType.Stacking, CollectionViewType.NoteTaking, CollectionViewType.Masonry, CollectionViewType.Tree].includes(doc?._viewType as any) || (doc?.type === DocumentType.RTF && !showTitle()?.includes('noMargin')) || doc?.type === DocumentType.LABEL) &&
+            return ([CollectionViewType.Stacking, CollectionViewType.NoteTaking, CollectionViewType.Masonry, CollectionViewType.Tree].includes(doc?._viewType as any) ||
+                (doc?.type === DocumentType.RTF && !showTitle()?.includes('noMargin')) ||
+                doc?.type === DocumentType.LABEL) &&
                 showTitle() &&
                 !StrCast(doc?.showTitle).includes(':hover')
                 ? 15
diff --git a/src/client/views/collections/CollectionNoteTakingView.tsx b/src/client/views/collections/CollectionNoteTakingView.tsx
index f442559fb..1854a4213 100644
--- a/src/client/views/collections/CollectionNoteTakingView.tsx
+++ b/src/client/views/collections/CollectionNoteTakingView.tsx
@@ -1,6 +1,6 @@
 import React = require('react');
 import { CursorProperty } from 'csstype';
-import { action, computed, IReactionDisposer, observable, reaction } from 'mobx';
+import { action, computed, IReactionDisposer, observable, reaction, runInAction } from 'mobx';
 import { observer } from 'mobx-react';
 import { DataSym, Doc, HeightSym, Opt, WidthSym } from '../../../fields/Doc';
 import { Id } from '../../../fields/FieldSymbols';
@@ -21,10 +21,12 @@ import { ContextMenuProps } from '../ContextMenuItem';
 import { LightboxView } from '../LightboxView';
 import { CollectionFreeFormDocumentView } from '../nodes/CollectionFreeFormDocumentView';
 import { DocFocusOptions, DocumentView, DocumentViewProps, ViewAdjustment } from '../nodes/DocumentView';
+import { FieldViewProps } from '../nodes/FieldView';
+import { FormattedTextBox } from '../nodes/formattedText/FormattedTextBox';
 import { StyleProp } from '../StyleProvider';
 import './CollectionNoteTakingView.scss';
 import { CollectionNoteTakingViewColumn } from './CollectionNoteTakingViewColumn';
-import CollectionNoteTakingViewDivider from './CollectionNoteTakingViewDivider';
+import { CollectionNoteTakingViewDivider } from './CollectionNoteTakingViewDivider';
 import { CollectionSubView } from './CollectionSubView';
 const _global = (window /* browser */ || global) /* node */ as any;
 
@@ -40,7 +42,6 @@ export type collectionNoteTakingViewProps = {
 
 @observer
 export class CollectionNoteTakingView extends CollectionSubView<Partial<collectionNoteTakingViewProps>>() {
-    _pivotFieldDisposer?: IReactionDisposer;
     _autoHeightDisposer?: IReactionDisposer;
     _masonryGridRef: HTMLDivElement | null = null;
     _draggerRef = React.createRef<HTMLDivElement>();
@@ -54,10 +55,10 @@ export class CollectionNoteTakingView extends CollectionSubView<Partial<collecti
         return this.props.chromeHidden || BoolCast(this.layoutDoc.chromeHidden);
     }
     @computed get columnHeaders() {
-        return Cast(this.layoutDoc._columnHeaders, listSpec(SchemaHeaderField), null);
+        return Cast(this.dataDoc.columnHeaders, listSpec(SchemaHeaderField), null);
     }
-    @computed get pivotField() {
-        return 'Col';
+    @computed get notetakingCategoryField() {
+        return 'noteTakingCategory';
     }
     @computed get filteredChildren() {
         return this.childLayoutPairs.filter(pair => pair.layout instanceof Doc && !pair.layout.hidden).map(pair => pair.layout);
@@ -90,7 +91,7 @@ export class CollectionNoteTakingView extends CollectionSubView<Partial<collecti
     constructor(props: any) {
         super(props);
         if (this.columnHeaders === undefined) {
-            this.layoutDoc._columnHeaders = new List<SchemaHeaderField>([new SchemaHeaderField('New Column')]);
+            this.dataDoc.columnHeaders = new List<SchemaHeaderField>([new SchemaHeaderField('New Column')]);
             this.columnStartXCoords = [0];
             // add all of the docs that have not been added to a column to this new column
         } else {
@@ -126,18 +127,16 @@ export class CollectionNoteTakingView extends CollectionSubView<Partial<collecti
         // filter out the currently dragged docs from the child docs, since we will insert them later
         if (rowCol.length && DragManager.docsBeingDragged.length) {
             const docIdsToRemove = new Set();
-            DragManager.docsBeingDragged.forEach(d => {
-                docIdsToRemove.add(d[Id]);
-            });
+            DragManager.docsBeingDragged.forEach(d => docIdsToRemove.add(d[Id]));
             docs = docs.filter(d => !docIdsToRemove.has(d[Id]));
         }
 
         // this will sort the docs into the correct columns (minus the ones you're currently dragging)
         docs.map(d => {
-            if (!d[this.pivotField]) {
-                d[this.pivotField] = columnHeaders.length > 0 ? columnHeaders[0].heading : `New Column`;
+            if (!d[this.notetakingCategoryField]) {
+                d[this.notetakingCategoryField] = columnHeaders.length > 0 ? columnHeaders[0].heading : `New Column`;
             }
-            const sectionValue = d[this.pivotField] as object;
+            const sectionValue = d[this.notetakingCategoryField] as object;
 
             // look for if header exists already
             const existingHeader = columnHeaders.find(sh => sh.heading === sectionValue.toString());
@@ -156,14 +155,15 @@ export class CollectionNoteTakingView extends CollectionSubView<Partial<collecti
         return sections;
     }
 
+    removeDocDragHighlight = () => {
+        setTimeout(
+            action(() => (this.docsDraggedRowCol.length = 0)),
+            100
+        );
+    };
     componentDidMount() {
         super.componentDidMount?.();
-        // reset section headers when a new filter is inputted
-        this._pivotFieldDisposer = reaction(
-            () => this.pivotField,
-            () => (this.layoutDoc._columnHeaders = new List())
-        );
-
+        document.addEventListener('pointerup', this.removeDocDragHighlight, true);
         this._autoHeightDisposer = reaction(
             () => this.layoutDoc._autoHeight,
             autoHeight => autoHeight && this.props.setHeight?.(Math.min(NumCast(this.layoutDoc._maxHeight, Number.MAX_SAFE_INTEGER), this.headerMargin + Math.max(...this.refList.map(r => Number(getComputedStyle(r).height.replace('px', ''))))))
@@ -171,8 +171,8 @@ export class CollectionNoteTakingView extends CollectionSubView<Partial<collecti
     }
 
     componentWillUnmount() {
+        document.removeEventListener('pointerup', this.removeDocDragHighlight, true);
         super.componentWillUnmount();
-        this._pivotFieldDisposer?.();
         this._autoHeightDisposer?.();
     }
 
@@ -227,6 +227,9 @@ export class CollectionNoteTakingView extends CollectionSubView<Partial<collecti
     };
 
     styleProvider = (doc: Doc | undefined, props: Opt<DocumentViewProps>, property: string) => {
+        if (property === StyleProp.BoxShadow && doc && DragManager.docsBeingDragged.includes(doc)) {
+            return `#9c9396  ${StrCast(doc?.boxShadow, '10px 10px 0.9vw')}`;
+        }
         if (property === StyleProp.Opacity && doc) {
             if (this.props.childOpacity) {
                 return this.props.childOpacity();
@@ -258,9 +261,9 @@ export class CollectionNoteTakingView extends CollectionSubView<Partial<collecti
                 docViewPath={this.props.docViewPath}
                 fitWidth={this.props.childFitWidth}
                 isContentActive={emptyFunction}
-                originalBackgroundColor={StrCast(doc.backgroundColor)}
+                onKey={this.onKeyDown}
                 //TODO: change this from a prop to a parameter passed into a function
-                isNoteTakingView={true}
+                dontHideOnDrag={true}
                 isDocumentActive={this.isContentActive}
                 LayoutTemplate={this.props.childLayoutTemplate}
                 LayoutTemplateString={this.props.childLayoutString}
@@ -307,7 +310,7 @@ export class CollectionNoteTakingView extends CollectionSubView<Partial<collecti
     // how to get the width of a document. Currently returns the width of the column (minus margins)
     // if a note doc. Otherwise, returns the normal width (for graphs, images, etc...)
     getDocWidth(d: Doc) {
-        const heading = d[this.pivotField] as object;
+        const heading = d[this.notetakingCategoryField] as object;
         const castedSectionValue = heading.toString();
         const existingHeader = this.columnHeaders.find(sh => sh.heading === castedSectionValue);
         const colStartXCoords = this.columnStartXCoords;
@@ -364,20 +367,14 @@ export class CollectionNoteTakingView extends CollectionSubView<Partial<collecti
         if (DragManager.docsBeingDragged.length && this.childDocList) {
             // get the current docs for the column based on the mouse's x coordinate
             // will use again later, which is why we're saving as local
-            const xCoord = e.clientX - 2 * this.gridGap;
+            const xCoord = this.props.ScreenToLocalTransform().transformPoint(e.clientX, e.clientY)[0] - 2 * this.gridGap;
             const colDocs = this.getDocsFromXCoord(xCoord);
             // get the index for where you need to insert the doc you are currently dragging
-            const clientY = e.clientY;
+            const clientY = this.props.ScreenToLocalTransform().transformPoint(e.clientX, e.clientY)[1];
             let dropInd = -1;
-            // unsure whether we still want this dropAfter field
-            // let dropAfter = 0;
-            // manually set to 140, because not sure how to get exact value
-            let pos0 = 140;
+            let pos0 = (this.refList.lastElement() as HTMLDivElement).children[0].getBoundingClientRect().height + this.yMargin * 2;
             colDocs.forEach((doc, i) => {
-                const noteTakingDocTransform = () => this.getDocTransform(doc);
-                let pos1 = noteTakingDocTransform()
-                    .inverse()
-                    .transformPoint(0, this.getDocHeight(doc) + 2 * this.gridGap)[1];
+                let pos1 = this.getDocHeight(doc) + 2 * this.gridGap;
                 pos1 += pos0;
                 // updating drop position based on y coordinates
                 const yCoordInBetween = clientY > pos0 && (clientY < pos1 || i == colDocs.length - 1);
@@ -393,10 +390,10 @@ export class CollectionNoteTakingView extends CollectionSubView<Partial<collecti
             // we alter the pivot fields of the docs in case they are moved to a new column.
             const colIndex = this.getColumnFromXCoord(xCoord);
             const colHeader = StrCast(this.columnHeaders[colIndex].heading);
-            DragManager.docsBeingDragged.forEach(d => (d[this.pivotField] = colHeader));
+            DragManager.docsBeingDragged.forEach(d => (d[this.notetakingCategoryField] = colHeader));
             // used to notify sections to re-render
-            // console.log([dropInd, this.getColumnFromXCoord(xCoord)])
-            this.docsDraggedRowCol = [dropInd, this.getColumnFromXCoord(xCoord)];
+            this.docsDraggedRowCol.length = 0;
+            this.docsDraggedRowCol.push(dropInd, this.getColumnFromXCoord(xCoord));
         }
     };
 
@@ -425,7 +422,7 @@ export class CollectionNoteTakingView extends CollectionSubView<Partial<collecti
         if (docs) {
             docs.map(d => {
                 if (d instanceof Promise) return;
-                const sectionValue = d[this.pivotField] as object;
+                const sectionValue = d[this.notetakingCategoryField] as object;
                 if (sectionValue.toString() == colHeader) {
                     docsMatchingHeader.push(d);
                 }
@@ -434,13 +431,24 @@ export class CollectionNoteTakingView extends CollectionSubView<Partial<collecti
         return docsMatchingHeader;
     };
 
+    @undoBatch
+    @action
+    onKeyDown = (e: React.KeyboardEvent, fieldProps: FieldViewProps) => {
+        const docView = fieldProps.DocumentView?.();
+        if (docView && (e.ctrlKey || docView.rootDoc._singleLine) && ['Enter'].includes(e.key)) {
+            e.stopPropagation?.();
+            const newDoc = Doc.MakeCopy(docView.rootDoc, true);
+            Doc.GetProto(newDoc).text = undefined;
+            FormattedTextBox.SelectOnLoad = newDoc[Id];
+            return this.addDocument?.(newDoc);
+        }
+    };
+
     @undoBatch
     @action
     onInternalDrop = (e: Event, de: DragManager.DropEvent) => {
         if (de.complete.docDragData) {
             if (super.onInternalDrop(e, de)) {
-                DragManager.docsBeingDragged = [];
-                // this.docsDraggedRowCol = []
                 // filter out the currently dragged docs from the child docs, since we will insert them later
                 const rowCol = this.docsDraggedRowCol;
                 const droppedDocs = this.childDocs.slice().filter((d: Doc, ind: number) => ind >= this.childDocs.length); // if the drop operation adds something to the end of the list, then use that as the new document (may be different than what was dropped e.g., in the case of a button which is dropped but which creates say, a note).
@@ -456,10 +464,9 @@ export class CollectionNoteTakingView extends CollectionSubView<Partial<collecti
                     if (rowCol[0] <= 0) {
                         docs.splice(0, 0, ...newDocs);
                     } else {
-                        const colDocs = this.getDocsFromXCoord(de.x);
+                        const colDocs = this.getDocsFromXCoord(this.props.ScreenToLocalTransform().transformPoint(de.x, de.y)[0]);
                         const previousDoc = colDocs[rowCol[0] - 1];
                         const previousDocIndex = docs.indexOf(previousDoc);
-                        console.log(`docs: ${previousDocIndex}`);
                         docs.splice(previousDocIndex + 1, 0, ...newDocs);
                     }
                 }
@@ -561,7 +568,7 @@ export class CollectionNoteTakingView extends CollectionSubView<Partial<collecti
                 renderChildren={this.children}
                 numGroupColumns={this.numGroupColumns}
                 gridGap={this.gridGap}
-                pivotField={this.pivotField}
+                pivotField={this.notetakingCategoryField}
                 columnStartXCoords={this.columnStartXCoords}
                 maxColWidth={this.maxColWdith}
                 PanelWidth={this.PanelWidth}
diff --git a/src/client/views/collections/CollectionNoteTakingViewColumn.tsx b/src/client/views/collections/CollectionNoteTakingViewColumn.tsx
index bdcb9c399..55d032498 100644
--- a/src/client/views/collections/CollectionNoteTakingViewColumn.tsx
+++ b/src/client/views/collections/CollectionNoteTakingViewColumn.tsx
@@ -1,27 +1,27 @@
-import React = require("react");
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { action, computed, observable } from "mobx";
-import { observer } from "mobx-react";
-import { Doc, DocListCast, Opt } from "../../../fields/Doc";
-import { Id } from "../../../fields/FieldSymbols";
-import { RichTextField } from "../../../fields/RichTextField";
-import { SchemaHeaderField } from "../../../fields/SchemaHeaderField";
-import { ScriptField } from "../../../fields/ScriptField";
-import { ImageField } from "../../../fields/URLField";
-import { TraceMobx } from "../../../fields/util";
-import { emptyFunction, returnEmptyString, setupMoveUpEvents } from "../../../Utils";
-import { Docs, DocUtils } from "../../documents/Documents";
-import { DocumentType } from "../../documents/DocumentTypes";
-import { DragManager } from "../../util/DragManager";
-import { SnappingManager } from "../../util/SnappingManager";
-import { Transform } from "../../util/Transform";
-import { undoBatch } from "../../util/UndoManager";
-import { ContextMenu } from "../ContextMenu";
-import { ContextMenuProps } from "../ContextMenuItem";
-import { EditableView } from "../EditableView";
-import { FormattedTextBox } from "../nodes/formattedText/FormattedTextBox";
-import "./CollectionNoteTakingView.scss";
-const higflyout = require("@hig/flyout");
+import React = require('react');
+import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
+import { action, computed, observable } from 'mobx';
+import { observer } from 'mobx-react';
+import { Doc, DocListCast, Opt } from '../../../fields/Doc';
+import { Id } from '../../../fields/FieldSymbols';
+import { RichTextField } from '../../../fields/RichTextField';
+import { SchemaHeaderField } from '../../../fields/SchemaHeaderField';
+import { ScriptField } from '../../../fields/ScriptField';
+import { ImageField } from '../../../fields/URLField';
+import { TraceMobx } from '../../../fields/util';
+import { emptyFunction, returnEmptyString, setupMoveUpEvents } from '../../../Utils';
+import { Docs, DocUtils } from '../../documents/Documents';
+import { DocumentType } from '../../documents/DocumentTypes';
+import { DragManager } from '../../util/DragManager';
+import { SnappingManager } from '../../util/SnappingManager';
+import { Transform } from '../../util/Transform';
+import { undoBatch } from '../../util/UndoManager';
+import { ContextMenu } from '../ContextMenu';
+import { ContextMenuProps } from '../ContextMenuItem';
+import { EditableView } from '../EditableView';
+import { FormattedTextBox } from '../nodes/formattedText/FormattedTextBox';
+import './CollectionNoteTakingView.scss';
+const higflyout = require('@hig/flyout');
 export const { anchorPoints } = higflyout;
 export const Flyout = higflyout.default;
 
@@ -39,7 +39,7 @@ interface CSVFieldColumnProps {
     // columnWidth: number;
     numGroupColumns: number;
     gridGap: number;
-    type: "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" | undefined;
+    type: 'string' | 'number' | 'bigint' | 'boolean' | 'symbol' | 'undefined' | 'object' | 'function' | undefined;
     headings: () => object[];
     renderChildren: (docs: Doc[]) => JSX.Element[];
     addDocument: (doc: Doc | Doc[]) => boolean;
@@ -48,37 +48,37 @@ interface CSVFieldColumnProps {
     observeHeight: (myref: any) => void;
     unobserveHeight: (myref: any) => void;
     editableViewProps: any;
-    resizeColumns: (n: number) => void
-    columnStartXCoords: number[]
-    PanelWidth: number
-    maxColWidth: number
+    resizeColumns: (n: number) => void;
+    columnStartXCoords: number[];
+    PanelWidth: number;
+    maxColWidth: number;
     // docsByColumnHeader: Map<string, Doc[]>
     // setDocsForColHeader: (key: string, docs: Doc[]) => void
 }
 
 @observer
 export class CollectionNoteTakingViewColumn extends React.Component<CSVFieldColumnProps> {
-    @observable private _background = "inherit";
+    @observable private _background = 'inherit';
 
     @computed get columnWidth() {
-      // base cases
-      if (!this.props.columnHeaders || !this.props.headingObject || this.props.columnHeaders.length == 1) {
-        return this.props.maxColWidth
-      }
-      const i = this.props.columnHeaders.indexOf(this.props.headingObject)
-      if (i < 0) {
-        return this.props.maxColWidth
-      }
-      const endColValue = i == this.props.numGroupColumns - 1 ? this.props.PanelWidth : this.props.columnStartXCoords[i+1]
-      // TODO make the math work here. 35 is half of 70, which is the current width of the divider
-      return endColValue - this.props.columnStartXCoords[i] - 30
+        // base cases
+        if (!this.props.columnHeaders || !this.props.headingObject || this.props.columnHeaders.length == 1) {
+            return this.props.maxColWidth;
+        }
+        const i = this.props.columnHeaders.indexOf(this.props.headingObject);
+        if (i < 0) {
+            return this.props.maxColWidth;
+        }
+        const endColValue = i == this.props.numGroupColumns - 1 ? this.props.PanelWidth : this.props.columnStartXCoords[i + 1];
+        // TODO make the math work here. 35 is half of 70, which is the current width of the divider
+        return endColValue - this.props.columnStartXCoords[i] - 30;
     }
 
     private dropDisposer?: DragManager.DragDropDisposer;
     private _headerRef: React.RefObject<HTMLDivElement> = React.createRef();
 
     @observable _heading = this.props.headingObject ? this.props.headingObject.heading : this.props.heading;
-    @observable _color = this.props.headingObject ? this.props.headingObject.color : "#f1efeb";
+    @observable _color = this.props.headingObject ? this.props.headingObject.color : '#f1efeb';
     _ele: HTMLElement | null = null;
 
     // This is likely similar to what we will be doing. Why do we need to make these refs?
@@ -90,7 +90,7 @@ export class CollectionNoteTakingViewColumn extends React.Component<CSVFieldColu
             this.props.observeHeight(ele);
             this.dropDisposer = DragManager.MakeDropTarget(ele, this.columnDrop.bind(this));
         }
-    }
+    };
 
     componentWillUnmount() {
         this.props.unobserveHeight(this._ele);
@@ -105,10 +105,10 @@ export class CollectionNoteTakingViewColumn extends React.Component<CSVFieldColu
     getValue = (value: string): any => {
         const parsed = parseInt(value);
         if (!isNaN(parsed)) return parsed;
-        if (value.toLowerCase().indexOf("true") > -1) return true;
-        if (value.toLowerCase().indexOf("false") > -1) return false;
+        if (value.toLowerCase().indexOf('true') > -1) return true;
+        if (value.toLowerCase().indexOf('false') > -1) return false;
         return value;
-    }
+    };
 
     @action
     headingChanged = (value: string, shiftDown?: boolean) => {
@@ -117,7 +117,7 @@ export class CollectionNoteTakingViewColumn extends React.Component<CSVFieldColu
             if (this.props.columnHeaders?.map(i => i.heading).indexOf(castedValue.toString()) !== -1) {
                 return false;
             }
-            this.props.docList.forEach(d => d[this.props.pivotField] = castedValue);
+            this.props.docList.forEach(d => (d[this.props.pivotField] = castedValue));
             if (this.props.headingObject) {
                 this.props.headingObject.setHeading(castedValue.toString());
                 this._heading = this.props.headingObject.heading;
@@ -125,11 +125,11 @@ export class CollectionNoteTakingViewColumn extends React.Component<CSVFieldColu
             return true;
         }
         return false;
-    }
+    };
 
-    @action pointerEntered = () => SnappingManager.GetIsDragging() && (this._background = "#b4b4b4");
-    @action pointerLeave = () => this._background = "inherit";
-    textCallback = (char: string) => this.addNewTextDoc("-typed text-", false, true);
+    @action pointerEntered = () => SnappingManager.GetIsDragging() && (this._background = '#b4b4b4');
+    @action pointerLeave = () => (this._background = 'inherit');
+    textCallback = (char: string) => this.addNewTextDoc('-typed text-', false, true);
 
     @action
     addNewTextDoc = (value: string, shiftDown?: boolean, forceEmptyNote?: boolean) => {
@@ -139,46 +139,46 @@ export class CollectionNoteTakingViewColumn extends React.Component<CSVFieldColu
         const colValue = this.getValue(this.props.heading);
         newDoc[key] = colValue;
         FormattedTextBox.SelectOnLoad = newDoc[Id];
-        FormattedTextBox.SelectOnLoadChar = forceEmptyNote ? "" : " ";
+        FormattedTextBox.SelectOnLoadChar = forceEmptyNote ? '' : ' ';
         return this.props.addDocument?.(newDoc) || false;
-    }
+    };
 
     @action
     deleteColumn = () => {
         if (!this.props.columnHeaders) {
-          return
+            return;
         }
         if (this.props.headingObject) {
-          const index = this.props.columnHeaders.indexOf(this.props.headingObject);
-          const newIndex = index == 0 ? 1 : index - 1
-          const newHeader = this.props.columnHeaders[newIndex];
-          this.props.docList.forEach(d => d[this.props.pivotField] = newHeader.heading.toString())
-          this.props.columnHeaders.splice(index, 1);
-          this.props.resizeColumns(this.props.columnHeaders.length)
+            const index = this.props.columnHeaders.indexOf(this.props.headingObject);
+            const newIndex = index == 0 ? 1 : index - 1;
+            const newHeader = this.props.columnHeaders[newIndex];
+            this.props.docList.forEach(d => (d[this.props.pivotField] = newHeader.heading.toString()));
+            this.props.columnHeaders.splice(index, 1);
+            this.props.resizeColumns(this.props.columnHeaders.length);
         }
-    }
+    };
 
     headerDown = (e: React.PointerEvent<HTMLDivElement>) => setupMoveUpEvents(this, e, this.startDrag, emptyFunction, emptyFunction);
 
-    //TODO: I think this is where I'm supposed to edit stuff 
+    //TODO: I think this is where I'm supposed to edit stuff
     startDrag = (e: PointerEvent, down: number[], delta: number[]) => {
-        console.log('in startDrag')
+        console.log('in startDrag');
         // is MakeAlias a way to make a copy of a doc without rendering it?
         const alias = Doc.MakeAlias(this.props.Document);
         // alias._width = this.props.columnWidth / (this.props.columnHeaders?.length || 1);
         alias._width = this.columnWidth;
         alias._pivotField = undefined;
         let value = this.getValue(this._heading);
-        value = typeof value === "string" ? `"${value}"` : value;
+        value = typeof value === 'string' ? `"${value}"` : value;
         alias.viewSpecScript = ScriptField.MakeFunction(`doc.${this.props.pivotField} === ${value}`, { doc: Doc.name });
         if (alias.viewSpecScript) {
-            const options = {hideSource: false}
+            const options = { hideSource: false };
             DragManager.StartDocumentDrag([this._headerRef.current!], new DragManager.DocumentDragData([alias]), e.clientX, e.clientY, options);
-            console.log('in startDrag')
+            console.log('in startDrag');
             return true;
         }
         return false;
-    }
+    };
 
     menuCallback = (x: number, y: number) => {
         ContextMenu.Instance.clearItems();
@@ -187,44 +187,62 @@ export class CollectionNoteTakingViewColumn extends React.Component<CSVFieldColu
         const dataDoc = this.props.DataDoc || this.props.Document;
         const pivotValue = this.getValue(this.props.heading);
 
-        DocUtils.addDocumentCreatorMenuItems((doc) => {
-            const key = this.props.pivotField;
-            doc[key] = this.getValue(this.props.heading);
-            FormattedTextBox.SelectOnLoad = doc[Id];
-            return this.props.addDocument?.(doc);
-        }, this.props.addDocument, x, y, true, this.props.pivotField, pivotValue);
+        DocUtils.addDocumentCreatorMenuItems(
+            doc => {
+                const key = this.props.pivotField;
+                doc[key] = this.getValue(this.props.heading);
+                FormattedTextBox.SelectOnLoad = doc[Id];
+                return this.props.addDocument?.(doc);
+            },
+            this.props.addDocument,
+            x,
+            y,
+            true,
+            this.props.pivotField,
+            pivotValue
+        );
 
-        Array.from(Object.keys(Doc.GetProto(dataDoc))).filter(fieldKey => dataDoc[fieldKey] instanceof RichTextField || dataDoc[fieldKey] instanceof ImageField || typeof (dataDoc[fieldKey]) === "string").map(fieldKey =>
-            docItems.push({
-                description: ":" + fieldKey, event: () => {
-                    const created = DocUtils.DocumentFromField(dataDoc, fieldKey, Doc.GetProto(this.props.Document));
-                    if (created) {
-                        if (this.props.Document.isTemplateDoc) {
-                            Doc.MakeMetadataFieldTemplate(created, this.props.Document);
+        Array.from(Object.keys(Doc.GetProto(dataDoc)))
+            .filter(fieldKey => dataDoc[fieldKey] instanceof RichTextField || dataDoc[fieldKey] instanceof ImageField || typeof dataDoc[fieldKey] === 'string')
+            .map(fieldKey =>
+                docItems.push({
+                    description: ':' + fieldKey,
+                    event: () => {
+                        const created = DocUtils.DocumentFromField(dataDoc, fieldKey, Doc.GetProto(this.props.Document));
+                        if (created) {
+                            if (this.props.Document.isTemplateDoc) {
+                                Doc.MakeMetadataFieldTemplate(created, this.props.Document);
+                            }
+                            return this.props.addDocument?.(created);
                         }
-                        return this.props.addDocument?.(created);
-                    }
-                }, icon: "compress-arrows-alt"
-            }));
-        Array.from(Object.keys(Doc.GetProto(dataDoc))).filter(fieldKey => DocListCast(dataDoc[fieldKey]).length).map(fieldKey =>
-            docItems.push({
-                description: ":" + fieldKey, event: () => {
-                    const created = Docs.Create.CarouselDocument([], { _width: 400, _height: 200, title: fieldKey });
-                    if (created) {
-                        const container = this.props.Document.resolvedDataDoc ? Doc.GetProto(this.props.Document) : this.props.Document;
-                        if (container.isTemplateDoc) {
-                            Doc.MakeMetadataFieldTemplate(created, container);
-                            return Doc.AddDocToList(container, Doc.LayoutFieldKey(container), created);
+                    },
+                    icon: 'compress-arrows-alt',
+                })
+            );
+        Array.from(Object.keys(Doc.GetProto(dataDoc)))
+            .filter(fieldKey => DocListCast(dataDoc[fieldKey]).length)
+            .map(fieldKey =>
+                docItems.push({
+                    description: ':' + fieldKey,
+                    event: () => {
+                        const created = Docs.Create.CarouselDocument([], { _width: 400, _height: 200, title: fieldKey });
+                        if (created) {
+                            const container = this.props.Document.resolvedDataDoc ? Doc.GetProto(this.props.Document) : this.props.Document;
+                            if (container.isTemplateDoc) {
+                                Doc.MakeMetadataFieldTemplate(created, container);
+                                return Doc.AddDocToList(container, Doc.LayoutFieldKey(container), created);
+                            }
+                            return this.props.addDocument?.(created) || false;
                         }
-                        return this.props.addDocument?.(created) || false;
-                    }
-                }, icon: "compress-arrows-alt"
-            }));
-        !Doc.UserDoc().noviceMode && ContextMenu.Instance.addItem({ description: "Doc Fields ...", subitems: docItems, icon: "eye" });
-        !Doc.UserDoc().noviceMode && ContextMenu.Instance.addItem({ description: "Containers ...", subitems: layoutItems, icon: "eye" });
-        ContextMenu.Instance.setDefaultItem("::", (name: string): void => {
-            Doc.GetProto(this.props.Document)[name] = "";
-            const created = Docs.Create.TextDocument("", { title: name, _width: 250, _autoHeight: true });
+                    },
+                    icon: 'compress-arrows-alt',
+                })
+            );
+        !Doc.UserDoc().noviceMode && ContextMenu.Instance.addItem({ description: 'Doc Fields ...', subitems: docItems, icon: 'eye' });
+        !Doc.UserDoc().noviceMode && ContextMenu.Instance.addItem({ description: 'Containers ...', subitems: layoutItems, icon: 'eye' });
+        ContextMenu.Instance.setDefaultItem('::', (name: string): void => {
+            Doc.GetProto(this.props.Document)[name] = '';
+            const created = Docs.Create.TextDocument('', { title: name, _width: 250, _autoHeight: true });
             if (created) {
                 if (this.props.Document.isTemplateDoc) {
                     Doc.MakeMetadataFieldTemplate(created, this.props.Document);
@@ -233,98 +251,100 @@ export class CollectionNoteTakingViewColumn extends React.Component<CSVFieldColu
             }
         });
         ContextMenu.Instance.displayMenu(x, y, undefined, true);
-    }
+    };
 
     @computed get innards() {
         TraceMobx();
         const key = this.props.pivotField;
         const heading = this._heading;
         const columnYMargin = this.props.headingObject ? 0 : this.props.yMargin;
-        const evContents = heading ? heading : "25";
-        const headingView = this.props.headingObject ?
-            <div key={heading} className="collectionNoteTakingView-sectionHeader" ref={this._headerRef}
+        const evContents = heading ? heading : '25';
+        const headingView = this.props.headingObject ? (
+            <div
+                key={heading}
+                className="collectionNoteTakingView-sectionHeader"
+                ref={this._headerRef}
                 style={{
                     marginTop: 2 * this.props.yMargin,
                     // width: (this.props.columnWidth) /
                     //     ((uniqueHeadings.length) || 1)
-                    width: this.columnWidth - 20
+                    width: this.columnWidth - 20,
                 }}>
-                <div className="collectionNoteTakingView-sectionHeader-subCont" onPointerDown={this.headerDown}
-                    title={evContents === `No Value` ?
-                        `Documents that don't have a ${key} value will go here. This column cannot be removed.` : ""}
-                    style={{ background: evContents !== `No Value` ? this._color : "inherit" }}>
-                    <EditableView
-                        GetValue={() => evContents}
-                        SetValue={this.headingChanged}
-                        contents={evContents}
-                        oneLine={true}
-                    />
+                <div
+                    className="collectionNoteTakingView-sectionHeader-subCont"
+                    onPointerDown={this.headerDown}
+                    title={evContents === `No Value` ? `Documents that don't have a ${key} value will go here. This column cannot be removed.` : ''}
+                    style={{ background: evContents !== `No Value` ? this._color : 'inherit' }}>
+                    <EditableView GetValue={() => evContents} SetValue={this.headingChanged} contents={evContents} oneLine={true} />
                 </div>
-            </div> : (null);
+            </div>
+        ) : null;
         // const templatecols = `${this.props.columnWidth / this.props.numGroupColumns}px `;
         const templatecols = `${this.columnWidth}px `;
         const type = this.props.Document.type;
-        return <>
-            {headingView}
-            {<div>
-              <div key={`${heading}-stack`} className={`collectionNoteTakingView-Nodes`}
-                  style={{
-                      padding: `${columnYMargin}px ${0}px ${this.props.yMargin}px ${0}px`,
-                      margin: "auto",
-                      width: "max-content", //singleColumn ? undefined : `${cols * (style.columnWidth + style.gridGap) + 2 * style.xMargin - style.gridGap}px`,
-                      height: 'max-content',
-                      position: "relative",
-                      gridGap: this.props.gridGap,
-                      gridTemplateColumns: templatecols,
-                      gridAutoRows: "0px"
-                  }}>
-                  {this.props.renderChildren(this.props.docList)}
-              </div>
+        return (
+            <>
+                {headingView}
+                {
+                    <div>
+                        <div
+                            key={`${heading}-stack`}
+                            className={`collectionNoteTakingView-Nodes`}
+                            style={{
+                                padding: `${columnYMargin}px ${0}px ${this.props.yMargin}px ${0}px`,
+                                margin: 'auto',
+                                width: 'max-content', //singleColumn ? undefined : `${cols * (style.columnWidth + style.gridGap) + 2 * style.xMargin - style.gridGap}px`,
+                                height: 'max-content',
+                                position: 'relative',
+                                gridGap: this.props.gridGap,
+                                gridTemplateColumns: templatecols,
+                                gridAutoRows: '0px',
+                            }}>
+                            {this.props.renderChildren(this.props.docList)}
+                        </div>
 
-              {!this.props.chromeHidden && type !== DocumentType.PRES ?
-                  <div className="collectionNoteTakingView-DocumentButtons"
-                      // style={{ width: this.props.columnWidth / this.props.numGroupColumns, marginBottom: 10 }}>
-                      style={{ width: this.columnWidth - 20, marginBottom: 10 }}>
-                      <div key={`${heading}-add-document`} className="collectionNoteTakingView-addDocumentButton">
-                          <EditableView
-                              GetValue={returnEmptyString}
-                              SetValue={this.addNewTextDoc}
-                              textCallback={this.textCallback}
-                              placeholder={"Type ':' for commands"}
-                              contents={"+ New Node"}
-                              menuCallback={this.menuCallback}
-                          />
-                      </div>
-                      <div key={`${this.props.Document[Id]}-addGroup`} className="collectionNoteTakingView-addDocumentButton">
-                          <EditableView {...this.props.editableViewProps} />
-                      </div>
-                      {(this.props.columnHeaders?.length && this.props.columnHeaders.length > 1) && 
-                          <button className="collectionNoteTakingView-sectionDelete" onClick={this.deleteColumn}>
-                          <FontAwesomeIcon icon="trash" size="lg" />
-                      </button>
-                      }
-                  </div>
-                  : null}
-              </div>
-            }
-        </>;
+                        {!this.props.chromeHidden && type !== DocumentType.PRES ? (
+                            <div
+                                className="collectionNoteTakingView-DocumentButtons"
+                                // style={{ width: this.props.columnWidth / this.props.numGroupColumns, marginBottom: 10 }}>
+                                style={{ width: this.columnWidth - 20, marginBottom: 10 }}>
+                                <div key={`${heading}-add-document`} className="collectionNoteTakingView-addDocumentButton">
+                                    <EditableView GetValue={returnEmptyString} SetValue={this.addNewTextDoc} textCallback={this.textCallback} placeholder={"Type ':' for commands"} contents={'+ New Node'} menuCallback={this.menuCallback} />
+                                </div>
+                                <div key={`${this.props.Document[Id]}-addGroup`} className="collectionNoteTakingView-addDocumentButton">
+                                    <EditableView {...this.props.editableViewProps} />
+                                </div>
+                                {this.props.columnHeaders?.length && this.props.columnHeaders.length > 1 && (
+                                    <button className="collectionNoteTakingView-sectionDelete" onClick={this.deleteColumn}>
+                                        <FontAwesomeIcon icon="trash" size="lg" />
+                                    </button>
+                                )}
+                            </div>
+                        ) : null}
+                    </div>
+                }
+            </>
+        );
     }
 
-
     render() {
         TraceMobx();
         const heading = this._heading;
         return (
-            <div className={"collectionNoteTakingViewFieldColumn" + (SnappingManager.GetIsDragging() ? "Dragging" : "")} key={heading}
+            <div
+                className={'collectionNoteTakingViewFieldColumn' + (SnappingManager.GetIsDragging() ? 'Dragging' : '')}
+                key={heading}
                 style={{
-                  //TODO: change this so that it's based on the column width 
+                    //TODO: change this so that it's based on the column width
                     width: this.columnWidth,
-                    height: "100%",
-                    background: this._background
+                    height: '100%',
+                    background: this._background,
                 }}
-                ref={this.createColumnDropRef} onPointerEnter={this.pointerEntered} onPointerLeave={this.pointerLeave}>
+                ref={this.createColumnDropRef}
+                onPointerEnter={this.pointerEntered}
+                onPointerLeave={this.pointerLeave}>
                 {this.innards}
-            </div >
+            </div>
         );
     }
-}
\ No newline at end of file
+}
diff --git a/src/client/views/collections/CollectionNoteTakingViewDivider.tsx b/src/client/views/collections/CollectionNoteTakingViewDivider.tsx
index ed5dc3715..7d31b3193 100644
--- a/src/client/views/collections/CollectionNoteTakingViewDivider.tsx
+++ b/src/client/views/collections/CollectionNoteTakingViewDivider.tsx
@@ -1,61 +1,63 @@
-import { action, observable } from "mobx";
-import * as React from "react";
+import { action, observable } from 'mobx';
+import * as React from 'react';
 
 interface DividerProps {
-  index: number
-  xMargin: number
-  setColumnStartXCoords: (movementX: number, colIndex: number) => void
+    index: number;
+    xMargin: number;
+    setColumnStartXCoords: (movementX: number, colIndex: number) => void;
 }
 
-export default class Divider extends React.Component<DividerProps>{
-  @observable private isHoverActive = false;
-  @observable private isResizingActive = false;
-  
-  @action
-  private registerResizing = (e: React.PointerEvent<HTMLDivElement>) => {
-      e.stopPropagation();
-      e.preventDefault();
-      window.removeEventListener("pointermove", this.onPointerMove);
-      window.removeEventListener("pointerup", this.onPointerUp);
-      window.addEventListener("pointermove", this.onPointerMove);
-      window.addEventListener("pointerup", this.onPointerUp);
-      this.isResizingActive = true;
-  }
+export class CollectionNoteTakingViewDivider extends React.Component<DividerProps> {
+    @observable private isHoverActive = false;
+    @observable private isResizingActive = false;
 
-  @action
-  private onPointerUp = () => {
-      this.isResizingActive = false;
-      this.isHoverActive = false;
-      window.removeEventListener("pointermove", this.onPointerMove);
-      window.removeEventListener("pointerup", this.onPointerUp);
-  }
+    @action
+    private registerResizing = (e: React.PointerEvent<HTMLDivElement>) => {
+        e.stopPropagation();
+        e.preventDefault();
+        window.removeEventListener('pointermove', this.onPointerMove);
+        window.removeEventListener('pointerup', this.onPointerUp);
+        window.addEventListener('pointermove', this.onPointerMove);
+        window.addEventListener('pointerup', this.onPointerUp);
+        this.isResizingActive = true;
+    };
 
-  @action
-  onPointerMove = ({ movementX }: PointerEvent) => {
-    this.props.setColumnStartXCoords(movementX, this.props.index)
-  }
-  
-  render() {
-    return (
-      <div className="columnResizer"
-        style={{
-          display: "flex", 
-          alignItems: "center", 
-          cursor: "col-resize"
-        }}
-        onPointerEnter={action(() => this.isHoverActive = true)}
-        onPointerLeave={action(() => !this.isResizingActive && (this.isHoverActive = false))}
-      >
-        <div className="columnResizer-handler" onPointerDown={e => this.registerResizing(e)}
-          style={{
-            height: "95%",
-            width: 12,
-            borderRight: "4px solid #282828",
-            borderLeft: "4px solid #282828",
-            margin: "0px 10px"
-          }}
-        />
-      </div>
-    )
-  }
-}
\ No newline at end of file
+    @action
+    private onPointerUp = () => {
+        this.isResizingActive = false;
+        this.isHoverActive = false;
+        window.removeEventListener('pointermove', this.onPointerMove);
+        window.removeEventListener('pointerup', this.onPointerUp);
+    };
+
+    @action
+    onPointerMove = ({ movementX }: PointerEvent) => {
+        this.props.setColumnStartXCoords(movementX, this.props.index);
+    };
+
+    render() {
+        return (
+            <div
+                className="columnResizer"
+                style={{
+                    display: 'flex',
+                    alignItems: 'center',
+                    cursor: 'col-resize',
+                }}
+                onPointerEnter={action(() => (this.isHoverActive = true))}
+                onPointerLeave={action(() => !this.isResizingActive && (this.isHoverActive = false))}>
+                <div
+                    className="columnResizer-handler"
+                    onPointerDown={e => this.registerResizing(e)}
+                    style={{
+                        height: '95%',
+                        width: 12,
+                        borderRight: '4px solid #282828',
+                        borderLeft: '4px solid #282828',
+                        margin: '0px 10px',
+                    }}
+                />
+            </div>
+        );
+    }
+}
diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx
index 1927db51e..ef68cadd7 100644
--- a/src/client/views/collections/CollectionStackingView.tsx
+++ b/src/client/views/collections/CollectionStackingView.tsx
@@ -447,8 +447,6 @@ export class CollectionStackingView extends CollectionSubView<Partial<collection
                 const newDocs = droppedDocs.length ? droppedDocs : de.complete.docDragData.droppedDocuments; // if nothing was added to the end of the list, then presumably the dropped documents were already in the list, but possibly got reordered so we use them.
 
                 const docs = this.childDocList;
-                // reset drag manager docs, because we just dropped
-                DragManager.docsBeingDragged = [];
                 // still figuring out where to add the document
                 if (docs && newDocs.length) {
                     const insertInd = dropInd === -1 ? docs.length : dropInd + dropAfter;
@@ -456,6 +454,8 @@ export class CollectionStackingView extends CollectionSubView<Partial<collection
                     newDocs.filter(ndoc => docs.indexOf(ndoc) !== -1).forEach(ndoc => docs.splice(docs.indexOf(ndoc), 1));
                     docs.splice(insertInd - offset, 0, ...newDocs);
                 }
+                // reset drag manager docs, because we just dropped
+                DragManager.docsBeingDragged.length = 0;
             }
         } else if (de.complete.linkDragData?.dragDocument.context === this.props.Document && de.complete.linkDragData?.linkDragView?.props.CollectionFreeFormDocumentView?.()) {
             const source = Docs.Create.TextDocument('', { _width: 200, _height: 75, _fitWidth: true, title: 'dropped annotation' });
diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx
index afb618b34..1ee1aec5a 100644
--- a/src/client/views/nodes/DocumentView.tsx
+++ b/src/client/views/nodes/DocumentView.tsx
@@ -156,9 +156,7 @@ export interface DocumentViewSharedProps {
     scriptContext?: any; // can be assigned anything and will be passed as 'scriptContext' to any OnClick script that executes on this document
     createNewFilterDoc?: () => void;
     updateFilterDoc?: (doc: Doc) => void;
-    // Parker added both of these
-    originalBackgroundColor?: string;
-    isNoteTakingView?: boolean;
+    dontHideOnDrag?: boolean;
 }
 
 // these props are specific to DocuentViews
@@ -494,12 +492,6 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
     startDragging(x: number, y: number, dropAction: dropActionType, hideSource = false) {
         if (this._mainCont.current) {
             const dragData = new DragManager.DocumentDragData([this.props.Document]);
-            if (this.props.isNoteTakingView) {
-                dragData.draggedDocuments.forEach((doc) => {
-                doc.backgroundColor = "#C9DAEF";
-                doc.opacity = 0.5;
-              });
-            }
             const [left, top] = this.props.ScreenToLocalTransform().scale(this.NativeDimScaling).inverse().transformPoint(0, 0);
             dragData.offset = this.props
                 .ScreenToLocalTransform()
@@ -511,22 +503,16 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
             dragData.treeViewDoc = this.props.treeViewDoc;
             dragData.removeDocument = this.props.removeDocument;
             dragData.moveDocument = this.props.moveDocument;
-            //dragData.dimSource : 
-            // dragEffects field, set dim 
+            //dragData.dimSource :
+            // dragEffects field, set dim
             // add kv pairs to a doc, swap properties with the node while dragging, and then swap when dropping
             // add a dragEffects prop to DocumentView as a function that sets up. Each view has its own prop, when you start dragging:
-            // in Draganager, figure out which doc(s) you're dragging and change what opacity function returns  
+            // in Draganager, figure out which doc(s) you're dragging and change what opacity function returns
             const ffview = this.props.CollectionFreeFormDocumentView?.().props.CollectionFreeFormView;
-            ffview && runInAction(() => (ffview.ChildDrag = this.props.DocumentView()));            
-            DragManager.StartDocumentDrag([this._mainCont.current], dragData, x, y, { hideSource: hideSource || (!dropAction && !this.layoutDoc.onDragStar && !this.props.isNoteTakingView)},
-                () => setTimeout(action(() => {
-                  ffview && (ffview.ChildDrag = undefined)
-                  //TODO: is there a better way than adding another field to the props? Not quite sure how "this" works tbh
-                  if (this.props.isNoteTakingView) {
-                    this.props.Document.backgroundColor = "";
-                    this.props.Document.opacity = 1;
-                  }
-                }))); // this needs to happen after the drop event is processed.
+            ffview && runInAction(() => (ffview.ChildDrag = this.props.DocumentView()));
+            DragManager.StartDocumentDrag([this._mainCont.current], dragData, x, y, { hideSource: hideSource || (!dropAction && !this.layoutDoc.onDragStart && !this.props.dontHideOnDrag) }, () =>
+                setTimeout(action(() => ffview && (ffview.ChildDrag = undefined)))
+            ); // this needs to happen after the drop event is processed.
             ffview?.setupDragLines(false);
         }
     }
diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
index b8ee89ef2..add83f4e0 100644
--- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx
+++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
@@ -1001,7 +1001,9 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
             () => ({ sidebarHeight: this.sidebarHeight, textHeight: this.textHeight, autoHeight: this.autoHeight, marginsHeight: this.autoHeightMargins }),
             ({ sidebarHeight, textHeight, autoHeight, marginsHeight }) => {
                 const newHeight = this.contentScaling * (marginsHeight + Math.max(sidebarHeight, textHeight));
-                autoHeight && newHeight && this.props.setHeight?.(newHeight);
+                if (autoHeight && newHeight && newHeight !== this.rootDoc.height) {
+                    this.props.setHeight?.(newHeight);
+                }
             },
             { fireImmediately: true }
         );
@@ -1695,7 +1697,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
             if (this.props.setHeight && scrollHeight && this.props.renderDepth && !this.props.dontRegisterView) {
                 // if top === 0, then the text box is growing upward (as the overlay caption) which doesn't contribute to the height computation
                 const setScrollHeight = () => (this.rootDoc[this.fieldKey + '-scrollHeight'] = scrollHeight);
-                if (this.rootDoc === this.layoutDoc.doc || this.layoutDoc.resolvedDataDoc) {
+                if (this.rootDoc === this.layoutDoc || this.layoutDoc.resolvedDataDoc) {
                     setScrollHeight();
                 } else {
                     setTimeout(setScrollHeight, 10); // if we have a template that hasn't been resolved yet, we can't set the height or we'd be setting it on the unresolved template.  So set a timeout and hope its arrived...
-- 
cgit v1.2.3-70-g09d2


From 26670c8b9eb6e2fd981c3a0997bff5556b60504b Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Mon, 8 Aug 2022 09:34:51 -0400
Subject: made props.showTitle = '' override doc.showTitle.  fixed
 de-autoLinking when text box is empty

---
 src/client/views/StyleProvider.tsx                        | 1 +
 src/client/views/nodes/LinkDocPreview.tsx                 | 3 ++-
 src/client/views/nodes/formattedText/FormattedTextBox.tsx | 6 +++---
 3 files changed, 6 insertions(+), 4 deletions(-)

(limited to 'src/client/views/nodes/formattedText/FormattedTextBox.tsx')

diff --git a/src/client/views/StyleProvider.tsx b/src/client/views/StyleProvider.tsx
index a83163eb0..3bd4f5152 100644
--- a/src/client/views/StyleProvider.tsx
+++ b/src/client/views/StyleProvider.tsx
@@ -124,6 +124,7 @@ export function DefaultStyleProvider(doc: Opt<Doc>, props: Opt<DocumentViewProps
             return (
                 (doc &&
                     !doc.presentationTargetDoc &&
+                    props?.showTitle?.() !== '' &&
                     StrCast(
                         doc._showTitle,
                         props?.showTitle?.() ||
diff --git a/src/client/views/nodes/LinkDocPreview.tsx b/src/client/views/nodes/LinkDocPreview.tsx
index a12564839..85b1f8d9e 100644
--- a/src/client/views/nodes/LinkDocPreview.tsx
+++ b/src/client/views/nodes/LinkDocPreview.tsx
@@ -5,7 +5,7 @@ import { observer } from 'mobx-react';
 import wiki from 'wikijs';
 import { Doc, DocCastAsync, DocListCast, HeightSym, Opt, WidthSym } from '../../../fields/Doc';
 import { Cast, NumCast, StrCast } from '../../../fields/Types';
-import { emptyFunction, returnEmptyDoclist, returnEmptyFilter, returnFalse, returnNone, setupMoveUpEvents } from '../../../Utils';
+import { emptyFunction, returnEmptyDoclist, returnEmptyFilter, returnEmptyString, returnFalse, returnNone, setupMoveUpEvents } from '../../../Utils';
 import { DocServer } from '../../DocServer';
 import { Docs, DocUtils } from '../../documents/Documents';
 import { DocumentType } from '../../documents/DocumentTypes';
@@ -236,6 +236,7 @@ export class LinkDocPreview extends React.Component<LinkDocPreviewProps> {
                             isDocumentActive={returnFalse}
                             isContentActive={returnFalse}
                             addDocument={returnFalse}
+                            showTitle={returnEmptyString}
                             removeDocument={returnFalse}
                             addDocTab={returnFalse}
                             pinToPres={returnFalse}
diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
index add83f4e0..a018f51c2 100644
--- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx
+++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
@@ -382,9 +382,9 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
     };
 
     autoLink = () => {
+        const newAutoLinks = new Set<Doc>();
+        const oldAutoLinks = DocListCast(this.props.Document.links).filter(link => link.linkRelationship === LinkManager.AutoKeywords);
         if (this._editorView?.state.doc.textContent) {
-            const newAutoLinks = new Set<Doc>();
-            const oldAutoLinks = DocListCast(this.props.Document.links).filter(link => link.linkRelationship === LinkManager.AutoKeywords);
             const f = this._editorView.state.selection.from;
             const t = this._editorView.state.selection.to;
             var tr = this._editorView.state.tr as any;
@@ -393,8 +393,8 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
             DocListCast(Doc.MyPublishedDocs.data).forEach(term => (tr = this.hyperlinkTerm(tr, term, newAutoLinks)));
             tr = tr.setSelection(new TextSelection(tr.doc.resolve(f), tr.doc.resolve(t)));
             this._editorView?.dispatch(tr);
-            oldAutoLinks.filter(oldLink => !newAutoLinks.has(oldLink) && oldLink.anchor2 !== this.rootDoc).forEach(LinkManager.Instance.deleteLink);
         }
+        oldAutoLinks.filter(oldLink => !newAutoLinks.has(oldLink) && oldLink.anchor2 !== this.rootDoc).forEach(LinkManager.Instance.deleteLink);
     };
 
     updateTitle = () => {
-- 
cgit v1.2.3-70-g09d2


From 2a1d6793d33d9c72295d23965aefd23f2004bbcb Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Mon, 8 Aug 2022 11:48:27 -0400
Subject: cleaning up link ui.   linkPreviews (not from linkMenu) have an edit
 button.  link lines work when in lightboxview.

---
 .../CollectionFreeFormLinkView.tsx                 |   5 +-
 .../CollectionFreeFormLinksView.tsx                |   5 +-
 src/client/views/linking/LinkEditor.scss           |  65 +++++-----
 src/client/views/linking/LinkEditor.tsx            | 141 ++++++++++++---------
 src/client/views/linking/LinkMenuItem.tsx          |  89 +------------
 src/client/views/nodes/DocumentLinksButton.tsx     |   2 +-
 src/client/views/nodes/DocumentView.tsx            |  16 ++-
 src/client/views/nodes/LinkAnchorBox.tsx           |   2 +-
 src/client/views/nodes/LinkDocPreview.tsx          |  18 ++-
 .../views/nodes/formattedText/FormattedTextBox.tsx |   4 +-
 10 files changed, 149 insertions(+), 198 deletions(-)

(limited to 'src/client/views/nodes/formattedText/FormattedTextBox.tsx')

diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx
index d979ef961..bf9de6760 100644
--- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx
+++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx
@@ -195,7 +195,10 @@ export class CollectionFreeFormLinkView extends React.Component<CollectionFreeFo
         const bDocBounds = (B.props as any).DocumentView?.().getBounds() || { left: 0, right: 0, top: 0, bottom: 0 };
         const aleft = this.visibleX(adiv);
         const bleft = this.visibleX(bdiv);
-        const clipped = aleft !== a.left || atop !== a.top || bleft !== b.left || btop !== b.top;
+        const aclipped = aleft !== a.left || atop !== a.top;
+        const bclipped = bleft !== b.left || btop !== b.top;
+        if (aclipped && bclipped) return undefined;
+        const clipped = aclipped || bclipped;
         const pt1 = [aleft + a.width / 2, atop + a.height / 2];
         const pt2 = [bleft + b.width / 2, btop + b.width / 2];
         const pt1vec = [(bDocBounds.left + bDocBounds.right) / 2 - pt1[0], (bDocBounds.top + bDocBounds.bottom) / 2 - pt1[1]];
diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx
index 8720c9097..b8344dc0c 100644
--- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx
+++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx
@@ -5,11 +5,14 @@ import { DocumentManager } from '../../../util/DocumentManager';
 import './CollectionFreeFormLinksView.scss';
 import { CollectionFreeFormLinkView } from './CollectionFreeFormLinkView';
 import React = require('react');
+import { LightboxView } from '../../LightboxView';
 
 @observer
 export class CollectionFreeFormLinksView extends React.Component<React.PropsWithChildren<{}>> {
     @computed get uniqueConnections() {
-        return Array.from(new Set(DocumentManager.Instance.LinkedDocumentViews)).map(c => <CollectionFreeFormLinkView key={c.l[Id]} A={c.a} B={c.b} LinkDocs={[c.l]} />);
+        return Array.from(new Set(DocumentManager.Instance.LinkedDocumentViews))
+            .filter(c => !LightboxView.LightboxDoc || (LightboxView.IsLightboxDocView(c.a.docViewPath) && LightboxView.IsLightboxDocView(c.b.docViewPath)))
+            .map(c => <CollectionFreeFormLinkView key={c.l[Id]} A={c.a} B={c.b} LinkDocs={[c.l]} />);
     }
 
     render() {
diff --git a/src/client/views/linking/LinkEditor.scss b/src/client/views/linking/LinkEditor.scss
index 1d6496d3c..b0ee4e46d 100644
--- a/src/client/views/linking/LinkEditor.scss
+++ b/src/client/views/linking/LinkEditor.scss
@@ -1,10 +1,11 @@
-@import "../global/globalCssVariables";
+@import '../global/globalCssVariables';
 
 .linkEditor {
     width: 100%;
     height: auto;
     font-size: 13px; // TODO
     user-select: none;
+    max-width: 280px;
 }
 
 .linkEditor-button-back {
@@ -20,19 +21,20 @@
 }
 
 .linkEditor-info {
-    //border-bottom: 0.5px solid $light-gray;
-    //padding-bottom: 1px;
-    padding: 12px;
+    padding-top: 12px;
     padding-left: 5px;
+    padding-bottom: 3px;
     //margin-bottom: 6px;
     display: flex;
     justify-content: space-between;
     color: black;
 
     .linkEditor-linkedTo {
-        width: calc(100% - 26px);
-        padding-left: 5px;
-        padding-right: 5px;
+        width: calc(100% - 46px);
+        overflow: hidden;
+        position: relative;
+        text-overflow: ellipsis;
+        white-space: pre;
 
         .linkEditor-downArrow {
             &:hover {
@@ -77,11 +79,14 @@
         width: 20px;
     }
 }
+.linkEditor-deleteBtn {
+    padding-left: 3px;
+}
 
 .linkEditor-description {
     padding-left: 26px;
-    padding-right: 6.5px;
     padding-bottom: 3.5px;
+    display: flex;
 
     .linkEditor-description-label {
         text-decoration-color: black;
@@ -96,7 +101,6 @@
             //border: 1px solid grey;
             //border-radius: 4px;
             padding-left: 2px;
-            padding-right: 2px;
             //margin-right: 4px;
             color: black;
             text-decoration-color: grey;
@@ -104,17 +108,13 @@
 
         .linkEditor-description-add-button {
             display: inline;
-            /* float: right; */
             border-radius: 7px;
             font-size: 9px;
             background: black;
-            /* padding: 3px; */
-            padding-top: 4px;
-            padding-left: 7px;
-            padding-bottom: 4px;
-            padding-right: 8px;
             height: 80%;
             color: white;
+            padding: 3px;
+            margin-left: 3px;
 
             &:hover {
                 cursor: pointer;
@@ -146,6 +146,7 @@
     padding-left: 26px;
     padding-right: 6.5px;
     padding-bottom: 15px;
+    display: flex;
 
     &:hover {
         cursor: pointer;
@@ -153,12 +154,11 @@
 
     .linkEditor-followingDropdown-label {
         color: black;
+        padding-right: 3px;
     }
 
     .linkEditor-followingDropdown-dropdown {
-
         .linkEditor-followingDropdown-header {
-
             border: 1px solid grey;
             border-radius: 4px;
             //background-color: rgb(236, 236, 236);
@@ -195,27 +195,25 @@
                     background-color: rgb(187, 220, 231);
                 }
             }
-
         }
     }
-
-
 }
 
-
-
-
-
-
 .linkEditor-button,
 .linkEditor-addbutton {
-    width: 18px;
-    height: 18px;
-    padding: 0;
-    // font-size: 12px;
-    border-radius: 10px;
-
-
+    width: 15%;
+    border-radius: 7px;
+    font-size: 9px;
+    background: black;
+    padding: 3px;
+    height: 80%;
+    color: white;
+    text-align: center;
+    margin: auto;
+    margin-left: 3px;
+    > svg {
+        margin: auto;
+    }
     &:disabled {
         background-color: gray;
     }
@@ -270,7 +268,6 @@
     }
 }
 
-
 .linkEditor-dropdown {
     width: 100%;
     position: relative;
@@ -334,4 +331,4 @@
     .linkEditor-button {
         margin-left: 3px;
     }
-}
\ No newline at end of file
+}
diff --git a/src/client/views/linking/LinkEditor.tsx b/src/client/views/linking/LinkEditor.tsx
index ba301962b..d23d38854 100644
--- a/src/client/views/linking/LinkEditor.tsx
+++ b/src/client/views/linking/LinkEditor.tsx
@@ -9,11 +9,12 @@ import { undoBatch } from '../../util/UndoManager';
 import './LinkEditor.scss';
 import { LinkRelationshipSearch } from './LinkRelationshipSearch';
 import React = require('react');
+import { emptyFunction, returnFalse, setupMoveUpEvents } from '../../../Utils';
 
 interface LinkEditorProps {
     sourceDoc: Doc;
     linkDoc: Doc;
-    showLinks: () => void;
+    showLinks?: () => void;
     hideback?: boolean;
 }
 @observer
@@ -22,13 +23,6 @@ export class LinkEditor extends React.Component<LinkEditorProps> {
     @observable relationship = StrCast(LinkManager.currentLink?.linkRelationship);
     @observable zoomFollow = StrCast(this.props.sourceDoc.followLinkZoom);
     @observable openDropdown: boolean = false;
-    @observable showInfo: boolean = false;
-    @computed get infoIcon() {
-        if (this.showInfo) {
-            return 'chevron-up';
-        }
-        return 'chevron-down';
-    }
     @observable private buttonColor: string = '';
     @observable private relationshipButtonColor: string = '';
     @observable private relationshipSearchVisibility: string = 'none';
@@ -36,12 +30,6 @@ export class LinkEditor extends React.Component<LinkEditorProps> {
 
     //@observable description = this.props.linkDoc.description ? StrCast(this.props.linkDoc.description) : "DESCRIPTION";
 
-    @undoBatch
-    deleteLink = (): void => {
-        LinkManager.Instance.deleteLink(this.props.linkDoc);
-        this.props.showLinks();
-    };
-
     @undoBatch
     setRelationshipValue = action((value: string) => {
         if (LinkManager.currentLink) {
@@ -173,7 +161,7 @@ export class LinkEditor extends React.Component<LinkEditorProps> {
         //NOTE: confusingly, the classnames for the following relationship JSX elements are the same as the for the description elements for shared CSS
         return (
             <div className="linkEditor-description">
-                <div className="linkEditor-description-label">Link Relationship:</div>
+                <div className="linkEditor-description-label">Relationship:</div>
                 <div className="linkEditor-description-input">
                     <div className="linkEditor-description-editing">
                         <input
@@ -214,7 +202,7 @@ export class LinkEditor extends React.Component<LinkEditorProps> {
     get editDescription() {
         return (
             <div className="linkEditor-description">
-                <div className="linkEditor-description-label">Link Description:</div>
+                <div className="linkEditor-description-label">Description:</div>
                 <div className="linkEditor-description-input">
                     <div className="linkEditor-description-editing">
                         <input style={{ width: '100%' }} autoComplete={'off'} id="input" value={this.description} placeholder={'Enter link description'} onKeyDown={this.onDescriptionKey} onChange={this.handleDescriptionChange}></input>
@@ -284,68 +272,99 @@ export class LinkEditor extends React.Component<LinkEditorProps> {
         );
     }
 
-    @action
-    changeInfo = () => {
-        this.showInfo = !this.showInfo;
+    autoMove = (e: React.PointerEvent) => {
+        setupMoveUpEvents(this, e, returnFalse, emptyFunction, undoBatch(action(() => (this.props.linkDoc.linkAutoMove = !this.props.linkDoc.linkAutoMove))));
+    };
+
+    showAnchor = (e: React.PointerEvent) => {
+        setupMoveUpEvents(this, e, returnFalse, emptyFunction, undoBatch(action(() => (this.props.linkDoc.hidden = !this.props.linkDoc.hidden))));
+    };
+
+    showLink = (e: React.PointerEvent) => {
+        setupMoveUpEvents(this, e, returnFalse, emptyFunction, undoBatch(action(() => (this.props.linkDoc.linkDisplay = !this.props.linkDoc.linkDisplay))));
+    };
+
+    deleteLink = (e: React.PointerEvent): void => {
+        setupMoveUpEvents(this, e, returnFalse, emptyFunction, undoBatch(action(() => LinkManager.Instance.deleteLink(this.props.linkDoc))));
     };
 
     render() {
         const destination = LinkManager.getOppositeAnchor(this.props.linkDoc, this.props.sourceDoc);
 
         return !destination ? null : (
-            <div className="linkEditor" tabIndex={0} onKeyDown={e => e.stopPropagation()}>
+            <div className="linkEditor" tabIndex={0} onKeyDown={e => e.stopPropagation()} onPointerDown={e => e.stopPropagation()}>
                 <div className="linkEditor-info">
-                    <Tooltip
-                        title={
-                            <>
-                                <div className="dash-tooltip">Return to link menu</div>
-                            </>
-                        }
-                        placement="top">
-                        <button className="linkEditor-button-back" style={{ display: this.props.hideback ? 'none' : '' }} onClick={this.props.showLinks}>
-                            <FontAwesomeIcon icon="arrow-left" size="sm" />{' '}
-                        </button>
-                    </Tooltip>
+                    {!this.props.showLinks ? null : (
+                        <Tooltip title={<div className="dash-tooltip">Return to link menu</div>} placement="top">
+                            <button className="linkEditor-button-back" style={{ display: this.props.hideback ? 'none' : '' }} onPointerDown={e => setupMoveUpEvents(this, e, returnFalse, emptyFunction, () => this.props.showLinks?.())}>
+                                <FontAwesomeIcon icon="arrow-left" size="sm" />{' '}
+                            </button>
+                        </Tooltip>
+                    )}
                     <p className="linkEditor-linkedTo">
                         Editing Link to: <b>{StrCast(destination.proto?.title, StrCast(destination.title, 'untitled'))}</b>
                     </p>
-                    <Tooltip
-                        title={
-                            <>
-                                <div className="dash-tooltip">Show more link information</div>
-                            </>
-                        }
-                        placement="top">
-                        <div className="linkEditor-downArrow">
-                            <FontAwesomeIcon className="button" icon={this.infoIcon} size="lg" onPointerDown={this.changeInfo} />
+                    <Tooltip title={<div className="dash-tooltip">Delete Link</div>}>
+                        <div className="linkEditor-deleteBtn" onPointerDown={this.deleteLink} onClick={e => e.stopPropagation()}>
+                            <FontAwesomeIcon className="fa-icon" icon="trash" size="sm" />
                         </div>
                     </Tooltip>
                 </div>
-                {this.showInfo ? (
-                    <div className="linkEditor-moreInfo">
-                        <div>
-                            {this.props.linkDoc.author ? (
-                                <div>
-                                    {' '}
-                                    <b>Author:</b> {StrCast(this.props.linkDoc.author)}
-                                </div>
-                            ) : null}
-                        </div>
-                        <div>
-                            {this.props.linkDoc.creationDate ? (
-                                <div>
-                                    {' '}
-                                    <b>Creation Date:</b>
-                                    {DateCast(this.props.linkDoc.creationDate).toString()}
-                                </div>
-                            ) : null}
-                        </div>
-                    </div>
-                ) : null}
+                <div className="linkEditor-moreInfo">
+                    {this.props.linkDoc.author ? (
+                        <>
+                            {' '}
+                            <b>Author:</b> {StrCast(this.props.linkDoc.author)}
+                        </>
+                    ) : null}
+                    {this.props.linkDoc.creationDate ? (
+                        <>
+                            {' '}
+                            <b>Creation Date:</b>
+                            {DateCast(this.props.linkDoc.creationDate).toString()}
+                        </>
+                    ) : null}
+                </div>
 
                 {this.editDescription}
                 {this.editRelationship}
                 {this.editZoomFollow}
+                <div className="linkEditor-description">
+                    Show Anchor:
+                    <Tooltip title={<div className="dash-tooltip">{this.props.linkDoc.hidden ? 'Show Link Anchor' : 'Hide Link Anchor'}</div>}>
+                        <div
+                            className="linkEditor-button"
+                            style={{ background: this.props.linkDoc.hidden ? 'gray' : '#4476f7' /* $medium-blue                                       */ }}
+                            onPointerDown={this.showAnchor}
+                            onClick={e => e.stopPropagation()}>
+                            <FontAwesomeIcon className="fa-icon" icon={'eye'} size="sm" />
+                        </div>
+                    </Tooltip>
+                </div>
+                <div className="linkEditor-description">
+                    Show Link Line:
+                    <Tooltip title={<div className="dash-tooltip">{this.props.linkDoc.linkDisplay ? 'Hide Link Line' : 'Show Link Line'}</div>}>
+                        <div
+                            className="linkEditor-button"
+                            style={{ background: this.props.linkDoc.hidden ? 'gray' : this.props.linkDoc.linkDisplay ? '#4476f7' /* $medium-blue */ : '' }}
+                            onPointerDown={this.showLink}
+                            onClick={e => e.stopPropagation()}>
+                            <FontAwesomeIcon className="fa-icon" icon={'project-diagram'} size="sm" />
+                        </div>
+                    </Tooltip>
+                </div>
+                <div className="linkEditor-description">
+                    Freeze Anchor:
+                    <Tooltip title={<div className="dash-tooltip">{this.props.linkDoc.linkAutoMove ? 'Click to freeze link anchor position' : 'Click to auto move link anchor'}</div>}>
+                        <div
+                            className="linkEditor-button"
+                            style={{ background: this.props.linkDoc.hidden ? 'gray' : this.props.linkDoc.linkAutoMove ? '' : '#4476f7' /* $medium-blue */ }}
+                            onPointerDown={this.autoMove}
+                            onClick={e => e.stopPropagation()}>
+                            <FontAwesomeIcon className="fa-icon" icon={'play'} size="sm" />
+                        </div>
+                    </Tooltip>
+                </div>
                 {this.followingDropdown}
             </div>
         );
diff --git a/src/client/views/linking/LinkMenuItem.tsx b/src/client/views/linking/LinkMenuItem.tsx
index ed856a4ab..60428fc98 100644
--- a/src/client/views/linking/LinkMenuItem.tsx
+++ b/src/client/views/linking/LinkMenuItem.tsx
@@ -125,33 +125,6 @@ export class LinkMenuItem extends React.Component<LinkMenuItemProps> {
         );
     };
 
-    deleteLink = (e: React.PointerEvent): void => {
-        setupMoveUpEvents(
-            this,
-            e,
-            returnFalse,
-            emptyFunction,
-            undoBatch(
-                action(() => {
-                    this.props.linkDoc.linksToAnnotation && Hypothesis.deleteLink(this.props.linkDoc, this.props.sourceDoc, this.props.destinationDoc);
-                    LinkManager.Instance.deleteLink(this.props.linkDoc);
-                })
-            )
-        );
-    };
-
-    autoMove = (e: React.PointerEvent) => {
-        setupMoveUpEvents(this, e, returnFalse, emptyFunction, undoBatch(action(() => (this.props.linkDoc.linkAutoMove = !this.props.linkDoc.linkAutoMove))));
-    };
-
-    showLink = (e: React.PointerEvent) => {
-        setupMoveUpEvents(this, e, returnFalse, emptyFunction, undoBatch(action(() => (this.props.linkDoc.linkDisplay = !this.props.linkDoc.linkDisplay))));
-    };
-
-    showAnchor = (e: React.PointerEvent) => {
-        setupMoveUpEvents(this, e, returnFalse, emptyFunction, undoBatch(action(() => (this.props.linkDoc.hidden = !this.props.linkDoc.hidden))));
-    };
-
     render() {
         const destinationIcon = Doc.toIcon(this.props.destinationDoc) as any as IconProp;
 
@@ -183,7 +156,7 @@ export class LinkMenuItem extends React.Component<LinkMenuItemProps> {
                                 linkSrc: this.props.sourceDoc,
                                 linkDoc: this.props.linkDoc,
                                 showHeader: false,
-                                location: [e.clientX, e.clientY + 20],
+                                location: [this._drag.current?.getBoundingClientRect().right ?? 100, this._drag.current?.getBoundingClientRect().top ?? e.clientY],
                             })
                         }
                         onPointerDown={this.onLinkButtonDown}>
@@ -206,69 +179,11 @@ export class LinkMenuItem extends React.Component<LinkMenuItemProps> {
                         </div>
 
                         <div className="linkMenu-item-buttons" ref={this._buttonRef}>
-                            <Tooltip
-                                title={
-                                    <>
-                                        <div className="dash-tooltip">{this.props.linkDoc.hidden ? 'Show Link Anchor' : 'Hide Link Anchor'}</div>
-                                    </>
-                                }>
-                                <div className="button" ref={this._editRef} style={{ background: this.props.linkDoc.hidden ? '' : '#4476f7' /* $medium-blue */ }} onPointerDown={this.showAnchor} onClick={e => e.stopPropagation()}>
-                                    <FontAwesomeIcon className="fa-icon" icon={'eye'} size="sm" />
-                                </div>
-                            </Tooltip>
-
-                            <Tooltip
-                                title={
-                                    <>
-                                        <div className="dash-tooltip">{this.props.linkDoc.linkDisplay ? 'Hide Link Line' : 'Show Link Line'}</div>
-                                    </>
-                                }>
-                                <div
-                                    className="button"
-                                    ref={this._editRef}
-                                    style={{ background: this.props.linkDoc.hidden ? 'gray' : this.props.linkDoc.linkDisplay ? '#4476f7' /* $medium-blue */ : '' }}
-                                    onPointerDown={this.showLink}
-                                    onClick={e => e.stopPropagation()}>
-                                    <FontAwesomeIcon className="fa-icon" icon={'project-diagram'} size="sm" />
-                                </div>
-                            </Tooltip>
-
-                            <Tooltip
-                                title={
-                                    <>
-                                        <div className="dash-tooltip">{this.props.linkDoc.linkAutoMove ? 'Click to freeze link anchor position' : 'Click to auto move link anchor'}</div>
-                                    </>
-                                }>
-                                <div
-                                    className="button"
-                                    ref={this._editRef}
-                                    style={{ background: this.props.linkDoc.hidden ? 'gray' : !this.props.linkDoc.linkAutoMove ? '' : '#4476f7' /* $medium-blue */ }}
-                                    onPointerDown={this.autoMove}
-                                    onClick={e => e.stopPropagation()}>
-                                    <FontAwesomeIcon className="fa-icon" icon={'play'} size="sm" />
-                                </div>
-                            </Tooltip>
-
-                            <Tooltip
-                                title={
-                                    <>
-                                        <div className="dash-tooltip">Edit Link</div>
-                                    </>
-                                }>
+                            <Tooltip title={<div className="dash-tooltip">Edit Link</div>}>
                                 <div className="button" ref={this._editRef} onPointerDown={this.onEdit} onClick={e => e.stopPropagation()}>
                                     <FontAwesomeIcon className="fa-icon" icon="edit" size="sm" />
                                 </div>
                             </Tooltip>
-                            <Tooltip
-                                title={
-                                    <>
-                                        <div className="dash-tooltip">Delete Link</div>
-                                    </>
-                                }>
-                                <div className="button" onPointerDown={this.deleteLink} onClick={e => e.stopPropagation()}>
-                                    <FontAwesomeIcon className="fa-icon" icon="trash" size="sm" />
-                                </div>
-                            </Tooltip>
                         </div>
                     </div>
                 </div>
diff --git a/src/client/views/nodes/DocumentLinksButton.tsx b/src/client/views/nodes/DocumentLinksButton.tsx
index 5939d1680..a37de7f69 100644
--- a/src/client/views/nodes/DocumentLinksButton.tsx
+++ b/src/client/views/nodes/DocumentLinksButton.tsx
@@ -307,7 +307,7 @@ export class DocumentLinksButton extends React.Component<DocumentLinksButtonProp
             <div
                 className="documentLinksButton-wrapper"
                 style={{
-                    transform: this.props.InMenu ? undefined : `scale(${this.props.scaling})`,
+                    transform: `scale(${this.props.scaling?.() || 1})`,
                 }}>
                 {(this.props.InMenu && (DocumentLinksButton.StartLink || this.props.StartLink)) || (!DocumentLinksButton.LinkEditorDocView && !this.props.InMenu) ? (
                     <Tooltip title={<div className="dash-tooltip">{title}</div>}>{this.linkButtonInner}</Tooltip>
diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx
index 1ee1aec5a..2524d66dd 100644
--- a/src/client/views/nodes/DocumentView.tsx
+++ b/src/client/views/nodes/DocumentView.tsx
@@ -1070,7 +1070,7 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
                     <DocumentLinksButton
                         View={this.props.DocumentView()}
                         scaling={this.linkButtonInverseScaling}
-                        Offset={[this.topMost ? 0 : !this.props.isSelected() ? -15 : -30, undefined, undefined, this.topMost ? 10 : !this.props.isSelected() ? -15 : -30]}
+                        Offset={[this.topMost ? 0 : !this.props.isSelected() ? -15 : -36, undefined, undefined, this.topMost ? 10 : !this.props.isSelected() ? -15 : -28]}
                     />
                 )}
                 {audioView}
@@ -1298,6 +1298,7 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
     isHovering = () => this._isHovering;
     @observable _isHovering = false;
     @observable _: string = '';
+    _hoverTimeout: any = undefined;
     @computed get renderDoc() {
         TraceMobx();
         const thumb = ImageCast(this.layoutDoc['thumb-frozen'], ImageCast(this.layoutDoc.thumb))?.url?.href.replace('.png', '_m.png');
@@ -1308,8 +1309,17 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
                 <div
                     className={`documentView-node${this.topMost ? '-topmost' : ''}`}
                     id={this.props.Document[Id]}
-                    onPointerEnter={action(() => (this._isHovering = true))}
-                    onPointerLeave={action(() => (this._isHovering = false))}
+                    onPointerEnter={action(() => {
+                        clearTimeout(this._hoverTimeout);
+                        this._isHovering = true;
+                    })}
+                    onPointerLeave={action(() => {
+                        clearTimeout(this._hoverTimeout);
+                        this._hoverTimeout = setTimeout(
+                            action(() => (this._isHovering = false)),
+                            500
+                        );
+                    })}
                     style={{
                         background: isButton || thumb ? undefined : this.backgroundColor,
                         opacity: this.opacity,
diff --git a/src/client/views/nodes/LinkAnchorBox.tsx b/src/client/views/nodes/LinkAnchorBox.tsx
index 85a8622ec..5102eae51 100644
--- a/src/client/views/nodes/LinkAnchorBox.tsx
+++ b/src/client/views/nodes/LinkAnchorBox.tsx
@@ -136,7 +136,7 @@ export class LinkAnchorBox extends ViewBoxBaseComponent<FieldViewProps>() {
         return (
             <div
                 className={`linkAnchorBox-cont${small ? '-small' : ''}`}
-                onPointerLeave={LinkDocPreview.Clear}
+                //onPointerLeave={} //LinkDocPreview.Clear}
                 onPointerEnter={e =>
                     LinkDocPreview.SetLinkInfo({
                         docProps: this.props,
diff --git a/src/client/views/nodes/LinkDocPreview.tsx b/src/client/views/nodes/LinkDocPreview.tsx
index 85b1f8d9e..93ca22d5d 100644
--- a/src/client/views/nodes/LinkDocPreview.tsx
+++ b/src/client/views/nodes/LinkDocPreview.tsx
@@ -17,6 +17,7 @@ import { undoBatch } from '../../util/UndoManager';
 import { DocumentView, DocumentViewSharedProps } from './DocumentView';
 import './LinkDocPreview.scss';
 import React = require('react');
+import { LinkEditor } from '../linking/LinkEditor';
 
 interface LinkDocPreviewProps {
     linkDoc?: Doc;
@@ -118,13 +119,15 @@ export class LinkDocPreview extends React.Component<LinkDocPreviewProps> {
         }
         return undefined;
     }
-    deleteLink = (e: React.PointerEvent) => {
+    @observable _showEditor = false;
+    editLink = (e: React.PointerEvent): void => {
+        LinkManager.currentLink = this.props.linkDoc;
         setupMoveUpEvents(
             this,
             e,
             returnFalse,
             emptyFunction,
-            undoBatch(() => this._linkDoc && LinkManager.Instance.deleteLink(this._linkDoc))
+            action(() => (this._showEditor = !this._showEditor))
         );
     };
     nextHref = (e: React.PointerEvent) => {
@@ -183,9 +186,9 @@ export class LinkDocPreview extends React.Component<LinkDocPreviewProps> {
                         </div>
                     </Tooltip>
 
-                    <Tooltip title={<div className="dash-tooltip">Delete Link</div>} placement="top">
-                        <div className="linkDocPreview-button" onPointerDown={this.deleteLink}>
-                            <FontAwesomeIcon className="linkDocPreview-fa-icon" icon="trash" color="white" size="sm" />
+                    <Tooltip title={<div className="dash-tooltip">Edit Link</div>} placement="top">
+                        <div className="linkDocPreview-button" onPointerDown={this.editLink}>
+                            <FontAwesomeIcon className="linkDocPreview-fa-icon" icon="edit" color="white" size="sm" />
                         </div>
                     </Tooltip>
                 </div>
@@ -271,8 +274,9 @@ export class LinkDocPreview extends React.Component<LinkDocPreviewProps> {
                 className="linkDocPreview"
                 ref={this._linkDocRef}
                 onPointerDown={this.followLinkPointerDown}
-                style={{ left: this.props.location[0], top: this.props.location[1], width: this.width() + borders, height: this.height() + borders + (this.props.showHeader ? 37 : 0) }}>
-                {this.docPreview}
+                style={{ left: this.props.location[0], top: this.props.location[1], width: this._showEditor ? 'auto' : this.width() + borders, height: this._showEditor ? 'max-content' : this.height() + borders + (this.props.showHeader ? 37 : 0) }}>
+                {this._showEditor ? null : this.docPreview}
+                {!this._showEditor || !this._linkSrc || !this._linkDoc ? null : <LinkEditor sourceDoc={this._linkSrc} linkDoc={this._linkDoc} showLinks={action(() => (this._showEditor = !this._showEditor))} />}
             </div>
         );
     }
diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
index a018f51c2..40b0d285c 100644
--- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx
+++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
@@ -24,7 +24,7 @@ import { addStyleSheet, addStyleSheetRule, clearStyleSheetRules, emptyFunction,
 import { GoogleApiClientUtils, Pulls, Pushes } from '../../../apis/google_docs/GoogleApiClientUtils';
 import { DocServer } from '../../../DocServer';
 import { Docs, DocUtils } from '../../../documents/Documents';
-import { DocumentType } from '../../../documents/DocumentTypes';
+import { CollectionViewType, DocumentType } from '../../../documents/DocumentTypes';
 import { DictationManager } from '../../../util/DictationManager';
 import { DocumentManager } from '../../../util/DocumentManager';
 import { DragManager } from '../../../util/DragManager';
@@ -1751,7 +1751,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
     }
     @computed get sidebarCollection() {
         const renderComponent = (tag: string) => {
-            const ComponentTag = tag === 'freeform' ? CollectionFreeFormView : tag === 'tree' ? CollectionTreeView : tag === 'translation' ? FormattedTextBox : CollectionStackingView;
+            const ComponentTag = tag === CollectionViewType.Freeform ? CollectionFreeFormView : tag === CollectionViewType.Tree ? CollectionTreeView : tag === 'translation' ? FormattedTextBox : CollectionStackingView;
             return ComponentTag === CollectionStackingView ? (
                 <SidebarAnnos
                     ref={this._sidebarRef}
-- 
cgit v1.2.3-70-g09d2


From 4b2f131d91e71f4514642b5846713e9c3b68210b Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Mon, 8 Aug 2022 12:54:06 -0400
Subject: fixed autolinking to not match partial word substrings.  restored
 textbox dictation.

---
 src/client/documents/Documents.ts                  |   5 +-
 src/client/util/DictationManager.ts                | 439 +++++++++++----------
 src/client/views/DocumentDecorations.tsx           |   1 -
 src/client/views/linking/LinkMenuItem.tsx          |   4 +-
 .../views/nodes/formattedText/FormattedTextBox.tsx |  96 +++--
 5 files changed, 282 insertions(+), 263 deletions(-)

(limited to 'src/client/views/nodes/formattedText/FormattedTextBox.tsx')

diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts
index 9d00664ad..c7ea04839 100644
--- a/src/client/documents/Documents.ts
+++ b/src/client/documents/Documents.ts
@@ -1287,10 +1287,11 @@ export namespace DocUtils {
 
     export let ActiveRecordings: { props: FieldViewProps; getAnchor: () => Doc }[] = [];
 
-    export function MakeLinkToActiveAudio(getSourceDoc: () => Doc, broadcastEvent = true) {
+    export function MakeLinkToActiveAudio(getSourceDoc: () => Doc | undefined, broadcastEvent = true) {
         broadcastEvent && runInAction(() => (DocumentManager.Instance.RecordingEvent = DocumentManager.Instance.RecordingEvent + 1));
         return DocUtils.ActiveRecordings.map(audio => {
-            const link = DocUtils.MakeLink({ doc: getSourceDoc() }, { doc: audio.getAnchor() || audio.props.Document }, 'recording annotation:linked recording', 'recording timeline');
+            const sourceDoc = getSourceDoc();
+            const link = sourceDoc && DocUtils.MakeLink({ doc: sourceDoc }, { doc: audio.getAnchor() || audio.props.Document }, 'recording annotation:linked recording', 'recording timeline');
             link && (link.followLinkLocation = 'add:right');
             return link;
         });
diff --git a/src/client/util/DictationManager.ts b/src/client/util/DictationManager.ts
index a6dcda4bc..13f036838 100644
--- a/src/client/util/DictationManager.ts
+++ b/src/client/util/DictationManager.ts
@@ -1,37 +1,35 @@
-import * as interpreter from "words-to-numbers";
+import * as interpreter from 'words-to-numbers';
 // @ts-ignore  bcz: how are you supposed to include these definitions since dom-speech-recognition isn't a module?
-import type { } from "@types/dom-speech-recognition";
-import { Doc, Opt } from "../../fields/Doc";
-import { List } from "../../fields/List";
-import { RichTextField } from "../../fields/RichTextField";
-import { listSpec } from "../../fields/Schema";
-import { Cast, CastCtor } from "../../fields/Types";
-import { AudioField, ImageField } from "../../fields/URLField";
-import { Utils } from "../../Utils";
-import { Docs } from "../documents/Documents";
-import { DocumentType } from "../documents/DocumentTypes";
-import { DictationOverlay } from "../views/DictationOverlay";
-import { DocumentView } from "../views/nodes/DocumentView";
-import { SelectionManager } from "./SelectionManager";
-import { UndoManager } from "./UndoManager";
-
+import type {} from '@types/dom-speech-recognition';
+import { Doc, Opt } from '../../fields/Doc';
+import { List } from '../../fields/List';
+import { RichTextField } from '../../fields/RichTextField';
+import { listSpec } from '../../fields/Schema';
+import { Cast, CastCtor } from '../../fields/Types';
+import { AudioField, ImageField } from '../../fields/URLField';
+import { Utils } from '../../Utils';
+import { Docs } from '../documents/Documents';
+import { DocumentType } from '../documents/DocumentTypes';
+import { DictationOverlay } from '../views/DictationOverlay';
+import { DocumentView } from '../views/nodes/DocumentView';
+import { SelectionManager } from './SelectionManager';
+import { UndoManager } from './UndoManager';
 
 /**
  * This namespace provides a singleton instance of a manager that
  * handles the listening and text-conversion of user speech.
- * 
+ *
  * The basic manager functionality can be attained by the DictationManager.Controls namespace, which provide
  * a simple recording operation that returns the interpreted text as a string.
- * 
+ *
  * Additionally, however, the DictationManager also exposes the ability to execute voice commands within Dash.
  * It stores a default library of registered commands that can be triggered by listen()'ing for a phrase and then
  * passing the results into the execute() function.
- * 
+ *
  * In addition to compile-time default commands, you can invoke DictationManager.Commands.Register(Independent|Dependent)
  * to add new commands as classes or components are constructed.
  */
 export namespace DictationManager {
-
     /**
      * Some type maneuvering to access Webkit's built-in
      * speech recognizer.
@@ -42,27 +40,26 @@ export namespace DictationManager {
         }
     }
     const { webkitSpeechRecognition }: CORE.IWindow = window as any as CORE.IWindow;
-    export const placeholder = "Listening...";
+    export const placeholder = 'Listening...';
 
     export namespace Controls {
-
-        export const Infringed = "unable to process: dictation manager still involved in previous session";
+        export const Infringed = 'unable to process: dictation manager still involved in previous session';
         const browser = (() => {
             const identifier = navigator.userAgent.toLowerCase();
-            if (identifier.indexOf("safari") >= 0) {
-                return "Safari";
+            if (identifier.indexOf('safari') >= 0) {
+                return 'Safari';
             }
-            if (identifier.indexOf("chrome") >= 0) {
-                return "Chrome";
+            if (identifier.indexOf('chrome') >= 0) {
+                return 'Chrome';
             }
-            if (identifier.indexOf("firefox") >= 0) {
-                return "Firefox";
+            if (identifier.indexOf('firefox') >= 0) {
+                return 'Firefox';
             }
-            return "Unidentified Browser";
+            return 'Unidentified Browser';
         })();
         const unsupported = `listening is not supported in ${browser}`;
-        const intraSession = ". ";
-        const interSession = " ... ";
+        const intraSession = '. ';
+        const interSession = ' ... ';
 
         export let isListening = false;
         let isManuallyStopped = false;
@@ -74,7 +71,7 @@ export namespace DictationManager {
 
         export type InterimResultHandler = (results: string) => any;
         export type ContinuityArgs = { indefinite: boolean } | false;
-        export type DelimiterArgs = { inter: string, intra: string };
+        export type DelimiterArgs = { inter: string; intra: string };
         export type ListeningUIStatus = { interim: boolean } | false;
 
         export interface ListeningOptions {
@@ -105,21 +102,21 @@ export namespace DictationManager {
             try {
                 results = await (pendingListen = listenImpl(options));
                 pendingListen = undefined;
-                // if (results) {
-                //     Utils.CopyText(results);
-                //     if (overlay) {
-                //         DictationOverlay.Instance.isListening = false;
-                //         const execute = options?.tryExecute;
-                //         DictationOverlay.Instance.dictatedPhrase = execute ? results.toLowerCase() : results;
-                //         DictationOverlay.Instance.dictationSuccess = execute ? await DictationManager.Commands.execute(results) : true;
-                //     }
-                //     options?.tryExecute && await DictationManager.Commands.execute(results);
-                // }
+                if (results) {
+                    Utils.CopyText(results);
+                    if (overlay) {
+                        DictationOverlay.Instance.isListening = false;
+                        const execute = options?.tryExecute;
+                        DictationOverlay.Instance.dictatedPhrase = execute ? results.toLowerCase() : results;
+                        DictationOverlay.Instance.dictationSuccess = execute ? await DictationManager.Commands.execute(results) : true;
+                    }
+                    options?.tryExecute && (await DictationManager.Commands.execute(results));
+                }
             } catch (e: any) {
                 console.log(e);
                 if (overlay) {
                     DictationOverlay.Instance.isListening = false;
-                    DictationOverlay.Instance.dictatedPhrase = results = `dictation error: ${"error" in e ? e.error : "unknown error"}`;
+                    DictationOverlay.Instance.dictatedPhrase = results = `dictation error: ${'error' in e ? e.error : 'unknown error'}`;
                     DictationOverlay.Instance.dictationSuccess = false;
                 }
             } finally {
@@ -131,7 +128,7 @@ export namespace DictationManager {
 
         const listenImpl = (options?: Partial<ListeningOptions>) => {
             if (!recognizer) {
-                console.log("DictationManager:" + unsupported);
+                console.log('DictationManager:' + unsupported);
                 return unsupported;
             }
             if (isListening) {
@@ -146,16 +143,18 @@ export namespace DictationManager {
             const intra = options?.delimiters?.intra;
             const inter = options?.delimiters?.inter;
 
-            recognizer.onstart = () => console.log("initiating speech recognition session...");
+            recognizer.onstart = () => console.log('initiating speech recognition session...');
             recognizer.interimResults = handler !== undefined;
             recognizer.continuous = continuous === undefined ? false : continuous !== false;
-            recognizer.lang = language === undefined ? "en-US" : language;
+            recognizer.lang = language === undefined ? 'en-US' : language;
 
             recognizer.start();
 
             return new Promise<string>((resolve, reject) => {
-                recognizer.onerror = (e: any) => { // e is SpeechRecognitionError but where is that defined? 
-                    if (!(indefinite && e.error === "no-speech")) {
+                recognizer.onerror = (e: any) => {
+                    console.log('SPEECH error:', encodeURIComponent);
+                    // e is SpeechRecognitionError but where is that defined?
+                    if (!(indefinite && e.error === 'no-speech')) {
                         recognizer.stop();
                         resolve(e);
                         //reject(e);
@@ -163,9 +162,10 @@ export namespace DictationManager {
                 };
 
                 recognizer.onresult = (e: SpeechRecognitionEvent) => {
+                    console.log('RESULT: ', e);
                     current = synthesize(e, intra);
                     let matchedTerminator: string | undefined;
-                    if (options?.terminators && (matchedTerminator = options.terminators.find(end => current ? current.trim().toLowerCase().endsWith(end.toLowerCase()) : false))) {
+                    if (options?.terminators && (matchedTerminator = options.terminators.find(end => (current ? current.trim().toLowerCase().endsWith(end.toLowerCase()) : false)))) {
                         current = matchedTerminator;
                         recognizer.abort();
                         return complete();
@@ -175,6 +175,7 @@ export namespace DictationManager {
                 };
 
                 recognizer.onend = (e: Event) => {
+                    console.log('END: ', e);
                     if (!indefinite || isManuallyStopped) {
                         return complete();
                     }
@@ -187,11 +188,12 @@ export namespace DictationManager {
                 };
 
                 const complete = () => {
+                    console.log('COMPLETE:');
                     if (indefinite) {
                         current && sessionResults.push(current);
                         sessionResults.length && resolve(sessionResults.join(inter || interSession));
                     } else {
-                        resolve(current || "");
+                        resolve(current || '');
                     }
                     current = undefined;
                     sessionResults = [];
@@ -201,7 +203,6 @@ export namespace DictationManager {
                     recognizer.onerror = null;
                     recognizer.onend = null;
                 };
-
             });
         };
 
@@ -222,171 +223,173 @@ export namespace DictationManager {
             }
             return transcripts.join(delimiter || intraSession);
         };
-
     }
 
-    // export namespace Commands {
-
-    //     export const dictationFadeDuration = 2000;
-
-    //     export type IndependentAction = (target: DocumentView) => any | Promise<any>;
-    //     export type IndependentEntry = { action: IndependentAction, restrictTo?: DocumentType[] };
-
-    //     export type DependentAction = (target: DocumentView, matches: RegExpExecArray) => any | Promise<any>;
-    //     export type DependentEntry = { expression: RegExp, action: DependentAction, restrictTo?: DocumentType[] };
-
-    //     export const RegisterIndependent = (key: string, value: IndependentEntry) => Independent.set(key, value);
-    //     export const RegisterDependent = (entry: DependentEntry) => Dependent.push(entry);
-
-    //     export const execute = async (phrase: string) => {
-    //         return UndoManager.RunInBatch(async () => {
-    //             const targets = SelectionManager.Views();
-    //             if (!targets || !targets.length) {
-    //                 return;
-    //             }
-
-    //             phrase = phrase.toLowerCase();
-    //             const entry = Independent.get(phrase);
-
-    //             if (entry) {
-    //                 let success = false;
-    //                 const restrictTo = entry.restrictTo;
-    //                 for (const target of targets) {
-    //                     if (!restrictTo || validate(target, restrictTo)) {
-    //                         await entry.action(target);
-    //                         success = true;
-    //                     }
-    //                 }
-    //                 return success;
-    //             }
-
-    //             for (const entry of Dependent) {
-    //                 const regex = entry.expression;
-    //                 const matches = regex.exec(phrase);
-    //                 regex.lastIndex = 0;
-    //                 if (matches !== null) {
-    //                     let success = false;
-    //                     const restrictTo = entry.restrictTo;
-    //                     for (const target of targets) {
-    //                         if (!restrictTo || validate(target, restrictTo)) {
-    //                             await entry.action(target, matches);
-    //                             success = true;
-    //                         }
-    //                     }
-    //                     return success;
-    //                 }
-    //             }
-
-    //             return false;
-    //         }, "Execute Command");
-    //     };
-
-    //     const ConstructorMap = new Map<DocumentType, CastCtor>([
-    //         [DocumentType.COL, listSpec(Doc)],
-    //         [DocumentType.AUDIO, AudioField],
-    //         [DocumentType.IMG, ImageField],
-    //         [DocumentType.IMPORT, listSpec(Doc)],
-    //         [DocumentType.RTF, "string"]
-    //     ]);
-
-    //     const tryCast = (view: DocumentView, type: DocumentType) => {
-    //         const ctor = ConstructorMap.get(type);
-    //         if (!ctor) {
-    //             return false;
-    //         }
-    //         return Cast(Doc.GetProto(view.props.Document).data, ctor) !== undefined;
-    //     };
-
-    //     const validate = (target: DocumentView, types: DocumentType[]) => {
-    //         for (const type of types) {
-    //             if (tryCast(target, type)) {
-    //                 return true;
-    //             }
-    //         }
-    //         return false;
-    //     };
-
-    //     const interpretNumber = (number: string) => {
-    //         const initial = parseInt(number);
-    //         if (!isNaN(initial)) {
-    //             return initial;
-    //         }
-    //         const converted = interpreter.wordsToNumbers(number, { fuzzy: true });
-    //         if (converted === null) {
-    //             return NaN;
-    //         }
-    //         return typeof converted === "string" ? parseInt(converted) : converted;
-    //     };
-
-    //     const Independent = new Map<string, IndependentEntry>([
-
-    //         ["clear", {
-    //             action: (target: DocumentView) => Doc.GetProto(target.props.Document).data = new List(),
-    //             restrictTo: [DocumentType.COL]
-    //         }],
-
-    //         ["open fields", {
-    //             action: (target: DocumentView) => {
-    //                 const kvp = Docs.Create.KVPDocument(target.props.Document, { _width: 300, _height: 300 });
-    //                 target.props.addDocTab(kvp, "add:right");
-    //             }
-    //         }],
-
-    //         ["new outline", {
-    //             action: (target: DocumentView) => {
-    //                 const newBox = Docs.Create.TextDocument("", { _width: 400, _height: 200, title: "My Outline", _autoHeight: true });
-    //                 const proto = newBox.proto!;
-    //                 const prompt = "Press alt + r to start dictating here...";
-    //                 const head = 3;
-    //                 const anchor = head + prompt.length;
-    //                 const proseMirrorState = `{"doc":{"type":"doc","content":[{"type":"ordered_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"type":"text","text":"${prompt}"}]}]}]}]},"selection":{"type":"text","anchor":${anchor},"head":${head}}}`;
-    //                 proto.data = new RichTextField(proseMirrorState);
-    //                 proto.backgroundColor = "#eeffff";
-    //                 target.props.addDocTab(newBox, "add:right");
-    //             }
-    //         }]
-
-    //     ]);
-
-    //     const Dependent = new Array<DependentEntry>(
-
-    //         {
-    //             expression: /create (\w+) documents of type (image|nested collection)/g,
-    //             action: (target: DocumentView, matches: RegExpExecArray) => {
-    //                 const count = interpretNumber(matches[1]);
-    //                 const what = matches[2];
-    //                 const dataDoc = Doc.GetProto(target.props.Document);
-    //                 const fieldKey = "data";
-    //                 if (isNaN(count)) {
-    //                     return;
-    //                 }
-    //                 for (let i = 0; i < count; i++) {
-    //                     let created: Doc | undefined;
-    //                     switch (what) {
-    //                         case "image":
-    //                             created = Docs.Create.ImageDocument("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg");
-    //                             break;
-    //                         case "nested collection":
-    //                             created = Docs.Create.FreeformDocument([], {});
-    //                             break;
-    //                     }
-    //                     created && Doc.AddDocToList(dataDoc, fieldKey, created);
-    //                 }
-    //             },
-    //             restrictTo: [DocumentType.COL]
-    //         },
-
-    //         {
-    //             expression: /view as (freeform|stacking|masonry|schema|tree)/g,
-    //             action: (target: DocumentView, matches: RegExpExecArray) => {
-    //                 const mode = matches[1];
-    //                 mode && (target.props.Document._viewType = mode);
-    //             },
-    //             restrictTo: [DocumentType.COL]
-    //         }
-
-    //     );
-
-    // }
-
-}
\ No newline at end of file
+    export namespace Commands {
+        export const dictationFadeDuration = 2000;
+
+        export type IndependentAction = (target: DocumentView) => any | Promise<any>;
+        export type IndependentEntry = { action: IndependentAction; restrictTo?: DocumentType[] };
+
+        export type DependentAction = (target: DocumentView, matches: RegExpExecArray) => any | Promise<any>;
+        export type DependentEntry = { expression: RegExp; action: DependentAction; restrictTo?: DocumentType[] };
+
+        export const RegisterIndependent = (key: string, value: IndependentEntry) => Independent.set(key, value);
+        export const RegisterDependent = (entry: DependentEntry) => Dependent.push(entry);
+
+        export const execute = async (phrase: string) => {
+            return UndoManager.RunInBatch(async () => {
+                console.log('PHRASE: ' + phrase);
+                const targets = SelectionManager.Views();
+                if (!targets || !targets.length) {
+                    return;
+                }
+
+                phrase = phrase.toLowerCase();
+                const entry = Independent.get(phrase);
+
+                if (entry) {
+                    let success = false;
+                    const restrictTo = entry.restrictTo;
+                    for (const target of targets) {
+                        if (!restrictTo || validate(target, restrictTo)) {
+                            await entry.action(target);
+                            success = true;
+                        }
+                    }
+                    return success;
+                }
+
+                for (const entry of Dependent) {
+                    const regex = entry.expression;
+                    const matches = regex.exec(phrase);
+                    regex.lastIndex = 0;
+                    if (matches !== null) {
+                        let success = false;
+                        const restrictTo = entry.restrictTo;
+                        for (const target of targets) {
+                            if (!restrictTo || validate(target, restrictTo)) {
+                                await entry.action(target, matches);
+                                success = true;
+                            }
+                        }
+                        return success;
+                    }
+                }
+
+                return false;
+            }, 'Execute Command');
+        };
+
+        const ConstructorMap = new Map<DocumentType, CastCtor>([
+            [DocumentType.COL, listSpec(Doc)],
+            [DocumentType.AUDIO, AudioField],
+            [DocumentType.IMG, ImageField],
+            [DocumentType.IMPORT, listSpec(Doc)],
+            [DocumentType.RTF, 'string'],
+        ]);
+
+        const tryCast = (view: DocumentView, type: DocumentType) => {
+            const ctor = ConstructorMap.get(type);
+            if (!ctor) {
+                return false;
+            }
+            return Cast(Doc.GetProto(view.props.Document).data, ctor) !== undefined;
+        };
+
+        const validate = (target: DocumentView, types: DocumentType[]) => {
+            for (const type of types) {
+                if (tryCast(target, type)) {
+                    return true;
+                }
+            }
+            return false;
+        };
+
+        const interpretNumber = (number: string) => {
+            const initial = parseInt(number);
+            if (!isNaN(initial)) {
+                return initial;
+            }
+            const converted = interpreter.wordsToNumbers(number, { fuzzy: true });
+            if (converted === null) {
+                return NaN;
+            }
+            return typeof converted === 'string' ? parseInt(converted) : converted;
+        };
+
+        const Independent = new Map<string, IndependentEntry>([
+            [
+                'clear',
+                {
+                    action: (target: DocumentView) => (Doc.GetProto(target.props.Document).data = new List()),
+                    restrictTo: [DocumentType.COL],
+                },
+            ],
+
+            [
+                'open fields',
+                {
+                    action: (target: DocumentView) => {
+                        const kvp = Docs.Create.KVPDocument(target.props.Document, { _width: 300, _height: 300 });
+                        target.props.addDocTab(kvp, 'add:right');
+                    },
+                },
+            ],
+
+            [
+                'new outline',
+                {
+                    action: (target: DocumentView) => {
+                        const newBox = Docs.Create.TextDocument('', { _width: 400, _height: 200, title: 'My Outline', _autoHeight: true });
+                        const proto = newBox.proto!;
+                        const prompt = 'Press alt + r to start dictating here...';
+                        const head = 3;
+                        const anchor = head + prompt.length;
+                        const proseMirrorState = `{"doc":{"type":"doc","content":[{"type":"ordered_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"type":"text","text":"${prompt}"}]}]}]}]},"selection":{"type":"text","anchor":${anchor},"head":${head}}}`;
+                        proto.data = new RichTextField(proseMirrorState);
+                        proto.backgroundColor = '#eeffff';
+                        target.props.addDocTab(newBox, 'add:right');
+                    },
+                },
+            ],
+        ]);
+
+        const Dependent = new Array<DependentEntry>(
+            {
+                expression: /create (\w+) documents of type (image|nested collection)/g,
+                action: (target: DocumentView, matches: RegExpExecArray) => {
+                    const count = interpretNumber(matches[1]);
+                    const what = matches[2];
+                    const dataDoc = Doc.GetProto(target.props.Document);
+                    const fieldKey = 'data';
+                    if (isNaN(count)) {
+                        return;
+                    }
+                    for (let i = 0; i < count; i++) {
+                        let created: Doc | undefined;
+                        switch (what) {
+                            case 'image':
+                                created = Docs.Create.ImageDocument('https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg');
+                                break;
+                            case 'nested collection':
+                                created = Docs.Create.FreeformDocument([], {});
+                                break;
+                        }
+                        created && Doc.AddDocToList(dataDoc, fieldKey, created);
+                    }
+                },
+                restrictTo: [DocumentType.COL],
+            },
+
+            {
+                expression: /view as (freeform|stacking|masonry|schema|tree)/g,
+                action: (target: DocumentView, matches: RegExpExecArray) => {
+                    const mode = matches[1];
+                    mode && (target.props.Document._viewType = mode);
+                },
+                restrictTo: [DocumentType.COL],
+            }
+        );
+    }
+}
diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx
index 0db9eab69..7628beef2 100644
--- a/src/client/views/DocumentDecorations.tsx
+++ b/src/client/views/DocumentDecorations.tsx
@@ -491,7 +491,6 @@ export class DocumentDecorations extends React.Component<{ PanelWidth: number; P
                     let actualdW = Math.max(width + dW * scale, 20);
                     let actualdH = Math.max(height + dH * scale, 20);
                     const fixedAspect = nwidth && nheight && (!doc._fitWidth || e.ctrlKey || doc.nativeHeightUnfrozen);
-                    console.log(fixedAspect);
                     if (fixedAspect) {
                         if ((Math.abs(dW) > Math.abs(dH) && ((!dragBottom && !dragTop) || !modifyNativeDim)) || dragRight) {
                             if (dragRight && modifyNativeDim) {
diff --git a/src/client/views/linking/LinkMenuItem.tsx b/src/client/views/linking/LinkMenuItem.tsx
index 60428fc98..3f9db2612 100644
--- a/src/client/views/linking/LinkMenuItem.tsx
+++ b/src/client/views/linking/LinkMenuItem.tsx
@@ -6,14 +6,12 @@ import { observer } from 'mobx-react';
 import { Doc, DocListCast } from '../../../fields/Doc';
 import { Cast, StrCast } from '../../../fields/Types';
 import { WebField } from '../../../fields/URLField';
-import { emptyFunction, returnFalse, setupMoveUpEvents } from '../../../Utils';
+import { emptyFunction, setupMoveUpEvents } from '../../../Utils';
 import { DocumentType } from '../../documents/DocumentTypes';
 import { DocumentManager } from '../../util/DocumentManager';
 import { DragManager } from '../../util/DragManager';
-import { Hypothesis } from '../../util/HypothesisUtils';
 import { LinkFollower } from '../../util/LinkFollower';
 import { LinkManager } from '../../util/LinkManager';
-import { undoBatch } from '../../util/UndoManager';
 import { DocumentView } from '../nodes/DocumentView';
 import { LinkDocPreview } from '../nodes/LinkDocPreview';
 import './LinkMenuItem.scss';
diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
index 40b0d285c..849deb04e 100644
--- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx
+++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
@@ -426,28 +426,26 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
         const editorView = this._editorView;
         if (editorView && (editorView as any).docView && !Doc.AreProtosEqual(target, this.rootDoc)) {
             const autoLinkTerm = StrCast(target.title).replace(/^@/, '');
-            const flattened1 = this.findInNode(editorView, editorView.state.doc, autoLinkTerm);
             var alink: Doc | undefined;
-            flattened1.forEach((flat, i) => {
-                const flattened = this.findInNode(this._editorView!, this._editorView!.state.doc, autoLinkTerm);
-                this._searchIndex = ++this._searchIndex > flattened.length - 1 ? 0 : this._searchIndex;
+            this.findInNode(editorView, editorView.state.doc, autoLinkTerm).forEach(sel => {
                 const splitter = editorView.state.schema.marks.splitter.create({ id: Utils.GenerateGuid() });
-                const sel = flattened[i];
-                tr = tr.addMark(sel.from, sel.to, splitter);
-                tr.doc.nodesBetween(sel.from, sel.to, (node: any, pos: number, parent: any) => {
-                    if (node.firstChild === null && !node.marks.find((m: Mark) => m.type.name === schema.marks.noAutoLinkAnchor.name) && node.marks.find((m: Mark) => m.type.name === schema.marks.splitter.name)) {
-                        alink =
-                            alink ??
-                            (DocListCast(this.Document.links).find(link => Doc.AreProtosEqual(Cast(link.anchor1, Doc, null), this.rootDoc) && Doc.AreProtosEqual(Cast(link.anchor2, Doc, null), target)) ||
-                                DocUtils.MakeLink({ doc: this.props.Document }, { doc: target }, LinkManager.AutoKeywords)!);
-                        newAutoLinks.add(alink);
-                        const allAnchors = [{ href: Doc.localServerPath(target), title: 'a link', anchorId: this.props.Document[Id] }];
-                        allAnchors.push(...(node.marks.find((m: Mark) => m.type.name === schema.marks.autoLinkAnchor.name)?.attrs.allAnchors ?? []));
-                        const link = editorView.state.schema.marks.autoLinkAnchor.create({ allAnchors, title: 'auto term', location: 'add:right' });
-                        tr = tr.addMark(pos, pos + node.nodeSize, link);
-                    }
-                });
-                tr = tr.removeMark(sel.from, sel.to, splitter);
+                if (!sel.$anchor.pos || editorView.state.doc.textBetween(sel.$anchor.pos - 1, sel.$to.pos).trim() === autoLinkTerm) {
+                    tr = tr.addMark(sel.from, sel.to, splitter);
+                    tr.doc.nodesBetween(sel.from, sel.to, (node: any, pos: number, parent: any) => {
+                        if (node.firstChild === null && !node.marks.find((m: Mark) => m.type.name === schema.marks.noAutoLinkAnchor.name) && node.marks.find((m: Mark) => m.type.name === schema.marks.splitter.name)) {
+                            alink =
+                                alink ??
+                                (DocListCast(this.Document.links).find(link => Doc.AreProtosEqual(Cast(link.anchor1, Doc, null), this.rootDoc) && Doc.AreProtosEqual(Cast(link.anchor2, Doc, null), target)) ||
+                                    DocUtils.MakeLink({ doc: this.props.Document }, { doc: target }, LinkManager.AutoKeywords)!);
+                            newAutoLinks.add(alink);
+                            const allAnchors = [{ href: Doc.localServerPath(target), title: 'a link', anchorId: this.props.Document[Id] }];
+                            allAnchors.push(...(node.marks.find((m: Mark) => m.type.name === schema.marks.autoLinkAnchor.name)?.attrs.allAnchors ?? []));
+                            const link = editorView.state.schema.marks.autoLinkAnchor.create({ allAnchors, title: 'auto term', location: 'add:right' });
+                            tr = tr.addMark(pos, pos + node.nodeSize, link);
+                        }
+                    });
+                    tr = tr.removeMark(sel.from, sel.to, splitter);
+                }
             });
         }
         return tr;
@@ -841,6 +839,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
         }
     };
     recordDictation = () => {
+        console.log('RECORD DICTATIN:');
         DictationManager.Controls.listen({
             interimHandler: this.setDictationContent,
             continuous: { indefinite: false },
@@ -853,26 +852,35 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
     stopDictation = (abort: boolean) => DictationManager.Controls.stop(!abort);
 
     setDictationContent = (value: string) => {
+        console.log('DICTATION CONETNT: ' + value);
         if (this._editorView && this._recordingStart) {
+            console.log('STEP 1');
             if (this._break) {
-                const textanchor = Docs.Create.TextanchorDocument({ title: 'dictation anchor' });
-                this.addDocument(textanchor);
-                const link = DocUtils.MakeLinkToActiveAudio(() => textanchor, false).lastElement();
-                link && (Doc.GetProto(link).isDictation = true);
-                if (!link) return;
-                const audioanchor = Cast(link.anchor2, Doc, null);
-                if (!audioanchor) return;
-                audioanchor.backgroundColor = 'tan';
-                const audiotag = this._editorView.state.schema.nodes.audiotag.create({
-                    timeCode: NumCast(audioanchor._timecodeToShow),
-                    audioId: audioanchor[Id],
-                    textId: textanchor[Id],
-                });
-                Doc.GetProto(textanchor).title = 'dictation:' + audiotag.attrs.timeCode;
-                const tr = this._editorView.state.tr.insert(this._editorView.state.doc.content.size, audiotag);
-                const tr2 = tr.setSelection(TextSelection.create(tr.doc, tr.doc.content.size));
-                this._editorView.dispatch(tr.setSelection(TextSelection.create(tr2.doc, tr2.doc.content.size)));
+                console.log('BREAK');
+                const textanchorFunc = () => {
+                    const tanch = Docs.Create.TextanchorDocument({ title: 'dictation anchor' });
+                    return this.addDocument(tanch) ? tanch : undefined;
+                };
+                const link = DocUtils.MakeLinkToActiveAudio(textanchorFunc, false).lastElement();
+                if (link) {
+                    Doc.GetProto(link).isDictation = true;
+                    const audioanchor = Cast(link.anchor2, Doc, null);
+                    const textanchor = Cast(link.anchor1, Doc, null);
+                    if (audioanchor) {
+                        audioanchor.backgroundColor = 'tan';
+                        const audiotag = this._editorView.state.schema.nodes.audiotag.create({
+                            timeCode: NumCast(audioanchor._timecodeToShow),
+                            audioId: audioanchor[Id],
+                            textId: textanchor[Id],
+                        });
+                        Doc.GetProto(textanchor).title = 'dictation:' + audiotag.attrs.timeCode;
+                        const tr = this._editorView.state.tr.insert(this._editorView.state.doc.content.size, audiotag);
+                        const tr2 = tr.setSelection(TextSelection.create(tr.doc, tr.doc.content.size));
+                        this._editorView.dispatch(tr.setSelection(TextSelection.create(tr2.doc, tr2.doc.content.size)));
+                    }
+                }
             }
+            console.log('FINALIziNG');
             const from = this._editorView.state.selection.from;
             this._break = false;
             const tr = this._editorView.state.tr.insertText(value);
@@ -1468,7 +1476,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
             const editor = this._editorView!;
             const pcords = editor.posAtCoords({ left: e.clientX, top: e.clientY });
             !this.props.isSelected(true) && editor.dispatch(editor.state.tr.setSelection(new TextSelection(editor.state.doc.resolve(pcords?.pos || 0))));
-            let target = (e.target as any).parentElement; // hrefs are stored on the database of the <a> node that wraps the hyerlink <span>
+            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);
         }
@@ -1725,7 +1733,17 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
 
     @computed get audioHandle() {
         return (
-            <div className="formattedTextBox-dictation" onClick={action(e => (this._recording = !this._recording))}>
+            <div
+                className="formattedTextBox-dictation"
+                onPointerDown={e =>
+                    setupMoveUpEvents(
+                        this,
+                        e,
+                        returnFalse,
+                        emptyFunction,
+                        action(e => (this._recording = !this._recording))
+                    )
+                }>
                 <FontAwesomeIcon className="formattedTextBox-audioFont" style={{ color: this._recording ? 'red' : 'blue', transitionDelay: '0.6s', opacity: this._recording ? 1 : 0.25 }} icon={'microphone'} size="sm" />
             </div>
         );
-- 
cgit v1.2.3-70-g09d2


From f9cded6755ee236d88e21b3b2d4c6da357d059b2 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Mon, 8 Aug 2022 15:47:35 -0400
Subject: moved 5 sec anno recording button to documentButtonsBar.  made
 recording button appear only when there is one & click to play recording.

---
 src/client/util/CurrentUserUtils.ts                |  3 +-
 src/client/util/DictationManager.ts                |  4 --
 src/client/views/DocumentButtonBar.tsx             | 24 ++++++-
 src/client/views/PropertiesButtons.tsx             |  9 ---
 src/client/views/nodes/DocumentView.scss           |  6 +-
 src/client/views/nodes/DocumentView.tsx            | 82 +++++++++++++---------
 src/client/views/nodes/button/FontIconBox.tsx      |  9 ++-
 .../views/nodes/formattedText/FormattedTextBox.tsx | 12 +---
 8 files changed, 90 insertions(+), 59 deletions(-)

(limited to 'src/client/views/nodes/formattedText/FormattedTextBox.tsx')

diff --git a/src/client/util/CurrentUserUtils.ts b/src/client/util/CurrentUserUtils.ts
index 7856c913b..d19874720 100644
--- a/src/client/util/CurrentUserUtils.ts
+++ b/src/client/util/CurrentUserUtils.ts
@@ -107,7 +107,7 @@ export class CurrentUserUtils {
         const reqdClickList = reqdTempOpts.map(opts => {
             const allOpts = {...reqdClickOpts, ...opts.opts};
             const clickDoc = tempClicks ? DocListCast(tempClicks.data).find(doc => doc.title === opts.opts.title): undefined;
-            return DocUtils.AssignOpts(clickDoc, allOpts) ?? Docs.Create.ScriptingDocument(ScriptField.MakeScript(opts.script,allOpts));
+            return DocUtils.AssignOpts(clickDoc, allOpts) ?? Docs.Create.ScriptingDocument(ScriptField.MakeScript(opts.script, allOpts),allOpts);
         });
 
         const reqdOpts:DocumentOptions = { title: "child click editors", _height:75, system: true};
@@ -633,6 +633,7 @@ export class CurrentUserUtils {
             { 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_);}'}},
+            { title: "Dictate",toolTip: "Dictate",      btnType: ButtonType.ToggleButton, icon: "microphone",   scripts: {onClick:'{ return toggleDictation(_readOnly_);}'}},
         ];
     }
 
diff --git a/src/client/util/DictationManager.ts b/src/client/util/DictationManager.ts
index 13f036838..0a61f3478 100644
--- a/src/client/util/DictationManager.ts
+++ b/src/client/util/DictationManager.ts
@@ -152,7 +152,6 @@ export namespace DictationManager {
 
             return new Promise<string>((resolve, reject) => {
                 recognizer.onerror = (e: any) => {
-                    console.log('SPEECH error:', encodeURIComponent);
                     // e is SpeechRecognitionError but where is that defined?
                     if (!(indefinite && e.error === 'no-speech')) {
                         recognizer.stop();
@@ -162,7 +161,6 @@ export namespace DictationManager {
                 };
 
                 recognizer.onresult = (e: SpeechRecognitionEvent) => {
-                    console.log('RESULT: ', e);
                     current = synthesize(e, intra);
                     let matchedTerminator: string | undefined;
                     if (options?.terminators && (matchedTerminator = options.terminators.find(end => (current ? current.trim().toLowerCase().endsWith(end.toLowerCase()) : false)))) {
@@ -175,7 +173,6 @@ export namespace DictationManager {
                 };
 
                 recognizer.onend = (e: Event) => {
-                    console.log('END: ', e);
                     if (!indefinite || isManuallyStopped) {
                         return complete();
                     }
@@ -188,7 +185,6 @@ export namespace DictationManager {
                 };
 
                 const complete = () => {
-                    console.log('COMPLETE:');
                     if (indefinite) {
                         current && sessionResults.push(current);
                         sessionResults.length && resolve(sessionResults.join(inter || interSession));
diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx
index 1d4056759..265df3abc 100644
--- a/src/client/views/DocumentButtonBar.tsx
+++ b/src/client/views/DocumentButtonBar.tsx
@@ -6,7 +6,7 @@ import { observer } from 'mobx-react';
 import { Doc } from '../../fields/Doc';
 import { RichTextField } from '../../fields/RichTextField';
 import { Cast, NumCast } from '../../fields/Types';
-import { emptyFunction, setupMoveUpEvents, simulateMouseClick } from '../../Utils';
+import { emptyFunction, returnFalse, setupMoveUpEvents, simulateMouseClick } from '../../Utils';
 import { GoogleAuthenticationManager } from '../apis/GoogleAuthenticationManager';
 import { Pulls, Pushes } from '../apis/google_docs/GoogleApiClientUtils';
 import { Docs } from '../documents/Documents';
@@ -334,6 +334,27 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV
             </Tooltip>
         );
     }
+
+    @observable _isRecording = false;
+    @computed
+    get recordButton() {
+        const targetDoc = this.view0?.props.Document;
+        return !targetDoc ? null : (
+            <Tooltip title={<div className="dash-tooltip">{'Click to record 5 second annotation'}</div>}>
+                <div
+                    className="documentButtonBar-icon"
+                    style={{ backgroundColor: this._isRecording ? 'red' : targetDoc.isLinkButton ? Colors.LIGHT_BLUE : Colors.DARK_GRAY, color: targetDoc.isLinkButton ? Colors.BLACK : Colors.WHITE }}
+                    onClick={undoBatch(
+                        action(e => {
+                            this._isRecording = true;
+                            this.props.views().map(view => view?.docView?.recordAudioAnnotation(action(() => (this._isRecording = false))));
+                        })
+                    )}>
+                    <FontAwesomeIcon className="documentdecorations-icon" size="sm" icon="microphone" />
+                </div>
+            </Tooltip>
+        );
+    }
     @observable _aliasDown = false;
     onTemplateButton = action((e: React.PointerEvent): void => {
         this._tooltipOpen = false;
@@ -411,6 +432,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV
                         <DocumentLinksButton View={this.view0} AlwaysOn={true} InMenu={true} StartLink={false} />
                     </div>
                 ) : null}
+                <div className="documentButtonBar-button">{this.recordButton}</div>
                 {
                     Doc.noviceMode ? null : <div className="documentButtonBar-button">{this.templateButton}</div>
                     /*<div className="documentButtonBar-button">
diff --git a/src/client/views/PropertiesButtons.tsx b/src/client/views/PropertiesButtons.tsx
index 39e7b89c1..80c2c7705 100644
--- a/src/client/views/PropertiesButtons.tsx
+++ b/src/client/views/PropertiesButtons.tsx
@@ -68,14 +68,6 @@ export class PropertiesButtons extends React.Component<{}, {}> {
             on => 'thumbtack'
         );
     }
-    @computed get dictationButton() {
-        return this.propertyToggleBtn(
-            'Dictate',
-            '_showAudio',
-            on => `${on ? 'Hide' : 'Show'} dictation/recording controls`,
-            on => 'microphone'
-        );
-    }
     @computed get maskButton() {
         return this.propertyToggleBtn(
             'Mask',
@@ -365,7 +357,6 @@ export class PropertiesButtons extends React.Component<{}, {}> {
                 {toggle(this.titleButton)}
                 {toggle(this.captionButton)}
                 {toggle(this.lockButton)}
-                {toggle(this.dictationButton, { display: isNovice ? 'none' : '' })}
                 {toggle(this.onClickButton)}
                 {toggle(this.fitWidthButton)}
                 {toggle(this.freezeThumb)}
diff --git a/src/client/views/nodes/DocumentView.scss b/src/client/views/nodes/DocumentView.scss
index c02692bfb..6ea697a2f 100644
--- a/src/client/views/nodes/DocumentView.scss
+++ b/src/client/views/nodes/DocumentView.scss
@@ -65,11 +65,13 @@
         width: 25px;
         height: 25;
         position: absolute;
-        top: 10px;
-        left: 10px;
+        top: 0;
+        left: 50%;
         border-radius: 25px;
         background: white;
         opacity: 0.3;
+        pointer-events: all;
+        cursor: default;
 
         svg {
             width: 90% !important;
diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx
index 2524d66dd..4b2bd07ef 100644
--- a/src/client/views/nodes/DocumentView.tsx
+++ b/src/client/views/nodes/DocumentView.tsx
@@ -10,7 +10,7 @@ import { List } from '../../../fields/List';
 import { ObjectField } from '../../../fields/ObjectField';
 import { listSpec } from '../../../fields/Schema';
 import { ScriptField } from '../../../fields/ScriptField';
-import { BoolCast, Cast, ImageCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
+import { BoolCast, Cast, DocCast, ImageCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
 import { AudioField } from '../../../fields/URLField';
 import { GetEffectiveAcl, SharingPermissions, TraceMobx } from '../../../fields/util';
 import { MobileInterface } from '../../../mobile/MobileInterface';
@@ -52,6 +52,8 @@ import { RadialMenu } from './RadialMenu';
 import { ScriptingBox } from './ScriptingBox';
 import { PresBox } from './trails/PresBox';
 import React = require('react');
+import { DictationManager } from '../../util/DictationManager';
+import { Tooltip } from '@material-ui/core';
 const { Howl } = require('howler');
 
 interface Window {
@@ -1005,16 +1007,16 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
     linkButtonInverseScaling = () => (this.props.NativeDimScaling?.() || 1) * this.props.DocumentView().screenToLocalTransform().Scale;
     @computed get contents() {
         TraceMobx();
-        const audioView = !this.layoutDoc._showAudio ? null : (
-            <div className="documentView-audioBackground" onPointerDown={this.recordAudioAnnotation} onPointerEnter={this.onPointerEnter}>
-                <FontAwesomeIcon
-                    className="documentView-audioFont"
-                    style={{ color: [DocListCast(this.dataDoc[this.LayoutFieldKey + '-audioAnnotations']).length ? 'blue' : 'gray', 'green', 'red'][this._mediaState] }}
-                    icon={!DocListCast(this.dataDoc[this.LayoutFieldKey + '-audioAnnotations']).length ? 'microphone' : 'file-audio'}
-                    size="sm"
-                />
-            </div>
-        );
+        const audioAnnosCount = Cast(this.dataDoc[this.LayoutFieldKey + '-audioAnnotations'], listSpec(AudioField), null)?.length;
+        const audioTextAnnos = Cast(this.dataDoc[this.LayoutFieldKey + '-audioAnnotations-text'], listSpec('string'), null);
+        const audioView =
+            (!this.props.isSelected() && !this._isHovering) || this.props.renderDepth === -1 || SnappingManager.GetIsDragging() || (!audioAnnosCount && !this._mediaState) ? null : (
+                <Tooltip title={<div>{audioTextAnnos?.lastElement()}</div>}>
+                    <div className="documentView-audioBackground" onPointerDown={this.playAnnotation}>
+                        <FontAwesomeIcon className="documentView-audioFont" style={{ color: [audioAnnosCount ? 'blue' : 'gray', 'green', 'red'][this._mediaState] }} icon={!audioAnnosCount ? 'microphone' : 'file-audio'} size="sm" />
+                    </div>
+                </Tooltip>
+            );
 
         return (
             <div
@@ -1148,26 +1150,29 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
     }
 
     @action
-    onPointerEnter = () => {
+    playAnnotation = () => {
         const self = this;
-        const audioAnnos = DocListCast(this.dataDoc[this.LayoutFieldKey + '-audioAnnotations']);
-        if (audioAnnos && audioAnnos.length && this._mediaState === 0) {
-            const anno = audioAnnos[Math.floor(Math.random() * audioAnnos.length)];
-            anno.data instanceof AudioField &&
-                new Howl({
-                    src: [anno.data.url.href],
-                    format: ['mp3'],
-                    autoplay: true,
-                    loop: false,
-                    volume: 0.5,
-                    onend: function () {
-                        runInAction(() => (self._mediaState = 0));
-                    },
-                });
+        const audioAnnos = Cast(this.dataDoc[this.LayoutFieldKey + '-audioAnnotations'], listSpec(AudioField), null);
+        const anno = audioAnnos.lastElement();
+        if (anno instanceof AudioField && this._mediaState === 0) {
+            new Howl({
+                src: [anno.url.href],
+                format: ['mp3'],
+                autoplay: true,
+                loop: false,
+                volume: 0.5,
+                onend: function () {
+                    runInAction(() => {
+                        console.log('PLAYED');
+                        self._mediaState = 0;
+                    });
+                },
+            });
             this._mediaState = 1;
         }
     };
-    recordAudioAnnotation = () => {
+
+    recordAudioAnnotation = (onEnd?: () => void) => {
         let gumStream: any;
         let recorder: any;
         const self = this;
@@ -1176,18 +1181,30 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
                 audio: true,
             })
             .then(function (stream) {
+                let audioTextAnnos = Cast(self.dataDoc[self.LayoutFieldKey + '-audioAnnotations-text'], listSpec('string'), null);
+                if (audioTextAnnos) audioTextAnnos.push('');
+                else audioTextAnnos = self.dataDoc[self.LayoutFieldKey + '-audioAnnotations-text'] = new List<string>(['']);
+                DictationManager.Controls.listen({
+                    interimHandler: value => (audioTextAnnos[audioTextAnnos.length - 1] = value),
+                    continuous: { indefinite: false },
+                }).then(results => {
+                    if (results && [DictationManager.Controls.Infringed].includes(results)) {
+                        DictationManager.Controls.stop();
+                    }
+                    onEnd?.();
+                });
+
                 gumStream = stream;
                 recorder = new MediaRecorder(stream);
                 recorder.ondataavailable = async (e: any) => {
                     const [{ result }] = await Networking.UploadFilesToServer(e.data);
                     if (!(result instanceof Error)) {
-                        const audioDoc = Docs.Create.AudioDocument(result.accessPaths.agnostic.client, { title: 'audio test', _width: 200, _height: 32 });
-                        audioDoc.treeViewExpandedView = 'layout';
-                        const audioAnnos = Cast(self.dataDoc[self.LayoutFieldKey + '-audioAnnotations'], listSpec(Doc));
+                        const audioField = new AudioField(result.accessPaths.agnostic.client);
+                        const audioAnnos = Cast(self.dataDoc[self.LayoutFieldKey + '-audioAnnotations'], listSpec(AudioField), null);
                         if (audioAnnos === undefined) {
-                            self.dataDoc[self.LayoutFieldKey + '-audioAnnotations'] = new List([audioDoc]);
+                            self.dataDoc[self.LayoutFieldKey + '-audioAnnotations'] = new List([audioField]);
                         } else {
-                            audioAnnos.push(audioDoc);
+                            audioAnnos.push(audioField);
                         }
                     }
                 };
@@ -1195,6 +1212,7 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
                 recorder.start();
                 setTimeout(() => {
                     recorder.stop();
+                    DictationManager.Controls.stop(false);
                     runInAction(() => (self._mediaState = 0));
                     gumStream.getAudioTracks()[0].stop();
                 }, 5000);
diff --git a/src/client/views/nodes/button/FontIconBox.tsx b/src/client/views/nodes/button/FontIconBox.tsx
index 78ef85ec2..d3b95e25a 100644
--- a/src/client/views/nodes/button/FontIconBox.tsx
+++ b/src/client/views/nodes/button/FontIconBox.tsx
@@ -1,7 +1,7 @@
 import { IconProp } from '@fortawesome/fontawesome-svg-core';
 import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
 import { Tooltip } from '@material-ui/core';
-import { action, computed, observable } from 'mobx';
+import { action, computed, observable, runInAction } from 'mobx';
 import { observer } from 'mobx-react';
 import * as React from 'react';
 import { ColorState, SketchPicker } from 'react-color';
@@ -710,6 +710,13 @@ ScriptingGlobals.add(function toggleNoAutoLinkAnchor(checkResult?: boolean) {
     }
     if (editorView) RichTextMenu.Instance?.toggleNoAutoLinkAnchor();
 });
+ScriptingGlobals.add(function toggleDictation(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;
diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
index 849deb04e..929cca1ea 100644
--- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx
+++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
@@ -771,7 +771,6 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
         const uicontrols: ContextMenuProps[] = [];
         !Doc.noviceMode && uicontrols.push({ description: `${FormattedTextBox._canAnnotate ? "Don't" : ''} Show Menu on Selections`, event: () => (FormattedTextBox._canAnnotate = !FormattedTextBox._canAnnotate), icon: 'expand-arrows-alt' });
         uicontrols.push({ description: !this.Document._noSidebar ? 'Hide Sidebar Handle' : 'Show Sidebar Handle', event: () => (this.layoutDoc._noSidebar = !this.layoutDoc._noSidebar), icon: 'expand-arrows-alt' });
-        uicontrols.push({ description: `${this.layoutDoc._showAudio ? 'Hide' : 'Show'} Dictation Icon`, event: () => (this.layoutDoc._showAudio = !this.layoutDoc._showAudio), icon: 'expand-arrows-alt' });
         uicontrols.push({ description: 'Show Highlights...', noexpand: true, subitems: highlighting, icon: 'hand-point-right' });
         !Doc.noviceMode &&
             uicontrols.push({
@@ -839,7 +838,6 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
         }
     };
     recordDictation = () => {
-        console.log('RECORD DICTATIN:');
         DictationManager.Controls.listen({
             interimHandler: this.setDictationContent,
             continuous: { indefinite: false },
@@ -852,11 +850,8 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
     stopDictation = (abort: boolean) => DictationManager.Controls.stop(!abort);
 
     setDictationContent = (value: string) => {
-        console.log('DICTATION CONETNT: ' + value);
         if (this._editorView && this._recordingStart) {
-            console.log('STEP 1');
             if (this._break) {
-                console.log('BREAK');
                 const textanchorFunc = () => {
                     const tanch = Docs.Create.TextanchorDocument({ title: 'dictation anchor' });
                     return this.addDocument(tanch) ? tanch : undefined;
@@ -880,7 +875,6 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
                     }
                 }
             }
-            console.log('FINALIziNG');
             const from = this._editorView.state.selection.from;
             this._break = false;
             const tr = this._editorView.state.tr.insertText(value);
@@ -1732,7 +1726,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
             .scale(1 / NumCast(this.layoutDoc._viewScale, 1) / (this.props.NativeDimScaling?.() || 1));
 
     @computed get audioHandle() {
-        return (
+        return !this._recording ? null : (
             <div
                 className="formattedTextBox-dictation"
                 onPointerDown={e =>
@@ -1744,7 +1738,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
                         action(e => (this._recording = !this._recording))
                     )
                 }>
-                <FontAwesomeIcon className="formattedTextBox-audioFont" style={{ color: this._recording ? 'red' : 'blue', transitionDelay: '0.6s', opacity: this._recording ? 1 : 0.25 }} icon={'microphone'} size="sm" />
+                <FontAwesomeIcon className="formattedTextBox-audioFont" style={{ color: 'red' }} icon={'microphone'} size="sm" />
             </div>
         );
     }
@@ -1898,7 +1892,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
                     </div>
                     {this.noSidebar || this.props.dontSelectOnLoad || !this.SidebarShown || this.sidebarWidthPercent === '0%' ? null : this.sidebarCollection}
                     {this.noSidebar || this.Document._noSidebar || this.props.dontSelectOnLoad || this.Document._singleLine ? null : this.sidebarHandle}
-                    {!this.layoutDoc._showAudio ? null : this.audioHandle}
+                    {this.audioHandle}
                 </div>
             </div>
         );
-- 
cgit v1.2.3-70-g09d2


From bca0026764fe554e1066b2f432e749371450d239 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Tue, 9 Aug 2022 11:35:00 -0400
Subject: added an audio annotation button to the anchor menu bar.

---
 src/client/views/DocumentButtonBar.tsx             |  12 +-
 src/client/views/MarqueeAnnotator.tsx              |   1 +
 src/client/views/SidebarAnnos.tsx                  |   1 +
 src/client/views/nodes/DocumentView.tsx            |  35 ++--
 .../views/nodes/formattedText/FormattedTextBox.tsx |  11 ++
 src/client/views/pdf/AnchorMenu.tsx                |  14 ++
 src/fields/documentSchemas.ts                      | 182 ++++++++++-----------
 7 files changed, 145 insertions(+), 111 deletions(-)

(limited to 'src/client/views/nodes/formattedText/FormattedTextBox.tsx')

diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx
index 265df3abc..81e417fca 100644
--- a/src/client/views/DocumentButtonBar.tsx
+++ b/src/client/views/DocumentButtonBar.tsx
@@ -21,7 +21,7 @@ import './DocumentButtonBar.scss';
 import { Colors } from './global/globalEnums';
 import { MetadataEntryMenu } from './MetadataEntryMenu';
 import { DocumentLinksButton } from './nodes/DocumentLinksButton';
-import { DocumentView } from './nodes/DocumentView';
+import { DocumentView, DocumentViewInternal } from './nodes/DocumentView';
 import { DashFieldView } from './nodes/formattedText/DashFieldView';
 import { GoogleRef } from './nodes/formattedText/FormattedTextBox';
 import { TemplateMenu } from './TemplateMenu';
@@ -347,7 +347,15 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV
                     onClick={undoBatch(
                         action(e => {
                             this._isRecording = true;
-                            this.props.views().map(view => view?.docView?.recordAudioAnnotation(action(() => (this._isRecording = false))));
+                            this.props.views().map(
+                                view =>
+                                    view &&
+                                    DocumentViewInternal.recordAudioAnnotation(
+                                        view.dataDoc,
+                                        view.LayoutFieldKey,
+                                        action(() => (this._isRecording = false))
+                                    )
+                            );
                         })
                     )}>
                     <FontAwesomeIcon className="documentdecorations-icon" size="sm" icon="microphone" />
diff --git a/src/client/views/MarqueeAnnotator.tsx b/src/client/views/MarqueeAnnotator.tsx
index b01ee5f42..f90ad8bb5 100644
--- a/src/client/views/MarqueeAnnotator.tsx
+++ b/src/client/views/MarqueeAnnotator.tsx
@@ -65,6 +65,7 @@ export class MarqueeAnnotator extends React.Component<MarqueeAnnotatorProps> {
 
         AnchorMenu.Instance.OnCrop = (e: PointerEvent) => this.props.anchorMenuCrop?.(this.highlight('rgba(173, 216, 230, 0.75)', true), true);
         AnchorMenu.Instance.OnClick = (e: PointerEvent) => this.props.anchorMenuClick?.()?.(this.highlight('rgba(173, 216, 230, 0.75)', true));
+        AnchorMenu.Instance.OnAudio = unimplementedFunction;
         AnchorMenu.Instance.Highlight = this.highlight;
         AnchorMenu.Instance.GetAnchor = (savedAnnotations?: ObservableMap<number, HTMLDivElement[]>) => this.highlight('rgba(173, 216, 230, 0.75)', true, savedAnnotations);
         AnchorMenu.Instance.onMakeAnchor = AnchorMenu.Instance.GetAnchor;
diff --git a/src/client/views/SidebarAnnos.tsx b/src/client/views/SidebarAnnos.tsx
index 1c14c7cd5..90d9c3c43 100644
--- a/src/client/views/SidebarAnnos.tsx
+++ b/src/client/views/SidebarAnnos.tsx
@@ -74,6 +74,7 @@ export class SidebarAnnos extends React.Component<FieldViewProps & ExtraProps> {
         DocUtils.MakeLink({ doc: anchor }, { doc: target }, 'inline comment:comment on');
         this.addDocument(target);
         this._stackRef.current?.focusDocument(target);
+        return target;
     };
     makeDocUnfiltered = (doc: Doc) => {
         if (DocListCast(this.props.rootDoc[this.sidebarKey]).includes(doc)) {
diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx
index 4b2bd07ef..f87581875 100644
--- a/src/client/views/nodes/DocumentView.tsx
+++ b/src/client/views/nodes/DocumentView.tsx
@@ -206,7 +206,6 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
     public static SelectAfterContextMenu = true; //  whether a document should be selected after it's contextmenu is triggered.
     _animateScaleTime = 300; // milliseconds;
     @observable _animateScalingTo = 0;
-    @observable _mediaState = 0;
     @observable _pendingDoubleClick = false;
     private _disposers: { [name: string]: IReactionDisposer } = {};
     private _downX: number = 0;
@@ -879,7 +878,6 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
             !appearance && cm.addItem({ description: 'UI Controls...', subitems: appearanceItems, icon: 'compass' });
 
             if (!Doc.IsSystem(this.rootDoc) && this.rootDoc._viewType !== CollectionViewType.Docking && this.props.ContainingCollectionDoc?._viewType !== CollectionViewType.Tree) {
-                !Doc.noviceMode && appearanceItems.splice(0, 0, { description: `${!this.layoutDoc._showAudio ? 'Show' : 'Hide'} Audio Button`, event: action(() => (this.layoutDoc._showAudio = !this.layoutDoc._showAudio)), icon: 'microphone' });
                 const existingOnClick = cm.findByDescription('OnClick...');
                 const onClicks: ContextMenuProps[] = existingOnClick && 'subitems' in existingOnClick ? existingOnClick.subitems : [];
 
@@ -1010,10 +1008,15 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
         const audioAnnosCount = Cast(this.dataDoc[this.LayoutFieldKey + '-audioAnnotations'], listSpec(AudioField), null)?.length;
         const audioTextAnnos = Cast(this.dataDoc[this.LayoutFieldKey + '-audioAnnotations-text'], listSpec('string'), null);
         const audioView =
-            (!this.props.isSelected() && !this._isHovering) || this.props.renderDepth === -1 || SnappingManager.GetIsDragging() || (!audioAnnosCount && !this._mediaState) ? null : (
+            (!this.props.isSelected() && !this._isHovering && this.dataDoc.audioAnnoState !== 2) || this.props.renderDepth === -1 || SnappingManager.GetIsDragging() || (!audioAnnosCount && !this.dataDoc.audioAnnoState) ? null : (
                 <Tooltip title={<div>{audioTextAnnos?.lastElement()}</div>}>
                     <div className="documentView-audioBackground" onPointerDown={this.playAnnotation}>
-                        <FontAwesomeIcon className="documentView-audioFont" style={{ color: [audioAnnosCount ? 'blue' : 'gray', 'green', 'red'][this._mediaState] }} icon={!audioAnnosCount ? 'microphone' : 'file-audio'} size="sm" />
+                        <FontAwesomeIcon
+                            className="documentView-audioFont"
+                            style={{ color: [audioAnnosCount ? 'blue' : 'gray', 'green', 'red'][NumCast(this.dataDoc.audioAnnoState)] }}
+                            icon={!audioAnnosCount ? 'microphone' : 'file-audio'}
+                            size="sm"
+                        />
                     </div>
                 </Tooltip>
             );
@@ -1154,7 +1157,7 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
         const self = this;
         const audioAnnos = Cast(this.dataDoc[this.LayoutFieldKey + '-audioAnnotations'], listSpec(AudioField), null);
         const anno = audioAnnos.lastElement();
-        if (anno instanceof AudioField && this._mediaState === 0) {
+        if (anno instanceof AudioField && this.dataDoc.audioAnnoState === 0) {
             new Howl({
                 src: [anno.url.href],
                 format: ['mp3'],
@@ -1163,27 +1166,25 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
                 volume: 0.5,
                 onend: function () {
                     runInAction(() => {
-                        console.log('PLAYED');
-                        self._mediaState = 0;
+                        self.dataDoc.audioAnnoState = 0;
                     });
                 },
             });
-            this._mediaState = 1;
+            this.dataDoc.audioAnnoState = 1;
         }
     };
 
-    recordAudioAnnotation = (onEnd?: () => void) => {
+    static recordAudioAnnotation(dataDoc: Doc, field: string, onEnd?: () => void) {
         let gumStream: any;
         let recorder: any;
-        const self = this;
         navigator.mediaDevices
             .getUserMedia({
                 audio: true,
             })
             .then(function (stream) {
-                let audioTextAnnos = Cast(self.dataDoc[self.LayoutFieldKey + '-audioAnnotations-text'], listSpec('string'), null);
+                let audioTextAnnos = Cast(dataDoc[field + '-audioAnnotations-text'], listSpec('string'), null);
                 if (audioTextAnnos) audioTextAnnos.push('');
-                else audioTextAnnos = self.dataDoc[self.LayoutFieldKey + '-audioAnnotations-text'] = new List<string>(['']);
+                else audioTextAnnos = dataDoc[field + '-audioAnnotations-text'] = new List<string>(['']);
                 DictationManager.Controls.listen({
                     interimHandler: value => (audioTextAnnos[audioTextAnnos.length - 1] = value),
                     continuous: { indefinite: false },
@@ -1200,24 +1201,24 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps
                     const [{ result }] = await Networking.UploadFilesToServer(e.data);
                     if (!(result instanceof Error)) {
                         const audioField = new AudioField(result.accessPaths.agnostic.client);
-                        const audioAnnos = Cast(self.dataDoc[self.LayoutFieldKey + '-audioAnnotations'], listSpec(AudioField), null);
+                        const audioAnnos = Cast(dataDoc[field + '-audioAnnotations'], listSpec(AudioField), null);
                         if (audioAnnos === undefined) {
-                            self.dataDoc[self.LayoutFieldKey + '-audioAnnotations'] = new List([audioField]);
+                            dataDoc[field + '-audioAnnotations'] = new List([audioField]);
                         } else {
                             audioAnnos.push(audioField);
                         }
                     }
                 };
-                runInAction(() => (self._mediaState = 2));
+                runInAction(() => (dataDoc.audioAnnoState = 2));
                 recorder.start();
                 setTimeout(() => {
                     recorder.stop();
                     DictationManager.Controls.stop(false);
-                    runInAction(() => (self._mediaState = 0));
+                    runInAction(() => (dataDoc.audioAnnoState = 0));
                     gumStream.getAudioTracks()[0].stop();
                 }, 5000);
             });
-    };
+    }
 
     captionStyleProvider = (doc: Opt<Doc>, props: Opt<DocumentViewInternalProps>, property: string) => this.props?.styleProvider?.(doc, props, property + ':caption');
     @computed get innards() {
diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
index 929cca1ea..223441b3b 100644
--- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx
+++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
@@ -63,6 +63,7 @@ import applyDevTools = require('prosemirror-dev-tools');
 import React = require('react');
 import { text } from 'body-parser';
 import { CollectionTreeView } from '../../collections/CollectionTreeView';
+import { DocumentViewInternal } from '../DocumentView';
 const translateGoogleApi = require('translate-google-api');
 
 export interface FormattedTextBoxProps {
@@ -249,6 +250,16 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
             !this.layoutDoc.showSidebar && this.toggleSidebar();
             this._sidebarRef.current?.anchorMenuClick(this.getAnchor());
         };
+        AnchorMenu.Instance.OnAudio = (e: PointerEvent) => {
+            !this.layoutDoc.showSidebar && this.toggleSidebar();
+            const anchor = this.getAnchor();
+            const target = this._sidebarRef.current?.anchorMenuClick(anchor);
+            if (target) {
+                anchor.followLinkAudio = true;
+                DocumentViewInternal.recordAudioAnnotation(Doc.GetProto(target), Doc.LayoutFieldKey(target));
+                target.title = ComputedField.MakeFunction(`self["text-audioAnnotations-text"].lastElement()`);
+            }
+        };
         AnchorMenu.Instance.Highlight = action((color: string, isLinkButton: boolean) => {
             this._editorView?.state && RichTextMenu.Instance.setHighlight(color, this._editorView, this._editorView?.dispatch);
             return undefined;
diff --git a/src/client/views/pdf/AnchorMenu.tsx b/src/client/views/pdf/AnchorMenu.tsx
index 1a1120b6c..ee2ae10a7 100644
--- a/src/client/views/pdf/AnchorMenu.tsx
+++ b/src/client/views/pdf/AnchorMenu.tsx
@@ -49,6 +49,7 @@ export class AnchorMenu extends AntimodeMenu<AntimodeMenuProps> {
 
     public OnCrop: (e: PointerEvent) => void = unimplementedFunction;
     public OnClick: (e: PointerEvent) => void = unimplementedFunction;
+    public OnAudio: (e: PointerEvent) => void = unimplementedFunction;
     public StartDrag: (e: PointerEvent, ele: HTMLElement) => void = unimplementedFunction;
     public StartCropDrag: (e: PointerEvent, ele: HTMLElement) => void = unimplementedFunction;
     public Highlight: (color: string, isPushpin: boolean) => Opt<Doc> = (color: string, isPushpin: boolean) => undefined;
@@ -92,6 +93,10 @@ export class AnchorMenu extends AntimodeMenu<AntimodeMenuProps> {
         );
     };
 
+    audioDown = (e: React.PointerEvent) => {
+        setupMoveUpEvents(this, e, returnFalse, returnFalse, e => this.OnAudio?.(e));
+    };
+
     cropDown = (e: React.PointerEvent) => {
         setupMoveUpEvents(
             this,
@@ -196,6 +201,15 @@ export class AnchorMenu extends AntimodeMenu<AntimodeMenuProps> {
                               <FontAwesomeIcon icon="comment-alt" size="lg" />
                           </button>
                       </Tooltip>,
+                      AnchorMenu.Instance.OnAudio === unimplementedFunction ? (
+                          <></>
+                      ) : (
+                          <Tooltip key="annoaudiotate" title={<div className="dash-tooltip">{'Click to Record Annotation'}</div>}>
+                              <button className="antimodeMenu-button annotate" onPointerDown={this.audioDown} style={{ cursor: 'grab' }}>
+                                  <FontAwesomeIcon icon="microphone" size="lg" />
+                              </button>
+                          </Tooltip>
+                      ),
                       //NOTE: link popup is currently in progress
                       <Tooltip key="link" title={<div className="dash-tooltip">{'Find document to link to selected text'}</div>}>
                           <button className="antimodeMenu-button link" onPointerDown={this.toggleLinkPopup} style={{}}>
diff --git a/src/fields/documentSchemas.ts b/src/fields/documentSchemas.ts
index be39e0709..24b5a359d 100644
--- a/src/fields/documentSchemas.ts
+++ b/src/fields/documentSchemas.ts
@@ -1,116 +1,114 @@
-import { makeInterface, createSchema, listSpec } from "./Schema";
-import { ScriptField } from "./ScriptField";
-import { Doc } from "./Doc";
-import { DateField } from "./DateField";
-import { SchemaHeaderField } from "./SchemaHeaderField";
+import { makeInterface, createSchema, listSpec } from './Schema';
+import { ScriptField } from './ScriptField';
+import { Doc } from './Doc';
+import { DateField } from './DateField';
+import { SchemaHeaderField } from './SchemaHeaderField';
 
 export const documentSchema = createSchema({
     // content properties
-    type: "string",             // enumerated type of document -- should be template-specific (ie, start with an '_')
-    title: "string",            // document title (can be on either data document or layout)
-    isTemplateForField: "string",// if specified, it indicates the document is a template that renders the specified field
-    creationDate: DateField,    // when the document was created
-    links: listSpec(Doc),       // computed (readonly) list of links associated with this document
+    type: 'string', // enumerated type of document -- should be template-specific (ie, start with an '_')
+    title: 'string', // document title (can be on either data document or layout)
+    isTemplateForField: 'string', // if specified, it indicates the document is a template that renders the specified field
+    creationDate: DateField, // when the document was created
+    links: listSpec(Doc), // computed (readonly) list of links associated with this document
 
     // "Location" properties in a very general sense
-    _curPage: "number",         // current page of a page based document
-    _currentFrame: "number",    // current frame of a frame based collection (e.g., a progressive slide)
-    lastFrame: "number",        // last frame of a frame based collection (e.g., a progressive slide)
-    activeFrame: "number",      // the active frame of a frame based animated document 
-    _currentTimecode: "number", // current play back time of a temporal document (video / audio)
-    _timecodeToShow: "number",  // the time that a document should be displayed (e.g., time an annotation should be displayed on a video)
-    _timecodeToHIde: "number",  // the time that a document should be hidden
-    markers: listSpec(Doc),     // list of markers for audio / video
-    x: "number",                // x coordinate when in a freeform view 
-    y: "number",                // y coordinate when in a freeform view 
-    z: "number",                // z "coordinate" - non-zero specifies the overlay layer of a freeformview
-    zIndex: "number",           // zIndex of a document in a freeform view
-    _scrollTop: "number",       // scroll position of a scrollable document (pdf, text, web)
-    lat: "number",
-    lng: "number",
+    _curPage: 'number', // current page of a page based document
+    _currentFrame: 'number', // current frame of a frame based collection (e.g., a progressive slide)
+    lastFrame: 'number', // last frame of a frame based collection (e.g., a progressive slide)
+    activeFrame: 'number', // the active frame of a frame based animated document
+    _currentTimecode: 'number', // current play back time of a temporal document (video / audio)
+    _timecodeToShow: 'number', // the time that a document should be displayed (e.g., time an annotation should be displayed on a video)
+    _timecodeToHIde: 'number', // the time that a document should be hidden
+    markers: listSpec(Doc), // list of markers for audio / video
+    x: 'number', // x coordinate when in a freeform view
+    y: 'number', // y coordinate when in a freeform view
+    z: 'number', // z "coordinate" - non-zero specifies the overlay layer of a freeformview
+    zIndex: 'number', // zIndex of a document in a freeform view
+    _scrollTop: 'number', // scroll position of a scrollable document (pdf, text, web)
+    lat: 'number',
+    lng: 'number',
 
     // appearance properties on the layout
-    "_backgroundGrid-spacing": "number", // the size of the grid for collection views
-    _autoHeight: "boolean",     // whether the height of the document should be computed automatically based on its contents
-    _nativeWidth: "number",     // native width of document which determines how much document contents are scaled when the document's width is set
-    _nativeHeight: "number",    // "
-    _width: "number",           // width of document in its container's coordinate system
-    _height: "number",          // "
-    _xPadding: "number",        // pixels of padding on left/right of collectionfreeformview contents when fitContentsToBox is set
-    _yPadding: "number",        // pixels of padding on top/bottom of collectionfreeformview contents when fitContentsToBox is set
-    _xMargin: "number",         // margin added on left/right of most documents to add separation from their container
-    _yMargin: "number",         // margin added on top/bottom of most documents to add separation from their container
-    _overflow: "string",        // sets overflow behvavior for CollectionFreeForm views
-    _showCaption: "string",     // whether editable caption text is overlayed at the bottom of the document 
-    _showTitle: "string",       // the fieldkey(s) whose contents should be displayed at the top of the document. separate multiple keys with ";".  Use :hover suffix to indicate title should be shown on hover
-    _showAudio: "boolean",      // whether to show the audio record icon on documents
-    _pivotField: "string",      // specifies which field key should be used as the timeline/pivot axis
-    _columnsFill: "boolean",    // whether documents in a stacking view column should be sized to fill the column
-    _columnsSort: "string",     // how a document should be sorted "ascending", "descending", undefined (none)   
-    _columnsHideIfEmpty: "boolean",   // whether empty stacking view column headings should be hidden
+    '_backgroundGrid-spacing': 'number', // the size of the grid for collection views
+    _autoHeight: 'boolean', // whether the height of the document should be computed automatically based on its contents
+    _nativeWidth: 'number', // native width of document which determines how much document contents are scaled when the document's width is set
+    _nativeHeight: 'number', // "
+    _width: 'number', // width of document in its container's coordinate system
+    _height: 'number', // "
+    _xPadding: 'number', // pixels of padding on left/right of collectionfreeformview contents when fitContentsToBox is set
+    _yPadding: 'number', // pixels of padding on top/bottom of collectionfreeformview contents when fitContentsToBox is set
+    _xMargin: 'number', // margin added on left/right of most documents to add separation from their container
+    _yMargin: 'number', // margin added on top/bottom of most documents to add separation from their container
+    _overflow: 'string', // sets overflow behvavior for CollectionFreeForm views
+    _showCaption: 'string', // whether editable caption text is overlayed at the bottom of the document
+    _showTitle: 'string', // the fieldkey(s) whose contents should be displayed at the top of the document. separate multiple keys with ";".  Use :hover suffix to indicate title should be shown on hover
+    _pivotField: 'string', // specifies which field key should be used as the timeline/pivot axis
+    _columnsFill: 'boolean', // whether documents in a stacking view column should be sized to fill the column
+    _columnsSort: 'string', // how a document should be sorted "ascending", "descending", undefined (none)
+    _columnsHideIfEmpty: 'boolean', // whether empty stacking view column headings should be hidden
     _columnHeaders: listSpec(SchemaHeaderField), // header descriptions for stacking/masonry
     _schemaHeaders: listSpec(SchemaHeaderField), // header descriptions for schema views
-    _fontSize: "string",
-    _fontFamily: "string",
-    _sidebarWidthPercent: "string", // percent of text window width taken up by sidebar
+    _fontSize: 'string',
+    _fontFamily: 'string',
+    _sidebarWidthPercent: 'string', // percent of text window width taken up by sidebar
 
     // appearance properties on the data document
-    backgroundColor: "string",  // background color of document
-    borderRounding: "string",   // border radius rounding of document
-    boxShadow: "string",        // the amount of shadow around the perimeter of a document
-    color: "string",            // foreground color of document
-    fitContentsToBox: "boolean",// whether freeform view contents should be zoomed/panned to fill the area of the document view box
-    fontSize: "string",
-    hidden: "boolean",          // whether a document should not be displayed
-    isInkMask: "boolean",       // is the document a mask (ie, sits on top of other documents, has an unbounded width/height that is dark, and content uses 'hard-light' mix-blend-mode to let other documents pop through)
-    layout: "string",           // this is the native layout string for the document.  templates can be added using other fields and setting layoutKey below
-    layoutKey: "string",        // holds the field key for the field that actually holds the current lyoat
-    letterSpacing: "string",
-    opacity: "number",          // opacity of document
-    strokeWidth: "number",
-    strokeBezier: "number",
-    strokeStartMarker: "string",
-    strokeEndMarker: "string",
-    strokeDash: "string",
-    textTransform: "string",
-    treeViewOpen: "boolean",    //  flag denoting whether the documents sub-tree (contents) is visible or hidden
-    treeViewExpandedView: "string", // name of field whose contents are being displayed as the document's subtree
-    treeViewExpandedViewLock: "boolean", // whether the expanded view can be changed
-    treeViewOpenIsTransient: "boolean", // ignores the treeViewOpen flag (for allowing a view to not be slaved to other views of the document)
-    treeViewType: "string", // whether tree view is an outline, file syste or (default) hierarchy. For outline, clicks edit document titles immediately since double-click opening is turned off
+    backgroundColor: 'string', // background color of document
+    borderRounding: 'string', // border radius rounding of document
+    boxShadow: 'string', // the amount of shadow around the perimeter of a document
+    color: 'string', // foreground color of document
+    fitContentsToBox: 'boolean', // whether freeform view contents should be zoomed/panned to fill the area of the document view box
+    fontSize: 'string',
+    hidden: 'boolean', // whether a document should not be displayed
+    isInkMask: 'boolean', // is the document a mask (ie, sits on top of other documents, has an unbounded width/height that is dark, and content uses 'hard-light' mix-blend-mode to let other documents pop through)
+    layout: 'string', // this is the native layout string for the document.  templates can be added using other fields and setting layoutKey below
+    layoutKey: 'string', // holds the field key for the field that actually holds the current lyoat
+    letterSpacing: 'string',
+    opacity: 'number', // opacity of document
+    strokeWidth: 'number',
+    strokeBezier: 'number',
+    strokeStartMarker: 'string',
+    strokeEndMarker: 'string',
+    strokeDash: 'string',
+    textTransform: 'string',
+    treeViewOpen: 'boolean', //  flag denoting whether the documents sub-tree (contents) is visible or hidden
+    treeViewExpandedView: 'string', // name of field whose contents are being displayed as the document's subtree
+    treeViewExpandedViewLock: 'boolean', // whether the expanded view can be changed
+    treeViewOpenIsTransient: 'boolean', // ignores the treeViewOpen flag (for allowing a view to not be slaved to other views of the document)
+    treeViewType: 'string', // whether tree view is an outline, file syste or (default) hierarchy. For outline, clicks edit document titles immediately since double-click opening is turned off
 
     // interaction and linking properties
-    ignoreClick: "boolean",     // whether documents ignores input clicks (but does not ignore manipulation and other events) 
-    onClick: ScriptField,       // script to run when document is clicked (can be overriden by an onClick prop)
+    ignoreClick: 'boolean', // whether documents ignores input clicks (but does not ignore manipulation and other events)
+    onClick: ScriptField, // script to run when document is clicked (can be overriden by an onClick prop)
     onPointerDown: ScriptField, // script to run when document is clicked (can be overriden by an onClick prop)
-    onPointerUp: ScriptField,   // script to run when document is clicked (can be overriden by an onClick prop)
-    onDragStart: ScriptField,   // script to run when document is dragged (without being selected).  the script should return the Doc to be dropped.
-    followLinkLocation: "string",// flag for where to place content when following a click interaction (e.g., add:right, inPlace, default, ) 
-    hideLinkButton: "boolean",  // whether the blue link counter button should be hidden
-    hideAllLinks: "boolean",    // whether all individual blue anchor dots should be hidden
-    linkDisplay: "boolean",     // whether a link connection should be shown between link anchor endpoints.
-    isInPlaceContainer: "boolean",// whether the marked object will display addDocTab() calls that target "inPlace" destinations
-    isLinkButton: "boolean",    // whether document functions as a link follow button to follow the first link on the document when clicked   
-    layers: listSpec("string"), // which layers the document is part of
-    _lockedPosition: "boolean",  // whether the document can be moved (dragged)
-    _lockedTransform: "boolean",// whether a freeformview can pan/zoom
-    displayArrow: "boolean", // toggles directed arrows
+    onPointerUp: ScriptField, // script to run when document is clicked (can be overriden by an onClick prop)
+    onDragStart: ScriptField, // script to run when document is dragged (without being selected).  the script should return the Doc to be dropped.
+    followLinkLocation: 'string', // flag for where to place content when following a click interaction (e.g., add:right, inPlace, default, )
+    hideLinkButton: 'boolean', // whether the blue link counter button should be hidden
+    hideAllLinks: 'boolean', // whether all individual blue anchor dots should be hidden
+    linkDisplay: 'boolean', // whether a link connection should be shown between link anchor endpoints.
+    isInPlaceContainer: 'boolean', // whether the marked object will display addDocTab() calls that target "inPlace" destinations
+    isLinkButton: 'boolean', // whether document functions as a link follow button to follow the first link on the document when clicked
+    layers: listSpec('string'), // which layers the document is part of
+    _lockedPosition: 'boolean', // whether the document can be moved (dragged)
+    _lockedTransform: 'boolean', // whether a freeformview can pan/zoom
+    displayArrow: 'boolean', // toggles directed arrows
 
     // drag drop properties
-    _stayInCollection: "boolean",// whether document can be dropped into a different collection
-    dragFactory: Doc,           // the document that serves as the "template" for the onDragStart script.  ie, to drag out copies of the dragFactory document.
-    dropAction: "string",       // override specifying what should happen when this document is dropped (can be "alias", "copy", "move")
-    targetDropAction: "string", // allows the target of a drop event to specify the dropAction ("alias", "copy", "move") NOTE: if the document is dropped within the same collection, the dropAction is coerced to 'move'
-    childDropAction: "string",  // specify the override for what should happen when the child of a collection is dragged from it and dropped (can be "alias" or "copy")
-    removeDropProperties: listSpec("string"), // properties that should be removed from the alias/copy/etc of this document when it is dropped
+    _stayInCollection: 'boolean', // whether document can be dropped into a different collection
+    dragFactory: Doc, // the document that serves as the "template" for the onDragStart script.  ie, to drag out copies of the dragFactory document.
+    dropAction: 'string', // override specifying what should happen when this document is dropped (can be "alias", "copy", "move")
+    targetDropAction: 'string', // allows the target of a drop event to specify the dropAction ("alias", "copy", "move") NOTE: if the document is dropped within the same collection, the dropAction is coerced to 'move'
+    childDropAction: 'string', // specify the override for what should happen when the child of a collection is dragged from it and dropped (can be "alias" or "copy")
+    removeDropProperties: listSpec('string'), // properties that should be removed from the alias/copy/etc of this document when it is dropped
 });
 
-
 export const collectionSchema = createSchema({
     childLayoutTemplate: Doc, // layout template to use to render children of a collecion
-    childLayoutString: "string", //layout string to use to render children of a collection
+    childLayoutString: 'string', //layout string to use to render children of a collection
     childClickedOpenTemplateView: Doc, // layout template to apply to a child when its clicked on in a collection and opened (requires onChildClick or other script to read this value and apply template)
-    childDontRegisterViews: "boolean", // whether views made of this document are registered so that they can be found when drawing links 
+    childDontRegisterViews: 'boolean', // whether views made of this document are registered so that they can be found when drawing links
     onChildClick: ScriptField, // script to run for each child when its clicked
     onChildDoubleClick: ScriptField, // script to run for each child when its clicked
     onCheckedClick: ScriptField, // script to run when a checkbox is clicked next to a child in a tree view
-- 
cgit v1.2.3-70-g09d2


From 0e8afc8e90efdf8037aa233a496e7d7bec75d908 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Tue, 9 Aug 2022 13:06:20 -0400
Subject: adjusted tootlip for showing pivot view of dashfieldview.  removed
 scrollbars for autoheight textboxes - metadata views weren't resizing
 properly.

---
 src/client/views/nodes/formattedText/DashFieldView.tsx    | 14 +++++++++-----
 src/client/views/nodes/formattedText/FormattedTextBox.tsx |  2 +-
 2 files changed, 10 insertions(+), 6 deletions(-)

(limited to 'src/client/views/nodes/formattedText/FormattedTextBox.tsx')

diff --git a/src/client/views/nodes/formattedText/DashFieldView.tsx b/src/client/views/nodes/formattedText/DashFieldView.tsx
index 8c8b74560..d2f7b5677 100644
--- a/src/client/views/nodes/formattedText/DashFieldView.tsx
+++ b/src/client/views/nodes/formattedText/DashFieldView.tsx
@@ -216,7 +216,7 @@ export class DashFieldViewInternal extends React.Component<IDashFieldViewInterna
     onPointerDownLabelSpan = (e: any) => {
         setupMoveUpEvents(this, e, returnFalse, returnFalse, e => {
             DashFieldViewMenu.createFieldView = this.createPivotForField;
-            DashFieldViewMenu.Instance.show(e.clientX, e.clientY + 16);
+            DashFieldViewMenu.Instance.show(e.clientX, e.clientY + 16, this._fieldKey);
         });
     };
 
@@ -253,17 +253,21 @@ export class DashFieldViewMenu extends AntimodeMenu<AntimodeMenuProps> {
         DashFieldViewMenu.Instance.fadeOut(true);
     };
 
-    public show = (x: number, y: number) => {
+    @observable _fieldKey = '';
+
+    @action
+    public show = (x: number, y: number, fieldKey: string) => {
+        this._fieldKey = fieldKey;
         this.jumpTo(x, y, true);
         const hideMenu = () => {
             this.fadeOut(true);
-            document.removeEventListener('pointerdown', hideMenu);
+            document.removeEventListener('pointerdown', hideMenu, true);
         };
-        document.addEventListener('pointerdown', hideMenu);
+        document.addEventListener('pointerdown', hideMenu, true);
     };
     render() {
         const buttons = [
-            <Tooltip key="trash" title={<div className="dash-tooltip">{'Remove Link Anchor'}</div>}>
+            <Tooltip key="trash" title={<div className="dash-tooltip">{`Show Pivot Viewer for '${this._fieldKey}'`}</div>}>
                 <button className="antimodeMenu-button" onPointerDown={this.showFields}>
                     <FontAwesomeIcon icon="eye" size="lg" />
                 </button>
diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
index 223441b3b..e027ab0bd 100644
--- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx
+++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
@@ -1884,7 +1884,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
                         style={{
                             width: this.props.dontSelectOnLoad ? '100%' : `calc(100% - ${this.sidebarWidthPercent})`,
                             pointerEvents: !active && !SnappingManager.GetIsDragging() ? 'none' : undefined,
-                            overflow: this.layoutDoc._singleLine ? 'hidden' : undefined,
+                            overflow: this.layoutDoc._singleLine ? 'hidden' : this.layoutDoc._autoHeight ? 'visible' : undefined,
                         }}
                         onScroll={this.onScroll}
                         onDrop={this.ondrop}>
-- 
cgit v1.2.3-70-g09d2


From a63f017c213563728f45f2caa7415843f50f3559 Mon Sep 17 00:00:00 2001
From: bobzel <zzzman@gmail.com>
Date: Tue, 9 Aug 2022 19:50:33 -0400
Subject: fixed click on menu button for text box with hyperlink to not bring
 up buttonBar.  fixed right click on hyperlink to just bring up button bar,
 but not native context menu.  fixe stacking view child pointer events so that
 sidebar documents in lightbox are editable.

---
 src/client/views/DocumentButtonBar.tsx                    |  7 +------
 src/client/views/collections/CollectionStackingView.tsx   |  5 +++--
 src/client/views/nodes/formattedText/FormattedTextBox.tsx | 10 +++++-----
 3 files changed, 9 insertions(+), 13 deletions(-)

(limited to 'src/client/views/nodes/formattedText/FormattedTextBox.tsx')

diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx
index 81e417fca..1f8550ad6 100644
--- a/src/client/views/DocumentButtonBar.tsx
+++ b/src/client/views/DocumentButtonBar.tsx
@@ -274,12 +274,7 @@ export class DocumentButtonBar extends React.Component<{ views: () => (DocumentV
     get menuButton() {
         const targetDoc = this.view0?.props.Document;
         return !targetDoc ? null : (
-            <Tooltip
-                title={
-                    <>
-                        <div className="dash-tooltip">{`Open Context Menu`}</div>
-                    </>
-                }>
+            <Tooltip title={<div className="dash-tooltip">{`Open Context Menu`}</div>}>
                 <div className="documentButtonBar-icon" style={{ color: 'white', cursor: 'pointer' }} onClick={e => this.openContextMenu(e)}>
                     <FontAwesomeIcon className="documentdecorations-icon" icon="bars" />
                 </div>
diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx
index ef68cadd7..d4efef47a 100644
--- a/src/client/views/collections/CollectionStackingView.tsx
+++ b/src/client/views/collections/CollectionStackingView.tsx
@@ -300,9 +300,10 @@ export class CollectionStackingView extends CollectionSubView<Partial<collection
             return this.addDocument?.(newDoc);
         }
     };
-    isContentActive = () => this.props.isSelected() || this.props.isContentActive();
+    isContentActive = () => (this.props.isSelected() || this.props.isContentActive() ? true : this.props.isSelected() === false || this.props.isContentActive() === false ? false : undefined);
 
-    isChildContentActive = () => this.props.isDocumentActive?.() && (this.props.childDocumentsActive?.() || BoolCast(this.rootDoc.childDocumentsActive));
+    isChildContentActive = () =>
+        this.props.isDocumentActive?.() && (this.props.childDocumentsActive?.() || BoolCast(this.rootDoc.childDocumentsActive)) ? true : this.props.childDocumentsActive?.() === false || this.rootDoc.childDocumentsActive === false ? false : undefined;
     // this is what renders the document that you see on the screen
     // called in Children: this actually adds a document to our children list
     getDisplayDoc(doc: Doc, width: () => number) {
diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
index e027ab0bd..f61533619 100644
--- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx
+++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx
@@ -703,9 +703,9 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
 
         const editor = this._editorView!;
         const pcords = editor.posAtCoords({ left: e.clientX, top: e.clientY });
-        let target = (e.target as any).parentElement; // hrefs are stored on the database of the <a> node that wraps the hyerlink <span>
+        let target = e.target as any; // hrefs are stored on the database of the <a> node that wraps the hyerlink <span>
         while (target && !target.dataset?.targethrefs) target = target.parentElement;
-        if (target) {
+        if (target && !(e.nativeEvent as any).dash) {
             const hrefs = (target.dataset?.targethrefs as string)
                 ?.trim()
                 .split(' ')
@@ -724,6 +724,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
                         AnchorMenu.Instance.jumpTo(e.clientX, e.clientY, true);
                     })
                 );
+            e.preventDefault();
             e.stopPropagation();
             return;
         }
@@ -1474,10 +1475,10 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
         document.removeEventListener('pointermove', this.onSelectMove);
     };
     onPointerUp = (e: React.PointerEvent): void => {
-        if (!this._editorView?.state.selection.empty && FormattedTextBox._canAnnotate) this.setupAnchorMenu();
+        if (!this._editorView?.state.selection.empty && FormattedTextBox._canAnnotate && !(e.nativeEvent as any).dash) this.setupAnchorMenu();
         if (!this._downEvent) return;
         this._downEvent = false;
-        if (this.props.isContentActive(true)) {
+        if (this.props.isContentActive(true) && !(e.nativeEvent as any).dash) {
             const editor = this._editorView!;
             const pcords = editor.posAtCoords({ left: e.clientX, top: e.clientY });
             !this.props.isSelected(true) && editor.dispatch(editor.state.tr.setSelection(new TextSelection(editor.state.doc.resolve(pcords?.pos || 0))));
@@ -1795,7 +1796,6 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FieldViewProps
                 />
             ) : (
                 <div onPointerDown={e => setupMoveUpEvents(this, e, returnFalse, emptyFunction, () => SelectionManager.SelectView(this.props.DocumentView?.()!, false), true)}>
-                    //@ts-ignore
                     <ComponentTag
                         {...OmitKeys(this.props, ['NativeWidth', 'NativeHeight', 'setContentView']).omit}
                         NativeWidth={returnZero}
-- 
cgit v1.2.3-70-g09d2

