import { IconProp } from '@fortawesome/fontawesome-svg-core';
import { Dropdown, DropdownType, Type } from 'browndash-components';
import { Howl } from 'howler';
import { IReactionDisposer, action, computed, makeObservable, observable, reaction, runInAction } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
import { Bounce, Fade, Flip, JackInTheBox, Roll, Rotate, Zoom } from 'react-awesome-reveal';
import { Utils, emptyFunction, isTargetChildOf as isParentOf, lightOrDark, returnEmptyString, returnFalse, returnTrue, returnVal, simulateMouseClick } from '../../../Utils';
import { Doc, DocListCast, Field, Opt, StrListCast } from '../../../fields/Doc';
import { AclPrivate, Animation, AudioPlay, DocData, DocViews } from '../../../fields/DocSymbols';
import { Id } from '../../../fields/FieldSymbols';
import { InkTool } from '../../../fields/InkField';
import { List } from '../../../fields/List';
import { listSpec } from '../../../fields/Schema';
import { ScriptField } from '../../../fields/ScriptField';
import { BoolCast, Cast, DocCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types';
import { AudioField } from '../../../fields/URLField';
import { GetEffectiveAcl, TraceMobx } from '../../../fields/util';
import { DocServer } from '../../DocServer';
import { Networking } from '../../Network';
import { GooglePhotos } from '../../apis/google_docs/GooglePhotosClientUtils';
import { CollectionViewType, DocumentType } from '../../documents/DocumentTypes';
import { DocOptions, DocUtils, Docs } from '../../documents/Documents';
import { DictationManager } from '../../util/DictationManager';
import { DocumentManager } from '../../util/DocumentManager';
import { DragManager, dropActionType } from '../../util/DragManager';
import { FollowLinkScript } from '../../util/LinkFollower';
import { LinkManager } from '../../util/LinkManager';
import { ScriptingGlobals } from '../../util/ScriptingGlobals';
import { SearchUtil } from '../../util/SearchUtil';
import { SelectionManager } from '../../util/SelectionManager';
import { SettingsManager } from '../../util/SettingsManager';
import { SharingManager } from '../../util/SharingManager';
import { SnappingManager } from '../../util/SnappingManager';
import { UndoManager, undoBatch, undoable } from '../../util/UndoManager';
import { ContextMenu } from '../ContextMenu';
import { ContextMenuProps } from '../ContextMenuItem';
import { DocComponent, ViewBoxInterface } from '../DocComponent';
import { EditableView } from '../EditableView';
import { GestureOverlay } from '../GestureOverlay';
import { LightboxView } from '../LightboxView';
import { StyleProp } from '../StyleProvider';
import { DocumentContentsView, ObserverJsxParser } from './DocumentContentsView';
import { DocumentLinksButton } from './DocumentLinksButton';
import './DocumentView.scss';
import { FieldViewProps, FieldViewSharedProps } from './FieldView';
import { KeyValueBox } from './KeyValueBox';
import { LinkAnchorBox } from './LinkAnchorBox';
import { FormattedTextBox } from './formattedText/FormattedTextBox';
import { PresEffect, PresEffectDirection } from './trails';
interface Window {
    MediaRecorder: MediaRecorder;
}
declare class MediaRecorder {
    constructor(e: any); // whatever MediaRecorder has
}

export enum OpenWhereMod {
    none = '',
    left = 'left',
    right = 'right',
    top = 'top',
    bottom = 'bottom',
    keyvalue = 'keyValue',
}
export enum OpenWhere {
    lightbox = 'lightbox',
    add = 'add',
    addLeft = 'add:left',
    addRight = 'add:right',
    addBottom = 'add:bottom',
    close = 'close',
    toggle = 'toggle',
    toggleRight = 'toggle:right',
    replace = 'replace',
    replaceRight = 'replace:right',
    replaceLeft = 'replace:left',
    inParent = 'inParent',
    inParentFromScreen = 'inParentFromScreen',
    overlay = 'overlay',
    addRightKeyvalue = 'add:right:keyValue',
}

export function returnEmptyDocViewList() {
    return [] as DocumentView[];
}
export interface DocumentViewProps extends FieldViewSharedProps {
    hideDecorations?: boolean; // whether to suppress all DocumentDecorations when doc is selected
    hideResizeHandles?: boolean; // whether to suppress resized handles on doc decorations when this document is selected
    hideTitle?: boolean; // forces suppression of title. e.g, treeView document labels suppress titles in case they are globally active via settings
    hideDecorationTitle?: boolean; // forces suppression of title. e.g, treeView document labels suppress titles in case they are globally active via settings
    hideDocumentButtonBar?: boolean;
    hideOpenButton?: boolean;
    hideDeleteButton?: boolean;
    hideLinkAnchors?: boolean;
    hideLinkButton?: boolean;
    hideCaptions?: boolean;
    contentPointerEvents?: 'none' | 'all' | undefined; // pointer events allowed for content of a document view.  eg. set to "none" in menuSidebar for sharedDocs so that you can select a document, but not interact with its contents
    dontCenter?: 'x' | 'y' | 'xy';
    childHideDecorationTitle?: boolean;
    childHideResizeHandles?: boolean;
    childDragAction?: dropActionType; // allows child documents to be dragged out of collection without holding the embedKey or dragging the doc decorations title bar.
    dragWhenActive?: boolean;
    dontHideOnDrag?: boolean;
    suppressSetHeight?: boolean;
    onClickScriptDisable?: 'never' | 'always'; // undefined = only when selected
    DataTransition?: () => string | undefined;
    NativeWidth?: () => number;
    NativeHeight?: () => number;
    contextMenuItems?: () => { script: ScriptField; filter?: ScriptField; label: string; icon: string }[];
    dragConfig?: (data: DragManager.DocumentDragData) => void;
    dragStarting?: () => void;
    dragEnding?: () => void;
}
@observer
export class DocumentViewInternal extends DocComponent<FieldViewProps & DocumentViewProps>() {
    // this makes mobx trace() statements more descriptive
    public get displayName()  { return 'DocumentViewInternal(' + this.Document.title + ')'; } // prettier-ignore
    public static SelectAfterContextMenu = true; //  whether a document should be selected after it's contextmenu is triggered.
    /**
     * This function is filled in by MainView to allow non-viewBox views to add Docs as tabs without
     * needing to know about/reference MainView
     */
    public static addDocTabFunc: (doc: Doc, location: OpenWhere) => boolean = returnFalse;

    private _disposers: { [name: string]: IReactionDisposer } = {};
    private _doubleClickTimeout: NodeJS.Timeout | undefined;
    private _singleClickFunc: undefined | (() => any);
    private _longPressSelector: NodeJS.Timeout | undefined;
    private _downX: number = 0;
    private _downY: number = 0;
    private _downTime: number = 0;
    private _lastTap: number = 0;
    private _doubleTap = false;
    private _mainCont = React.createRef<HTMLDivElement>();
    private _titleRef = React.createRef<EditableView>();
    private _dropDisposer?: DragManager.DragDropDisposer;
    constructor(props: FieldViewProps & DocumentViewProps) {
        super(props);
        makeObservable(this);
    }

    @observable _changingTitleField = false;
    @observable _titleDropDownInnerWidth = 0; // width of menu dropdown when setting doc title
    @observable _mounted = false; // turn off all pointer events if component isn't yet mounted (enables nested Docs in alternate UI textboxes that appear on hover which otherwise would grab focus from the text box, reverting to the original UI )
    @observable _isContentActive: boolean | undefined = undefined;
    @observable _pointerEvents: 'none' | 'all' | 'visiblePainted' | undefined = undefined;
    @observable _componentView: Opt<ViewBoxInterface> = undefined; // needs to be accessed from DocumentView wrapper class
    @observable _animateScaleTime: Opt<number> = undefined; // milliseconds for animating between views.  defaults to 300 if not uset
    @observable _animateScalingTo = 0;

    get _contentDiv()  { return this._mainCont.current; } // prettier-ignore
    get _docView()     { return this._props.DocumentView?.(); } // prettier-ignore

    animateScaleTime = () => this._animateScaleTime ?? 100;
    style = (doc: Doc, sprop: StyleProp | string) => this._props.styleProvider?.(doc, this._props, sprop);
    @computed get layout_showTitle()   { return this.style(this.layoutDoc, StyleProp.ShowTitle) as Opt<string>; } // prettier-ignore
    @computed get opacity()            { return this.style(this.layoutDoc, StyleProp.Opacity); } // prettier-ignore
    @computed get boxShadow()          { return this.style(this.layoutDoc, StyleProp.BoxShadow); } // prettier-ignore
    @computed get borderRounding()     { return this.style(this.layoutDoc, StyleProp.BorderRounding); } // prettier-ignore
    @computed get widgetDecorations()  { return this.style(this.layoutDoc, StyleProp.Decorations); } // prettier-ignore
    @computed get backgroundBoxColor() { return this.style(this.layoutDoc, StyleProp.BackgroundColor + ':box'); } // prettier-ignore
    @computed get headerMargin()       { return this.style(this.layoutDoc, StyleProp.HeaderMargin) ?? 0; } // prettier-ignore
    @computed get layout_showCaption() { return this.style(this.layoutDoc, StyleProp.ShowCaption) ?? 0;  } // prettier-ignore
    @computed get titleHeight()        { return this.style(this.layoutDoc, StyleProp.TitleHeight) ?? 0;  } // prettier-ignore
    @computed get docContents()        { return this.style(this.Document, StyleProp.DocContents); } // prettier-ignore
    @computed get highlighting()       { return this.style(this.Document, StyleProp.Highlighting); } // prettier-ignore
    @computed get borderPath()         { return this.style(this.Document, StyleProp.BorderPath); } // prettier-ignore

    @computed get onClickHandler() {
        return this._props.onClickScript?.() ?? this._props.onBrowseClickScript?.() ?? ScriptCast(this.Document.onClick, ScriptCast(this.layoutDoc.onClick));
    }
    @computed get onDoubleClickHandler() {
        return this._props.onDoubleClickScript?.() ?? ScriptCast(this.layoutDoc.onDoubleClick, ScriptCast(this.Document.onDoubleClick));
    }
    @computed get onPointerDownHandler() {
        return this._props.onPointerDownScript?.() ?? ScriptCast(this.layoutDoc.onPointerDown, ScriptCast(this.Document.onPointerDown));
    }
    @computed get onPointerUpHandler() {
        return this._props.onPointerUpScript?.() ?? ScriptCast(this.layoutDoc.onPointerUp, ScriptCast(this.Document.onPointerUp));
    }

    @computed get disableClickScriptFunc() {
        const onScriptDisable = this._props.onClickScriptDisable ?? this._componentView?.onClickScriptDisable?.() ?? this.layoutDoc.onClickScriptDisable;
        // prettier-ignore
        return (
            DocumentView.LongPress ||
            onScriptDisable === 'always' ||
            (onScriptDisable !== 'never' && (this.rootSelected() || this._componentView?.isAnyChildContentActive?.()))
        );
    }
    @computed get _rootSelected() {
        return this._props.isSelected() || BoolCast(this._props.TemplateDataDocument && this._props.rootSelected?.());
    }
    /// disable pointer events on content when there's an enabled onClick script (but not the browse script) and the contents aren't forced active, or if contents are marked inactive
    @computed get _contentPointerEvents() {
        TraceMobx();
        return this._props.contentPointerEvents ??
            ((!this.disableClickScriptFunc && //
                this.onClickHandler &&
                !this._props.onBrowseClickScript?.() &&
                this.isContentActive() !== true) ||
                this.isContentActive() === false)
            ? 'none'
            : this._pointerEvents;
    }

    // We need to use allrelatedLinks to get not just links to the document as a whole, but links to
    // anchors that are not rendered as DocumentViews (marked as 'layout_unrendered' with their 'annotationOn' set to this document).  e.g.,
    //     - PDF text regions are rendered as an Annotations without generating a DocumentView, '
    //     - RTF selections are rendered via Prosemirror and have a mark which contains the Document ID for the annotation link
    //     - and links to PDF/Web docs at a certain scroll location never create an explicit view.
    // For each of these, we create LinkAnchorBox's on the border of the DocumentView.
    @computed get directLinks() {
        TraceMobx();
        return LinkManager.Instance.getAllRelatedLinks(this.Document).filter(
            link =>
                (link.link_matchEmbeddings ? link.link_anchor_1 === this.Document : Doc.AreProtosEqual(link.link_anchor_1 as Doc, this.Document)) ||
                (link.link_matchEmbeddings ? link.link_anchor_2 === this.Document : Doc.AreProtosEqual(link.link_anchor_2 as Doc, this.Document)) ||
                ((link.link_anchor_1 as Doc)?.layout_unrendered && Doc.AreProtosEqual((link.link_anchor_1 as Doc)?.annotationOn as Doc, this.Document)) ||
                ((link.link_anchor_2 as Doc)?.layout_unrendered && Doc.AreProtosEqual((link.link_anchor_2 as Doc)?.annotationOn as Doc, this.Document))
        );
    }
    @computed get _allLinks() {
        TraceMobx();
        return LinkManager.Instance.getAllRelatedLinks(this.Document).filter(link => !link.link_matchEmbeddings || link.link_anchor_1 === this.Document || link.link_anchor_2 === this.Document);
    }

    @computed get filteredLinks() {
        return DocUtils.FilterDocs(this.directLinks, this._props.childFilters?.() ?? [], []).filter(d => d.link_displayLine || Doc.UserDoc().showLinkLines);
    }

    componentWillUnmount() {
        this.cleanupHandlers(true);
    }

    componentDidMount() {
        runInAction(() => (this._mounted = true));
        this.setupHandlers();
        this._disposers.contentActive = reaction(
            () =>
                //  true  - if the document has been activated directly or indirectly (by having its children selected)
                //  false - if its pointer events are explicitly turned off or if it's container tells it that it's inactive
                // undefined - it is not active, but it should be responsive to actions that might activate it or its contents (eg clicking)
                this._props.isContentActive() === false || this._props.pointerEvents?.() === 'none'
                    ? false
                    : Doc.ActiveTool !== InkTool.None || SnappingManager.CanEmbed || this.rootSelected() || this.Document.forceActive || this._componentView?.isAnyChildContentActive?.() || this._props.isContentActive()
                      ? true
                      : undefined,
            active => (this._isContentActive = active),
            { fireImmediately: true }
        );
        this._disposers.pointerevents = reaction(
            () => this.style(this.Document, StyleProp.PointerEvents),
            pointerevents => (this._pointerEvents = pointerevents),
            { fireImmediately: true }
        );
    }
    preDrop = (e: Event, de: DragManager.DropEvent, dropAction: dropActionType) => {
        const dragData = de.complete.docDragData;
        if (dragData && this.isContentActive() && !this.props.dontRegisterView) {
            dragData.dropAction = dropAction ? dropAction : dragData.dropAction;
            e.stopPropagation();
        }
    };
    setupHandlers() {
        this.cleanupHandlers(false);
        if (this._mainCont.current) {
            this._dropDisposer = DragManager.MakeDropTarget(this._mainCont.current, this.drop.bind(this), this.Document, this.preDrop);
        }
    }

    cleanupHandlers(unbrush: boolean) {
        this._dropDisposer?.();
        unbrush && Doc.UnBrushDoc(this.Document);
        Object.values(this._disposers).forEach(disposer => disposer?.());
    }

    startDragging(x: number, y: number, dropAction: dropActionType, hideSource = false) {
        const docView = this._docView;
        if (this._mainCont.current && docView) {
            const views = SelectionManager.Views.filter(dv => dv.ContentDiv);
            const selected = views.length > 1 && views.some(dv => dv.Document === this.Document) ? views : [docView];
            const dragData = new DragManager.DocumentDragData(selected.map(dv => dv.Document));
            const screenXf = docView.screenToViewTransform();
            const [left, top] = screenXf.inverse().transformPoint(0, 0);
            dragData.offset = screenXf.transformDirection(x - left, y - top);
            dragData.dropAction = dropAction;
            dragData.removeDocument = this._props.removeDocument;
            dragData.moveDocument = this._props.moveDocument;
            dragData.draggedViews = [docView];
            dragData.canEmbed = this.Document.dragAction ?? this._props.dragAction ? true : false;
            (this._props.dragConfig ?? this._componentView?.dragConfig)?.(dragData);
            DragManager.StartDocumentDrag(
                selected.map(dv => dv.ContentDiv!),
                dragData,
                x,
                y,
                { hideSource: hideSource || (!dropAction && !this.layoutDoc.onDragStart && !this._props.dontHideOnDrag) }
            ); // this needs to happen after the drop event is processed.
        }
    }

    // switches text input focus to the title bar of the document (and displays the title bar if it hadn't been)
    setTitleFocus = () => {
        if (!StrCast(this.layoutDoc._layout_showTitle)) this.layoutDoc._layout_showTitle = 'title';
        setTimeout(() => this._titleRef.current?.setIsFocused(true)); // use timeout in case title wasn't shown to allow re-render so that titleref will be defined
    };
    onClick = action((e: React.MouseEvent | React.PointerEvent) => {
        if (this._props.isGroupActive?.() === 'child' && !this._props.isDocumentActive?.()) return;
        const documentView = this._docView;
        if (documentView && !this.Document.ignoreClick && this._props.renderDepth >= 0 && Utils.isClick(e.clientX, e.clientY, this._downX, this._downY, this._downTime)) {
            let stopPropagate = true;
            let preventDefault = true;
            !this.layoutDoc._keepZWhenDragged && this._props.bringToFront?.(this.Document);
            const scriptProps = {
                this: this.Document,
                _readOnly_: false,
                scriptContext: this._props.scriptContext,
                documentView,
                clientX: e.clientX,
                clientY: e.clientY,
                shiftKey: e.shiftKey,
                altKey: e.altKey,
                metaKey: e.metaKey,
                value: undefined,
            };
            if (this._doubleTap) {
                const defaultDblclick = this._props.defaultDoubleClick?.() || this.Document.defaultDoubleClick;
                if (this.onDoubleClickHandler?.script) {
                    UndoManager.RunInBatch(() => this.onDoubleClickHandler.script.run(scriptProps, console.log).result?.select && this._props.select(false), 'on double click: ' + this.Document.title);
                } else if (!Doc.IsSystem(this.Document) && defaultDblclick !== 'ignore') {
                    UndoManager.RunInBatch(() => LightboxView.Instance.AddDocTab(this.Document, OpenWhere.lightbox), 'double tap');
                    SelectionManager.DeselectAll();
                    Doc.UnBrushDoc(this.Document);
                } else {
                    this._singleClickFunc?.();
                }
                this._doubleClickTimeout && clearTimeout(this._doubleClickTimeout);
                this._doubleClickTimeout = undefined;
                this._singleClickFunc = undefined;
            } else {
                let clickFunc: undefined | (() => any);
                if (!this.disableClickScriptFunc && this.onClickHandler?.script) {
                    clickFunc = undoable(() => {
                        // use this view's add doc func to override method for following links to undisplayed documents.
                        // e.g., if this document is part of a labeled 'lightbox' container, then documents will be shown in this container of in the global lightbox
                        const oldFunc = DocumentViewInternal.addDocTabFunc;
                        DocumentViewInternal.addDocTabFunc = this._props.addDocTab;
                        this.onClickHandler?.script.run(scriptProps, console.log).result?.select && this._props.select(false);
                        DocumentViewInternal.addDocTabFunc = oldFunc;
                    }, 'click ' + this.Document.title);
                } else {
                    // onDragStart implies a button doc that we don't want to select when clicking. RootDocument & isTemplateForField implies we're clicking on part of a template instance and we want to select the whole template, not the part
                    if ((this.layoutDoc.onDragStart || this._props.TemplateDataDocument) && !(e.ctrlKey || e.button > 0)) {
                        stopPropagate = false; // don't stop propagation for field templates -- want the selection to propagate up to the root document of the template
                    }
                    preventDefault = false;
                }
                const sendToBack = e.altKey;
                this._singleClickFunc =
                    // prettier-ignore
                    clickFunc ?? (() => (sendToBack ? documentView._props.bringToFront?.(this.Document, true) : 
                                        this._props.select(e.ctrlKey||e.shiftKey, e.metaKey)));
                const waitFordblclick = this._props.waitForDoubleClickToClick?.() ?? this.Document.waitForDoubleClickToClick;
                if ((clickFunc && waitFordblclick !== 'never') || waitFordblclick === 'always') {
                    this._doubleClickTimeout && clearTimeout(this._doubleClickTimeout);
                    this._doubleClickTimeout = setTimeout(this._singleClickFunc, 300);
                } else if (!DocumentView.LongPress) {
                    this._singleClickFunc();
                    this._singleClickFunc = undefined;
                }
            }
            stopPropagate && e.stopPropagation();
            preventDefault && e.preventDefault();
        }
    });

    onPointerDown = (e: React.PointerEvent): void => {
        if (this._props.isGroupActive?.() === 'child' && !this._props.isDocumentActive?.()) return;
        this._longPressSelector = setTimeout(() => DocumentView.LongPress && this._props.select(false), 1000);
        if (!GestureOverlay.DownDocView) GestureOverlay.DownDocView = this._docView;

        this._downX = e.clientX;
        this._downY = e.clientY;
        this._downTime = Date.now();
        if ((Doc.ActiveTool === InkTool.None || this._props.addDocTab === returnFalse) && !(this._props.TemplateDataDocument && !(e.ctrlKey || e.button > 0))) {
            // click events stop here if the document is active and no modes are overriding it
            // if this is part of a template, let the event go up to the template root unless right/ctrl clicking
            if (
                // prettier-ignore
                (this._props.isDocumentActive?.() || this._props.isContentActive?.()) &&
                !this._props.onBrowseClickScript?.() &&
                !this.Document.ignoreClick &&
                e.button === 0 &&
                !Doc.IsInMyOverlay(this.layoutDoc)
            ) {
                e.stopPropagation();
                // don't preventDefault.  Goldenlayout, PDF text selection and RTF text selection all need it to go though

                // listen to move events when document content isn't active or document is always draggable
                if (!this.layoutDoc._lockedPosition && (!this.isContentActive() || BoolCast(this.layoutDoc._dragWhenActive, this._props.dragWhenActive))) {
                    document.addEventListener('pointermove', this.onPointerMove);
                }
            }
            document.addEventListener('pointerup', this.onPointerUp);
        }
    };

    onPointerMove = (e: PointerEvent): void => {
        if (e.buttons !== 1 || [InkTool.Highlighter, InkTool.Pen, InkTool.Write].includes(Doc.ActiveTool)) return;

        if (!Utils.isClick(e.clientX, e.clientY, this._downX, this._downY, Date.now())) {
            this.cleanupPointerEvents();
            this._longPressSelector && clearTimeout(this._longPressSelector);
            this.startDragging(this._downX, this._downY, ((e.ctrlKey || e.altKey) && 'embed') || ((this.Document.dragAction || this._props.dragAction || undefined) as dropActionType));
        }
    };

    cleanupPointerEvents = () => {
        document.removeEventListener('pointermove', this.onPointerMove);
        document.removeEventListener('pointerup', this.onPointerUp);
    };

    onPointerUp = (e: PointerEvent): void => {
        this.cleanupPointerEvents();
        this._longPressSelector && clearTimeout(this._longPressSelector);

        if (this.onPointerUpHandler?.script) {
            this.onPointerUpHandler.script.run({ this: this.Document }, console.log);
        } else if (e.button === 0 && Utils.isClick(e.clientX, e.clientY, this._downX, this._downY, this._downTime)) {
            this._doubleTap = (this.onDoubleClickHandler?.script || this.Document.defaultDoubleClick !== 'ignore') && Date.now() - this._lastTap < Utils.CLICK_TIME;
            if (!this.isContentActive()) this._lastTap = Date.now(); // don't want to process the start of a double tap if the doucment is selected
        }
        if (DocumentView.LongPress) e.preventDefault();
    };

    toggleFollowLink = undoable((zoom?: boolean, setTargetToggle?: boolean): void => {
        const hadOnClick = this.Document.onClick;
        this.noOnClick();
        this.Document.onClick = hadOnClick ? undefined : FollowLinkScript();
        this.Document.waitForDoubleClickToClick = hadOnClick ? undefined : 'never';
    }, 'toggle follow link');

    followLinkOnClick = undoable(() => {
        this.Document.ignoreClick = false;
        this.Document.onClick = FollowLinkScript();
        this.Document.followLinkToggle = false;
        this.Document.followLinkZoom = false;
        this.Document.followLinkLocation = undefined;
    }, 'follow link on click');

    noOnClick = undoable(() => {
        this.Document.ignoreClick = false;
        this.Document.onClick = this.Document[DocData].onClick = undefined;
    }, 'default on click');

    deleteClicked = undoable(() => this._props.removeDocument?.(this.Document), 'delete doc');
    setToggleDetail = undoable(
        (defaultLayout: string, scriptFieldKey: 'onClick') =>
            (this.Document[scriptFieldKey] = ScriptField.MakeScript(
                `toggleDetail(documentView, "${StrCast(this.Document.layout_fieldKey)
                    .replace('layout_', '')
                    .replace(/^layout$/, 'detail')}", "${defaultLayout}")`,
                { documentView: 'any' }
            )),
        'set toggle detail'
    );

    drop = undoable((e: Event, de: DragManager.DropEvent) => {
        if (this._props.dontRegisterView || this._props.LayoutTemplateString?.includes(LinkAnchorBox.name)) return false;
        if (this.Document === Doc.ActiveDashboard) {
            e.stopPropagation();
            e.preventDefault();
            alert((e.target as any)?.closest?.('*.lm_content') ? "You can't perform this move most likely because you didn't drag the document's title bar to enable embedding in a different document." : 'Linking to document tabs not yet supported.');
            return true;
        }
        const annoData = de.complete.annoDragData;
        const linkdrag = annoData ?? de.complete.linkDragData;
        if (linkdrag) {
            linkdrag.linkSourceDoc = linkdrag.linkSourceGetAnchor();
            if (linkdrag.linkSourceDoc && linkdrag.linkSourceDoc !== this.Document) {
                if (annoData && !annoData.dropDocument) {
                    annoData.dropDocument = annoData.dropDocCreator(undefined);
                }
                if (annoData || this.Document !== linkdrag.linkSourceDoc.embedContainer) {
                    const dropDoc = annoData?.dropDocument ?? this._componentView?.getAnchor?.(true) ?? this.Document;
                    const linkDoc = DocUtils.MakeLink(linkdrag.linkSourceDoc, dropDoc, {}, undefined, [de.x, de.y - 50]);
                    if (linkDoc) {
                        de.complete.linkDocument = linkDoc;
                        linkDoc.layout_isSvg = true;
                        DocumentManager.LinkCommonAncestor(linkDoc)?.ComponentView?.addDocument?.(linkDoc);
                    }
                }
                e.stopPropagation();
                return true;
            }
        }
        return false;
    }, 'drop doc');

    importDocument = () => {
        const input = document.createElement('input');
        input.type = 'file';
        input.accept = '.zip';
        input.onchange = _e => {
            if (input.files) {
                const batch = UndoManager.StartBatch('importing');
                Doc.importDocument(input.files[0]).then(doc => {
                    if (doc instanceof Doc) {
                        this._props.addDocTab(doc, OpenWhere.addRight);
                        batch.end();
                    }
                });
            }
        };
        input.click();
    };

    onContextMenu = (e?: React.MouseEvent, pageX?: number, pageY?: number) => {
        if (e && this.layoutDoc._layout_hideContextMenu && Doc.noviceMode) {
            e.preventDefault();
            e.stopPropagation();
            //!this._props.isSelected(true) && SelectionManager.SelectView(this.DocumentView(), false);
        }
        // the touch onContextMenu is button 0, the pointer onContextMenu is button 2
        if (e) {
            if ((e.button === 0 && !e.ctrlKey) || e.isDefaultPrevented()) {
                e.preventDefault();
                return;
            }
            e.preventDefault();
            e.stopPropagation();
            e.persist();

            if (!navigator.userAgent.includes('Mozilla') && (Math.abs(this._downX - e?.clientX) > 3 || Math.abs(this._downY - e?.clientY) > 3)) {
                return;
            }
        }

        const cm = ContextMenu.Instance;
        if (!cm || (e as any)?.nativeEvent?.SchemaHandled || SnappingManager.ExploreMode) return;

        if (e && !(e.nativeEvent as any).dash) {
            const onDisplay = () => {
                if (this.Document.type !== DocumentType.MAP) DocumentViewInternal.SelectAfterContextMenu && this._props.select(false); // on a mac, the context menu is triggered on mouse down, but a YouTube video becaomes interactive when selected which means that the context menu won't show up.  by delaying the selection until hopefully after the pointer up, the context menu will appear.
                setTimeout(() => simulateMouseClick(document.elementFromPoint(e.clientX, e.clientY), e.clientX, e.clientY, e.screenX, e.screenY));
            };
            if (navigator.userAgent.includes('Macintosh')) {
                cm.displayMenu((e?.pageX || pageX || 0) - 15, (e?.pageY || pageY || 0) - 15, undefined, undefined, onDisplay);
            } else {
                onDisplay();
            }
            return;
        }

        const customScripts = Cast(this.Document.contextMenuScripts, listSpec(ScriptField), []);
        StrListCast(this.Document.contextMenuLabels).forEach((label, i) =>
            cm.addItem({ description: label, event: () => customScripts[i]?.script.run({ documentView: this, this: this.Document, scriptContext: this._props.scriptContext }), icon: 'sticky-note' })
        );
        this._props.contextMenuItems?.().forEach(item => item.label && cm.addItem({ description: item.label, event: () => item.script.script.run({ this: this.Document, scriptContext: this._props.scriptContext }), icon: item.icon as IconProp }));

        if (!this.Document.isFolder) {
            const templateDoc = Cast(this.Document[StrCast(this.Document.layout_fieldKey)], Doc, null);
            const appearance = cm.findByDescription('Appearance...');
            const appearanceItems: ContextMenuProps[] = appearance && 'subitems' in appearance ? appearance.subitems : [];

            if (this._props.renderDepth === 0) {
                appearanceItems.splice(0, 0, { description: 'Open in Lightbox', event: () => LightboxView.Instance.SetLightboxDoc(this.Document), icon: 'external-link-alt' });
            }
            appearanceItems.push({ description: 'Pin', event: () => this._props.pinToPres(this.Document, {}), icon: 'eye' });
            !Doc.noviceMode && templateDoc && appearanceItems.push({ description: 'Open Template   ', event: () => this._props.addDocTab(templateDoc, OpenWhere.addRight), icon: 'eye' });
            !appearance && appearanceItems.length && cm.addItem({ description: 'Appearance...', subitems: appearanceItems, icon: 'compass' });

            if (this._props.bringToFront) {
                const zorders = cm.findByDescription('ZOrder...');
                const zorderItems: ContextMenuProps[] = zorders && 'subitems' in zorders ? zorders.subitems : [];
                zorderItems.push({ description: 'Bring to Front', event: () => SelectionManager.Views.forEach(dv => dv._props.bringToFront?.(dv.Document, false)), icon: 'arrow-up' });
                zorderItems.push({ description: 'Send to Back', event: () => SelectionManager.Views.forEach(dv => dv._props.bringToFront?.(dv.Document, true)), icon: 'arrow-down' });
                zorderItems.push({
                    description: !this.layoutDoc._keepZDragged ? 'Keep ZIndex when dragged' : 'Allow ZIndex to change when dragged',
                    event: undoBatch(action(() => (this.layoutDoc._keepZWhenDragged = !this.layoutDoc._keepZWhenDragged))),
                    icon: 'hand-point-up',
                });
                !zorders && cm.addItem({ description: 'Z Order...', addDivider: true, noexpand: true, subitems: zorderItems, icon: 'layer-group' });
            }

            if (!Doc.IsSystem(this.Document) && !this.Document.hideClickBehaviors && !this._props.hideClickBehaviors) {
                const existingOnClick = cm.findByDescription('OnClick...');
                const onClicks: ContextMenuProps[] = existingOnClick && 'subitems' in existingOnClick ? existingOnClick.subitems : [];

                onClicks.push({ description: 'Enter Portal', event: undoable(e => DocUtils.makeIntoPortal(this.Document, this.layoutDoc, this._allLinks), 'make into portal'), icon: 'window-restore' });
                !Doc.noviceMode && onClicks.push({ description: 'Toggle Detail', event: this.setToggleDetail, icon: 'concierge-bell' });

                if (!this.Document.annotationOn) {
                    onClicks.push({ description: this.onClickHandler ? 'Remove Click Behavior' : 'Follow Link', event: () => this.toggleFollowLink(false, false), icon: 'link' });
                    !Doc.noviceMode && onClicks.push({ description: 'Edit onClick Script', event: () => UndoManager.RunInBatch(() => DocUtils.makeCustomViewClicked(this.Document, undefined, 'onClick'), 'edit onClick'), icon: 'terminal' });
                    cm.addItem({ description: 'OnClick...', noexpand: true, subitems: onClicks, icon: 'mouse-pointer' });
                } else if (LinkManager.Links(this.Document).length) {
                    onClicks.push({ description: 'Restore On Click default', event: () => this.noOnClick(), icon: 'link' });
                    onClicks.push({ description: 'Follow Link on Click', event: () => this.followLinkOnClick(), icon: 'link' });
                    !existingOnClick && cm.addItem({ description: 'OnClick...', subitems: onClicks, icon: 'mouse-pointer' });
                }
            }

            const funcs: ContextMenuProps[] = [];
            if (!Doc.noviceMode && this.layoutDoc.onDragStart) {
                funcs.push({ description: 'Drag an Embedding', icon: 'edit', event: () => this.Document.dragFactory && (this.layoutDoc.onDragStart = ScriptField.MakeFunction('getEmbedding(this.dragFactory)')) });
                funcs.push({ description: 'Drag a Copy', icon: 'edit', event: () => this.Document.dragFactory && (this.layoutDoc.onDragStart = ScriptField.MakeFunction('getCopy(this.dragFactory, true)')) });
                funcs.push({ description: 'Drag Document', icon: 'edit', event: () => (this.layoutDoc.onDragStart = undefined) });
                cm.addItem({ description: 'OnDrag...', noexpand: true, subitems: funcs, icon: 'asterisk' });
            }

            const more = cm.findByDescription('More...');
            const moreItems = more && 'subitems' in more ? more.subitems : [];
            if (!Doc.IsSystem(this.Document)) {
                if (!Doc.noviceMode) {
                    moreItems.push({ description: 'Make View of Metadata Field', event: () => Doc.MakeMetadataFieldTemplate(this.Document, this._props.TemplateDataDocument), icon: 'concierge-bell' });
                    moreItems.push({ description: `${this.Document._chromeHidden ? 'Show' : 'Hide'} Chrome`, event: () => (this.Document._chromeHidden = !this.Document._chromeHidden), icon: 'project-diagram' });

                    if (Cast(Doc.GetProto(this.Document).data, listSpec(Doc))) {
                        moreItems.push({ description: 'Export to Google Photos Album', event: () => GooglePhotos.Export.CollectionToAlbum({ collection: this.Document }).then(console.log), icon: 'caret-square-right' });
                        moreItems.push({ description: 'Tag Child Images via Google Photos', event: () => GooglePhotos.Query.TagChildImages(this.Document), icon: 'caret-square-right' });
                        moreItems.push({ description: 'Write Back Link to Album', event: () => GooglePhotos.Transactions.AddTextEnrichment(this.Document), icon: 'caret-square-right' });
                    }
                    moreItems.push({ description: 'Copy ID', event: () => Utils.CopyText(Doc.globalServerPath(this.Document)), icon: 'fingerprint' });
                }
            }

            !more && moreItems.length && cm.addItem({ description: 'More...', subitems: moreItems, icon: 'eye' });
        }
        const constantItems: ContextMenuProps[] = [];
        if (!Doc.IsSystem(this.Document) && this.Document._type_collection !== CollectionViewType.Docking) {
            constantItems.push({ description: 'Zip Export', icon: 'download', event: async () => Doc.Zip(this.Document) });
            (this.Document._type_collection !== CollectionViewType.Docking || !Doc.noviceMode) && constantItems.push({ description: 'Share', event: () => SharingManager.Instance.open(this._docView), icon: 'users' });
            if (this._props.removeDocument && Doc.ActiveDashboard !== this.Document) {
                // need option to gray out menu items ... preferably with a '?' that explains why they're grayed out (eg., no permissions)
                constantItems.push({ description: 'Close', event: this.deleteClicked, icon: 'times' });
            }
        }
        constantItems.push({ description: 'Show Metadata', event: () => this._props.addDocTab(this.Document, OpenWhere.addRightKeyvalue), icon: 'table-columns' });
        cm.addItem({ description: 'General...', noexpand: false, subitems: constantItems, icon: 'question' });

        const help = cm.findByDescription('Help...');
        const helpItems: ContextMenuProps[] = help && 'subitems' in help ? help.subitems : [];
        !Doc.noviceMode && helpItems.push({ description: 'Text Shortcuts Ctrl+/', event: () => this._props.addDocTab(Docs.Create.PdfDocument('/assets/cheat-sheet.pdf', { _width: 300, _height: 300 }), OpenWhere.addRight), icon: 'keyboard' });
        !Doc.noviceMode && helpItems.push({ description: 'Print Document in Console', event: () => console.log(this.Document), icon: 'hand-point-right' });
        !Doc.noviceMode && helpItems.push({ description: 'Print DataDoc in Console', event: () => console.log(this.dataDoc), icon: 'hand-point-right' });

        let documentationDescription: string | undefined = undefined;
        let documentationLink: string | undefined = undefined;
        switch (this.Document.type) {
            case DocumentType.COL:
                documentationDescription = 'See collection documentation';
                documentationLink = 'https://brown-dash.github.io/Dash-Documentation/views/';
                break;
            case DocumentType.PDF:
                documentationDescription = 'See PDF node documentation';
                documentationLink = 'https://brown-dash.github.io/Dash-Documentation/documents/pdf/';
                break;
            case DocumentType.VID:
                documentationDescription = 'See video node documentation';
                documentationLink = 'https://brown-dash.github.io/Dash-Documentation/documents/tempMedia/video';
                break;
            case DocumentType.AUDIO:
                documentationDescription = 'See audio node documentation';
                documentationLink = 'https://brown-dash.github.io/Dash-Documentation/documents/tempMedia/audio';
                break;
            case DocumentType.WEB:
                documentationDescription = 'See webpage node documentation';
                documentationLink = 'https://brown-dash.github.io/Dash-Documentation/documents/webpage/';
                break;
            case DocumentType.IMG:
                documentationDescription = 'See image node documentation';
                documentationLink = 'https://brown-dash.github.io/Dash-Documentation/documents/images/';
                break;
            case DocumentType.RTF:
                documentationDescription = 'See text node documentation';
                documentationLink = 'https://brown-dash.github.io/Dash-Documentation/documents/text/';
                break;
            case DocumentType.DATAVIZ:
                documentationDescription = 'See DataViz node documentation';
                documentationLink = 'https://brown-dash.github.io/Dash-Documentation/documents/dataViz/';
                break;
        }
        // Add link to help documentation (unless the doc contents have been overriden in which case the documentation isn't relevant)
        if (!this.docContents && documentationDescription && documentationLink) {
            helpItems.push({
                description: documentationDescription,
                event: () => window.open(documentationLink, '_blank'),
                icon: 'book',
            });
        }
        if (!help) cm.addItem({ description: 'Help...', noexpand: !Doc.noviceMode, subitems: helpItems, icon: 'question' });
        else cm.moveAfter(help);

        e?.stopPropagation(); // DocumentViews should stop propagation of this event
        cm.displayMenu((e?.pageX || pageX || 0) - 15, (e?.pageY || pageY || 0) - 15, undefined, undefined, undefined);
    };

    rootSelected = () => this._rootSelected;
    panelHeight = () => this._props.PanelHeight() - this.headerMargin;
    screenToLocalContent = () => this._props.ScreenToLocalTransform().translate(0, -this.headerMargin);
    onClickFunc = this.disableClickScriptFunc ? undefined : () => this.onClickHandler;
    setHeight = (height: number) => !this._props.suppressSetHeight && (this.layoutDoc._height = height);
    setContentView = action((view: ViewBoxInterface) => (this._componentView = view));
    isContentActive = (): boolean | undefined => this._isContentActive;
    childFilters = () => [...this._props.childFilters(), ...StrListCast(this.layoutDoc.childFilters)];

    contentPointerEvents = () => this._contentPointerEvents;

    anchorPanelWidth = () => this._props.PanelWidth() || 1;
    anchorPanelHeight = () => this._props.PanelHeight() || 1;
    anchorStyleProvider = (doc: Opt<Doc>, props: Opt<FieldViewProps>, property: string): any => {
        // prettier-ignore
        switch (property.split(':')[0]) {
            case StyleProp.ShowTitle:     return '';
            case StyleProp.PointerEvents: return 'none';
            case StyleProp.Highlighting:  return undefined;
            case StyleProp.Opacity:       {
                const filtered = DocUtils.FilterDocs(this.directLinks, this._props.childFilters?.() ?? [], []).filter(d => d.link_displayLine || Doc.UserDoc().showLinkLines);
                return filtered.some(link => link._link_displayArrow) ? 0 : undefined;
            }
        }
        return this._props.styleProvider?.(doc, props, property);
    };

    removeLinkByHiding = (link: Doc) => () => (link.link_displayLine = false);
    @computed get allLinkEndpoints() {
        // the small blue dots that mark the endpoints of links
        if (this._componentView instanceof KeyValueBox || this._props.hideLinkAnchors || this.layoutDoc.layout_hideLinkAnchors || this._props.dontRegisterView || this.layoutDoc.layout_unrendered) return null;
        return this.filteredLinks.map(link => (
            <div className="documentView-anchorCont" key={link[Id]}>
                <DocumentView
                    {...this._props}
                    isContentActive={returnFalse}
                    Document={link}
                    containerViewPath={this._props.docViewPath}
                    PanelWidth={this.anchorPanelWidth}
                    PanelHeight={this.anchorPanelHeight}
                    dontRegisterView={false}
                    layout_showTitle={returnEmptyString}
                    hideCaptions={true}
                    hideLinkAnchors={true}
                    layout_fitWidth={returnTrue}
                    removeDocument={this.removeLinkByHiding(link)}
                    styleProvider={this.anchorStyleProvider}
                    LayoutTemplate={undefined}
                    LayoutTemplateString={LinkAnchorBox.LayoutString(`link_anchor_${LinkManager.anchorIndex(link, this.Document)}`)}
                />
            </div>
        ));
    }

    @computed get viewBoxContents() {
        TraceMobx();
        const isInk = this.layoutDoc._layout_isSvg && !this._props.LayoutTemplateString;
        const noBackground = this.Document.isGroup && !this._props.LayoutTemplateString?.includes(KeyValueBox.name) && (!this.layoutDoc.backgroundColor || this.layoutDoc.backgroundColor === 'transparent');
        return (
            <div
                className="documentView-contentsView"
                style={{
                    pointerEvents: (isInk || noBackground ? 'none' : this.contentPointerEvents()) ?? (this._mounted ? 'all' : 'none'),
                    height: this.headerMargin ? `calc(100% - ${this.headerMargin}px)` : undefined,
                }}>
                <DocumentContentsView
                    {...this._props}
                    layoutFieldKey={StrCast(this.Document.layout_fieldKey, 'layout')}
                    pointerEvents={this.contentPointerEvents}
                    setContentViewBox={this.setContentView}
                    childFilters={this.childFilters}
                    PanelHeight={this.panelHeight}
                    setHeight={this.setHeight}
                    isContentActive={this.isContentActive}
                    ScreenToLocalTransform={this.screenToLocalContent}
                    rootSelected={this.rootSelected}
                    onClickScript={this.onClickFunc}
                    setTitleFocus={this.setTitleFocus}
                    hideClickBehaviors={BoolCast(this.Document.hideClickBehaviors)}
                />
                {this.layoutDoc.layout_hideAllLinks ? null : this.allLinkEndpoints}
            </div>
        );
    }

    captionStyleProvider = (doc: Opt<Doc>, props: Opt<FieldViewProps>, property: string) => this._props?.styleProvider?.(doc, props, property + ':caption');
    fieldsDropdown = (reqdFields: string[], dropdownWidth: number, placeholder: string, onChange: (val: string | number) => void, onClose: () => void) => {
        const filteredFields = Object.entries(DocOptions).reduce((set, [field, opts]) => (opts.filterable ? set.add(field) : set), new Set(reqdFields));
        return (
            <div style={{ width: dropdownWidth }}>
                <div
                    ref={action((r: any) => r && (this._titleDropDownInnerWidth = Number(getComputedStyle(r).width.replace('px', ''))))}
                    onPointerDown={action(e => (this._changingTitleField = true))}
                    style={{ width: 'max-content', transformOrigin: 'left', transform: `scale(${this.titleHeight / 30 /* height of Dropdown */})` }}>
                    <Dropdown
                        activeChanged={action(isOpen => !isOpen && (this._changingTitleField = false))}
                        selectedVal={placeholder}
                        setSelectedVal={onChange}
                        color={SettingsManager.userColor}
                        background={SettingsManager.userVariantColor}
                        type={Type.TERT}
                        closeOnSelect={true}
                        dropdownType={DropdownType.SELECT}
                        items={Array.from(filteredFields).map(facet => ({ val: facet, text: facet }))}
                        width={100}
                        fillWidth
                    />
                </div>
            </div>
        );
    };
    /**
     * displays a 'title' at the top of a document. The title contents default to the 'title' field, but can be changed to one or more fields by
     * setting layout_showTitle using the format:   field1[;field2[...][:hover]]
     * from the UI, this is done by clicking the title field and prefixin the format with '#'.  eg.,  #field1[;field2;...][:hover]
     **/
    @computed get titleView() {
        const showTitle = this.layout_showTitle?.split(':')[0];
        const showTitleHover = this.layout_showTitle?.includes(':hover');

        const targetDoc = showTitle?.startsWith('_') ? this.layoutDoc : this.Document;
        const background = StrCast(
            this.layoutDoc.layout_headingColor,
            StrCast(SharingManager.Instance.users.find(u => u.user.email === this.dataDoc.author)?.sharingDoc.headingColor, StrCast(Doc.SharingDoc().headingColor, SettingsManager.userBackgroundColor))
        );
        const dropdownWidth = this._titleRef.current?._editing || this._changingTitleField ? Math.max(10, (this._titleDropDownInnerWidth * this.titleHeight) / 30) : 0;
        const sidebarWidthPercent = +StrCast(this.layoutDoc.layout_sidebarWidthPercent).replace('%', '');

        return !showTitle ? null : (
            <div
                className={`documentView-titleWrapper${showTitleHover ? '-hover' : ''}`}
                key="title"
                style={{
                    zIndex: 1,
                    position: this.headerMargin ? 'relative' : 'absolute',
                    height: this.titleHeight,
                    width: 100 - sidebarWidthPercent + '%',
                    color: background === 'transparent' ? SettingsManager.userColor : lightOrDark(background),
                    background,
                    pointerEvents: (!this.disableClickScriptFunc && this.onClickHandler) || this.Document.ignoreClick ? 'none' : this.isContentActive() || this._props.isDocumentActive?.() ? 'all' : undefined,
                }}>
                {!dropdownWidth
                    ? null
                    : this.fieldsDropdown(
                          [StrCast(this.layoutDoc.layout_showTitle)],
                          dropdownWidth,
                          StrCast(this.layoutDoc.layout_showTitle).split(':')[0],
                          action((field: string | number) => {
                              if (this.layoutDoc.layout_showTitle) {
                                  this.layoutDoc._layout_showTitle = field;
                              } else if (!this._props.layout_showTitle) {
                                  Doc.UserDoc().layout_showTitle = field;
                              }
                              this._changingTitleField = false;
                          }),
                          action(() => (this._changingTitleField = false))
                      )}
                <div
                    style={{
                        width: `calc(100% - ${dropdownWidth}px)`,
                        minWidth: '100px',
                        color: this._titleRef.current?._editing || this._changingTitleField ? 'black' : undefined,
                        background: this._titleRef.current?._editing || this._changingTitleField ? 'yellow' : undefined,
                    }}>
                    <EditableView
                        ref={this._titleRef}
                        contents={showTitle
                            .split(';')
                            .map(field => targetDoc[field.trim()]?.toString())
                            .join(' \\ ')}
                        display="block"
                        oneLine={true}
                        fontSize={(this.titleHeight / 15) * 10}
                        GetValue={() => (showTitle.split(';').length !== 1 ? '#' + showTitle : Field.toKeyValueString(this.Document, showTitle.split(';')[0]))}
                        SetValue={undoBatch((input: string) => {
                            if (input?.startsWith('#')) {
                                if (this.layoutDoc.layout_showTitle) {
                                    this.layoutDoc._layout_showTitle = input?.substring(1);
                                } else if (!this._props.layout_showTitle) {
                                    Doc.UserDoc().layout_showTitle = input?.substring(1) ?? 'author_date';
                                }
                            } else if (showTitle && !showTitle.includes('Date') && showTitle !== 'author') {
                                KeyValueBox.SetField(targetDoc, showTitle, input);
                            }
                            return true;
                        })}
                    />
                </div>
            </div>
        );
    }

    @computed get captionView() {
        return !this.layout_showCaption ? null : (
            <div
                className="documentView-captionWrapper"
                style={{
                    pointerEvents: this.Document.ignoreClick ? 'none' : this.isContentActive() || this._props.isDocumentActive?.() ? 'all' : undefined,
                    background: StrCast(this.layoutDoc._backgroundColor, 'rgba(0,0,0,0.2)'),
                    color: lightOrDark(StrCast(this.layoutDoc._backgroundColor, 'black')),
                }}>
                <FormattedTextBox
                    {...this._props}
                    yPadding={10}
                    xPadding={10}
                    fieldKey={this.layout_showCaption}
                    styleProvider={this.captionStyleProvider}
                    dontRegisterView={true}
                    noSidebar={true}
                    dontScale={true}
                    renderDepth={this._props.renderDepth}
                    isContentActive={this.isContentActive}
                />
            </div>
        );
    }

    renderDoc = (style: object) => {
        TraceMobx();
        const showTitle = this.layout_showTitle?.split(':')[0];
        return !DocCast(this.Document) || GetEffectiveAcl(this.dataDoc) === AclPrivate
            ? null
            : this.docContents ?? (
                  <div
                      className="documentView-node"
                      id={this.Document[Id]}
                      style={{
                          ...style,
                          background: this.backgroundBoxColor,
                          opacity: this.opacity,
                          cursor: Doc.ActiveTool === InkTool.None ? 'grab' : 'crosshair',
                          color: StrCast(this.layoutDoc.color, 'inherit'),
                          fontFamily: StrCast(this.Document._text_fontFamily, 'inherit'),
                          fontSize: Cast(this.Document._text_fontSize, 'string', null),
                          transform: this._animateScalingTo ? `scale(${this._animateScalingTo})` : undefined,
                          transition: !this._animateScalingTo ? this._props.DataTransition?.() : `transform ${this.animateScaleTime() / 1000}s ease-${this._animateScalingTo < 1 ? 'in' : 'out'}`,
                      }}>
                      {this._props.hideTitle || (!showTitle && !this.layout_showCaption) ? (
                          this.viewBoxContents
                      ) : (
                          <div className="documentView-styleWrapper">
                              {this.titleView}
                              {this.viewBoxContents}
                              {this.captionView}
                          </div>
                      )}
                      {this.widgetDecorations ?? null}
                  </div>
              );
    };

    render() {
        TraceMobx();
        const highlighting = this.highlighting;
        const borderPath = this.borderPath;
        const boxShadow = !highlighting
            ? this.boxShadow
            : highlighting && this.borderRounding && highlighting.highlightStyle !== 'dashed'
              ? `0 0 0 ${highlighting.highlightIndex}px ${highlighting.highlightColor}`
              : this.boxShadow || (this.Document.isTemplateForField ? 'black 0.2vw 0.2vw 0.8vw' : undefined);
        const renderDoc = this.renderDoc({
            borderRadius: this.borderRounding,
            outline: highlighting && !this.borderRounding && !highlighting.highlightStroke ? `${highlighting.highlightColor} ${highlighting.highlightStyle} ${highlighting.highlightIndex}px` : 'solid 0px',
            border: highlighting && this.borderRounding && highlighting.highlightStyle === 'dashed' ? `${highlighting.highlightStyle} ${highlighting.highlightColor} ${highlighting.highlightIndex}px` : undefined,
            boxShadow,
            clipPath: borderPath?.clipPath,
        });

        return (
            <div
                className={`${DocumentView.ROOT_DIV} docView-hack`}
                ref={this._mainCont}
                onContextMenu={this.onContextMenu}
                onPointerDown={this.onPointerDown}
                onClick={this.onClick}
                onPointerEnter={e => (!SnappingManager.IsDragging || SnappingManager.CanEmbed) && Doc.BrushDoc(this.Document)}
                onPointerOver={e => (!SnappingManager.IsDragging || SnappingManager.CanEmbed) && Doc.BrushDoc(this.Document)}
                onPointerLeave={e => !isParentOf(this._contentDiv, document.elementFromPoint(e.nativeEvent.x, e.nativeEvent.y)) && Doc.UnBrushDoc(this.Document)}
                style={{
                    borderRadius: this.borderRounding,
                    pointerEvents: this._pointerEvents === 'visiblePainted' ? 'none' : this._pointerEvents, // visible painted means that the underlying doc contents are irregular and will process their own pointer events (otherwise, the contents are expected to fill the entire doc view box so we can handle pointer events here)
                }}>
                <>
                    {this._componentView instanceof KeyValueBox ? renderDoc : DocumentViewInternal.AnimationEffect(renderDoc, this.Document[Animation], this.Document)}
                    {borderPath?.jsx}
                </>
            </div>
        );
    }

    /**
     * returns an entrance animation effect function to wrap a JSX element
     * @param presEffectDoc presentation effects document that specifies the animation effect parameters
     * @returns a function that will wrap a JSX animation element wrapping any JSX element
     */
    public static AnimationEffect(renderDoc: JSX.Element, presEffectDoc: Opt<Doc>, root: Doc) {
        const dir = presEffectDoc?.presentation_effectDirection ?? presEffectDoc?.followLinkAnimDirection;
        const effectProps = {
            left: dir === PresEffectDirection.Left,
            right: dir === PresEffectDirection.Right,
            top: dir === PresEffectDirection.Top,
            bottom: dir === PresEffectDirection.Bottom,
            opposite: true,
            delay: 0,
            duration: Cast(presEffectDoc?.presentation_transition, 'number', Cast(presEffectDoc?.followLinkTransitionTime, 'number', null)),
        };
        //prettier-ignore
        switch (StrCast(presEffectDoc?.presentation_effect, StrCast(presEffectDoc?.followLinkAnimEffect))) {
            default: 
            case PresEffect.None:       return renderDoc;
            case PresEffect.Zoom:       return <Zoom {...effectProps}>{renderDoc}</Zoom>;
            case PresEffect.Fade:       return <Fade {...effectProps}>{renderDoc}</Fade>;
            case PresEffect.Flip:       return <Flip {...effectProps}>{renderDoc}</Flip>;
            case PresEffect.Rotate:     return <Rotate {...effectProps}>{renderDoc}</Rotate>;
            case PresEffect.Bounce:     return <Bounce {...effectProps}>{renderDoc}</Bounce>;
            case PresEffect.Roll:       return <Roll {...effectProps}>{renderDoc}</Roll>;
            case PresEffect.Lightspeed: return <JackInTheBox {...effectProps}>{renderDoc}</JackInTheBox>;
        }
    }
    public static recordAudioAnnotation(dataDoc: Doc, field: string, onRecording?: (stop: () => void) => void, onEnd?: () => void) {
        let gumStream: any;
        let recorder: any;
        navigator.mediaDevices
            .getUserMedia({
                audio: true,
            })
            .then(function (stream) {
                let audioTextAnnos = Cast(dataDoc[field + '_audioAnnotations_text'], listSpec('string'), null);
                if (audioTextAnnos) audioTextAnnos.push('');
                else audioTextAnnos = dataDoc[field + '_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({ file: e.data });
                    if (!(result instanceof Error)) {
                        const audioField = new AudioField(result.accessPaths.agnostic.client);
                        const audioAnnos = Cast(dataDoc[field + '_audioAnnotations'], listSpec(AudioField), null);
                        if (audioAnnos === undefined) {
                            dataDoc[field + '_audioAnnotations'] = new List([audioField]);
                        } else {
                            audioAnnos.push(audioField);
                        }
                    }
                };
                //runInAction(() => (dataDoc.audioAnnoState = 'recording'));
                recorder.start();
                const stopFunc = () => {
                    recorder.stop();
                    DictationManager.Controls.stop(false);
                    runInAction(() => (dataDoc.audioAnnoState = 'stopped'));
                    gumStream.getAudioTracks()[0].stop();
                };
                if (onRecording) onRecording(stopFunc);
                else setTimeout(stopFunc, 5000);
            });
    }
}

@observer
export class DocumentView extends DocComponent<DocumentViewProps>() {
    public static ROOT_DIV = 'documentView-effectsWrapper';
    public get displayName() {  return 'DocumentView(' + this.Document?.title + ')';  } // prettier-ignore
    public ContentRef = React.createRef<HTMLDivElement>();
    private _htmlOverlayEffect: Opt<Doc>;
    private _disposers: { [name: string]: IReactionDisposer } = {};
    private _viewTimer: NodeJS.Timeout | undefined;
    private _animEffectTimer: NodeJS.Timeout | undefined;
    public Guid = Utils.GenerateGuid(); // a unique id associated with the main <div>. used by LinkBox's Xanchor to find the arrowhead locations.

    @computed public static get exploreMode() {
        return () => (SnappingManager.ExploreMode ? ScriptField.MakeScript('CollectionBrowseClick(documentView, clientX, clientY)', { documentView: 'any', clientX: 'number', clientY: 'number' })! : undefined);
    }

    constructor(props: DocumentViewProps) {
        super(props);
        makeObservable(this);
    }

    // want the htmloverlay to be able to fade in but we also want it to be display 'none' until it is needed.
    // unfortunately, CSS can't transition animate any properties for something that is display 'none'.
    // so we need to first activate the div, then, after a render timeout, start the opacity transition.
    @observable private _enableHtmlOverlayTransitions: boolean = false;
    @observable private _docViewInternal: DocumentViewInternal | undefined | null = undefined;
    @observable private _htmlOverlayText: Opt<string> = undefined;
    @observable private _isHovering = false;
    @observable private _selected = false;
    @observable public static LongPress = false;

    @computed private get shouldNotScale() {
        return (this.layout_fitWidth && !this.nativeWidth) || this._props.LayoutTemplateString?.includes(KeyValueBox.name) || [CollectionViewType.Docking].includes(this.Document._type_collection as any);
    }
    @computed private get effectiveNativeWidth() {
        return this.shouldNotScale ? 0 : this.nativeWidth || NumCast(this.layoutDoc.width);
    }
    @computed private get effectiveNativeHeight() {
        return this.shouldNotScale ? 0 : this.nativeHeight || NumCast(this.layoutDoc.height);
    }
    @computed private get nativeScaling() {
        if (this.shouldNotScale) return 1;
        const minTextScale = this.Document.type === DocumentType.RTF ? 0.1 : 0;
        if (this.layout_fitWidth || this._props.PanelHeight() / (this.effectiveNativeHeight || 1) > this._props.PanelWidth() / (this.effectiveNativeWidth || 1)) {
            return Math.max(minTextScale, this._props.PanelWidth() / (this.effectiveNativeWidth || 1)); // width-limited or layout_fitWidth
        }
        return Math.max(minTextScale, this._props.PanelHeight() / (this.effectiveNativeHeight || 1)); // height-limited or unscaled
    }
    @computed private get panelWidth() {
        return this.effectiveNativeWidth ? this.effectiveNativeWidth * this.nativeScaling : this._props.PanelWidth();
    }
    @computed private get panelHeight() {
        if (this.effectiveNativeHeight && (!this.layout_fitWidth || !this.layoutDoc.layout_reflowVertical)) {
            return Math.min(this._props.PanelHeight(), this.effectiveNativeHeight * this.nativeScaling);
        }
        return this._props.PanelHeight();
    }
    @computed private get Xshift() {
        return this.effectiveNativeWidth ? Math.max(0, (this._props.PanelWidth() - this.effectiveNativeWidth * this.nativeScaling) / 2) : 0;
    }
    @computed private get Yshift() {
        return this.effectiveNativeWidth &&
            this.effectiveNativeHeight &&
            Math.abs(this.Xshift) < 0.001 &&
            (!this.layoutDoc.layout_reflowVertical || (!this.layout_fitWidth && this.effectiveNativeHeight * this.nativeScaling <= this._props.PanelHeight()))
            ? Math.max(0, (this._props.PanelHeight() - this.effectiveNativeHeight * this.nativeScaling) / 2)
            : 0;
    }
    @computed private get hideLinkButton() {
        return (
            this._props.hideLinkButton ||
            this._props.renderDepth === -1 || //
            (this.IsSelected && this._props.renderDepth) ||
            !this._isHovering ||
            (!this.IsSelected && this.layoutDoc.layout_hideLinkButton) ||
            SnappingManager.IsDragging ||
            SnappingManager.IsResizing
        );
    }

    componentDidMount() {
        runInAction(() => this.Document[DocViews].add(this));
        this._disposers.onViewMounted = reaction(() => ScriptCast(this.Document.onViewMounted)?.script?.run({ this: this.Document }).result, emptyFunction);
        !BoolCast(this.Document.dontRegisterView, this._props.dontRegisterView) && DocumentManager.Instance.AddView(this);
    }

    componentWillUnmount() {
        this._viewTimer && clearTimeout(this._viewTimer);
        runInAction(() => this.Document[DocViews].delete(this));
        Object.values(this._disposers).forEach(disposer => disposer?.());
        !BoolCast(this.Document.dontRegisterView, this._props.dontRegisterView) && DocumentManager.Instance.RemoveView(this);
    }

    public set IsSelected(val)  { runInAction(() => (this._selected = val)); } // prettier-ignore
    public get IsSelected()     { return this._selected; } // prettier-ignore
    public get topMost()        { return this._props.renderDepth === 0; } // prettier-ignore
    public get ContentDiv()     { return this._docViewInternal?._contentDiv; } // prettier-ignore
    public get ComponentView()  { return this._docViewInternal?._componentView; } // prettier-ignore
    public get allLinks()       { return this._docViewInternal?._allLinks ?? []; } // prettier-ignore

    get LayoutFieldKey() {
        return Doc.LayoutFieldKey(this.Document, this._props.LayoutTemplateString);
    }

    @computed get layout_fitWidth() {
        return this._props.layout_fitWidth?.(this.layoutDoc) ?? this.layoutDoc?.layout_fitWidth;
    }
    @computed get anchorViewDoc() {
        return this._props.LayoutTemplateString?.includes('link_anchor_2') ? DocCast(this.Document['link_anchor_2']) : this._props.LayoutTemplateString?.includes('link_anchor_1') ? DocCast(this.Document['link_anchor_1']) : undefined;
    }

    @computed get getBounds(): Opt<{ left: number; top: number; right: number; bottom: number; transition?: string }> {
        if (!this.ContentDiv || Doc.AreProtosEqual(this.Document, Doc.UserDoc())) {
            return undefined;
        }
        if (this.ComponentView?.screenBounds?.()) {
            return this.ComponentView.screenBounds();
        }
        const xf = this.screenToContentsTransform().scale(this.nativeScaling).inverse();
        const [[left, top], [right, bottom]] = [xf.transformPoint(0, 0), xf.transformPoint(this.panelWidth, this.panelHeight)];

        if (this._props.LayoutTemplateString?.includes(LinkAnchorBox.name)) {
            const docuBox = this.ContentDiv.getElementsByClassName('linkAnchorBox-cont');
            if (docuBox.length) return { ...docuBox[0].getBoundingClientRect(), transition: undefined };
        }
        // transition is returned so that the bounds will 'update' at the end of an animated transition.  This is needed by xAnchor in LinkBox
        const transition = this.docViewPath().find((parent: DocumentView) => parent.DataTransition?.() || parent.ComponentView?.viewTransition?.());
        return { left, top, right, bottom, transition: transition?.DataTransition?.() || transition?.ComponentView?.viewTransition?.() };
    }

    @computed get nativeWidth() {
        return this._props.LayoutTemplateString?.includes(KeyValueBox.name) ? 0 : returnVal(this._props.NativeWidth?.(), Doc.NativeWidth(this.layoutDoc, this._props.TemplateDataDocument, !this.layout_fitWidth));
    }
    @computed get nativeHeight() {
        return this._props.LayoutTemplateString?.includes(KeyValueBox.name) ? 0 : returnVal(this._props.NativeHeight?.(), Doc.NativeHeight(this.layoutDoc, this._props.TemplateDataDocument, !this.layout_fitWidth));
    }
    @computed public get centeringX() { return this._props.dontCenter?.includes('x') ? 0 : this.Xshift; } // prettier-ignore
    @computed public get centeringY() { return this._props.dontCenter?.includes('y') ? 0 : this.Yshift; } // prettier-ignore

    /**
     * path of DocumentViews hat contains this DocumentView (does not includes this DocumentView thouhg)
     */
    public get containerViewPath() { return this._props.containerViewPath; } // prettier-ignore
    public get CollectionFreeFormView() { return this.CollectionFreeFormDocumentView?.CollectionFreeFormView; } // prettier-ignore
    public get CollectionFreeFormDocumentView() { return this._props.CollectionFreeFormDocumentView?.(); } // prettier-ignore

    public clearViewTransition = () => {
        this._viewTimer && clearTimeout(this._viewTimer);
        this.layoutDoc._viewTransition = undefined;
    };
    public noOnClick = () => this._docViewInternal?.noOnClick();
    public toggleFollowLink = (zoom?: boolean, setTargetToggle?: boolean): void => this._docViewInternal?.toggleFollowLink(zoom, setTargetToggle);
    public setToggleDetail = (defaultLayout = '', scriptFieldKey = 'onClick') => this._docViewInternal?.setToggleDetail(defaultLayout, scriptFieldKey);
    public onContextMenu = (e?: React.MouseEvent, pageX?: number, pageY?: number) => this._docViewInternal?.onContextMenu?.(e, pageX, pageY);
    public cleanupPointerEvents = () => this._docViewInternal?.cleanupPointerEvents();
    public startDragging = (x: number, y: number, dropAction: dropActionType, hideSource = false) => this._docViewInternal?.startDragging(x, y, dropAction, hideSource);
    public showContextMenu = (pageX: number, pageY: number) => this._docViewInternal?.onContextMenu(undefined, pageX, pageY);

    public toggleNativeDimensions = () => this._docViewInternal && this.Document.type !== DocumentType.INK && Doc.toggleNativeDimensions(this.layoutDoc, this.NativeDimScaling() ?? 1, this._props.PanelWidth(), this._props.PanelHeight());

    public iconify(finished?: () => void, animateTime?: number) {
        this.ComponentView?.updateIcon?.();
        const animTime = this._docViewInternal?.animateScaleTime();
        runInAction(() => this._docViewInternal && animateTime !== undefined && (this._docViewInternal._animateScaleTime = animateTime));
        const finalFinished = action(() => {
            finished?.();
            this._docViewInternal && (this._docViewInternal._animateScaleTime = animTime);
        });
        const layout_fieldKey = Cast(this.Document.layout_fieldKey, 'string', null);
        if (layout_fieldKey !== 'layout_icon') {
            this.switchViews(true, 'icon', finalFinished);
            if (layout_fieldKey && layout_fieldKey !== 'layout' && layout_fieldKey !== 'layout_icon') this.Document.deiconifyLayout = layout_fieldKey.replace('layout_', '');
        } else {
            const deiconifyLayout = Cast(this.Document.deiconifyLayout, 'string', null);
            this.switchViews(deiconifyLayout ? true : false, deiconifyLayout, finalFinished);
            this.Document.deiconifyLayout = undefined;
            this._props.bringToFront?.(this.Document);
        }
    }

    public playAnnotation = () => {
        const self = this;
        const audioAnnoState = this.dataDoc.audioAnnoState ?? 'stopped';
        const audioAnnos = Cast(this.dataDoc[this.LayoutFieldKey + '_audioAnnotations'], listSpec(AudioField), null);
        const anno = audioAnnos?.lastElement();
        if (anno instanceof AudioField) {
            switch (audioAnnoState) {
                case 'stopped':
                    this.dataDoc[AudioPlay] = new Howl({
                        src: [anno.url.href],
                        format: ['mp3'],
                        autoplay: true,
                        loop: false,
                        volume: 0.5,
                        onend: action(() => (self.dataDoc.audioAnnoState = 'stopped')),
                    });
                    this.dataDoc.audioAnnoState = 'playing';
                    break;
                case 'playing':
                    this.dataDoc[AudioPlay]?.stop();
                    this.dataDoc.audioAnnoState = 'stopped';
                    break;
            }
        }
    };

    public setTextHtmlOverlay = action((text: string | undefined, effect?: Doc) => {
        this._htmlOverlayText = text;
        this._htmlOverlayEffect = effect;
    });
    public setAnimateScaling = action((scale: number, time?: number) => {
        if (this._docViewInternal) {
            this._docViewInternal._animateScalingTo = scale;
            this._docViewInternal._animateScaleTime = time;
        }
    });
    public setAnimEffect = (presEffect: Doc, timeInMs: number, afterTrans?: () => void) => {
        this._animEffectTimer && clearTimeout(this._animEffectTimer);
        this.Document[Animation] = presEffect;
        this._animEffectTimer = setTimeout(() => (this.Document[Animation] = undefined), timeInMs);
    };
    public setViewTransition = (transProp: string, timeInMs: number, afterTrans?: () => void, dataTrans = false) => {
        this._viewTimer = DocumentView.SetViewTransition([this.layoutDoc], transProp, timeInMs, this._viewTimer, afterTrans, dataTrans);
    };

    public setCustomView = undoable((custom: boolean, layout: string): void => {
        Doc.setNativeView(this.Document);
        custom && DocUtils.makeCustomViewClicked(this.Document, Docs.Create.StackingDocument, layout, undefined);
    }, 'set custom view');

    public switchViews = (custom: boolean, view: string, finished?: () => void, useExistingLayout = false) => {
        runInAction(() => this._docViewInternal && (this._docViewInternal._animateScalingTo = 0.1)); // shrink doc
        setTimeout(
            action(() => {
                if (useExistingLayout && custom && this.Document['layout_' + view]) {
                    this.Document.layout_fieldKey = 'layout_' + view;
                } else {
                    this.setCustomView(custom, view);
                }
                this._docViewInternal && (this._docViewInternal._animateScalingTo = 1); // expand it
                setTimeout(
                    action(() => {
                        this._docViewInternal && (this._docViewInternal._animateScalingTo = 0);
                        finished?.();
                    }),
                    Math.max(0, (this._docViewInternal?.animateScaleTime() ?? 0) - 10)
                );
            }),
            Math.max(0, (this._docViewInternal?.animateScaleTime() ?? 0) - 10)
        );
    };
    /**
     * @returns a hierarchy path through  the nested DocumentViews that display this view.  The last element of the path is this view.
     */
    public docViewPath = () => (this.containerViewPath ? [...this.containerViewPath(), this] : [this]);

    layout_fitWidthFunc = (doc: Doc) => BoolCast(this.layout_fitWidth);
    screenToLocalScale = () => this._props.ScreenToLocalTransform().Scale;
    isSelected = () => this.IsSelected;
    select = (extendSelection: boolean, focusSelection?: boolean) => {
        if (this.IsSelected && SelectionManager.Views.length > 1) SelectionManager.DeselectView(this);
        else {
            SelectionManager.SelectView(this, extendSelection);
            if (focusSelection) {
                DocumentManager.Instance.showDocument(this.Document, {
                    willZoomCentered: true,
                    zoomScale: 0.9,
                    zoomTime: 500,
                });
            }
        }
    };
    DataTransition = () => this._props.DataTransition?.() || StrCast(this.Document.dataTransition);
    ShouldNotScale = () => this.shouldNotScale;
    NativeWidth = () => this.effectiveNativeWidth;
    NativeHeight = () => this.effectiveNativeHeight;
    PanelWidth = () => this.panelWidth;
    PanelHeight = () => this.panelHeight;
    NativeDimScaling = () => this.nativeScaling;
    hideLinkCount = () => (this.hideLinkButton ? true : false);
    selfView = () => this;
    /**
     * @returns Transform to the document view (in the coordinate system of whatever contains the DocumentView)
     */
    screenToViewTransform = () => this._props.ScreenToLocalTransform();
    /**
     * @returns Transform to the coordinate system of the contents of the document view (includes native dimension scaling and centering)
     */
    screenToContentsTransform = () =>
        this._props
            .ScreenToLocalTransform()
            .translate(-this.centeringX, -this.centeringY)
            .scale(1 / this.nativeScaling);

    htmlOverlay = () => {
        const effect = StrCast(this._htmlOverlayEffect?.presentation_effect, StrCast(this._htmlOverlayEffect?.followLinkAnimEffect));
        return (
            <div
                className="documentView-htmlOverlay"
                ref={r => {
                    const val = r?.style.display !== 'none'; // if the outer overlay has been displayed, trigger the innner div to start it's opacity fade in transition
                    if (r && val !== this._enableHtmlOverlayTransitions) {
                        setTimeout(action(() => (this._enableHtmlOverlayTransitions = val)));
                    }
                }}
                style={{ display: !this._htmlOverlayText ? 'none' : undefined }}>
                <div className="documentView-htmlOverlayInner" style={{ transition: `all 500ms`, opacity: this._enableHtmlOverlayTransitions ? 0.9 : 0 }}>
                    {DocumentViewInternal.AnimationEffect(
                        <div className="webBox-textHighlight">
                            <ObserverJsxParser autoCloseVoidElements={true} key={42} onError={(e: any) => console.log('PARSE error', e)} renderInWrapper={false} jsx={StrCast(this._htmlOverlayText)} />
                        </div>,
                        { ...(this._htmlOverlayEffect ?? {}), presentation_effect: effect ?? PresEffect.Zoom } as any as Doc,
                        this.Document
                    )}
                </div>
            </div>
        );
    };

    render() {
        TraceMobx();
        const xshift = Math.abs(this.Xshift) <= 0.001 ? this._props.PanelWidth() : undefined;
        const yshift = Math.abs(this.Yshift) <= 0.001 ? this._props.PanelHeight() : undefined;

        return (
            <div id={this.Guid} className="contentFittingDocumentView" onPointerEnter={action(() => (this._isHovering = true))} onPointerLeave={action(() => (this._isHovering = false))}>
                {!this.Document || !this._props.PanelWidth() ? null : (
                    <div
                        className="contentFittingDocumentView-previewDoc"
                        ref={this.ContentRef}
                        style={{
                            transform: `translate(${this.centeringX}px, ${this.centeringY}px)`,
                            width: xshift ?? `${this._props.PanelWidth() - this.Xshift * 2}px`,
                            height: this._props.forceAutoHeight ? undefined : yshift ?? (this.layout_fitWidth ? `${this.panelHeight}px` : `${(this.effectiveNativeHeight / this.effectiveNativeWidth) * this._props.PanelWidth()}px`),
                        }}>
                        <DocumentViewInternal
                            {...this._props}
                            fieldKey={this.LayoutFieldKey}
                            DataTransition={this.DataTransition}
                            DocumentView={this.selfView}
                            docViewPath={this.docViewPath}
                            PanelWidth={this.PanelWidth}
                            PanelHeight={this.PanelHeight}
                            NativeWidth={this.NativeWidth}
                            NativeHeight={this.NativeHeight}
                            NativeDimScaling={this.NativeDimScaling}
                            isSelected={this.isSelected}
                            select={this.select}
                            layout_fitWidth={this.layout_fitWidthFunc}
                            ScreenToLocalTransform={this.screenToContentsTransform}
                            focus={this._props.focus || emptyFunction}
                            ref={action((r: DocumentViewInternal | null) => r && (this._docViewInternal = r))}
                        />
                        {this.htmlOverlay()}
                        {this.ComponentView?.infoUI?.()}
                    </div>
                )}
                {/* display link count button */}
                <DocumentLinksButton hideCount={this.hideLinkCount} View={this} scaling={this.screenToLocalScale} OnHover={true} Bottom={this.topMost} ShowCount={true} />
            </div>
        );
    }

    public static SetViewTransition(docs: Doc[], transProp: string, timeInMs: number, timer?: NodeJS.Timeout | undefined, afterTrans?: () => void, dataTrans = false) {
        docs.forEach(doc => {
            doc._viewTransition = `${transProp} ${timeInMs}ms`;
            dataTrans && (doc.dataTransition = `${transProp} ${timeInMs}ms`);
        });
        timer && clearTimeout(timer);
        return setTimeout(
            () =>
                docs.forEach(doc => {
                    doc._viewTransition = undefined;
                    dataTrans && (doc.dataTransition = 'inherit');
                    afterTrans?.();
                }),
            timeInMs + 10
        );
    }

    // shows a stacking view collection (by default, but the user can change) of all documents linked to the source
    public static showBackLinks(linkAnchor: Doc) {
        const docId = Doc.CurrentUserEmail + Doc.GetProto(linkAnchor)[Id] + '-pivotish';
        // prettier-ignore
        DocServer.GetRefField(docId).then(docx =>
            LightboxView.Instance.SetLightboxDoc(
                (docx as Doc) ?? // reuse existing pivot view of documents, or else create a new collection
                Docs.Create.StackingDocument([], { title: linkAnchor.title + '-pivot', _width: 500, _height: 500, target: linkAnchor, onViewMounted: ScriptField.MakeScript('updateLinkCollection(this, this.target)') }, docId)
            )
        );
    }
}

ScriptingGlobals.add(function deiconifyView(documentView: DocumentView) {
    documentView.iconify();
    documentView.select(false);
});

ScriptingGlobals.add(function deiconifyViewToLightbox(documentView: DocumentView) {
    LightboxView.Instance.AddDocTab(documentView.Document, OpenWhere.lightbox, 'layout'); //, 0);
});

ScriptingGlobals.add(function toggleDetail(dv: DocumentView, detailLayoutKeySuffix: string, defaultLayout = '') {
    if (dv.Document.layout_fieldKey === 'layout_' + detailLayoutKeySuffix) dv.switchViews(defaultLayout ? true : false, defaultLayout, undefined, true);
    else dv.switchViews(true, detailLayoutKeySuffix, undefined, true);
});

ScriptingGlobals.add(function updateLinkCollection(linkCollection: Doc, linkSource: Doc) {
    const collectedLinks = DocListCast(linkCollection[DocData].data);
    let wid = NumCast(linkSource._width);
    let embedding: Doc | undefined;
    const links = LinkManager.Links(linkSource);
    links.forEach(link => {
        const other = LinkManager.getOppositeAnchor(link, linkSource);
        const otherdoc = DocCast(other?.annotationOn ?? other);
        if (otherdoc && !collectedLinks?.some(d => Doc.AreProtosEqual(d, otherdoc))) {
            embedding = Doc.MakeEmbedding(otherdoc);
            embedding.x = wid;
            embedding.y = 0;
            embedding._lockedPosition = false;
            wid += NumCast(otherdoc._width);
            Doc.AddDocToList(Doc.GetProto(linkCollection), 'data', embedding);
        }
    });
    embedding && DocServer.UPDATE_SERVER_CACHE(); // if a new embedding was made, update the client's server cache so that it will not come back as a promise
    return links;
});
ScriptingGlobals.add(function updateTagsCollection(collection: Doc) {
    const tag = StrCast(collection.title).split('-->')[1];
    const matchedTags = Array.from(SearchUtil.SearchCollection(Doc.MyFilesystem, tag, false, ['tags']).keys());
    const collectionDocs = DocListCast(collection[DocData].data).concat(collection);
    let wid = 100;
    let created = false;
    const matchedDocs = matchedTags
        .filter(tagDoc => !Doc.AreProtosEqual(collection, tagDoc))
        .map(tagDoc => {
            let embedding = collectionDocs.find(doc => Doc.AreProtosEqual(tagDoc, doc));
            if (!embedding) {
                embedding = Doc.MakeEmbedding(tagDoc);
                embedding.x = wid;
                embedding.y = 0;
                embedding._lockedPosition = false;
                wid += NumCast(tagDoc._width);
                created = true;
            }
            return embedding;
        });

    created && (collection[DocData].data = new List<Doc>(matchedDocs));
    return true;
});
