aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/WebBox.tsx
blob: 7b2fafaa97a58f415b7df4af8285e624d9423690 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { action, computed, IReactionDisposer, observable, ObservableMap, reaction, runInAction } from "mobx";
import { observer } from "mobx-react";
import * as WebRequest from 'web-request';
import { Doc, DocListCast, HeightSym, Opt, WidthSym } from "../../../fields/Doc";
import { documentSchema } from "../../../fields/documentSchemas";
import { Id } from "../../../fields/FieldSymbols";
import { HtmlField } from "../../../fields/HtmlField";
import { InkTool } from "../../../fields/InkField";
import { List } from "../../../fields/List";
import { listSpec, makeInterface } from "../../../fields/Schema";
import { ComputedField } from "../../../fields/ScriptField";
import { Cast, NumCast, StrCast } from "../../../fields/Types";
import { WebField } from "../../../fields/URLField";
import { TraceMobx } from "../../../fields/util";
import { emptyFunction, getWordAtPoint, OmitKeys, returnFalse, returnOne, setupMoveUpEvents, smoothScroll, Utils } from "../../../Utils";
import { Docs } from "../../documents/Documents";
import { DocumentType } from '../../documents/DocumentTypes';
import { CurrentUserUtils } from "../../util/CurrentUserUtils";
import { Scripting } from "../../util/Scripting";
import { SnappingManager } from "../../util/SnappingManager";
import { undoBatch } from "../../util/UndoManager";
import { CollectionFreeFormView } from "../collections/collectionFreeForm/CollectionFreeFormView";
import { ContextMenu } from "../ContextMenu";
import { ContextMenuProps } from "../ContextMenuItem";
import { ViewBoxAnnotatableComponent, ViewBoxAnnotatableProps } from "../DocComponent";
import { DocumentDecorations } from "../DocumentDecorations";
import { LightboxView } from "../LightboxView";
import { MarqueeAnnotator } from "../MarqueeAnnotator";
import { AnchorMenu } from "../pdf/AnchorMenu";
import { Annotation } from "../pdf/Annotation";
import { SidebarAnnos } from "../SidebarAnnos";
import { FieldView, FieldViewProps } from './FieldView';
import { LinkDocPreview } from "./LinkDocPreview";
import "./WebBox.scss";
import React = require("react");
const _global = (window /* browser */ || global /* node */) as any;
const htmlToText = require("html-to-text");

type WebDocument = makeInterface<[typeof documentSchema]>;
const WebDocument = makeInterface(documentSchema);

@observer
export class WebBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatableProps & FieldViewProps, WebDocument>(WebDocument) {
    public static LayoutString(fieldKey: string) { return FieldView.LayoutString(WebBox, fieldKey); }
    public static openSidebarWidth = 250;
    private _setPreviewCursor: undefined | ((x: number, y: number, drag: boolean) => void);
    private _mainCont: React.RefObject<HTMLDivElement> = React.createRef();
    private _outerRef: React.RefObject<HTMLDivElement> = React.createRef();
    private _disposers: { [name: string]: IReactionDisposer } = {};
    private _annotationLayer: React.RefObject<HTMLDivElement> = React.createRef();
    private _keyInput = React.createRef<HTMLInputElement>();
    private _initialScroll: Opt<number>;
    private _sidebarRef = React.createRef<SidebarAnnos>();
    @observable private _scrollTimer: any;
    @observable private _overlayAnnoInfo: Opt<Doc>;
    @observable private _marqueeing: number[] | undefined;
    @observable private _url: string = "hello";
    @observable private _isAnnotating = false;
    @observable private _iframeClick: HTMLIFrameElement | undefined = undefined;
    @observable private _iframe: HTMLIFrameElement | null = null;
    @observable private _savedAnnotations = new ObservableMap<number, HTMLDivElement[]>();
    @observable private _scrollHeight = 1500;
    @computed get scrollHeight() { return this._scrollHeight; }
    @computed get allAnnotations() { return DocListCast(this.dataDoc[this.annotationKey]); }
    @computed get inlineTextAnnotations() { return this.allAnnotations.filter(a => a.textInlineAnnotations); }
    @computed get webField() { return Cast(this.dataDoc[this.props.fieldKey], WebField)?.url; }

    constructor(props: any) {
        super(props);
        if (true) {// his.webField) {
            Doc.SetNativeWidth(this.dataDoc, Doc.NativeWidth(this.dataDoc) || 850);
            Doc.SetNativeHeight(this.dataDoc, Doc.NativeHeight(this.dataDoc) || this.Document[HeightSym]() / this.Document[WidthSym]() * 850);
        }
        if (this.layoutDoc[this.fieldKey + "-contentWidth"] === undefined) {
            this.layoutDoc[this.fieldKey + "-contentWidth"] = Doc.NativeWidth(this.layoutDoc);
        }
    }

    async componentDidMount() {
        this.props.setContentView?.(this); // this tells the DocumentView that this AudioBox is the "content" of the document.  this allows the DocumentView to indirectly call getAnchor() on the AudioBox when making a link.

        runInAction(() => {
            this._url = this.webField?.toString() || "";
            this._annotationKey = "annotations-" + WebBox.urlHash(this._url);
            // bcz: need to make sure that doc.data-annotations points to the currently active web page's annotations (this could/should be when the doc is created)
            this.dataDoc[this.fieldKey + "-annotations"] = ComputedField.MakeFunction(`copyField(this["${this.fieldKey}-annotations-"+urlHash(this["${this.fieldKey}"]?.url?.toString()))`);
        });

        this._disposers.selection = reaction(() => this.props.isSelected(),
            selected => !selected && setTimeout(() => {
                // Array.from(this._savedAnnotations.values()).forEach(v => v.forEach(a => a.remove()));
                // this._savedAnnotations.clear();
            })
        );

        if (this.webField?.href.indexOf("youtube") !== -1) {
            const youtubeaspect = 400 / 315;
            const nativeWidth = Doc.NativeWidth(this.layoutDoc);
            const nativeHeight = Doc.NativeHeight(this.layoutDoc);
            if (this.webField) {
                if (!nativeWidth || !nativeHeight || Math.abs(nativeWidth / nativeHeight - youtubeaspect) > 0.05) {
                    if (!nativeWidth) Doc.SetNativeWidth(this.layoutDoc, 600);
                    Doc.SetNativeHeight(this.layoutDoc, (nativeWidth || 600) / youtubeaspect);
                    this.layoutDoc._height = this.layoutDoc[WidthSym]() / youtubeaspect;
                }
            } // else it's an HTMLfield
        } else if (this.webField && !this.dataDoc.text) {
            const result = await WebRequest.get(Utils.CorsProxy(this.webField.href));
            if (result) {
                this.dataDoc.text = htmlToText.fromString(result.content);
            }
        }

        var quickScroll = true;
        this._disposers.scrollReaction = reaction(() => NumCast(this.layoutDoc._scrollTop),
            (scrollTop) => {
                if (quickScroll) this._initialScroll = scrollTop;
                else {
                    const viewTrans = StrCast(this.Document._viewTransition);
                    const durationMiliStr = viewTrans.match(/([0-9]*)ms/);
                    const durationSecStr = viewTrans.match(/([0-9.]*)s/);
                    const duration = durationMiliStr ? Number(durationMiliStr[1]) : durationSecStr ? Number(durationSecStr[1]) * 1000 : 0;
                    this.goTo(scrollTop, duration);
                }
            },
            { fireImmediately: true }
        );
        quickScroll = false;
    }
    componentWillUnmount() {
        Object.values(this._disposers).forEach(disposer => disposer?.());
        this._iframe?.removeEventListener('wheel', this.iframeWheel, true);
    }

    @action
    createTextAnnotation = (sel: Selection, selRange: Range) => {
        if (this._mainCont.current) {
            const clientRects = selRange.getClientRects();
            for (let i = 0; i < clientRects.length; i++) {
                const rect = clientRects.item(i);
                if (rect && rect.width !== this._mainCont.current.clientWidth) {
                    const annoBox = document.createElement("div");
                    annoBox.className = "marqueeAnnotator-annotationBox";
                    // transforms the positions from screen onto the pdf div
                    annoBox.style.top = (rect.top + this._mainCont.current.scrollTop).toString();
                    annoBox.style.left = (rect.left).toString();
                    annoBox.style.width = (rect.width).toString();
                    annoBox.style.height = (rect.height).toString();
                    this._annotationLayer.current && MarqueeAnnotator.previewNewAnnotation(this._savedAnnotations, this._annotationLayer.current, annoBox, 1);
                }
            }
        }
        //this._selectionText = selRange.cloneContents().textContent || "";

        // clear selection
        if (sel.empty) sel.empty();// Chrome
        else if (sel.removeAllRanges) sel.removeAllRanges();  // Firefox
    }

    menuControls = () => this.urlEditor; // controls to be added to the top bar when a document of this type is selected

    scrollFocus = (doc: Doc, smooth: boolean) => {
        if (DocListCast(this.props.Document[this.fieldKey + "-sidebar"]).includes(doc) && !this.SidebarShown) {
            this.toggleSidebar(!smooth);
        }
        if (this._sidebarRef?.current?.makeDocUnfiltered(doc)) return 1;
        if (doc !== this.rootDoc && this._outerRef.current) {
            const windowHeight = this.props.PanelHeight() / (this.props.scaling?.() || 1);
            const scrollTo = Utils.scrollIntoView(NumCast(doc.y), doc[HeightSym](), NumCast(this.layoutDoc._scrollTop), windowHeight, windowHeight * .1);
            if (scrollTo !== undefined) {
                const focusSpeed = smooth ? 500 : 0;
                this._initialScroll !== undefined && (this._initialScroll = scrollTo);
                this.goTo(scrollTo, focusSpeed);
                return focusSpeed;
            }
        }
        this._initialScroll = NumCast(doc.y);
        return 0;
    }

    getAnchor = () => {
        const anchor =
            AnchorMenu.Instance?.GetAnchor(this._savedAnnotations) ??
            Docs.Create.TextanchorDocument({
                title: StrCast(this.rootDoc.title + " " + this.layoutDoc._scrollTop),
                annotationOn: this.rootDoc,
                y: NumCast(this.layoutDoc._scrollTop),
            });
        this.addDocument(anchor);
        return anchor;
    }

    @action
    iframeUp = (e: PointerEvent) => {
        if (this._iframe?.contentWindow && this._iframe.contentDocument && !this._iframe.contentWindow.getSelection()?.isCollapsed) {
            this._iframe.contentDocument.addEventListener("pointerup", this.iframeUp);
            const mainContBounds = Utils.GetScreenTransform(this._mainCont.current!);
            const scale = (this.props.scaling?.() || 1) * mainContBounds.scale;
            const sel = this._iframe.contentWindow.getSelection();
            if (sel) {
                this.createTextAnnotation(sel, sel.getRangeAt(0));
                AnchorMenu.Instance.jumpTo(e.clientX * scale + mainContBounds.translateX,
                    e.clientY * scale + mainContBounds.translateY - NumCast(this.layoutDoc._scrollTop) * scale);
            }
        } else AnchorMenu.Instance.fadeOut(true);
    }
    @action
    iframeDown = (e: PointerEvent) => {
        const mainContBounds = Utils.GetScreenTransform(this._mainCont.current!);
        const scale = (this.props.scaling?.() || 1) * mainContBounds.scale;
        const word = getWordAtPoint(e.target, e.clientX, e.clientY);
        this._marqueeing = [e.clientX * scale + mainContBounds.translateX,
        e.clientY * scale + mainContBounds.translateY - NumCast(this.layoutDoc._scrollTop) * scale];
        if (word) {
            this._iframe?.contentDocument?.addEventListener("pointerup", this.iframeUp);
            setTimeout(action(() => this._marqueeing = undefined), 100); // bcz: hack .. anchor menu is setup within MarqueeAnnotator so we need to at least create the marqueeAnnotator even though we aren't using it.
        } else {
            this._iframeClick = this._iframe ?? undefined;
            this._isAnnotating = true;
            this.props.select(false);
            e.stopPropagation();
            e.preventDefault();
        }
    }

    isFirefox = () => {
        return "InstallTrigger" in window; // navigator.userAgent.indexOf("Chrome") !== -1;
    }
    iframeClick = () => this._iframeClick;
    iframeScaling = () => 1 / this.props.ScreenToLocalTransform().Scale;

    @action
    iframeLoaded = (e: any) => {
        const iframe = this._iframe;
        if (iframe?.contentDocument) {
            iframe?.contentDocument.addEventListener("pointerdown", this.iframeDown);
            this._scrollHeight = Math.max(this.scrollHeight, iframe?.contentDocument.body.scrollHeight);
            setTimeout(action(() => this._scrollHeight = Math.max(this.scrollHeight, iframe?.contentDocument?.body.scrollHeight || 0)), 5000);
            if (this._initialScroll !== undefined && this._outerRef.current) {
                this._outerRef.current.scrollTop = this._initialScroll;
                this._initialScroll = undefined;
            }
            iframe.setAttribute("enable-annotation", "true");
            iframe.contentDocument.addEventListener("click", undoBatch(action(e => {
                let href = "";
                for (let ele = e.target; ele; ele = ele.parentElement) {
                    href = (typeof (ele.href) === "string" ? ele.href : ele.href?.baseVal) || ele.parentElement?.href || href;
                }
                if (href && this.webField?.origin) {
                    this.submitURL(href.replace(Utils.prepend(""), this.webField?.origin));
                    if (this._outerRef.current) {
                        this._outerRef.current.scrollTop = NumCast(this.layoutDoc._scrollTop);
                        this._outerRef.current.scrollLeft = 0;
                    }
                }
            })));
            iframe.contentDocument.addEventListener('wheel', this.iframeWheel, false);
            //iframe.contentDocument.addEventListener('scroll', () => !this.active() && this._iframe && (this._iframe.scrollTop = NumCast(this.layoutDoc._scrollTop), false));
        }
    }

    @action
    iframeWheel = (e: any) => {
        if (!this._scrollTimer) {
            this._scrollTimer = setTimeout(action(() => this._scrollTimer = undefined), 250); // this turns events off on the iframe which allows scrolling to change direction smoothly
        }
    }

    @action
    setDashScrollTop = (scrollTop: number, timeout: number = 250) => {
        const iframeHeight = Math.max(1000, this._scrollHeight - this.panelHeight());
        timeout = scrollTop > iframeHeight ? 0 : timeout;
        this._scrollTimer && clearTimeout(this._scrollTimer);
        this._scrollTimer = setTimeout(action(() => {
            this._scrollTimer = undefined;
            if (!LinkDocPreview.LinkInfo && this._outerRef.current &&
                (!LightboxView.LightboxDoc || LightboxView.IsLightboxDocView(this.props.docViewPath()))) {
                this.layoutDoc._scrollTop = this._outerRef.current.scrollTop = scrollTop > iframeHeight ? iframeHeight : scrollTop;
            }
        }), timeout);
    }

    goTo = (scrollTop: number, duration: number) => {
        if (this._outerRef.current) {
            const iframeHeight = Math.max(1000, this._scrollHeight - this.panelHeight());
            scrollTop = scrollTop > iframeHeight + 50 ? iframeHeight : scrollTop;
            if (duration) {
                smoothScroll(duration, [this._outerRef.current], scrollTop);
                this.setDashScrollTop(scrollTop, duration);
            } else {
                this.setDashScrollTop(scrollTop);
            }
        }
    }

    @action
    forward = () => {
        const future = Cast(this.dataDoc[this.fieldKey + "-future"], listSpec("string"), []);
        const history = Cast(this.dataDoc[this.fieldKey + "-history"], listSpec("string"), []);
        if (future.length) {
            history.push(this._url);
            this.dataDoc[this.fieldKey] = new WebField(new URL(this._url = future.pop()!));
            this._annotationKey = "annotations-" + WebBox.urlHash(this._url);
            return true;
        }
        return false;
    }

    @action
    back = () => {
        const future = Cast(this.dataDoc[this.fieldKey + "-future"], listSpec("string"));
        const history = Cast(this.dataDoc[this.fieldKey + "-history"], listSpec("string"), []);
        if (history.length) {
            if (future === undefined) this.dataDoc[this.fieldKey + "-future"] = new List<string>([this._url]);
            else future.push(this._url);
            this.dataDoc[this.fieldKey] = new WebField(new URL(this._url = history.pop()!));
            this._annotationKey = "annotations-" + WebBox.urlHash(this._url);
            return true;
        }
        return false;
    }

    static urlHash = (s: string) => {
        return s.split('').reduce((a: any, b: any) => { a = ((a << 5) - a) + b.charCodeAt(0); return a & a; }, 0);
    }

    @action
    submitURL = (newUrl?: string) => {
        if (!newUrl) return;
        if (!newUrl.startsWith("http")) newUrl = "http://" + newUrl;
        try {
            const future = Cast(this.dataDoc[this.fieldKey + "-future"], listSpec("string"));
            const history = Cast(this.dataDoc[this.fieldKey + "-history"], listSpec("string"));
            const url = this.webField?.toString();
            if (url) {
                if (history === undefined) {
                    this.dataDoc[this.fieldKey + "-history"] = new List<string>([url]);
                } else {
                    history.push(url);
                }
                this.layoutDoc._scrollTop = 0;
                future && (future.length = 0);
            }
            this._url = newUrl;
            this._annotationKey = "annotations-" + WebBox.urlHash(this._url);
            this.dataDoc[this.fieldKey] = new WebField(new URL(newUrl));
        } catch (e) {
            console.log("WebBox URL error:" + this._url);
        }
        return true;
    }

    onWebUrlDrop = (e: React.DragEvent) => {
        const { dataTransfer } = e;
        const html = dataTransfer.getData("text/html");
        const uri = dataTransfer.getData("text/uri-list");
        const url = uri || html || this._url || "";
        const newurl = url.startsWith(window.location.origin) ?
            url.replace(window.location.origin, this._url?.match(/http[s]?:\/\/[^\/]*/)?.[0] || "") : url;
        this.submitURL(newurl);
        e.stopPropagation();
    }
    onWebUrlValueKeyDown = (e: React.KeyboardEvent) => {
        e.key === "Enter" && this.submitURL(this._keyInput.current!.value);
        e.stopPropagation();
    }

    @computed get urlEditor() {
        return (
            <div className="collectionMenu-webUrlButtons" onDrop={this.onWebUrlDrop} onDragOver={e => e.preventDefault()} >
                <input className="collectionMenu-urlInput" key={this._url}
                    placeholder="ENTER URL"
                    defaultValue={this._url}
                    onDrop={this.onWebUrlDrop}
                    onDragOver={e => e.preventDefault()}
                    onKeyDown={this.onWebUrlValueKeyDown}
                    onClick={(e) => {
                        this._keyInput.current!.select();
                        e.stopPropagation();
                    }}
                    ref={this._keyInput}
                />
                <div style={{ display: "flex", flexDirection: "row", justifyContent: "space-between", maxWidth: "250px", }}>
                    <button className="submitUrl" onClick={() => this.submitURL(this._keyInput.current!.value)} onDragOver={e => e.stopPropagation()} onDrop={this.onWebUrlDrop}>
                        GO
                    </button>
                    <button className="submitUrl" onClick={this.back}> <FontAwesomeIcon icon="caret-left" size="lg" /> </button>
                    <button className="submitUrl" onClick={this.forward}> <FontAwesomeIcon icon="caret-right" size="lg" />  </button>
                </div>
            </div>
        );
    }

    specificContextMenu = (e: React.MouseEvent): void => {
        const cm = ContextMenu.Instance;
        const funcs: ContextMenuProps[] = [];
        funcs.push({ description: (this.layoutDoc.useCors ? "Don't Use" : "Use") + " Cors", event: () => this.layoutDoc.useCors = !this.layoutDoc.useCors, icon: "snowflake" });
        funcs.push({ description: (this.layoutDoc[this.fieldKey + "-contentWidth"] ? "Unfreeze" : "Freeze") + " Content Width", event: () => this.layoutDoc[this.fieldKey + "-contentWidth"] = this.layoutDoc[this.fieldKey + "-contentWidth"] ? undefined : Doc.NativeWidth(this.layoutDoc), icon: "snowflake" });
        funcs.push({ description: "Toggle Annotation View ", event: () => this.Document._showSidebar = !this.Document._showSidebar, icon: "expand-arrows-alt" });
        cm.addItem({ description: "Options...", subitems: funcs, icon: "asterisk" });
    }

    @action
    onMarqueeDown = (e: React.PointerEvent) => {
        if (!e.altKey && e.button === 0 && this.isContentActive(true) && ![InkTool.Highlighter, InkTool.Pen].includes(CurrentUserUtils.SelectedTool)) {
            this._marqueeing = [e.clientX, e.clientY];
            this.props.select(false);
        }
    }
    @action finishMarquee = (x?: number, y?: number) => {
        this._marqueeing = undefined;
        this._isAnnotating = false;
        this._iframeClick = undefined;
        x !== undefined && y !== undefined && this._setPreviewCursor?.(x, y, false);
    }

    @computed
    get urlContent() {
        const field = this.dataDoc[this.props.fieldKey];
        let view;
        if (field instanceof HtmlField) {
            view = <span className="webBox-htmlSpan" dangerouslySetInnerHTML={{ __html: field.html }} />;
        } else if (field instanceof WebField) {
            const url = this.layoutDoc.useCors ? Utils.CorsProxy(field.url.href) : field.url.href;
            view = <iframe className="webBox-iframe" enable-annotation={"true"}
                style={{ pointerEvents: this._scrollTimer ? "none" : undefined }}
                ref={action((r: HTMLIFrameElement | null) => this._iframe = r)} src={url} onLoad={this.iframeLoaded}
                // the 'allow-top-navigation' and 'allow-top-navigation-by-user-activation' attributes are left out to prevent iframes from redirecting the top-level Dash page
                // sandbox={"allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-popups-to-escape-sandbox allow-presentation allow-same-origin allow-scripts"} />;
                sandbox={"allow-forms allow-modals allow-orientation-lock allow-pointer-lock allow-popups allow-popups-to-escape-sandbox allow-presentation allow-same-origin"} />;
        } else {
            view = <iframe className="webBox-iframe" enable-annotation={"true"}
                style={{ pointerEvents: this._scrollTimer ? "none" : undefined }} // if we allow pointer events when scrolling is on, then reversing direction does not work smoothly
                ref={action((r: HTMLIFrameElement | null) => this._iframe = r)} src={"https://crossorigin.me/https://cs.brown.edu"} />;
        }
        return view;
    }

    sidebarAddDocument = (doc: Doc | Doc[], sidebarKey?: string) => {
        if (!this.layoutDoc._showSidebar) this.toggleSidebar();
        return this.addDocument(doc, sidebarKey);
    }
    sidebarBtnDown = (e: React.PointerEvent) => {
        setupMoveUpEvents(this, e, (e, down, delta) => {
            const localDelta = this.props.ScreenToLocalTransform().scale(this.props.scaling?.() || 1).transformDirection(delta[0], delta[1]);
            const nativeWidth = NumCast(this.layoutDoc[this.fieldKey + "-nativeWidth"]);
            const curNativeWidth = NumCast(this.layoutDoc.nativeWidth, nativeWidth);
            const ratio = (curNativeWidth + localDelta[0] / (this.props.scaling?.() || 1)) / nativeWidth;
            if (ratio >= 1) {
                this.layoutDoc.nativeWidth = nativeWidth * ratio;
                this.layoutDoc._width = this.layoutDoc[WidthSym]() + localDelta[0];
                this.layoutDoc._showSidebar = nativeWidth !== this.layoutDoc._nativeWidth;
            }
            return false;
        }, emptyFunction, () => this.toggleSidebar());
    }
    @observable _previewNativeWidth: Opt<number> = undefined;
    @observable _previewWidth: Opt<number> = undefined;
    toggleSidebar = action((preview: boolean = false) => {
        const nativeWidth = NumCast(this.layoutDoc[this.fieldKey + "-nativeWidth"]);
        const ratio = ((!this.layoutDoc.nativeWidth || this.layoutDoc.nativeWidth === nativeWidth ? WebBox.openSidebarWidth : 0) + nativeWidth) / nativeWidth;
        const curNativeWidth = NumCast(this.layoutDoc.nativeWidth, nativeWidth);
        if (preview) {
            this._previewNativeWidth = nativeWidth * ratio;
            this._previewWidth = this.layoutDoc[WidthSym]() * nativeWidth * ratio / curNativeWidth;
            this._showSidebar = true;
        }
        else {
            this.layoutDoc.nativeWidth = nativeWidth * ratio;
            this.layoutDoc._width = this.layoutDoc[WidthSym]() * nativeWidth * ratio / curNativeWidth;
            this.layoutDoc._showSidebar = nativeWidth !== this.layoutDoc._nativeWidth;
        }
    });
    sidebarWidth = () => !this.SidebarShown ? 0 :
        this._previewWidth ? WebBox.openSidebarWidth :
            (NumCast(this.layoutDoc.nativeWidth) - Doc.NativeWidth(this.dataDoc)) * this.props.PanelWidth() /
            NumCast(this.layoutDoc.nativeWidth);

    @computed get content() {
        return <div className={"webBox-cont" + (!this.props.docViewPath().lastElement()?.docView?._pendingDoubleClick && this.isContentActive() && CurrentUserUtils.SelectedTool === InkTool.None && !DocumentDecorations.Instance?.Interacting ? "-interactive" : "")}
            style={{ width: NumCast(this.layoutDoc[this.fieldKey + "-contentWidth"]) || `${100 / (this.props.scaling?.() || 1)}%`, }}>
            {this.urlContent}
        </div>;
    }

    @computed get annotationLayer() {
        TraceMobx();
        return <div className="webBox-annotationLayer" style={{ height: Doc.NativeHeight(this.Document) || undefined }} ref={this._annotationLayer}>
            {this.inlineTextAnnotations.sort((a, b) => NumCast(a.y) - NumCast(b.y)).map(anno =>
                <Annotation {...this.props} fieldKey={this.annotationKey} showInfo={this.showInfo} dataDoc={this.dataDoc} anno={anno} key={`${anno[Id]}-annotation`} />)
            }
        </div>;

    }
    @observable _showSidebar = false;
    @computed get SidebarShown() { return this._showSidebar || this.layoutDoc._showSidebar ? true : false; }

    showInfo = action((anno: Opt<Doc>) => this._overlayAnnoInfo = anno);
    setPreviewCursor = (func?: (x: number, y: number, drag: boolean) => void) => this._setPreviewCursor = func;
    panelWidth = () => this.props.PanelWidth() / (this.props.scaling?.() || 1) - this.sidebarWidth(); // (this.Document.scrollHeight || Doc.NativeHeight(this.Document) || 0);
    panelHeight = () => this.props.PanelHeight() / (this.props.scaling?.() || 1); // () => this._pageSizes.length && this._pageSizes[0] ? this._pageSizes[0].width : Doc.NativeWidth(this.Document);
    scrollXf = () => this.props.ScreenToLocalTransform().translate(0, NumCast(this.layoutDoc._scrollTop));
    anchorMenuClick = () => this._sidebarRef.current?.anchorMenuClick;
    render() {
        const pointerEvents = this.props.layerProvider?.(this.layoutDoc) === false ? "none" : undefined;
        const previewScale = this._previewNativeWidth ? 1 - this.sidebarWidth() / this._previewNativeWidth : 1;
        const scale = previewScale * (this.props.scaling?.() || 1);
        return (
            <div className="webBox" ref={this._mainCont} style={{ pointerEvents: this.isContentActive() ? "all" : this.isContentActive() || SnappingManager.GetIsDragging() ? undefined : "none" }} >
                <div className={`webBox-container`} style={{ pointerEvents }} onContextMenu={this.specificContextMenu}>
                    <base target="_blank" />
                    <div className={"webBox-outerContent"} ref={this._outerRef}
                        style={{
                            width: `calc(${100 / scale}% - ${this.sidebarWidth() / scale * (this._previewWidth ? scale : 1)}px)`,
                            height: `${100 / scale}%`,
                            transform: `scale(${scale})`,
                            pointerEvents
                        }}
                        onWheel={e => { e.stopPropagation(); e.preventDefault(); }} // block wheel events from propagating since they're handled by the iframe
                        onScroll={e => this.setDashScrollTop(this._outerRef.current?.scrollTop || 0)}
                        onPointerDown={this.onMarqueeDown}
                    >
                        <div className={"webBox-innerContent"} style={{ height: NumCast(this.scrollHeight, 50), pointerEvents }}>
                            {this.content}
                            <CollectionFreeFormView {...OmitKeys(this.props, ["NativeWidth", "NativeHeight", "setContentView"]).omit}
                                renderDepth={this.props.renderDepth + 1}
                                isAnnotationOverlay={true}
                                fieldKey={this.annotationKey}
                                CollectionView={undefined}
                                setPreviewCursor={this.setPreviewCursor}
                                PanelWidth={this.panelWidth}
                                PanelHeight={this.panelHeight}
                                ScreenToLocalTransform={this.scrollXf}
                                scaling={returnOne}
                                dropAction={"alias"}
                                select={emptyFunction}
                                isContentActive={returnFalse}
                                ContentScaling={returnOne}
                                bringToFront={emptyFunction}
                                whenChildContentsActiveChanged={this.whenChildContentsActiveChanged}
                                removeDocument={this.removeDocument}
                                moveDocument={this.moveDocument}
                                addDocument={this.sidebarAddDocument}
                                childPointerEvents={true}
                                pointerEvents={this._isAnnotating || SnappingManager.GetIsDragging() ? "all" : "none"} />
                            {this.annotationLayer}
                        </div>
                    </div>
                    {!this._marqueeing || !this._mainCont.current || !this._annotationLayer.current ? (null) :
                        <MarqueeAnnotator rootDoc={this.rootDoc}
                            iframe={this.isFirefox() ? this.iframeClick : undefined}
                            iframeScaling={this.isFirefox() ? this.iframeScaling : undefined}
                            anchorMenuClick={this.anchorMenuClick}
                            scrollTop={0}
                            down={this._marqueeing} scaling={returnOne}
                            addDocument={this.addDocument}
                            docView={this.props.docViewPath().lastElement()}
                            finishMarquee={this.finishMarquee}
                            savedAnnotations={this._savedAnnotations}
                            annotationLayer={this._annotationLayer.current}
                            mainCont={this._mainCont.current} />}
                </div >
                <SidebarAnnos ref={this._sidebarRef}
                    {...this.props}
                    fieldKey={this.fieldKey}
                    rootDoc={this.rootDoc}
                    layoutDoc={this.layoutDoc}
                    dataDoc={this.dataDoc}
                    nativeWidth={this._previewNativeWidth ?? NumCast(this.layoutDoc._nativeWidth)}
                    showSidebar={this.SidebarShown}
                    sidebarAddDocument={this.sidebarAddDocument}
                    moveDocument={this.moveDocument}
                    removeDocument={this.removeDocument}
                    isContentActive={this.isContentActive}
                />
                <button className="webBox-overlayButton-sidebar" key="sidebar" title="Toggle Sidebar"
                    style={{ display: !this.isContentActive() ? "none" : undefined }}
                    onPointerDown={this.sidebarBtnDown} >
                    <FontAwesomeIcon style={{ color: "white" }} icon={"chevron-left"} size="sm" />
                </button>
            </div>);
    }
}
Scripting.addGlobal(function urlHash(url: string) { return WebBox.urlHash(url); });