import { library } from '@fortawesome/fontawesome-svg-core'; import { faBuffer, faHireAHelper } from '@fortawesome/free-brands-svg-icons'; import * as fa from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { action, computed, configure, observable, reaction, runInAction } from 'mobx'; import { observer } from 'mobx-react'; import "normalize.css"; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import Measure from 'react-measure'; import * as rp from 'request-promise'; import { Doc, DocListCast, Field, Opt, DocListCastAsync } from '../../fields/Doc'; import { List } from '../../fields/List'; import { PrefetchProxy } from '../../fields/Proxy'; import { listSpec } from '../../fields/Schema'; import { BoolCast, Cast, FieldValue, StrCast, PromiseValue } from '../../fields/Types'; import { TraceMobx } from '../../fields/util'; import { emptyFunction, emptyPath, returnEmptyDoclist, returnEmptyFilter, returnFalse, returnOne, returnTrue, returnZero, setupMoveUpEvents, simulateMouseClick, Utils } from '../../Utils'; import { GoogleAuthenticationManager } from '../apis/GoogleAuthenticationManager'; import { DocServer } from '../DocServer'; import { Docs, DocUtils } from '../documents/Documents'; import { DocumentType } from '../documents/DocumentTypes'; import { Networking } from '../Network'; import { CurrentUserUtils } from '../util/CurrentUserUtils'; import { DocumentManager } from '../util/DocumentManager'; import { GroupManager } from '../util/GroupManager'; import { HistoryUtil } from '../util/History'; import { Hypothesis } from '../util/HypothesisUtils'; import { LinkManager } from '../util/LinkManager'; import { Scripting } from '../util/Scripting'; 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 { Transform } from '../util/Transform'; import { TimelineMenu } from './animationtimeline/TimelineMenu'; import { CollectionDockingView } from './collections/CollectionDockingView'; import { MarqueeOptionsMenu } from './collections/collectionFreeForm/MarqueeOptionsMenu'; import { CollectionLinearView } from './collections/CollectionLinearView'; import { CollectionMenu } from './collections/CollectionMenu'; import { CollectionViewType } from './collections/CollectionView'; import { ContextMenu } from './ContextMenu'; import { DictationOverlay } from './DictationOverlay'; import { DocumentDecorations } from './DocumentDecorations'; import { FormatShapePane } from "./FormatShapePane"; import { GestureOverlay } from './GestureOverlay'; import { SEARCH_PANEL_HEIGHT } from './globalCssVariables.scss'; import { KeyManager } from './GlobalKeyHandler'; import { LinkMenu } from './linking/LinkMenu'; import "./MainView.scss"; import { AudioBox } from './nodes/AudioBox'; import { DocumentLinksButton } from './nodes/DocumentLinksButton'; import { DocumentView } from './nodes/DocumentView'; import { FormattedTextBox } from './nodes/formattedText/FormattedTextBox'; import { LinkDescriptionPopup } from './nodes/LinkDescriptionPopup'; import { LinkDocPreview } from './nodes/LinkDocPreview'; import { RadialMenu } from './nodes/RadialMenu'; import { TaskCompletionBox } from './nodes/TaskCompletedBox'; import { WebBox } from './nodes/WebBox'; import { OverlayView } from './OverlayView'; import { PDFMenu } from './pdf/PDFMenu'; import { PreviewCursor } from './PreviewCursor'; import { PropertiesView } from './PropertiesView'; import { SearchBox } from './search/SearchBox'; import { CollectionSubView, CollectionSubViewLoader } from './collections/CollectionSubView'; import ReactLoading from 'react-loading'; @observer export class MainView extends React.Component { public static Instance: MainView; private _buttonBarHeight = 36; private _docBtnRef = React.createRef(); private _mainViewRef = React.createRef(); @observable private _panelWidth: number = 0; @observable private _panelHeight: number = 0; @observable private _flyoutTranslate: boolean = false; @observable public flyoutWidth: number = 0; private get darkScheme() { return BoolCast(CurrentUserUtils.ActiveDashboard?.darkScheme); } @computed private get userDoc() { return Doc.UserDoc(); } @computed private get mainContainer() { return this.userDoc ? CurrentUserUtils.ActiveDashboard : CurrentUserUtils.GuestDashboard; } @computed public get mainFreeform(): Opt { return (docs => (docs && docs.length > 1) ? docs[1] : undefined)(DocListCast(this.mainContainer!.data)); } @computed public get searchDoc() { return Cast(this.userDoc.mySearchPanelDoc, Doc) as Doc; } @observable public sidebarContent: any = this.userDoc?.sidebar; @observable public panelContent: string = "none"; @observable public showProperties: boolean = false; public isPointerDown = false; @computed get selectedDocumentView() { if (SelectionManager.SelectedDocuments().length) { return SelectionManager.SelectedDocuments()[0]; } else { return undefined; } } propertiesWidth = () => Math.max(0, Math.min(this._panelWidth - 50, CurrentUserUtils.propertiesWidth || 0)); @computed get propertiesIcon() { if (this.propertiesWidth() < 10) { return "chevron-left"; } else { return "chevron-right"; } } @observable propertiesDownX: number | undefined; componentDidMount() { DocServer.setPlaygroundFields(["dataTransition", "_viewTransition", "_panX", "_panY", "_viewScale", "_viewType", "_chromeStatus"]); // can play with these fields on someone else's const tag = document.createElement('script'); const proto = DocServer.GetRefField("rtfProto").then(proto => { (proto instanceof Doc) && reaction(() => StrCast(proto.BROADCAST_MESSAGE), msg => msg && alert(msg)); }); tag.src = "https://www.youtube.com/iframe_api"; const firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode!.insertBefore(tag, firstScriptTag); window.removeEventListener("keydown", KeyManager.Instance.handle); window.addEventListener("keydown", KeyManager.Instance.handle); window.addEventListener("paste", KeyManager.Instance.paste as any); document.addEventListener("dash", (e: any) => { // event used by chrome plugin to tell Dash which document to focus on const id = FormattedTextBox.GetDocFromUrl(e.detail); DocServer.GetRefField(id).then(doc => { if (doc instanceof Doc) { DocumentManager.Instance.jumpToDocument(doc, false, undefined); } }); }); document.addEventListener("linkAnnotationToDash", Hypothesis.linkListener); } componentWillUnMount() { window.removeEventListener("keydown", KeyManager.Instance.handle); window.removeEventListener("pointerdown", this.globalPointerDown); window.removeEventListener("pointerup", this.globalPointerUp); window.removeEventListener("paste", KeyManager.Instance.paste as any); document.removeEventListener("linkAnnotationToDash", Hypothesis.linkListener); } constructor(props: Readonly<{}>) { super(props); MainView.Instance = this; this.sidebarContent.proto = undefined; CurrentUserUtils._urlState = HistoryUtil.parseUrl(window.location) || {} as any; // causes errors to be generated when modifying an observable outside of an action configure({ enforceActions: "observed" }); if (window.location.pathname !== "/home") { const pathname = window.location.pathname.substr(1).split("/"); if (pathname.length > 1) { const type = pathname[0]; if (type === "doc") { CurrentUserUtils.MainDocId = pathname[1]; if (!this.userDoc) { runInAction(() => this.closeFlyout()); DocServer.GetRefField(CurrentUserUtils.MainDocId).then(action((field: Opt) => field instanceof Doc && (CurrentUserUtils.GuestTarget = field))); } } } } library.add(fa.faEdit, fa.faTrash, fa.faTrashAlt, fa.faShare, fa.faDownload, fa.faExpandArrowsAlt, fa.faLayerGroup, fa.faExternalLinkAlt, fa.faCalendar, fa.faSquare, fa.faConciergeBell, fa.faWindowRestore, fa.faFolder, fa.faMapPin, fa.faMapMarker, fa.faFingerprint, fa.faCrosshairs, fa.faDesktop, fa.faUnlock, fa.faLock, fa.faLaptopCode, fa.faMale, fa.faCopy, fa.faHandPointLeft, fa.faHandPointRight, fa.faCompass, fa.faSnowflake, fa.faMicrophone, fa.faKeyboard, fa.faQuestion, fa.faTasks, fa.faPalette, fa.faAngleLeft, fa.faAngleRight, fa.faBell, fa.faCamera, fa.faExpand, fa.faCaretDown, fa.faCaretLeft, fa.faCaretRight, fa.faCaretSquareDown, fa.faCaretSquareRight, fa.faArrowsAltH, fa.faPlus, fa.faMinus, fa.faTerminal, fa.faToggleOn, fa.faFile, fa.faLocationArrow, fa.faSearch, fa.faFileDownload, fa.faFileUpload, fa.faStop, fa.faCalculator, fa.faWindowMaximize, fa.faAddressCard, fa.faQuestionCircle, fa.faArrowLeft, fa.faArrowRight, fa.faArrowDown, fa.faArrowUp, fa.faBolt, fa.faBullseye, fa.faCaretUp, fa.faCat, fa.faCheck, fa.faChevronRight, fa.faChevronLeft, fa.faChevronDown, fa.faChevronUp, fa.faClone, fa.faCloudUploadAlt, fa.faCommentAlt, fa.faCompressArrowsAlt, fa.faCut, fa.faEllipsisV, fa.faEraser, fa.faExclamation, fa.faFileAlt, fa.faFileAudio, fa.faFilePdf, fa.faFilm, fa.faFilter, fa.faFont, fa.faGlobeAmericas, fa.faGlobeAsia, fa.faHighlighter, fa.faLongArrowAltRight, fa.faMousePointer, fa.faMusic, fa.faObjectGroup, fa.faPause, fa.faPen, fa.faPenNib, fa.faPhone, fa.faPlay, fa.faPortrait, fa.faRedoAlt, fa.faStamp, fa.faStickyNote, fa.faTimesCircle, fa.faThumbtack, fa.faTree, fa.faTv, fa.faUndoAlt, fa.faVideo, fa.faAsterisk, fa.faBrain, fa.faImage, fa.faPaintBrush, fa.faTimes, fa.faEye, fa.faArrowsAlt, fa.faQuoteLeft, fa.faSortAmountDown, fa.faAlignLeft, fa.faAlignCenter, fa.faAlignRight, fa.faHeading, fa.faRulerCombined, fa.faFillDrip, fa.faLink, fa.faUnlink, fa.faBold, fa.faItalic, fa.faClipboard, fa.faUnderline, fa.faStrikethrough, fa.faSuperscript, fa.faSubscript, fa.faIndent, fa.faEyeDropper, fa.faPaintRoller, fa.faBars, fa.faBrush, fa.faShapes, fa.faEllipsisH, fa.faHandPaper, fa.faMap, fa.faUser, faHireAHelper, fa.faDesktop, fa.faTrashRestore, fa.faUsers, fa.faWrench, fa.faCog, fa.faMap, fa.faBellSlash, fa.faExpandAlt, fa.faArchive, fa.faBezierCurve, fa.faCircle, fa.faLongArrowAltRight, fa.faPenFancy, fa.faAngleDoubleRight, faBuffer, fa.faExpand, fa.faUndo, fa.faSlidersH, fa.faAngleDoubleLeft, fa.faAngleUp, fa.faAngleDown, fa.faPlayCircle, fa.faClock, fa.faRocket, fa.faExchangeAlt, faBuffer, fa.faHashtag, fa.faAlignJustify, fa.faCheckSquare, fa.faListUl, fa.faWindowMinimize, fa.faWindowRestore, fa.faTextWidth, fa.faTextHeight, fa.faClosedCaptioning, fa.faInfoCircle, fa.faTag, fa.faSyncAlt, fa.faPhotoVideo, fa.faArrowAltCircleDown, fa.faArrowAltCircleUp, fa.faArrowAltCircleLeft, fa.faArrowAltCircleRight, fa.faStopCircle, fa.faCheckCircle, fa.faGripVertical, fa.faSortUp, fa.faSortDown, fa.faTable, fa.faTh, fa.faThList, fa.faProjectDiagram, fa.faSignature, fa.faColumns, fa.faChevronCircleUp, fa.faUpload, fa.faBraille, fa.faChalkboard, fa.faPencilAlt, fa.faEyeSlash, fa.faSmile, fa.faIndent, fa.faOutdent, fa.faChartBar, fa.faBan, fa.faPhoneSlash, fa.faGripLines); this.initEventListeners(); this.initAuthenticationRouters(); } globalPointerDown = action((e: PointerEvent) => { this.isPointerDown = true; AudioBox.Enabled = true; const targets = document.elementsFromPoint(e.x, e.y); if (targets && targets.length && targets[0].className.toString().indexOf("contextMenu") === -1) { ContextMenu.Instance.closeMenu(); } if (targets && (targets.length && targets[0].className.toString() !== "timeline-menu-desc" && targets[0].className.toString() !== "timeline-menu-item" && targets[0].className.toString() !== "timeline-menu-input")) { TimelineMenu.Instance.closeMenu(); } if (targets && targets.length && SearchBox.Instance._searchbarOpen) { let check = false; const icon = "icon"; targets.forEach((thing) => { if (thing.className.toString() === "collectionSchemaView-searchContainer" || (thing as any)?.dataset[icon] === "filter" || thing.className.toString() === "collectionSchema-header-menuOptions" || thing.className.toString() === "altcollectionTimeView-treeView") { check = true; } }); if (check === false) { SearchBox.Instance.resetSearch(true); } } }); globalPointerUp = () => this.isPointerDown = false; initEventListeners = () => { window.addEventListener("drop", (e) => { e.preventDefault(); }, false); // drop event handler window.addEventListener("dragover", (e) => { e.preventDefault(); }, false); // drag event handler // click interactions for the context menu document.addEventListener("pointerdown", this.globalPointerDown); document.addEventListener("pointerup", this.globalPointerUp); } initAuthenticationRouters = async () => { // Load the user's active dashboard, or create a new one if initial session after signup const received = CurrentUserUtils.MainDocId; if (received && !this.userDoc) { reaction(() => CurrentUserUtils.GuestTarget, target => target && CurrentUserUtils.createNewDashboard(Doc.UserDoc()), { fireImmediately: true } ); } else { if (received && CurrentUserUtils._urlState.sharing) { reaction(() => CollectionDockingView.Instance && CollectionDockingView.Instance.initialized, initialized => initialized && received && DocServer.GetRefField(received).then(docField => { if (docField instanceof Doc && docField._viewType !== CollectionViewType.Docking) { CollectionDockingView.AddSplit(docField, "right"); } }), ); } const activeDash = PromiseValue(this.userDoc.activeDashboard); activeDash.then(dash => { if (dash instanceof Doc) CurrentUserUtils.openDashboard(this.userDoc, dash); else CurrentUserUtils.createNewDashboard(this.userDoc); }); } } @action createNewPresentation = async () => { await this.userDoc.myPresentations; if (this.userDoc.myPresentations === undefined) { this.userDoc.myPresentations = new PrefetchProxy(Docs.Create.TreeDocument([], { title: "PRESENTATION TRAILS", _height: 100, forceActive: true, boxShadow: "0 0", lockedPosition: true, treeViewOpen: true, system: true })); } const pres = Docs.Create.PresDocument(new List(), { title: "Untitled Presentation", _viewType: CollectionViewType.Stacking, _width: 400, _height: 500, targetDropAction: "alias", _chromeStatus: "replaced", boxShadow: "0 0", system: true }); CollectionDockingView.AddSplit(pres, "right"); Doc.UserDoc().activePresentation = pres; const myPresentations = Doc.UserDoc().myPresentations as Doc; Doc.AddDocToList(myPresentations, "data", pres); } onDrop = (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); } @action onResize = (r: any) => { this._panelWidth = r.offset.width;// - this.propertiesWidth(); this._panelHeight = r.offset.height; } @action getPWidth = () => this._panelWidth - this.propertiesWidth() getPHeight = () => this._panelHeight; getContentsHeight = () => this._panelHeight - this._buttonBarHeight; defaultBackgroundColors = (doc: Opt, renderDepth: number) => { if (doc?.type === DocumentType.COL) { const system = Doc.IsSystem(doc); return system ? "lightgrey" : StrCast(renderDepth > 0 ? Doc.UserDoc().activeCollectionNestedBackground : Doc.UserDoc().activeCollectionBackground); } if (this.darkScheme) { switch (doc?.type) { case DocumentType.FONTICON: return "white"; case DocumentType.RTF || DocumentType.LABEL || DocumentType.BUTTON: return "#2d2d2d"; case DocumentType.LINK: case DocumentType.COL: { if (doc._viewType !== CollectionViewType.Freeform && doc._viewType !== CollectionViewType.Time) return "rgb(62,62,62)"; } default: return "black"; } } else { switch (doc?.type) { case DocumentType.FONTICON: return "black"; case DocumentType.RTF: return "#f1efeb"; case DocumentType.BUTTON: case DocumentType.LABEL: return "lightgray"; case DocumentType.LINK: case DocumentType.COL: { if (doc._viewType !== CollectionViewType.Freeform && doc._viewType !== CollectionViewType.Time) return "lightgray"; } default: return "white"; } } } @computed get mainDocView() { return ; } @computed get dockingContent() { TraceMobx(); const mainContainer = this.mainContainer; const width = this.flyoutWidth + this.propertiesWidth(); return
{!mainContainer ? (null) : this.mainDocView}
; } @action onPropertiesPointerDown = (e: React.PointerEvent) => { setupMoveUpEvents(this, e, action((e: PointerEvent, down: number[], delta: number[]) => { CurrentUserUtils.propertiesWidth = this._panelWidth - e.clientX; return false; }), returnFalse, action(() => CurrentUserUtils.propertiesWidth = this.propertiesWidth() < 15 ? Math.min(this._panelWidth - 50, 250) : 0), false); } @action onFlyoutPointerDown = (e: React.PointerEvent) => { if (this._flyoutTranslate) { setupMoveUpEvents(this, e, action((e: PointerEvent) => { this.flyoutWidth = Math.max(e.clientX - 58, 0); if (this.flyoutWidth < 5) { this.panelContent = "none"; this._lastButton && (this._lastButton.color = "white"); this._lastButton && (this._lastButton._backgroundColor = ""); } return false; }), emptyFunction, action(() => { if (this.flyoutWidth < 15) MainView.expandFlyout(); else this.closeFlyout(); })); } } @computed get topOffset() { return (CollectionMenu.Instance?.Pinned ? 35 : 0) + Number(SEARCH_PANEL_HEIGHT.replace("px", "")); } flyoutWidthFunc = () => this.flyoutWidth; addDocTabFunc = (doc: Doc, where: string, libraryPath?: Doc[]): boolean => { return where === "close" ? CollectionDockingView.CloseSplit(doc) : doc.dockingConfig ? CurrentUserUtils.openDashboard(Doc.UserDoc(), doc) : CollectionDockingView.AddSplit(doc, "right"); } sidebarScreenToLocal = () => new Transform(0, (CollectionMenu.Instance.Pinned ? -35 : 0) - Number(SEARCH_PANEL_HEIGHT.replace("px", "")), 1); mainContainerXf = () => this.sidebarScreenToLocal().translate(-58, 0); @computed get flyout() { if (!this.sidebarContent) return null; return
{/* {this.flyoutWidth > 0 ?
: null} */} "lightgrey"} />
{this.docButtons}
; } @computed get menuPanel() { return
60} PanelHeight={this.getContentsHeight} renderDepth={0} focus={emptyFunction} backgroundColor={this.defaultBackgroundColors} parentActive={returnTrue} whenActiveChanged={emptyFunction} bringToFront={emptyFunction} docFilters={returnEmptyFilter} searchFilterDocs={returnEmptyDoclist} ContainingCollectionView={undefined} ContainingCollectionDoc={undefined} relative={true} scriptContext={this} />
; } @action closeFlyout = () => { this._lastButton && (this._lastButton.color = "white"); this._lastButton && (this._lastButton._backgroundColor = ""); this.panelContent = "none"; this.flyoutWidth = 0; } get groupManager() { return GroupManager.Instance; } _lastButton: Doc | undefined; @action selectMenu = (button: Doc) => { const title = StrCast(Doc.GetProto(button).title); this._lastButton && (this._lastButton.color = "white"); this._lastButton && (this._lastButton._backgroundColor = ""); if (this.panelContent === title && this.flyoutWidth !== 0) { this.panelContent = "none"; this.flyoutWidth = 0; } else { let panelDoc: Doc | undefined; switch (this.panelContent = title) { case "Settings": SettingsManager.Instance.open(); break; case "Catalog": SearchBox.Instance._searchFullDB = "My Stuff"; SearchBox.Instance.newsearchstring = ""; SearchBox.Instance.enter(undefined); break; default: panelDoc = button.target as any; break; } this.sidebarContent.proto = panelDoc; if (panelDoc) { MainView.expandFlyout(); button._backgroundColor = "lightgrey"; button.color = "black"; this._lastButton = button; } else this.flyoutWidth = 0; } return true; } @action closeProperties = () => { CurrentUserUtils.propertiesWidth = 0; } @computed get propertiesView() { TraceMobx(); return
; } @computed get mainInnerContent() { const rightFlyout = this.propertiesWidth() - 1; return <> {this.menuPanel}
{this.flyoutWidth !== 0 ?
: null}
{this.flyout} {this.expandButton}
{this.dockingContent} {this.showProperties ? (null) :
} {this.propertiesWidth() < 10 ? (null) : this.propertiesView}
; } @computed get mainContent() { const height = `calc(100% - ${this.topOffset}px)`; const pinned = FormatShapePane.Instance?.Pinned; const innerContent = this.mainInnerContent; return !this.userDoc ? (null) : ( {({ measureRef }) =>
{innerContent}
}
); } public static expandFlyout = action(() => { MainView.Instance._flyoutTranslate = true; MainView.Instance.flyoutWidth = (MainView.Instance.flyoutWidth || 250); }); @computed get expandButton() { return !this._flyoutTranslate ? (
) : (null); } addButtonDoc = (doc: Doc | Doc[]) => (doc instanceof Doc ? [doc] : doc).reduce((flg: boolean, doc) => { const ret = flg && Doc.AddDocToList(Doc.UserDoc().dockedBtns as Doc, "data", doc); ret && (doc._stayInCollection = undefined); return ret; }, true) remButtonDoc = (doc: Doc | Doc[]) => (doc instanceof Doc ? [doc] : doc).reduce((flg: boolean, doc) => flg && Doc.RemoveDocFromList(Doc.UserDoc().dockedBtns as Doc, "data", doc), true); moveButtonDoc = (doc: Doc | Doc[], targetCollection: Doc | undefined, addDocument: (document: Doc | Doc[]) => boolean) => this.remButtonDoc(doc) && addDocument(doc); buttonBarXf = () => { if (!this._docBtnRef.current) return Transform.Identity(); const { scale, translateX, translateY } = Utils.GetScreenTransform(this._docBtnRef.current); return new Transform(-translateX, -translateY, 1 / scale); } @computed get docButtons() { const dockedBtns = Doc.UserDoc()?.dockedBtns; if (dockedBtns instanceof Doc) { return
; } return (null); } get mainViewElement() { return document.getElementById("mainView-container"); } get mainViewRef() { return this._mainViewRef; } @computed get snapLines() { return !Doc.UserDoc().showSnapLines ? (null) :
{SnappingManager.horizSnapLines().map(l => )} {SnappingManager.vertSnapLines().map(l => )}
; } @computed get inkResources() { return ; } @computed get search() { return
{/*
{Doc.CurrentUserEmail}
*/}
; } @computed get invisibleWebBox() { // see note under the makeLink method in HypothesisUtils.ts return !DocumentLinksButton.invisibleWebDoc ? null :
500} PanelHeight={() => 800} NativeHeight={() => 500} NativeWidth={() => 800} ContentScaling={returnOne} docFilters={returnEmptyFilter} searchFilterDocs={returnEmptyDoclist} />
; } render() { return (
{this.inkResources} {this.search} {LinkDescriptionPopup.descriptionPopup ? : null} {DocumentLinksButton.EditLink ? : (null)} {LinkDocPreview.LinkInfo ? : (null)} {this.mainContent} {this.snapLines}
); } makeWebRef = (ele: HTMLDivElement) => { reaction(() => DocumentLinksButton.invisibleWebDoc, invisibleDoc => { ReactDOM.unmountComponentAtNode(ele); invisibleDoc && ReactDOM.render(
500} PanelHeight={() => 800} NativeHeight={() => 500} NativeWidth={() => 800} ContentScaling={returnOne} docFilters={returnEmptyFilter} searchFilterDocs={returnEmptyDoclist} />
;
, ele); var success = false; const onSuccess = () => { success = true; clearTimeout(interval); document.removeEventListener("editSuccess", onSuccess); }; // For some reason, Hypothes.is annotations don't load until a click is registered on the page, // so we keep simulating clicks until annotations have loaded and editing is successful const interval = setInterval(() => { !success && simulateMouseClick(ele, 50, 50, 50, 50); }, 500); setTimeout(() => !success && clearInterval(interval), 10000); // give up if no success after 10s document.addEventListener("editSuccess", onSuccess); }); } importDocument = () => { const input = document.createElement("input"); input.type = "file"; input.multiple = true; input.accept = ".zip, application/pdf, video/*, image/*, audio/*"; input.onchange = async _e => { const upload = Utils.prepend("/uploadDoc"); const formData = new FormData(); const file = input.files && input.files[0]; if (file && file.type === 'application/zip') { formData.append('file', file); formData.append('remap', "true"); const response = await fetch(upload, { method: "POST", body: formData }); const json = await response.json(); if (json !== "error") { const doc = await DocServer.GetRefField(json); if (doc instanceof Doc) { setTimeout(() => { SearchUtil.Search(`{!join from=id to=proto_i}id:link*`, true, {}).then(docs => { docs.docs.forEach(d => LinkManager.Instance.addLink(d)); }); }, 2000); // need to give solr some time to update so that this query will find any link docs we've added. } } } else if (input.files && input.files.length !== 0) { const importDocs = Cast(Doc.UserDoc().myImportDocs, Doc, null); const disposer = OverlayView.Instance.addElement(, { x: 300, y: 200 }); DocListCastAsync(importDocs.data).then(async list => { list?.push(... await DocUtils.uploadFilesToDocs(Array.from(input.files || []), {})); disposer(); }); } else { console.log("No file selected"); } }; input.click(); } } Scripting.addGlobal(function selectMainMenu(doc: Doc, title: string) { MainView.Instance.selectMenu(doc); }); Scripting.addGlobal(function toggleComicMode() { Doc.UserDoc().fontFamily = "Comic Sans MS"; Doc.UserDoc().renderStyle = Doc.UserDoc().renderStyle === "comic" ? undefined : "comic"; }); Scripting.addGlobal(function importDocument() { return MainView.Instance.importDocument(); }, "imports files from device directly into the import sidebar");