diff options
author | bobzel <zzzman@gmail.com> | 2022-03-02 14:43:48 -0500 |
---|---|---|
committer | bobzel <zzzman@gmail.com> | 2022-03-02 14:43:48 -0500 |
commit | 398a50bc1d7e77691620a4a6752fd38d4bb391b0 (patch) | |
tree | 42f56a2bc7cc1d661c3dfa61d49cc472fffb553c /src | |
parent | 35f0c9940d0ea7c0cb37c711557454b77ac038ad (diff) |
upgraded to typescript 4.6.2
Diffstat (limited to 'src')
34 files changed, 164 insertions, 164 deletions
diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 279916bac..df4aa3acf 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -1450,7 +1450,7 @@ export namespace DocUtils { if (doc) { const proto = Doc.GetProto(doc); proto.text = result.rawText; - proto.fileUpload = basename(pathname).replace("upload_", "").replace(/\.[a-z0-9]*$/, ""); + proto.fileUpload = pathname.replace(/.*\//, "").replace("upload_", "").replace(/\.[a-z0-9]*$/, ""); if (Upload.isImageInformation(result)) { const maxNativeDim = Math.min(Math.max(result.nativeHeight, result.nativeWidth), defaultNativeImageDim); proto["data-nativeOrientation"] = result.exifData?.data?.image?.Orientation; @@ -1485,7 +1485,8 @@ export namespace DocUtils { } export async function uploadFilesToDocs(files: File[], options: DocumentOptions) { const generatedDocuments: Doc[] = []; - for (const { source: { name, type }, result } of await Networking.UploadFilesToServer(files)) { + const upfiles = await Networking.UploadFilesToServer(files); + for (const { source: { name, type }, result } of upfiles) { name && type && processFileupload(generatedDocuments, name, type, result, options); } return generatedDocuments; diff --git a/src/client/util/CurrentUserUtils.ts b/src/client/util/CurrentUserUtils.ts index 6e2a72f3a..600c143a7 100644 --- a/src/client/util/CurrentUserUtils.ts +++ b/src/client/util/CurrentUserUtils.ts @@ -535,11 +535,11 @@ export class CurrentUserUtils { // setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools static async setupCreatorButtons(doc: Doc) { let alreadyCreatedButtons: string[] = []; - const dragCreatorSet = await Cast(doc.myItemCreators, Doc, null); + const dragCreatorSet = Cast(doc.myItemCreators, Doc, null); if (dragCreatorSet) { - const dragCreators = await Cast(dragCreatorSet.data, listSpec(Doc)); + const dragCreators = Cast(dragCreatorSet.data, listSpec(Doc)); if (dragCreators) { - const dragDocs = await Promise.all(dragCreators); + const dragDocs = await Promise.all(Array.from(dragCreators)); alreadyCreatedButtons = dragDocs.map(d => StrCast(d.title)); } } diff --git a/src/client/util/DictationManager.ts b/src/client/util/DictationManager.ts index a93b2f573..a086ac45e 100644 --- a/src/client/util/DictationManager.ts +++ b/src/client/util/DictationManager.ts @@ -1,4 +1,6 @@ import * as interpreter from "words-to-numbers"; +// @ts-ignore bcz: how are you supposed to include these definitions since dom-speech-recognition isn't a module? +import type { } from "@types/dom-speech-recognition"; import { Doc, Opt } from "../../fields/Doc"; import { List } from "../../fields/List"; import { RichTextField } from "../../fields/RichTextField"; @@ -13,6 +15,7 @@ import { DocumentView } from "../views/nodes/DocumentView"; import { SelectionManager } from "./SelectionManager"; import { UndoManager } from "./UndoManager"; + /** * This namespace provides a singleton instance of a manager that * handles the listening and text-conversion of user speech. @@ -112,7 +115,7 @@ export namespace DictationManager { } options?.tryExecute && await DictationManager.Commands.execute(results); } - } catch (e) { + } catch (e: any) { console.log(e); if (overlay) { DictationOverlay.Instance.isListening = false; @@ -188,7 +191,7 @@ export namespace DictationManager { current && sessionResults.push(current); sessionResults.length && resolve(sessionResults.join(inter || interSession)); } else { - resolve(current); + resolve(current || ""); } current = undefined; sessionResults = []; diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts index 66b6a1e44..e1dc96155 100644 --- a/src/client/util/DocumentManager.ts +++ b/src/client/util/DocumentManager.ts @@ -198,7 +198,7 @@ export class DocumentManager { originalTarget, willZoom, scale: presZoom, afterFocus: (didFocus: boolean) => new Promise<ViewAdjustment>(res => { focusAndFinish(didFocus); - res(); + res(ViewAdjustment.doNothing); }) }); } else { @@ -227,7 +227,7 @@ export class DocumentManager { willZoom, afterFocus: (didFocus: boolean) => new Promise<ViewAdjustment>(res => { !noSelect && focusAndFinish(didFocus); - res(); + res(ViewAdjustment.doNothing); }) }); // focus on the target in the context } else if (delay > 1500) { diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index ae3fa3170..c9c499fff 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -499,7 +499,7 @@ export namespace DragManager { screenX: e.screenX, screenY: e.screenY, detail: e.detail, - view: e.view ? e.view : new Window, + view: e.view ? e.view : new Window as any, nativeEvent: new DragEvent("dashDragAutoScroll"), currentTarget: target, target: target, diff --git a/src/client/util/Import & Export/DirectoryImportBox.tsx b/src/client/util/Import & Export/DirectoryImportBox.tsx index cf72cd0df..9eee75253 100644 --- a/src/client/util/Import & Export/DirectoryImportBox.tsx +++ b/src/client/util/Import & Export/DirectoryImportBox.tsx @@ -1,9 +1,7 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { BatchedArray } from "array-batcher"; -import "fs"; import { action, computed, IReactionDisposer, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; -import * as path from 'path'; import Measure, { ContentRect } from "react-measure"; import { Doc, DocListCast, DocListCastAsync, Opt } from "../../../fields/Doc"; import { Id } from "../../../fields/FieldSymbols"; @@ -120,7 +118,7 @@ export class DirectoryImportBox extends React.Component<FieldViewProps> { } const { accessPaths, exifData } = result; const path = Utils.prepend(accessPaths.agnostic.client); - const document = type && await DocUtils.DocumentFromType(type, path, { _width: 300, title: name }); + const document = type && await DocUtils.DocumentFromType(type, path, { _width: 300 }); const { data, error } = exifData; if (document) { Doc.GetProto(document).exif = error || Doc.Get.FromJson({ data }); diff --git a/src/client/util/LinkManager.ts b/src/client/util/LinkManager.ts index 62b13e2c6..df2c02a8d 100644 --- a/src/client/util/LinkManager.ts +++ b/src/client/util/LinkManager.ts @@ -194,7 +194,7 @@ export class LinkManager { afterFocus: (didFocus: boolean) => { finished?.(); res(ViewAdjustment.resetView); - return new Promise<ViewAdjustment>(res2 => res2()); + return new Promise<ViewAdjustment>(res2 => res2(ViewAdjustment.doNothing)); } }); } else { diff --git a/src/client/views/collections/collectionSchema/CollectionSchemaCells.tsx b/src/client/views/collections/collectionSchema/CollectionSchemaCells.tsx index a439a7998..6a9b27d02 100644 --- a/src/client/views/collections/collectionSchema/CollectionSchemaCells.tsx +++ b/src/client/views/collections/collectionSchema/CollectionSchemaCells.tsx @@ -3,9 +3,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { action, computed, observable } from "mobx"; import { observer } from "mobx-react"; import DatePicker from "react-datepicker"; -import "react-datepicker/dist/react-datepicker.css"; import { CellInfo } from "react-table"; -import "react-table/react-table.css"; import { DateField } from "../../../../fields/DateField"; import { Doc, DocListCast, Field, Opt } from "../../../../fields/Doc"; import { Id } from "../../../../fields/FieldSymbols"; @@ -31,7 +29,6 @@ import { DocumentIconContainer } from "../../nodes/DocumentIcon"; import { OverlayView } from "../../OverlayView"; import "./CollectionSchemaView.scss"; import { CollectionView } from "../CollectionView"; -const path = require('path'); // intialize cell properties export interface CellProps { @@ -495,8 +492,8 @@ export class CollectionSchemaImageCell extends CollectionSchemaCell { if (url.href.indexOf(window.location.origin) === -1) return Utils.CorsProxy(url.href); // otherwise, put it through the cors proxy erver if (!/\.(png|jpg|jpeg|gif|webp)$/.test(url.href.toLowerCase())) return url.href;//Why is this here — good question - const ext = path.extname(url.href); // the extension of the file - return url.href.replace(ext, "_o" + path.extname(url.href)); + const ext = "." + url.href.replace(/.*\./, "");// path.extname(url.href); // the extension of the file + return url.href.replace(ext, "_o" + ext); } render() { diff --git a/src/client/views/collections/collectionSchema/CollectionSchemaView.tsx b/src/client/views/collections/collectionSchema/CollectionSchemaView.tsx index b89246489..83d339f0a 100644 --- a/src/client/views/collections/collectionSchema/CollectionSchemaView.tsx +++ b/src/client/views/collections/collectionSchema/CollectionSchemaView.tsx @@ -4,7 +4,6 @@ import { action, computed, observable, untracked, trace } from "mobx"; import { observer } from "mobx-react"; import Measure from "react-measure"; import { Resize } from "react-table"; -import "react-table/react-table.css"; import { Doc, Opt } from "../../../../fields/Doc"; import { List } from "../../../../fields/List"; import { listSpec } from "../../../../fields/Schema"; @@ -147,43 +146,43 @@ export class CollectionSchemaView extends CollectionSubView(doc => doc) { const anyType = <div className={"columnMenu-option" + (type === ColumnType.Any ? " active" : "")} onClick={() => this.setColumnType(col, ColumnType.Any)}> <FontAwesomeIcon icon={"align-justify"} size="sm" /> - Any - </div>; + Any + </div>; const numType = <div className={"columnMenu-option" + (type === ColumnType.Number ? " active" : "")} onClick={() => this.setColumnType(col, ColumnType.Number)}> <FontAwesomeIcon icon={"hashtag"} size="sm" /> - Number - </div>; + Number + </div>; const textType = <div className={"columnMenu-option" + (type === ColumnType.String ? " active" : "")} onClick={() => this.setColumnType(col, ColumnType.String)}> <FontAwesomeIcon icon={"font"} size="sm" /> Text - </div>; + </div>; const boolType = <div className={"columnMenu-option" + (type === ColumnType.Boolean ? " active" : "")} onClick={() => this.setColumnType(col, ColumnType.Boolean)}> <FontAwesomeIcon icon={"check-square"} size="sm" /> Checkbox - </div>; + </div>; const listType = <div className={"columnMenu-option" + (type === ColumnType.List ? " active" : "")} onClick={() => this.setColumnType(col, ColumnType.List)}> <FontAwesomeIcon icon={"list-ul"} size="sm" /> List - </div>; + </div>; const docType = <div className={"columnMenu-option" + (type === ColumnType.Doc ? " active" : "")} onClick={() => this.setColumnType(col, ColumnType.Doc)}> <FontAwesomeIcon icon={"file"} size="sm" /> Document - </div>; + </div>; const imageType = <div className={"columnMenu-option" + (type === ColumnType.Image ? " active" : "")} onClick={() => this.setColumnType(col, ColumnType.Image)}> <FontAwesomeIcon icon={"image"} size="sm" /> Image - </div>; + </div>; const dateType = <div className={"columnMenu-option" + (type === ColumnType.Date ? " active" : "")} onClick={() => this.setColumnType(col, ColumnType.Date)}> <FontAwesomeIcon icon={"calendar"} size="sm" /> - Date - </div>; + Date + </div>; const allColumnTypes = <div className="columnMenu-types"> @@ -557,7 +556,7 @@ export class CollectionSchemaView extends CollectionSubView(doc => doc) { style={{ overflow: this.props.scrollOverflow === true ? "scroll" : undefined, backgroundColor: "white", pointerEvents: this.props.Document._searchDoc !== undefined && !this.props.isContentActive() && !SnappingManager.GetIsDragging() ? "none" : undefined, - width: name === "collectionSchemaView-searchContainer" ? "auto" : this.props.PanelWidth() || "100%", height: this.props.PanelHeight() || "100%", position: "relative", + width: this.props.PanelWidth() || "100%", height: this.props.PanelHeight() || "100%", position: "relative", }} > <div className="collectionSchemaView-tableContainer" style={{ width: `calc(100% - ${this.previewWidth()}px)` }} diff --git a/src/client/views/collections/collectionSchema/SchemaTable.tsx b/src/client/views/collections/collectionSchema/SchemaTable.tsx index 2219345f6..605481ddf 100644 --- a/src/client/views/collections/collectionSchema/SchemaTable.tsx +++ b/src/client/views/collections/collectionSchema/SchemaTable.tsx @@ -4,7 +4,6 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { action, computed, observable, trace } from "mobx"; import { observer } from "mobx-react"; import ReactTable, { CellInfo, Column, ComponentPropsGetterR, Resize, SortingRule } from "react-table"; -import "react-table/react-table.css"; import { DateField } from "../../../../fields/DateField"; import { AclPrivate, AclReadonly, DataSym, Doc, DocListCast, Field, Opt } from "../../../../fields/Doc"; import { Id } from "../../../../fields/FieldSymbols"; diff --git a/src/client/views/nodes/AudioBox.tsx b/src/client/views/nodes/AudioBox.tsx index c79828470..02451bdac 100644 --- a/src/client/views/nodes/AudioBox.tsx +++ b/src/client/views/nodes/AudioBox.tsx @@ -310,7 +310,9 @@ export class AudioBox extends ViewBoxAnnotatableComponent< ); DocUtils.ActiveRecordings.push(this); this._recorder.ondataavailable = async (e: any) => { + console.log("Data available", e); const [{ result }] = await Networking.UploadFilesToServer(e.data); + console.log("Data result", result); if (!(result instanceof Error)) { this.props.Document[this.props.fieldKey] = new AudioField(result.accessPaths.agnostic.client); } @@ -336,8 +338,8 @@ export class AudioBox extends ViewBoxAnnotatableComponent< (this.layoutDoc.dontAutoPlayFollowedLinks ? "" : "Don't") + " play when link is selected", event: () => - (this.layoutDoc.dontAutoPlayFollowedLinks = - !this.layoutDoc.dontAutoPlayFollowedLinks), + (this.layoutDoc.dontAutoPlayFollowedLinks = + !this.layoutDoc.dontAutoPlayFollowedLinks), icon: "expand-arrows-alt", }); funcs.push({ @@ -637,77 +639,77 @@ export class AudioBox extends ViewBoxAnnotatableComponent< </div> </div> ) : ( - <div - className={`audiobox-record${interactive}`} - style={{ backgroundColor: Colors.DARK_GRAY }} - > - <FontAwesomeIcon icon="microphone" /> + <div + className={`audiobox-record${interactive}`} + style={{ backgroundColor: Colors.DARK_GRAY }} + > + <FontAwesomeIcon icon="microphone" /> RECORD - </div> - )} + </div> + )} </div> ) : ( + <div + className="audiobox-controls" + style={{ + pointerEvents: + this._isAnyChildContentActive || this.props.isContentActive() + ? "all" + : "none", + }} + > + <div className="audiobox-dictation" /> <div - className="audiobox-controls" - style={{ - pointerEvents: - this._isAnyChildContentActive || this.props.isContentActive() - ? "all" - : "none", - }} + className="audiobox-player" + style={{ height: `${AudioBox.heightPercent}%` }} > - <div className="audiobox-dictation" /> <div - className="audiobox-player" - style={{ height: `${AudioBox.heightPercent}%` }} + className="audiobox-buttons" + title={this.mediaState === "paused" ? "play" : "pause"} + onClick={this.mediaState === "paused" ? this.Play : this.Pause} > - <div - className="audiobox-buttons" - title={this.mediaState === "paused" ? "play" : "pause"} - onClick={this.mediaState === "paused" ? this.Play : this.Pause} - > - {" "} - <FontAwesomeIcon - icon={this.mediaState === "paused" ? "play" : "pause"} - size={"1x"} - /> - </div> - <div - className="audiobox-buttons" - title={this._trimming ? "finish" : "trim"} - onClick={this._trimming ? this.finishTrim : this.startTrim} - > - <FontAwesomeIcon - icon={this._trimming ? "check" : "cut"} - size={"1x"} - /> - </div> - <div - className="audiobox-timeline" - style={{ - top: 0, - height: `100%`, - left: AudioBox.playheadWidth, - width: `calc(100% - ${AudioBox.playheadWidth}px)`, - background: "white", - }} - > - {this.renderTimeline} - </div> - {this.audio} - <div className="audioBox-current-time"> - {this._trimming ? - formatTime(Math.round(NumCast(this.layoutDoc._currentTimecode))) - : formatTime(Math.round(NumCast(this.layoutDoc._currentTimecode) - NumCast(this._trimStart)))} - </div> - <div className="audioBox-total-time"> - {this._trimming || !this._trimEnd ? - formatTime(Math.round(NumCast(this.duration))) - : formatTime(Math.round(NumCast(this.trimDuration)))} - </div> + {" "} + <FontAwesomeIcon + icon={this.mediaState === "paused" ? "play" : "pause"} + size={"1x"} + /> + </div> + <div + className="audiobox-buttons" + title={this._trimming ? "finish" : "trim"} + onClick={this._trimming ? this.finishTrim : this.startTrim} + > + <FontAwesomeIcon + icon={this._trimming ? "check" : "cut"} + size={"1x"} + /> + </div> + <div + className="audiobox-timeline" + style={{ + top: 0, + height: `100%`, + left: AudioBox.playheadWidth, + width: `calc(100% - ${AudioBox.playheadWidth}px)`, + background: "white", + }} + > + {this.renderTimeline} + </div> + {this.audio} + <div className="audioBox-current-time"> + {this._trimming ? + formatTime(Math.round(NumCast(this.layoutDoc._currentTimecode))) + : formatTime(Math.round(NumCast(this.layoutDoc._currentTimecode) - NumCast(this._trimStart)))} + </div> + <div className="audioBox-total-time"> + {this._trimming || !this._trimEnd ? + formatTime(Math.round(NumCast(this.duration))) + : formatTime(Math.round(NumCast(this.trimDuration)))} </div> </div> - )} + </div> + )} </div> ); } diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 67486dcf4..e2380bfba 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -1025,19 +1025,18 @@ export class DocumentViewInternal extends DocComponent<DocumentViewInternalProps display={"block"} fontSize={10} GetValue={() => showTitle.split(";").length === 1 ? showTitle + "=" + Field.toString(targetDoc[showTitle.split(";")[0]] as any as Field) : "#" + showTitle} - SetValue={undoBatch(input => { + SetValue={undoBatch((input: string) => { if (input?.startsWith("#")) { if (this.props.showTitle) { this.rootDoc._showTitle = input?.substring(1) ? input.substring(1) : undefined; } else { Doc.UserDoc().showTitle = input?.substring(1) ? input.substring(1) : "creationDate"; } - return true; } else { - var value = input.replace(new RegExp(showTitle + "="), ""); + var value = input.replace(new RegExp(showTitle + "="), "") as string | number; if (showTitle !== "title" && Number(value).toString() === value) value = Number(value); if (showTitle.includes("Date") || showTitle === "author") return true; - return Doc.SetInPlace(targetDoc, showTitle, value, true) ? true : true; + Doc.SetInPlace(targetDoc, showTitle, value, true); } return true; })} @@ -1148,7 +1147,7 @@ export class DocumentView extends React.Component<DocumentViewProps> { get LayoutFieldKey() { return this.docView?.LayoutFieldKey || "layout"; } get fitWidth() { return this.props.fitWidth?.(this.rootDoc) || this.layoutDoc.fitWidth; } - @computed get docViewPath() { return this.props.docViewPath ? [...this.props.docViewPath(), this] : [this]; } + @computed get docViewPath(): DocumentView[] { return this.props.docViewPath ? [...this.props.docViewPath(), this] : [this]; } @computed get layoutDoc() { return Doc.Layout(this.Document, this.props.LayoutTemplate?.()); } @computed get nativeWidth() { return this.docView?._componentView?.reverseNativeScaling?.() ? 0 : diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index 5d122ed54..112325cc3 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -188,7 +188,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent<ViewBoxAnnotatableProp if (url.href.indexOf(window.location.origin) === -1) return Utils.CorsProxy(url.href); if (!/\.(png|jpg|jpeg|gif|webp)$/.test(lower)) return url.href; //Why is this here - const ext = url.href.replace(/.*\./, "");//path.extname(url.href); + const ext = "." + url.href.replace(/.*\./, "");//path.extname(url.href); return url.href.replace(ext, this._curSuffix + ext); } diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx index d4ff40e8f..c2f4ea8da 100644 --- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx +++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx @@ -65,6 +65,7 @@ import React = require("react"); import { SidebarAnnos } from '../../SidebarAnnos'; import { Colors } from '../../global/globalEnums'; import { IconProp } from '@fortawesome/fontawesome-svg-core'; +import { UnknownErrorException } from 'pdfjs-dist/types/src/shared/util'; const translateGoogleApi = require("translate-google-api"); export interface FormattedTextBoxProps { @@ -1423,7 +1424,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<(FieldViewProp this.dataDoc[this.fieldKey + "-translation"] = result1 + "\r\n\r\n" + result[0]; }), 1000); }); - } catch (e) { console.log(e.message); } + } catch (e: any) { console.log(e.message); } this._lastText = curText; } } diff --git a/src/client/views/nodes/formattedText/ProsemirrorExampleTransfer.ts b/src/client/views/nodes/formattedText/ProsemirrorExampleTransfer.ts index 76a5675de..c76eda859 100644 --- a/src/client/views/nodes/formattedText/ProsemirrorExampleTransfer.ts +++ b/src/client/views/nodes/formattedText/ProsemirrorExampleTransfer.ts @@ -106,7 +106,7 @@ export function buildKeymap<S extends Schema<any>>(schema: S, props: any, mapKey bind("Mod-U", toggleEditableMark(schema.marks.underline)); //Commands for lists - bind("Ctrl-i", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => canEdit(state) && wrapInList(schema.nodes.ordered_list)(state, dispatch as any)); + bind("Ctrl-i", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => canEdit(state) && wrapInList(schema.nodes.ordered_list)(state as any, dispatch as any)); bind("Tab", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => { /// bcz; Argh!! replace layotuTEmpalteString with a onTab prop conditionally handles Tab); @@ -125,7 +125,7 @@ export function buildKeymap<S extends Schema<any>>(schema: S, props: any, mapKey dispatch(tx3); })) { // couldn't sink into an existing list, so wrap in a new one const newstate = state.applyTransaction(state.tr.setSelection(TextSelection.create(state.doc, range!.start, range!.end))); - if (!wrapInList(schema.nodes.ordered_list)(newstate.state, (tx2: Transaction) => { + if (!wrapInList(schema.nodes.ordered_list)(newstate.state as any, (tx2: Transaction) => { const tx3 = updateBullets(tx2, schema); // when promoting to a list, assume list will format things so don't copy the stored marks. marks && tx3.ensureMarks([...marks]); @@ -160,14 +160,14 @@ export function buildKeymap<S extends Schema<any>>(schema: S, props: any, mapKey }); //Commands to modify BlockType - bind("Ctrl->", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => canEdit((state) && wrapIn(schema.nodes.blockquote)(state, dispatch as any))); - bind("Alt-\\", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => canEdit(state) && setBlockType(schema.nodes.paragraph)(state, dispatch as any)); - bind("Shift-Ctrl-\\", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => canEdit(state) && setBlockType(schema.nodes.code_block)(state, dispatch as any)); + bind("Ctrl->", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => canEdit((state) && wrapIn(schema.nodes.blockquote)(state as any, dispatch as any))); + bind("Alt-\\", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => canEdit(state) && setBlockType(schema.nodes.paragraph)(state as any, dispatch as any)); + bind("Shift-Ctrl-\\", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => canEdit(state) && setBlockType(schema.nodes.code_block)(state as any, dispatch as any)); bind("Ctrl-m", (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => canEdit(state) && dispatch(state.tr.replaceSelectionWith(schema.nodes.equation.create({ fieldKey: "math" + Utils.GenerateGuid() })))); for (let i = 1; i <= 6; i++) { - bind("Shift-Ctrl-" + i, (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => canEdit(state) && setBlockType(schema.nodes.heading, { level: i })(state, dispatch as any)); + bind("Shift-Ctrl-" + i, (state: EditorState<S>, dispatch: (tx: Transaction<S>) => void) => canEdit(state) && setBlockType(schema.nodes.heading, { level: i })(state as any, dispatch as any)); } //Command to create a horizontal break line @@ -197,13 +197,13 @@ export function buildKeymap<S extends Schema<any>>(schema: S, props: any, mapKey bind("Backspace", (state: EditorState<S>, dispatch: (tx: Transaction<Schema<any, any>>) => void) => { if (!canEdit(state)) return true; - if (!deleteSelection(state, (tx: Transaction<Schema<any, any>>) => { + if (!deleteSelection(state, (tx: Transaction<S>) => { dispatch(updateBullets(tx, schema)); })) { - if (!joinBackward(state, (tx: Transaction<Schema<any, any>>) => { + if (!joinBackward(state, (tx: Transaction<S>) => { dispatch(updateBullets(tx, schema)); })) { - if (!selectNodeBackward(state, (tx: Transaction<Schema<any, any>>) => { + if (!selectNodeBackward(state, (tx: Transaction<S>) => { dispatch(updateBullets(tx, schema)); })) { return false; @@ -225,14 +225,14 @@ export function buildKeymap<S extends Schema<any>>(schema: S, props: any, mapKey const depth = trange ? liftTarget(trange) : undefined; const split = path.length > 5 && !path[path.length - 3].textContent && path[path.length - 6].type !== schema.nodes.list_item; if (split && trange && depth !== undefined && depth !== null) { - dispatch(state.tr.lift(trange, depth)); + dispatch(state.tr.lift(trange, depth) as any); return true; } const marks = state.storedMarks || (state.selection.$to.parentOffset && state.selection.$from.marks()); const cr = state.selection.$from.node().textContent.endsWith("\n"); - if (cr || !newlineInCode(state, dispatch)) { - if (!splitListItem(schema.nodes.list_item)(state, (tx2: Transaction) => { + if (cr || !newlineInCode(state, dispatch as any)) { + if (!splitListItem(schema.nodes.list_item)(state as any, (tx2: Transaction) => { const tx3 = updateBullets(tx2, schema); marks && tx3.ensureMarks([...marks]); marks && tx3.setStoredMarks([...marks]); diff --git a/src/client/views/nodes/formattedText/RichTextRules.ts b/src/client/views/nodes/formattedText/RichTextRules.ts index 711136469..bafae84dc 100644 --- a/src/client/views/nodes/formattedText/RichTextRules.ts +++ b/src/client/views/nodes/formattedText/RichTextRules.ts @@ -34,13 +34,9 @@ export class RichTextRules { wrappingInputRule( /^1\.\s$/, schema.nodes.ordered_list, - () => { - return ({ mapStyle: "decimal", bulletStyle: 1 }); - }, - (match: any, node: any) => { - return node.childCount + node.attrs.order === +match[1]; - }, - (type: any) => ({ type: type, attrs: { mapStyle: "decimal", bulletStyle: 1 } }) + () => ({ mapStyle: "decimal", bulletStyle: 1 }), + (match: any, node: any) => node.childCount + node.attrs.order === +match[1], + ((type: any) => ({ type: type, attrs: { mapStyle: "decimal", bulletStyle: 1 } })) as any ), // A. create alphabetical ordered list @@ -55,20 +51,16 @@ export class RichTextRules { (match: any, node: any) => { return node.childCount + node.attrs.order === +match[1]; }, - (type: any) => ({ type: type, attrs: { mapStyle: "multi", bulletStyle: 1 } }) + ((type: any) => ({ type: type, attrs: { mapStyle: "multi", bulletStyle: 1 } })) as any ), // * + - create bullet list wrappingInputRule(/^\s*([-+*])\s$/, schema.nodes.ordered_list, // match => { - () => { - return ({ mapStyle: "bullet" }); - // return ({ order: +match[1] }) - }, - (match: any, node: any) => { - return node.childCount + node.attrs.order === +match[1]; - }, - (type: any) => ({ type: type, attrs: { mapStyle: "bullet" } })), + () => ({ mapStyle: "bullet" }), // ({ order: +match[1] }) + (match: any, node: any) => node.childCount + node.attrs.order === +match[1], + ((type: any) => ({ type: type, attrs: { mapStyle: "bullet" } })) as any + ), // ``` create code block textblockTypeInputRule(/^```$/, schema.nodes.code_block), @@ -221,7 +213,7 @@ export class RichTextRules { tr.deleteRange(start, end).replaceSelectionWith(newNode); // replace insertion with a footnote. return tr.setSelection(new NodeSelection( // select the footnote node to open its display tr.doc.resolve( // get the location of the footnote node by subtracting the nodesize of the footnote from the current insertion point anchor (which will be immediately after the footnote node) - tr.selection.anchor - tr.selection.$anchor.nodeBefore!.nodeSize))); + tr.selection.anchor - (tr.selection.$anchor.nodeBefore?.nodeSize || 0)))); }), // activate a style by name using prefix '%<color name>' diff --git a/src/fields/CursorField.ts b/src/fields/CursorField.ts index 28467377b..a8a2859d2 100644 --- a/src/fields/CursorField.ts +++ b/src/fields/CursorField.ts @@ -50,7 +50,7 @@ export default class CursorField extends ObjectField { setPosition(position: CursorPosition) { this.data.position = position; this.data.metadata.timestamp = Date.now(); - this[OnUpdate](); + this[OnUpdate]?.(); } [Copy]() { diff --git a/src/fields/Doc.ts b/src/fields/Doc.ts index 0b9a8b3fe..63c67aeb0 100644 --- a/src/fields/Doc.ts +++ b/src/fields/Doc.ts @@ -216,7 +216,7 @@ export class Doc extends RefField { return self.resolvedDataDoc && !self.isTemplateForField ? self : Doc.GetProto(Cast(Doc.Layout(self).resolvedDataDoc, Doc, null) || self); } - @computed get __LAYOUT__() { + @computed get __LAYOUT__(): Doc | undefined { const templateLayoutDoc = Cast(Doc.LayoutField(this[SelfProxy]), Doc, null); if (templateLayoutDoc) { let renderFieldKey: any; diff --git a/src/fields/ObjectField.ts b/src/fields/ObjectField.ts index 92b2cfa60..9211afe86 100644 --- a/src/fields/ObjectField.ts +++ b/src/fields/ObjectField.ts @@ -3,7 +3,7 @@ import { OnUpdate, Parent, Copy, ToScriptString, ToString } from "./FieldSymbols import { Scripting } from "../client/util/Scripting"; export abstract class ObjectField { - public [OnUpdate](diff?: any) { } + public [OnUpdate]?: (diff?: any) => void; public [Parent]?: RefField | ObjectField; abstract [Copy](): ObjectField; diff --git a/src/fields/SchemaHeaderField.ts b/src/fields/SchemaHeaderField.ts index a53fa542e..3dc70ac19 100644 --- a/src/fields/SchemaHeaderField.ts +++ b/src/fields/SchemaHeaderField.ts @@ -82,32 +82,32 @@ export class SchemaHeaderField extends ObjectField { setHeading(heading: string) { this.heading = heading; - this[OnUpdate](); + this[OnUpdate]?.(); } setColor(color: string) { this.color = color; - this[OnUpdate](); + this[OnUpdate]?.(); } setType(type: ColumnType) { this.type = type; - this[OnUpdate](); + this[OnUpdate]?.(); } setWidth(width: number) { this.width = width; - this[OnUpdate](); + this[OnUpdate]?.(); } setDesc(desc: boolean | undefined) { this.desc = desc; - this[OnUpdate](); + this[OnUpdate]?.(); } setCollapsed(collapsed: boolean | undefined) { this.collapsed = collapsed; - this[OnUpdate](); + this[OnUpdate]?.(); } [Copy]() { diff --git a/src/fields/Types.ts b/src/fields/Types.ts index 220a30fe4..c90f3b6b3 100644 --- a/src/fields/Types.ts +++ b/src/fields/Types.ts @@ -111,5 +111,6 @@ export interface PromiseLike<T> { then(callback: (field: Opt<T>) => void): void; } export function PromiseValue<T extends Field>(field: FieldResult<T>): PromiseLike<Opt<T>> { - return field instanceof Promise ? field : { then(cb: ((field: Opt<T>) => void)) { return cb(field); } }; + if (field instanceof Promise) return field as Promise<Opt<T>>; + return { then(cb: ((field: Opt<T>) => void)) { return cb(field); } }; }
\ No newline at end of file diff --git a/src/scraping/buxton/final/BuxtonImporter.ts b/src/scraping/buxton/final/BuxtonImporter.ts index 684c00c0d..ee8dd5b5b 100644 --- a/src/scraping/buxton/final/BuxtonImporter.ts +++ b/src/scraping/buxton/final/BuxtonImporter.ts @@ -282,7 +282,7 @@ export default async function executeImport(emitter: ResultCallback, terminator: }); await transferAssets(); return parseFiles(wordDocuments, emitter, terminator); - } catch (e) { + } catch (e: any) { const message = [ "Unable to find a source directory.", "Please ensure that the following directory exists:", diff --git a/src/server/ActionUtilities.ts b/src/server/ActionUtilities.ts index d237869ed..bc8fd6f87 100644 --- a/src/server/ActionUtilities.ts +++ b/src/server/ActionUtilities.ts @@ -62,7 +62,7 @@ export async function log_execution<T>({ startMessage, endMessage, action, color log_helper(`${startMessage}...`, resolvedColor); try { result = await action(); - } catch (e) { + } catch (e: any) { error = e; } finally { log_helper(typeof endMessage === "string" ? endMessage : endMessage({ result, error }), resolvedColor); diff --git a/src/server/ApiManagers/UploadManager.ts b/src/server/ApiManagers/UploadManager.ts index 8da08fe33..bfa07d47a 100644 --- a/src/server/ApiManagers/UploadManager.ts +++ b/src/server/ApiManagers/UploadManager.ts @@ -48,10 +48,9 @@ export default class UploadManager extends ApiManager { method: Method.POST, subscription: "/uploadFormData", secureHandler: async ({ req, res }) => { - const form = new formidable.IncomingForm({ - keepExtensions: true, - uploadDir: pathToDirectory(Directory.parsed_files) - }); + const form = new formidable.IncomingForm(); + form.keepExtensions = true; + form.uploadDir = pathToDirectory(Directory.parsed_files); return new Promise<void>(resolve => { form.parse(req, async (_err, _fields, files) => { const results: Upload.FileResponse[] = []; @@ -144,7 +143,8 @@ export default class UploadManager extends ApiManager { subscription: "/uploadDoc", secureHandler: ({ req, res }) => { - const form = new formidable.IncomingForm({ keepExtensions: true }); + const form = new formidable.IncomingForm(); + form.keepExtensions = true; // let path = req.body.path; const ids: { [id: string]: string } = {}; let remap = true; @@ -222,7 +222,7 @@ export default class UploadManager extends ApiManager { id = getId(data.id); const docs = Object.keys(datadocs).map(key => datadocs[key]); docs.forEach(mapFn); - await Promise.all(docs.map((doc: any) => new Promise(res => { + await Promise.all(docs.map((doc: any) => new Promise<void>(res => { Database.Instance.replace(doc.id, doc, (err, r) => { err && console.log(err); res(); diff --git a/src/server/ApiManagers/UserManager.ts b/src/server/ApiManagers/UserManager.ts index fe80c6a7c..7be8a1e9f 100644 --- a/src/server/ApiManagers/UserManager.ts +++ b/src/server/ApiManagers/UserManager.ts @@ -22,7 +22,7 @@ export default class UserManager extends ApiManager { secureHandler: async ({ res }) => { const cursor = await Database.Instance.query({}, { email: 1, linkDatabaseId: 1, sharingDocumentId: 1 }, "users"); const results = await cursor.toArray(); - res.send(results.map(user => ({ email: user.email, linkDatabaseId: user.linkDatabaseId, sharingDocumentId: user.sharingDocumentId }))); + res.send(results.map((user: any) => ({ email: user.email, linkDatabaseId: user.linkDatabaseId, sharingDocumentId: user.sharingDocumentId }))); } }); diff --git a/src/server/DashSession/DashSessionAgent.ts b/src/server/DashSession/DashSessionAgent.ts index 03ba33fee..1a5934d8f 100644 --- a/src/server/DashSession/DashSessionAgent.ts +++ b/src/server/DashSession/DashSessionAgent.ts @@ -214,7 +214,7 @@ export class DashSessionAgent extends AppliedSessionAgent { // indicate success or failure mainLog(`${error === null ? green("successfully dispatched") : red("failed to dispatch")} ${zipName} to ${cyan(to)}`); error && mainLog(red(error.message)); - } catch (error) { + } catch (error: any) { mainLog(red("unable to dispatch zipped backup...")); mainLog(red(error.message)); } diff --git a/src/server/DashSession/Session/agents/monitor.ts b/src/server/DashSession/Session/agents/monitor.ts index 0fdaf07ff..9cb5ab576 100644 --- a/src/server/DashSession/Session/agents/monitor.ts +++ b/src/server/DashSession/Session/agents/monitor.ts @@ -178,7 +178,7 @@ export class Monitor extends IPCMessageReceiver { // ensure all necessary and no excess information is specified by the configuration file validate(config, configurationSchema, options); config = Utilities.preciseAssign({}, defaultConfig, config); - } catch (error) { + } catch (error: any) { if (error instanceof ValidationError) { console.log(red("\nSession configuration failed.")); console.log("The given session.config.json configuration file is invalid."); diff --git a/src/server/DashSession/Session/agents/promisified_ipc_manager.ts b/src/server/DashSession/Session/agents/promisified_ipc_manager.ts index 95aa686e6..f6c8de521 100644 --- a/src/server/DashSession/Session/agents/promisified_ipc_manager.ts +++ b/src/server/DashSession/Session/agents/promisified_ipc_manager.ts @@ -157,7 +157,7 @@ export class PromisifiedIPCManager { if (registered) { results = await Promise.all(registered.map(handler => handler(args))); } - } catch (e) { + } catch (e: any) { error = e; } if (!this.isDestroyed && this.target.send) { diff --git a/src/server/DashSession/Session/agents/server_worker.ts b/src/server/DashSession/Session/agents/server_worker.ts index 84d35b40e..634b0113d 100644 --- a/src/server/DashSession/Session/agents/server_worker.ts +++ b/src/server/DashSession/Session/agents/server_worker.ts @@ -138,7 +138,7 @@ export class ServerWorker extends IPCMessageReceiver { this.isInitialized = true; } this.shouldServerBeResponsive = true; - } catch (error) { + } catch (error: any) { // if we expect the server to be unavailable, i.e. during compilation, // the listening variable is false, activeExit will return early and the child // process will continue diff --git a/src/server/DashUploadUtils.ts b/src/server/DashUploadUtils.ts index 7073ee90b..552ab57a5 100644 --- a/src/server/DashUploadUtils.ts +++ b/src/server/DashUploadUtils.ts @@ -244,7 +244,7 @@ export namespace DashUploadUtils { // Use the request library to parse out file level image information in the headers const { headers } = (await new Promise<any>((resolve, reject) => { request.head(resolvedUrl, (error, res) => error ? reject(error) : resolve(res)); - }).catch(error => console.error(error))); + }).catch(console.error)); try { // Compute the native width and height ofthe image with an npm module const { width: nativeWidth, height: nativeHeight } = await requestImageSize(resolvedUrl); @@ -258,7 +258,7 @@ export namespace DashUploadUtils { filename, ...results }; - } catch (e) { + } catch (e: any) { console.log(e); return e; } diff --git a/src/server/Search.ts b/src/server/Search.ts index 68f61deb2..25bd8badf 100644 --- a/src/server/Search.ts +++ b/src/server/Search.ts @@ -49,7 +49,7 @@ export namespace Search { }, json: true }); - } catch (e) { + } catch (e: any) { console.log(red("Unable to clear search...")); console.log(red(e.message)); } diff --git a/src/server/apis/google/GoogleApiServerUtils.ts b/src/server/apis/google/GoogleApiServerUtils.ts index 64bafe7fb..4453b83bf 100644 --- a/src/server/apis/google/GoogleApiServerUtils.ts +++ b/src/server/apis/google/GoogleApiServerUtils.ts @@ -128,7 +128,7 @@ export namespace GoogleApiServerUtils { * @param userId the id of the Dash user making the request to the API * @returns the relevant 'googleapis' wrapper, if any */ - export async function GetEndpoint(sector: string, userId: string): Promise<Opt<Endpoint>> { + export async function GetEndpoint(sector: string, userId: string): Promise<Endpoint | void> { return new Promise(async resolve => { const auth = await retrieveOAuthClient(userId); if (!auth) { @@ -157,7 +157,7 @@ export namespace GoogleApiServerUtils { * npm-installed API wrappers that use authenticated client instances rather than access codes for * security. */ - export async function retrieveOAuthClient(userId: string): Promise<OAuth2Client> { + export async function retrieveOAuthClient(userId: string): Promise<OAuth2Client | void> { return new Promise(async resolve => { const { credentials, refreshed } = await retrieveCredentials(userId); if (!credentials) { diff --git a/src/server/remapUrl.ts b/src/server/remapUrl.ts index e9f9da25a..b8e17ec66 100644 --- a/src/server/remapUrl.ts +++ b/src/server/remapUrl.ts @@ -47,7 +47,7 @@ async function update() { await cursor.forEach(updateDoc); await Promise.all(updates.map(doc => { console.log(doc[0], doc[1]); - return new Promise(res => Database.Instance.update(doc[0], doc[1], () => { + return new Promise<void>(res => Database.Instance.update(doc[0], doc[1], () => { console.log("wrote " + JSON.stringify(doc[1])); res(); }, false)); diff --git a/src/server/server_Initialization.ts b/src/server/server_Initialization.ts index 06c701468..a10cd4983 100644 --- a/src/server/server_Initialization.ts +++ b/src/server/server_Initialization.ts @@ -31,7 +31,7 @@ const compiler = webpack(config); /* RouteSetter is a wrapper around the server that prevents the server from being exposed. */ export type RouteSetter = (server: RouteManager) => void; -export let disconnect: Function; +//export let disconnect: Function; export let resolvedPorts: { server: number, socket: number } = { server: 1050, socket: 4321 }; export let resolvedServerUrl: string; @@ -40,6 +40,14 @@ export default async function InitializeServer(routeSetter: RouteSetter) { const isRelease = determineEnvironment(); const app = buildWithMiddleware(express()); + const compiler = webpack(config); + + app.use(require("webpack-dev-middleware")(compiler, { + publicPath: config.output.publicPath + })); + + app.use(require("webpack-hot-middleware")(compiler)); + // route table managed by express. routes are tested sequentially against each of these map rules. when a match is found, the handler is called to process the request app.get(new RegExp(/^\/+$/), (req, res) => res.redirect(req.user ? "/home" : "/login")); // target urls that consist of one or more '/'s with nothing in between app.use(express.static(publicDirectory, { setHeaders: res => res.setHeader("Access-Control-Allow-Origin", "*") })); //all urls that start with dash's public directory: /files/ (e.g., /files/images, /files/audio, etc) @@ -66,7 +74,7 @@ export default async function InitializeServer(routeSetter: RouteSetter) { // a field on one client, that change must be broadcast to all other clients) await WebSocket.initialize(isRelease, app); - disconnect = async () => new Promise<Error>(resolve => server.close(resolve)); + //disconnect = async () => new Promise<Error>(resolve => server.close(resolve)); return isRelease; } |