diff options
91 files changed, 1311 insertions, 1280 deletions
diff --git a/package.json b/package.json index e0d0a72dd..8c9c865e0 100644 --- a/package.json +++ b/package.json @@ -1,167 +1,169 @@ { - "name": "dash", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "start": "nodemon --watch src/server/**/*.ts --exec ts-node src/server/index.ts", - "build": "webpack --env production", - "test": "mocha -r ts-node/register test/**/*.ts", - "tsc": "tsc" - }, - "devDependencies": { - "@types/chai": "^4.1.7", - "@types/mocha": "^5.2.6", - "@types/react-dom": "^16.8.2", - "@types/webpack-dev-middleware": "^2.0.2", - "@types/webpack-hot-middleware": "^2.16.4", - "awesome-typescript-loader": "^5.2.1", - "chai": "^4.2.0", - "copy-webpack-plugin": "^4.6.0", - "css-loader": "^2.1.1", - "file-loader": "^3.0.1", - "mocha": "^5.2.0", - "sass-loader": "^7.1.0", - "scss-loader": "0.0.1", - "style-loader": "^0.23.1", - "ts-node": "^7.0.1", - "typescript": "^3.4.1", - "webpack": "^4.29.6", - "webpack-cli": "^3.2.3", - "webpack-dev-middleware": "^3.6.1", - "webpack-dev-server": "^3.2.1", - "webpack-hot-middleware": "^2.24.3" - }, - "dependencies": { - "@fortawesome/fontawesome-free-solid": "^5.0.13", - "@fortawesome/fontawesome-svg-core": "^1.2.15", - "@fortawesome/free-solid-svg-icons": "^5.7.2", - "@fortawesome/react-fontawesome": "^0.1.4", - "@hig/flyout": "^1.0.3", - "@hig/theme-context": "^2.1.3", - "@hig/theme-data": "^2.3.3", - "@trendmicro/react-dropdown": "^1.3.0", - "@types/async": "^2.4.1", - "@types/bcrypt-nodejs": "0.0.30", - "@types/bluebird": "^3.5.25", - "@types/body-parser": "^1.17.0", - "@types/connect-flash": "0.0.34", - "@types/cookie-parser": "^1.4.1", - "@types/cookie-session": "^2.0.36", - "@types/d3-format": "^1.3.1", - "@types/express": "^4.16.1", - "@types/express-flash": "0.0.0", - "@types/express-session": "^1.15.12", - "@types/express-validator": "^3.0.0", - "@types/formidable": "^1.0.31", - "@types/jquery": "^3.3.29", - "@types/jsonwebtoken": "^8.3.2", - "@types/lodash": "^4.14.121", - "@types/mobile-detect": "^1.3.4", - "@types/mongodb": "^3.1.22", - "@types/mongoose": "^5.3.21", - "@types/node": "^10.12.30", - "@types/nodemailer": "^4.6.6", - "@types/passport": "^1.0.0", - "@types/passport-local": "^1.0.33", - "@types/prosemirror-commands": "^1.0.1", - "@types/prosemirror-history": "^1.0.1", - "@types/prosemirror-inputrules": "^1.0.2", - "@types/prosemirror-keymap": "^1.0.1", - "@types/prosemirror-model": "^1.7.0", - "@types/prosemirror-schema-basic": "^1.0.1", - "@types/prosemirror-schema-list": "^1.0.1", - "@types/prosemirror-state": "^1.2.3", - "@types/prosemirror-transform": "^1.1.0", - "@types/prosemirror-view": "^1.3.1", - "@types/pug": "^2.0.4", - "@types/react": "^16.8.7", - "@types/react-color": "^2.14.1", - "@types/react-measure": "^2.0.4", - "@types/react-table": "^6.7.22", - "@types/request": "^2.48.1", - "@types/request-promise": "^4.1.42", - "@types/socket.io": "^2.1.2", - "@types/socket.io-client": "^1.4.32", - "@types/typescript": "^2.0.0", - "@types/uuid": "^3.4.4", - "@types/webpack": "^4.4.25", - "async": "^2.6.2", - "babel-runtime": "^6.26.0", - "bcrypt-nodejs": "0.0.3", - "bluebird": "^3.5.3", - "body-parser": "^1.18.3", - "bootstrap": "^4.3.1", - "class-transformer": "^0.2.0", - "connect-flash": "^0.1.1", - "connect-mongo": "^2.0.3", - "cookie-parser": "^1.4.4", - "cookie-session": "^2.0.0-beta.3", - "crypto-browserify": "^3.11.0", - "d3-format": "^1.3.2", - "express": "^4.16.4", - "express-flash": "0.0.2", - "express-session": "^1.15.6", - "express-validator": "^5.3.1", - "expressjs": "^1.0.1", - "flexlayout-react": "^0.3.3", - "font-awesome": "^4.7.0", - "formidable": "^1.2.1", - "golden-layout": "^1.5.9", - "html-to-image": "^0.1.0", - "i": "^0.3.6", - "jsonwebtoken": "^8.5.0", - "jsx-to-string": "^1.4.0", - "lodash": "^4.17.11", - "mobile-detect": "^1.4.3", - "mobx": "^5.9.0", - "mobx-react": "^5.3.5", - "mobx-react-devtools": "^6.1.1", - "mongodb": "^3.1.13", - "mongoose": "^5.4.18", - "node-sass": "^4.11.0", - "nodemailer": "^5.1.1", - "nodemon": "^1.18.10", - "normalize.css": "^8.0.1", - "npm": "^6.9.0", - "passport": "^0.4.0", - "passport-local": "^1.0.0", - "prosemirror-commands": "^1.0.7", - "prosemirror-example-setup": "^1.0.1", - "prosemirror-history": "^1.0.4", - "prosemirror-keymap": "^1.0.1", - "prosemirror-model": "^1.7.0", - "prosemirror-schema-basic": "^1.0.0", - "prosemirror-schema-list": "^1.0.2", - "prosemirror-state": "^1.2.2", - "prosemirror-transform": "^1.1.3", - "prosemirror-view": "^1.8.3", - "pug": "^2.0.3", - "raw-loader": "^1.0.0", - "react": "^16.8.4", - "react-bootstrap": "^1.0.0-beta.5", - "react-bootstrap-dropdown-menu": "^1.1.15", - "react-color": "^2.17.0", - "react-dimensions": "^1.3.1", - "react-dom": "^16.8.4", - "react-golden-layout": "^1.0.6", - "react-image-lightbox": "^5.1.0", - "react-jsx-parser": "^1.15.0", - "react-measure": "^2.2.4", - "react-mosaic": "0.0.20", - "react-pdf": "^4.0.2", - "react-pdf-highlighter": "^2.1.2", - "react-pdf-js": "^4.0.2", - "react-simple-dropdown": "^3.2.3", - "react-split-pane": "^0.1.85", - "react-table": "^6.9.2", - "request": "^2.88.0", - "request-promise": "^4.2.4", - "socket.io": "^2.2.0", - "socket.io-client": "^2.2.0", - "typescript-collections": "^1.3.2", - "url-loader": "^1.1.2", - "uuid": "^3.3.2", - "xoauth2": "^1.2.0" - } + "name": "dash", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "start": "nodemon --watch src/server/**/*.ts --exec ts-node src/server/index.ts", + "build": "webpack --env production", + "test": "mocha -r ts-node/register test/**/*.ts", + "tsc": "tsc" + }, + "devDependencies": { + "@types/chai": "^4.1.7", + "@types/mocha": "^5.2.6", + "@types/react-dom": "^16.8.2", + "@types/webpack-dev-middleware": "^2.0.2", + "@types/webpack-hot-middleware": "^2.16.4", + "awesome-typescript-loader": "^5.2.1", + "chai": "^4.2.0", + "copy-webpack-plugin": "^4.6.0", + "css-loader": "^2.1.1", + "file-loader": "^3.0.1", + "mocha": "^5.2.0", + "sass-loader": "^7.1.0", + "scss-loader": "0.0.1", + "style-loader": "^0.23.1", + "ts-node": "^7.0.1", + "tslint": "^5.15.0", + "tslint-loader": "^3.5.4", + "typescript": "^3.4.1", + "webpack": "^4.29.6", + "webpack-cli": "^3.2.3", + "webpack-dev-middleware": "^3.6.1", + "webpack-dev-server": "^3.2.1", + "webpack-hot-middleware": "^2.24.3" + }, + "dependencies": { + "@fortawesome/fontawesome-free-solid": "^5.0.13", + "@fortawesome/fontawesome-svg-core": "^1.2.15", + "@fortawesome/free-solid-svg-icons": "^5.7.2", + "@fortawesome/react-fontawesome": "^0.1.4", + "@hig/flyout": "^1.0.3", + "@hig/theme-context": "^2.1.3", + "@hig/theme-data": "^2.3.3", + "@trendmicro/react-dropdown": "^1.3.0", + "@types/async": "^2.4.1", + "@types/bcrypt-nodejs": "0.0.30", + "@types/bluebird": "^3.5.25", + "@types/body-parser": "^1.17.0", + "@types/connect-flash": "0.0.34", + "@types/cookie-parser": "^1.4.1", + "@types/cookie-session": "^2.0.36", + "@types/d3-format": "^1.3.1", + "@types/express": "^4.16.1", + "@types/express-flash": "0.0.0", + "@types/express-session": "^1.15.12", + "@types/express-validator": "^3.0.0", + "@types/formidable": "^1.0.31", + "@types/jquery": "^3.3.29", + "@types/jsonwebtoken": "^8.3.2", + "@types/lodash": "^4.14.121", + "@types/mobile-detect": "^1.3.4", + "@types/mongodb": "^3.1.22", + "@types/mongoose": "^5.3.21", + "@types/node": "^10.12.30", + "@types/nodemailer": "^4.6.6", + "@types/passport": "^1.0.0", + "@types/passport-local": "^1.0.33", + "@types/prosemirror-commands": "^1.0.1", + "@types/prosemirror-history": "^1.0.1", + "@types/prosemirror-inputrules": "^1.0.2", + "@types/prosemirror-keymap": "^1.0.1", + "@types/prosemirror-model": "^1.7.0", + "@types/prosemirror-schema-basic": "^1.0.1", + "@types/prosemirror-schema-list": "^1.0.1", + "@types/prosemirror-state": "^1.2.3", + "@types/prosemirror-transform": "^1.1.0", + "@types/prosemirror-view": "^1.3.1", + "@types/pug": "^2.0.4", + "@types/react": "^16.8.7", + "@types/react-color": "^2.14.1", + "@types/react-measure": "^2.0.4", + "@types/react-table": "^6.7.22", + "@types/request": "^2.48.1", + "@types/request-promise": "^4.1.42", + "@types/socket.io": "^2.1.2", + "@types/socket.io-client": "^1.4.32", + "@types/typescript": "^2.0.0", + "@types/uuid": "^3.4.4", + "@types/webpack": "^4.4.25", + "async": "^2.6.2", + "babel-runtime": "^6.26.0", + "bcrypt-nodejs": "0.0.3", + "bluebird": "^3.5.3", + "body-parser": "^1.18.3", + "bootstrap": "^4.3.1", + "class-transformer": "^0.2.0", + "connect-flash": "^0.1.1", + "connect-mongo": "^2.0.3", + "cookie-parser": "^1.4.4", + "cookie-session": "^2.0.0-beta.3", + "crypto-browserify": "^3.11.0", + "d3-format": "^1.3.2", + "express": "^4.16.4", + "express-flash": "0.0.2", + "express-session": "^1.15.6", + "express-validator": "^5.3.1", + "expressjs": "^1.0.1", + "flexlayout-react": "^0.3.3", + "font-awesome": "^4.7.0", + "formidable": "^1.2.1", + "golden-layout": "^1.5.9", + "html-to-image": "^0.1.0", + "i": "^0.3.6", + "jsonwebtoken": "^8.5.0", + "jsx-to-string": "^1.4.0", + "lodash": "^4.17.11", + "mobile-detect": "^1.4.3", + "mobx": "^5.9.0", + "mobx-react": "^5.3.5", + "mobx-react-devtools": "^6.1.1", + "mongodb": "^3.1.13", + "mongoose": "^5.4.18", + "node-sass": "^4.11.0", + "nodemailer": "^5.1.1", + "nodemon": "^1.18.10", + "normalize.css": "^8.0.1", + "npm": "^6.9.0", + "passport": "^0.4.0", + "passport-local": "^1.0.0", + "prosemirror-commands": "^1.0.7", + "prosemirror-example-setup": "^1.0.1", + "prosemirror-history": "^1.0.4", + "prosemirror-keymap": "^1.0.1", + "prosemirror-model": "^1.7.0", + "prosemirror-schema-basic": "^1.0.0", + "prosemirror-schema-list": "^1.0.2", + "prosemirror-state": "^1.2.2", + "prosemirror-transform": "^1.1.3", + "prosemirror-view": "^1.8.3", + "pug": "^2.0.3", + "raw-loader": "^1.0.0", + "react": "^16.8.4", + "react-bootstrap": "^1.0.0-beta.5", + "react-bootstrap-dropdown-menu": "^1.1.15", + "react-color": "^2.17.0", + "react-dimensions": "^1.3.1", + "react-dom": "^16.8.4", + "react-golden-layout": "^1.0.6", + "react-image-lightbox": "^5.1.0", + "react-jsx-parser": "^1.15.0", + "react-measure": "^2.2.4", + "react-mosaic": "0.0.20", + "react-pdf": "^4.0.2", + "react-pdf-highlighter": "^2.1.2", + "react-pdf-js": "^4.0.2", + "react-simple-dropdown": "^3.2.3", + "react-split-pane": "^0.1.85", + "react-table": "^6.9.2", + "request": "^2.88.0", + "request-promise": "^4.2.4", + "socket.io": "^2.2.0", + "socket.io-client": "^2.2.0", + "typescript-collections": "^1.3.2", + "url-loader": "^1.1.2", + "uuid": "^3.3.2", + "xoauth2": "^1.2.0" + } } diff --git a/src/Utils.ts b/src/Utils.ts index a5d9bd0ca..8bd7f2f5c 100644 --- a/src/Utils.ts +++ b/src/Utils.ts @@ -18,7 +18,7 @@ export class Utils { return { scale: 1, translateX: 1, translateY: 1 } } const rect = ele.getBoundingClientRect(); - const scale = ele.offsetWidth == 0 && rect.width == 0 ? 1 : rect.width / ele.offsetWidth; + const scale = ele.offsetWidth === 0 && rect.width === 0 ? 1 : rect.width / ele.offsetWidth; const translateX = rect.left; const translateY = rect.top; @@ -86,4 +86,14 @@ export class Utils { } } +export function returnTrue() { + return true; +} + +export function returnFalse() { + return false; +} + +export function emptyFunction() { } + export type Without<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
\ No newline at end of file diff --git a/src/client/Server.ts b/src/client/Server.ts index 37e3c2c0d..45c7144ca 100644 --- a/src/client/Server.ts +++ b/src/client/Server.ts @@ -21,11 +21,11 @@ export class Server { let fn = (cb: (field: Opt<Field>) => void) => { let cached = this.ClientFieldsCached.get(fieldid); - if (!cached) { + if (cached === undefined) { this.ClientFieldsCached.set(fieldid, FieldWaiting); SocketStub.SEND_FIELD_REQUEST(fieldid, action((field: Field | undefined) => { let cached = this.ClientFieldsCached.get(fieldid); - if (cached != FieldWaiting) + if (cached !== FieldWaiting) cb(cached); else { if (field) { @@ -36,23 +36,22 @@ export class Server { cb(field) } })); - } else if (cached != FieldWaiting) { + } else if (cached !== FieldWaiting) { setTimeout(() => cb(cached as Field), 0); } else { - reaction(() => { - return this.ClientFieldsCached.get(fieldid); - }, (field, reaction) => { - if (field !== "<Waiting>") { - reaction.dispose() - cb(field) - } - }) + reaction(() => this.ClientFieldsCached.get(fieldid), + (field, reaction) => { + if (field !== FieldWaiting) { + reaction.dispose() + cb(field) + } + }) } } if (callback) { fn(callback); } else { - return new Promise(res => fn(res)); + return new Promise(fn); } } @@ -92,24 +91,23 @@ export class Server { } } } - reaction(() => { - return waitingFieldIds.map(id => this.ClientFieldsCached.get(id)); - }, (cachedFields, reaction) => { - if (!cachedFields.some(field => !field || field === FieldWaiting)) { - reaction.dispose(); - for (let field of cachedFields) { - let realField = field as Field; - existingFields[realField.Id] = realField; + reaction(() => waitingFieldIds.map(id => this.ClientFieldsCached.get(id)), + (cachedFields, reaction) => { + if (!cachedFields.some(field => !field)) { + reaction.dispose(); + for (let field of cachedFields) { + let realField = field as Field; + existingFields[realField.Id] = realField; + } + cb({ ...fields, ...existingFields }) } - cb({ ...fields, ...existingFields }) - } - }, { fireImmediately: true }) + }, { fireImmediately: true }) })); }; if (callback) { fn(callback); } else { - return new Promise(res => fn(res)); + return new Promise(fn); } } @@ -153,19 +151,19 @@ export class Server { @action private static cacheField(clientField: Field) { var cached = this.ClientFieldsCached.get(clientField.Id); - if (!cached || cached == FieldWaiting) { + if (!cached) { this.ClientFieldsCached.set(clientField.Id, clientField); } else { // probably should overwrite the values within any field that was already here... } - return this.ClientFieldsCached.get(clientField.Id) as Field; + return this.ClientFieldsCached.get(clientField.Id); } @action static updateField(field: { _id: string, data: any, type: Types }) { if (Server.ClientFieldsCached.has(field._id)) { var f = Server.ClientFieldsCached.get(field._id); - if (f && f != FieldWaiting) { + if (f) { // console.log("Applying : " + field._id); f.UpdateFromServer(field.data); f.init(() => { }); diff --git a/src/client/SocketStub.ts b/src/client/SocketStub.ts index 5045037c5..c3cd8bee6 100644 --- a/src/client/SocketStub.ts +++ b/src/client/SocketStub.ts @@ -55,7 +55,7 @@ export class SocketStub { if (callback) { fn(callback); } else { - return new Promise(res => fn(res)) + return new Promise(fn) } } diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 7d2f9cde1..aa109e779 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -17,7 +17,8 @@ import { HistogramOperation } from "../northstar/operations/HistogramOperation"; import { Server } from "../Server"; import { CollectionPDFView } from "../views/collections/CollectionPDFView"; import { CollectionVideoView } from "../views/collections/CollectionVideoView"; -import { CollectionView, CollectionViewType } from "../views/collections/CollectionView"; +import { CollectionView } from "../views/collections/CollectionView"; +import { CollectionViewType } from "../views/collections/CollectionBaseView"; import { AudioBox } from "../views/nodes/AudioBox"; import { FormattedTextBox } from "../views/nodes/FormattedTextBox"; import { ImageBox } from "../views/nodes/ImageBox"; diff --git a/src/client/northstar/core/BaseObject.ts b/src/client/northstar/core/BaseObject.ts index e9e766e31..f1761e643 100644 --- a/src/client/northstar/core/BaseObject.ts +++ b/src/client/northstar/core/BaseObject.ts @@ -4,7 +4,7 @@ import { IDisposable } from '../utils/IDisposable' export class BaseObject implements IEquatable, IDisposable { public Equals(other: Object): boolean { - return this == other; + return this === other; } public Dispose(): void { diff --git a/src/client/northstar/core/attribute/AttributeModel.ts b/src/client/northstar/core/attribute/AttributeModel.ts index 124a5b45a..230bfecc8 100644 --- a/src/client/northstar/core/attribute/AttributeModel.ts +++ b/src/client/northstar/core/attribute/AttributeModel.ts @@ -34,7 +34,7 @@ export class ColumnAttributeModel extends AttributeModel { } public Equals(other: ColumnAttributeModel): boolean { - return this.Attribute.rawName == other.Attribute.rawName; + return this.Attribute.rawName === other.Attribute.rawName; } } @@ -105,7 +105,7 @@ export class BackendAttributeModel extends AttributeModel { } public Equals(other: BackendAttributeModel): boolean { - return this.Id == other.Id; + return this.Id === other.Id; } }
\ No newline at end of file diff --git a/src/client/northstar/core/attribute/AttributeTransformationModel.ts b/src/client/northstar/core/attribute/AttributeTransformationModel.ts index cc5aa7154..f50b78d51 100644 --- a/src/client/northstar/core/attribute/AttributeTransformationModel.ts +++ b/src/client/northstar/core/attribute/AttributeTransformationModel.ts @@ -41,7 +41,7 @@ export class AttributeTransformationModel implements IEquatable { } public Equals(other: AttributeTransformationModel): boolean { - return this.AggregateFunction == other.AggregateFunction && + return this.AggregateFunction === other.AggregateFunction && this.AttributeModel.Equals(other.AttributeModel); } }
\ No newline at end of file diff --git a/src/client/northstar/core/attribute/CalculatedAttributeModel.ts b/src/client/northstar/core/attribute/CalculatedAttributeModel.ts index ab96c794d..0b8e0d12c 100644 --- a/src/client/northstar/core/attribute/CalculatedAttributeModel.ts +++ b/src/client/northstar/core/attribute/CalculatedAttributeModel.ts @@ -11,7 +11,7 @@ export class CalculatedAttributeManager { public static CreateBackendAttributeModel(id: string, dataType: DataType, displayName: string, codeName: string, visualizationHints: VisualizationHint[]): BackendAttributeModel { var filtered = this.AllCalculatedAttributes.filter(am => { if (am instanceof BackendAttributeModel && - am.Id == id) { + am.Id === id) { return true; } return false; @@ -27,7 +27,7 @@ export class CalculatedAttributeManager { public static CreateCodeAttributeModel(code: string, codeName: string, visualizationHints: VisualizationHint[]): CodeAttributeModel { var filtered = this.AllCalculatedAttributes.filter(am => { if (am instanceof CodeAttributeModel && - am.CodeName == codeName) { + am.CodeName === codeName) { return true; } return false; diff --git a/src/client/northstar/core/filter/FilterModel.ts b/src/client/northstar/core/filter/FilterModel.ts index aee99d2b6..20fca77f5 100644 --- a/src/client/northstar/core/filter/FilterModel.ts +++ b/src/client/northstar/core/filter/FilterModel.ts @@ -46,16 +46,16 @@ export class FilterModel { let filtered = baseOperation.FilterModels.filter(fm => fm && fm.ValueComparisons.length > 0); if (!isFirst && filtered.length > 0) { filterModels.push(...filtered); - ret = "(" + baseOperation.FilterModels.filter(fm => fm != null).map(fm => fm.ToPythonString()).join(" || ") + ")"; + ret = "(" + baseOperation.FilterModels.filter(fm => fm !== null).map(fm => fm.ToPythonString()).join(" || ") + ")"; } if (Utils.isBaseFilterConsumer(baseOperation) && baseOperation.Links) { let children = new Array<string>(); let linkedGraphNodes = baseOperation.Links; linkedGraphNodes.map(linkVm => { let filterDoc = linkVm.Get(KeyStore.LinkedFromDocs); - if (filterDoc && filterDoc != FieldWaiting && filterDoc instanceof Document) { + if (filterDoc && filterDoc !== FieldWaiting && filterDoc instanceof Document) { let filterHistogram = filterDoc.GetT(KeyStore.Data, HistogramField); - if (filterHistogram && filterHistogram != FieldWaiting) { + if (filterHistogram && filterHistogram !== FieldWaiting) { if (!visitedFilterProviders.has(filterHistogram.Data)) { let child = FilterModel.GetFilterModelsRecursive(filterHistogram.Data, visitedFilterProviders, filterModels, false); if (child !== "") { diff --git a/src/client/northstar/core/filter/ValueComparision.ts b/src/client/northstar/core/filter/ValueComparision.ts index 1e729d06e..1a3e461f5 100644 --- a/src/client/northstar/core/filter/ValueComparision.ts +++ b/src/client/northstar/core/filter/ValueComparision.ts @@ -20,7 +20,7 @@ export class ValueComparison { if (this.Predicate !== (other as ValueComparison).Predicate) return false; let isComplex = (typeof this.Value === "object"); - if (!isComplex && this.Value != (other as ValueComparison).Value) + if (!isComplex && this.Value !== (other as ValueComparison).Value) return false; if (isComplex && !this.Value.Equals((other as ValueComparison).Value)) return false; @@ -58,13 +58,13 @@ export class ValueComparison { var rawName = this.attributeModel.CodeName; switch (this.Predicate) { case Predicate.STARTS_WITH: - ret += rawName + " != null && " + rawName + ".StartsWith(" + val + ") "; + ret += rawName + " !== null && " + rawName + ".StartsWith(" + val + ") "; return ret; case Predicate.ENDS_WITH: - ret += rawName + " != null && " + rawName + ".EndsWith(" + val + ") "; + ret += rawName + " !== null && " + rawName + ".EndsWith(" + val + ") "; return ret; case Predicate.CONTAINS: - ret += rawName + " != null && " + rawName + ".Contains(" + val + ") "; + ret += rawName + " !== null && " + rawName + ".Contains(" + val + ") "; return ret; default: ret += rawName + " " + op + " " + val + " "; diff --git a/src/client/northstar/dash-fields/HistogramField.ts b/src/client/northstar/dash-fields/HistogramField.ts index 48731f52d..fa2a9c008 100644 --- a/src/client/northstar/dash-fields/HistogramField.ts +++ b/src/client/northstar/dash-fields/HistogramField.ts @@ -16,7 +16,7 @@ export class HistogramField extends BasicField<HistogramOperation> { omitKeys(obj: any, keys: any) { var dup: any = {}; for (var key in obj) { - if (keys.indexOf(key) == -1) { + if (keys.indexOf(key) === -1) { dup[key] = obj[key]; } } @@ -54,13 +54,13 @@ export class HistogramField extends BasicField<HistogramOperation> { let schema = CurrentUserUtils.GetNorthstarSchema(jp.SchemaName); if (schema) { CurrentUserUtils.GetAllNorthstarColumnAttributes(schema).map(attr => { - if (attr.displayName == jp.X.AttributeModel.Attribute.DisplayName) { + if (attr.displayName === jp.X.AttributeModel.Attribute.DisplayName) { X = new AttributeTransformationModel(new ColumnAttributeModel(attr), jp.X.AggregateFunction); } - if (attr.displayName == jp.Y.AttributeModel.Attribute.DisplayName) { + if (attr.displayName === jp.Y.AttributeModel.Attribute.DisplayName) { Y = new AttributeTransformationModel(new ColumnAttributeModel(attr), jp.Y.AggregateFunction); } - if (attr.displayName == jp.V.AttributeModel.Attribute.DisplayName) { + if (attr.displayName === jp.V.AttributeModel.Attribute.DisplayName) { V = new AttributeTransformationModel(new ColumnAttributeModel(attr), jp.V.AggregateFunction); } }); diff --git a/src/client/northstar/dash-nodes/HistogramBinPrimitiveCollection.ts b/src/client/northstar/dash-nodes/HistogramBinPrimitiveCollection.ts index 43e768c62..cdae90c8b 100644 --- a/src/client/northstar/dash-nodes/HistogramBinPrimitiveCollection.ts +++ b/src/client/northstar/dash-nodes/HistogramBinPrimitiveCollection.ts @@ -48,28 +48,28 @@ export class HistogramBinPrimitiveCollection { // adjust brush rects (stacking or not) var allBrushIndex = ModelHelpers.AllBrushIndex(this.histoResult); - var filteredBinPrims = this.BinPrimitives.filter(b => b.BrushIndex != allBrushIndex && b.DataValue != 0.0); + var filteredBinPrims = this.BinPrimitives.filter(b => b.BrushIndex !== allBrushIndex && b.DataValue !== 0.0); filteredBinPrims.reduce((sum, fbp) => { - if (histoBox.ChartType == ChartType.VerticalBar) { - if (this.histoOp.Y.AggregateFunction == AggregateFunction.Count) { + if (histoBox.ChartType === ChartType.VerticalBar) { + if (this.histoOp.Y.AggregateFunction === AggregateFunction.Count) { fbp.Rect = new PIXIRectangle(fbp.Rect.x, fbp.Rect.y - sum, fbp.Rect.width, fbp.Rect.height); fbp.MarginRect = new PIXIRectangle(fbp.MarginRect.x, fbp.MarginRect.y - sum, fbp.MarginRect.width, fbp.MarginRect.height); return sum + fbp.Rect.height; } - if (this.histoOp.Y.AggregateFunction == AggregateFunction.Avg) { + if (this.histoOp.Y.AggregateFunction === AggregateFunction.Avg) { var w = fbp.Rect.width / 2.0; fbp.Rect = new PIXIRectangle(fbp.Rect.x + sum, fbp.Rect.y, fbp.Rect.width / filteredBinPrims.length, fbp.Rect.height); fbp.MarginRect = new PIXIRectangle(fbp.MarginRect.x - w + sum + (fbp.Rect.width / 2.0), fbp.MarginRect.y, fbp.MarginRect.width, fbp.MarginRect.height); return sum + fbp.Rect.width; } } - else if (histoBox.ChartType == ChartType.HorizontalBar) { - if (this.histoOp.X.AggregateFunction == AggregateFunction.Count) { + else if (histoBox.ChartType === ChartType.HorizontalBar) { + if (this.histoOp.X.AggregateFunction === AggregateFunction.Count) { fbp.Rect = new PIXIRectangle(fbp.Rect.x + sum, fbp.Rect.y, fbp.Rect.width, fbp.Rect.height); fbp.MarginRect = new PIXIRectangle(fbp.MarginRect.x + sum, fbp.MarginRect.y, fbp.MarginRect.width, fbp.MarginRect.height); return sum + fbp.Rect.width; } - if (this.histoOp.X.AggregateFunction == AggregateFunction.Avg) { + if (this.histoOp.X.AggregateFunction === AggregateFunction.Avg) { var h = fbp.Rect.height / 2.0; fbp.Rect = new PIXIRectangle(fbp.Rect.x, fbp.Rect.y + sum, fbp.Rect.width, fbp.Rect.height / filteredBinPrims.length); fbp.MarginRect = new PIXIRectangle(fbp.MarginRect.x, fbp.MarginRect.y - h + sum + (fbp.Rect.height / 2.0), fbp.MarginRect.width, fbp.MarginRect.height); @@ -79,19 +79,19 @@ export class HistogramBinPrimitiveCollection { return 0; }, 0); this.BinPrimitives = this.BinPrimitives.reverse(); - var f = this.BinPrimitives.filter(b => b.BrushIndex == allBrushIndex); + var f = this.BinPrimitives.filter(b => b.BrushIndex === allBrushIndex); this.HitGeom = f.length > 0 ? f[0].Rect : PIXIRectangle.EMPTY; } private setupBrushing(bin: Bin, normalization: number) { var overlapBrushIndex = ModelHelpers.OverlapBrushIndex(this.histoResult); var orderedBrushes = [this.histoResult.brushes![0], this.histoResult.brushes![overlapBrushIndex]]; - this.histoResult.brushes!.map(brush => brush.brushIndex != 0 && brush.brushIndex != overlapBrushIndex && orderedBrushes.push(brush)); + this.histoResult.brushes!.map(brush => brush.brushIndex !== 0 && brush.brushIndex !== overlapBrushIndex && orderedBrushes.push(brush)); return { orderedBrushes, maxAxis: orderedBrushes.reduce((prev, Brush) => { let aggResult = this.getBinValue(normalization, bin, Brush.brushIndex!); - return aggResult != undefined && aggResult > prev ? aggResult : prev; + return aggResult !== undefined && aggResult > prev ? aggResult : prev; }, Number.MIN_VALUE) }; } @@ -99,7 +99,7 @@ export class HistogramBinPrimitiveCollection { private createHeatmapBinPrimitives(bin: Bin, brush: Brush, brushFactorSum: number): number { let unNormalizedValue = this.getBinValue(2, bin, brush.brushIndex!); - if (unNormalizedValue == undefined) + if (unNormalizedValue === undefined) return brushFactorSum; var normalizedValue = (unNormalizedValue - this._histoBox.ValueRange[0]) / (Math.abs((this._histoBox.ValueRange[1] - this._histoBox.ValueRange[0])) < HistogramBinPrimitiveCollection.TOLERANCE ? @@ -112,7 +112,7 @@ export class HistogramBinPrimitiveCollection { let [yFrom, yTo] = this.sizeConverter.DataToScreenYAxisRange(this._histoBox.VisualBinRanges, 1, bin); var returnBrushFactorSum = brushFactorSum; - if (allUnNormalizedValue != undefined) { + if (allUnNormalizedValue !== undefined) { var brushFactor = (unNormalizedValue / allUnNormalizedValue); returnBrushFactorSum += brushFactor; returnBrushFactorSum = Math.min(returnBrushFactorSum, 1.0); @@ -141,11 +141,11 @@ export class HistogramBinPrimitiveCollection { private createSinglePointChartBinPrimitives(bin: Bin, brush: Brush): number { let unNormalizedValue = this.getBinValue(2, bin, brush.brushIndex!); - if (unNormalizedValue != undefined) { + if (unNormalizedValue !== undefined) { let [xFrom, xTo] = this.sizeConverter.DataToScreenPointRange(0, bin, ModelHelpers.CreateAggregateKey(this.histoOp.Schema!.distinctAttributeParameters, this.histoOp.X, this.histoResult, brush.brushIndex!)); let [yFrom, yTo] = this.sizeConverter.DataToScreenPointRange(1, bin, ModelHelpers.CreateAggregateKey(this.histoOp.Schema!.distinctAttributeParameters, this.histoOp.Y, this.histoResult, brush.brushIndex!)); - if (xFrom != undefined && yFrom != undefined && xTo != undefined && yTo != undefined) + if (xFrom !== undefined && yFrom !== undefined && xTo !== undefined && yTo !== undefined) this.createBinPrimitive(-1, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, this.baseColorFromBrush(brush), 1, unNormalizedValue); } return 0; @@ -153,7 +153,7 @@ export class HistogramBinPrimitiveCollection { private createVerticalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number): number { let dataValue = this.getBinValue(1, bin, brush.brushIndex!); - if (dataValue != undefined) { + if (dataValue !== undefined) { let [yFrom, yValue, yTo] = this.sizeConverter.DataToScreenNormalizedRange(dataValue, normalization, 1, binBrushMaxAxis); let [xFrom, xTo] = this.sizeConverter.DataToScreenXAxisRange(this._histoBox.VisualBinRanges, 0, bin); @@ -163,14 +163,14 @@ export class HistogramBinPrimitiveCollection { this.sizeConverter.DataToScreenY(yValue - yMarginAbsolute) - this.sizeConverter.DataToScreenY(yValue + yMarginAbsolute)); this.createBinPrimitive(1, brush, marginRect, 0, xFrom, xTo, yFrom, yTo, - this.baseColorFromBrush(brush), normalization != 0 ? 1 : 0.6 * binBrushMaxAxis / this.sizeConverter.DataRanges[1] + 0.4, dataValue); + this.baseColorFromBrush(brush), normalization !== 0 ? 1 : 0.6 * binBrushMaxAxis / this.sizeConverter.DataRanges[1] + 0.4, dataValue); } return 0; } private createHorizontalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number): number { let dataValue = this.getBinValue(0, bin, brush.brushIndex!); - if (dataValue != undefined) { + if (dataValue !== undefined) { let [xFrom, xValue, xTo] = this.sizeConverter.DataToScreenNormalizedRange(dataValue, normalization, 0, binBrushMaxAxis); let [yFrom, yTo] = this.sizeConverter.DataToScreenYAxisRange(this._histoBox.VisualBinRanges, 1, bin); @@ -181,15 +181,15 @@ export class HistogramBinPrimitiveCollection { 2.0); this.createBinPrimitive(0, brush, marginRect, 0, xFrom, xTo, yFrom, yTo, - this.baseColorFromBrush(brush), normalization != 1 ? 1 : 0.6 * binBrushMaxAxis / this.sizeConverter.DataRanges[0] + 0.4, dataValue); + this.baseColorFromBrush(brush), normalization !== 1 ? 1 : 0.6 * binBrushMaxAxis / this.sizeConverter.DataRanges[0] + 0.4, dataValue); } return 0; } public getBinValue(axis: number, bin: Bin, brushIndex: number) { - var aggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Schema!.distinctAttributeParameters, axis == 0 ? this.histoOp.X : axis == 1 ? this.histoOp.Y : this.histoOp.V, this.histoResult, brushIndex); + var aggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Schema!.distinctAttributeParameters, axis === 0 ? this.histoOp.X : axis === 1 ? this.histoOp.Y : this.histoOp.V, this.histoResult, brushIndex); let dataValue = ModelHelpers.GetAggregateResult(bin, aggregateKey) as DoubleValueAggregateResult; - return dataValue != null && dataValue.hasResult ? dataValue.result : undefined; + return dataValue !== null && dataValue.hasResult ? dataValue.result : undefined; } private getMargin(bin: Bin, brush: Brush, axis: AttributeTransformationModel) { @@ -218,13 +218,13 @@ export class HistogramBinPrimitiveCollection { private baseColorFromBrush(brush: Brush): number { let bc = StyleConstants.BRUSH_COLORS; - if (brush.brushIndex == ModelHelpers.RestBrushIndex(this.histoResult)) { + if (brush.brushIndex === ModelHelpers.RestBrushIndex(this.histoResult)) { return StyleConstants.HIGHLIGHT_COLOR; } - else if (brush.brushIndex == ModelHelpers.OverlapBrushIndex(this.histoResult)) { + else if (brush.brushIndex === ModelHelpers.OverlapBrushIndex(this.histoResult)) { return StyleConstants.OVERLAP_COLOR; } - else if (brush.brushIndex == ModelHelpers.AllBrushIndex(this.histoResult)) { + else if (brush.brushIndex === ModelHelpers.AllBrushIndex(this.histoResult)) { return 0x00ff00; } else if (bc.length > 0) { diff --git a/src/client/northstar/dash-nodes/HistogramBox.tsx b/src/client/northstar/dash-nodes/HistogramBox.tsx index dd6e09900..ec9413649 100644 --- a/src/client/northstar/dash-nodes/HistogramBox.tsx +++ b/src/client/northstar/dash-nodes/HistogramBox.tsx @@ -55,7 +55,7 @@ export class HistogramBox extends React.Component<FieldViewProps> { dropX = (e: Event, de: DragManager.DropEvent) => { if (de.data instanceof DragManager.DocumentDragData) { let h = de.data.draggedDocuments[0].GetT(KeyStore.Data, HistogramField); - if (h && h != FieldWaiting) { + if (h && h !== FieldWaiting) { this.HistoOp.X = h.Data.X; } e.stopPropagation(); @@ -66,7 +66,7 @@ export class HistogramBox extends React.Component<FieldViewProps> { dropY = (e: Event, de: DragManager.DropEvent) => { if (de.data instanceof DragManager.DocumentDragData) { let h = de.data.draggedDocuments[0].GetT(KeyStore.Data, HistogramField); - if (h && h != FieldWaiting) { + if (h && h !== FieldWaiting) { this.HistoOp.Y = h.Data.X; } e.stopPropagation(); @@ -76,11 +76,11 @@ export class HistogramBox extends React.Component<FieldViewProps> { @action xLabelPointerDown = (e: React.PointerEvent) => { - this.HistoOp.X = new AttributeTransformationModel(this.HistoOp.X.AttributeModel, this.HistoOp.X.AggregateFunction == AggregateFunction.None ? AggregateFunction.Count : AggregateFunction.None); + this.HistoOp.X = new AttributeTransformationModel(this.HistoOp.X.AttributeModel, this.HistoOp.X.AggregateFunction === AggregateFunction.None ? AggregateFunction.Count : AggregateFunction.None); } @action yLabelPointerDown = (e: React.PointerEvent) => { - this.HistoOp.Y = new AttributeTransformationModel(this.HistoOp.Y.AttributeModel, this.HistoOp.Y.AggregateFunction == AggregateFunction.None ? AggregateFunction.Count : AggregateFunction.None); + this.HistoOp.Y = new AttributeTransformationModel(this.HistoOp.Y.AttributeModel, this.HistoOp.Y.AggregateFunction === AggregateFunction.None ? AggregateFunction.Count : AggregateFunction.None); } componentDidMount() { @@ -117,18 +117,18 @@ export class HistogramBox extends React.Component<FieldViewProps> { activateHistogramOperation(catalog?: Catalog) { if (catalog) { - this.props.doc.GetTAsync(this.props.fieldKey, HistogramField).then((histoOp: Opt<HistogramField>) => runInAction(() => { + this.props.Document.GetTAsync(this.props.fieldKey, HistogramField).then((histoOp: Opt<HistogramField>) => runInAction(() => { this.HistoOp = histoOp ? histoOp.Data : HistogramOperation.Empty; - if (this.HistoOp != HistogramOperation.Empty) { - reaction(() => this.props.doc.GetList(KeyStore.LinkedFromDocs, []), (docs: Document[]) => this.HistoOp.Links.splice(0, this.HistoOp.Links.length, ...docs), { fireImmediately: true }); - reaction(() => this.props.doc.GetList(KeyStore.BrushingDocs, []).length, + if (this.HistoOp !== HistogramOperation.Empty) { + reaction(() => this.props.Document.GetList(KeyStore.LinkedFromDocs, []), (docs: Document[]) => this.HistoOp.Links.splice(0, this.HistoOp.Links.length, ...docs), { fireImmediately: true }); + reaction(() => this.props.Document.GetList(KeyStore.BrushingDocs, []).length, () => { - let brushingDocs = this.props.doc.GetList(KeyStore.BrushingDocs, [] as Document[]); - let proto = this.props.doc.GetPrototype() as Document; + let brushingDocs = this.props.Document.GetList(KeyStore.BrushingDocs, [] as Document[]); + let proto = this.props.Document.GetPrototype() as Document; this.HistoOp.BrushLinks.splice(0, this.HistoOp.BrushLinks.length, ...brushingDocs.map((brush, i) => { brush.SetNumber(KeyStore.BackgroundColor, StyleConstants.BRUSH_COLORS[i % StyleConstants.BRUSH_COLORS.length]); let brushed = brush.GetList(KeyStore.BrushingDocs, [] as Document[]); - return { l: brush, b: brushed[0].Id == proto.Id ? brushed[1] : brushed[0] } + return { l: brush, b: brushed[0].Id === proto.Id ? brushed[1] : brushed[0] } })); }, { fireImmediately: true }); reaction(() => this.createOperationParamsCache, () => this.HistoOp.Update(), { fireImmediately: true }); @@ -139,8 +139,8 @@ export class HistogramBox extends React.Component<FieldViewProps> { render() { let labelY = this.HistoOp && this.HistoOp.Y ? this.HistoOp.Y.PresentedName : "<...>"; let labelX = this.HistoOp && this.HistoOp.X ? this.HistoOp.X.PresentedName : "<...>"; - var h = this.props.isTopMost ? this.PanelHeight : this.props.doc.GetNumber(KeyStore.Height, 0); - var w = this.props.isTopMost ? this.PanelWidth : this.props.doc.GetNumber(KeyStore.Width, 0); + var h = this.props.isTopMost ? this.PanelHeight : this.props.Document.GetNumber(KeyStore.Height, 0); + var w = this.props.isTopMost ? this.PanelWidth : this.props.Document.GetNumber(KeyStore.Width, 0); let loff = this.SizeConverter.LeftOffset; let toff = this.SizeConverter.TopOffset; let roff = this.SizeConverter.RightOffset; diff --git a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx index 0918bc0c4..a78703247 100644 --- a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx +++ b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx @@ -46,7 +46,7 @@ export class HistogramBoxPrimitives extends React.Component<HistogramPrimitivesP } private getSelectionToggle(binPrimitives: HistogramBinPrimitive[], allBrushIndex: number, filterModel: FilterModel) { - let rawAllBrushPrim = ArrayUtil.FirstOrDefault(binPrimitives, bp => bp.BrushIndex == allBrushIndex); + let rawAllBrushPrim = ArrayUtil.FirstOrDefault(binPrimitives, bp => bp.BrushIndex === allBrushIndex); if (!rawAllBrushPrim) return () => { } let allBrushPrim = rawAllBrushPrim; @@ -70,9 +70,9 @@ export class HistogramBoxPrimitives extends React.Component<HistogramPrimitivesP return <svg className="histogramboxprimitives-svgContainer"> {labels.reduce((prims, binLabel, i) => { let r = this.props.HistoBox.SizeConverter.DataToScreenRange(binLabel.minValue!, binLabel.maxValue!, axis); - prims.push(this.drawLine(r.xFrom, r.yFrom, axis == 0 ? 0 : r.xTo - r.xFrom, axis == 0 ? r.yTo - r.yFrom : 0)); - if (i == labels.length - 1) - prims.push(this.drawLine(axis == 0 ? r.xTo : r.xFrom, axis == 0 ? r.yFrom : r.yTo, axis == 0 ? 0 : r.xTo - r.xFrom, axis == 0 ? r.yTo - r.yFrom : 0)); + prims.push(this.drawLine(r.xFrom, r.yFrom, axis === 0 ? 0 : r.xTo - r.xFrom, axis === 0 ? r.yTo - r.yFrom : 0)); + if (i === labels.length - 1) + prims.push(this.drawLine(axis === 0 ? r.xTo : r.xFrom, axis === 0 ? r.yFrom : r.yTo, axis === 0 ? 0 : r.xTo - r.xFrom, axis === 0 ? r.yTo - r.yFrom : 0)); return prims; }, [] as JSX.Element[])} </svg> @@ -106,7 +106,7 @@ export class HistogramBoxPrimitives extends React.Component<HistogramPrimitivesP let transYpercent = `${r.y / this.renderDimension * 100}%` let widthXpercent = `${r.width / this.renderDimension * 100}%`; let heightYpercent = `${r.height / this.renderDimension * 100}%`; - return (<rect className={`histogramboxprimitives-${classExt}`} key={DashUtils.GenerateGuid()} onPointerDown={(e: React.PointerEvent) => { if (e.button == 0) tapHandler() }} + return (<rect className={`histogramboxprimitives-${classExt}`} key={DashUtils.GenerateGuid()} onPointerDown={(e: React.PointerEvent) => { if (e.button === 0) tapHandler() }} x={transXpercent} width={`${widthXpercent}`} y={transYpercent} height={`${heightYpercent}`} fill={color ? `${LABColor.RGBtoHexString(color)}` : "transparent"} />); } render() { diff --git a/src/client/northstar/dash-nodes/HistogramLabelPrimitives.tsx b/src/client/northstar/dash-nodes/HistogramLabelPrimitives.tsx index 93b237deb..dd62e9146 100644 --- a/src/client/northstar/dash-nodes/HistogramLabelPrimitives.tsx +++ b/src/client/northstar/dash-nodes/HistogramLabelPrimitives.tsx @@ -34,7 +34,7 @@ export class HistogramLabelPrimitives extends React.Component<HistogramPrimitive let vb = this.props.HistoBox.VisualBinRanges; if (!vb.length || !sc.Initialized) return (null); - let dim = (axis == 0 ? this.props.HistoBox.PanelWidth : this.props.HistoBox.PanelHeight) / ((axis == 0 && vb[axis] instanceof NominalVisualBinRange) ? + let dim = (axis === 0 ? this.props.HistoBox.PanelWidth : this.props.HistoBox.PanelHeight) / ((axis === 0 && vb[axis] instanceof NominalVisualBinRange) ? (12 + 5) : // (<number>FontStyles.AxisLabel.fontSize + 5))); sc.MaxLabelSizes[axis].coords[axis] + 5); @@ -47,17 +47,17 @@ export class HistogramLabelPrimitives extends React.Component<HistogramPrimitive let xStart = (axis === 0 ? r.xFrom + (r.xTo - r.xFrom) / 2.0 : r.xFrom - 10 - textWidth); let yStart = (axis === 1 ? r.yFrom - textHeight / 2 : r.yFrom); - if (axis == 0 && vb[axis] instanceof NominalVisualBinRange) { + if (axis === 0 && vb[axis] instanceof NominalVisualBinRange) { let space = (r.xTo - r.xFrom) / sc.RenderDimension * this.props.HistoBox.PanelWidth; xStart += Math.max(textWidth / 2, (1 - textWidth / space) * textWidth / 2) - textHeight / 2; } - let xPercent = axis == 1 ? `${xStart}px` : `${xStart / sc.RenderDimension * 100}%` - let yPercent = axis == 0 ? `${this.props.HistoBox.PanelHeight - sc.BottomOffset - textHeight}px` : `${yStart / sc.RenderDimension * 100}%` + let xPercent = axis === 1 ? `${xStart}px` : `${xStart / sc.RenderDimension * 100}%` + let yPercent = axis === 0 ? `${this.props.HistoBox.PanelHeight - sc.BottomOffset - textHeight}px` : `${yStart / sc.RenderDimension * 100}%` prims.push( <div className="histogramLabelPrimitives-placer" key={DashUtils.GenerateGuid()} style={{ transform: `translate(${xPercent}, ${yPercent})` }}> - <div className="histogramLabelPrimitives-gridlabel" style={{ transform: `rotate(${axis == 0 ? sc.LabelAngle : 0}rad)` }}> + <div className="histogramLabelPrimitives-gridlabel" style={{ transform: `rotate(${axis === 0 ? sc.LabelAngle : 0}rad)` }}> {label} </div> </div> diff --git a/src/client/northstar/manager/Gateway.ts b/src/client/northstar/manager/Gateway.ts index 5ae5e4f47..ba6fe2ad5 100644 --- a/src/client/northstar/manager/Gateway.ts +++ b/src/client/northstar/manager/Gateway.ts @@ -49,7 +49,7 @@ export class Gateway { public async Compile(data: any): Promise<CompileResults | undefined> { const json = await this.MakePostJsonRequest("compile", data); - if (json != null) { + if (json !== null) { const cr = CompileResults.fromJS(json); return cr; } @@ -108,7 +108,7 @@ export class Gateway { public async StartOperation(data: any): Promise<OperationReference | undefined> { const json = await this.MakePostJsonRequest("operation", data); - if (json != null) { + if (json !== null) { const or = OperationReference.fromJS(json); return or; } @@ -116,7 +116,7 @@ export class Gateway { public async GetResult(data: any): Promise<Result | undefined> { const json = await this.MakePostJsonRequest("result", data); - if (json != null) { + if (json !== null) { const res = Result.fromJS(json); return res; } @@ -163,7 +163,7 @@ export class Gateway { public static ConstructUrl(appendix: string): string { let base = Settings.Instance.ServerUrl; - if (base.slice(-1) == "/") { + if (base.slice(-1) === "/") { base = base.slice(0, -1); } let url = base + "/" + Settings.Instance.ServerApiPath + "/" + appendix; @@ -246,18 +246,18 @@ export class Settings { else { this.ServerUrl = environment["SERVER_URL"] ? environment["SERVER_URL"] : document.URL; }*/ - this.ServerUrl = environment["SERVER_URL"] ? environment["SERVER_URL"] : document.URL; - this.ServerApiPath = environment["SERVER_API_PATH"]; - this.SampleSize = environment["SAMPLE_SIZE"]; - this.XBins = environment["X_BINS"]; - this.YBins = environment["Y_BINS"]; - this.SplashTimeInMS = environment["SPLASH_TIME_IN_MS"]; - this.ShowFpsCounter = environment["SHOW_FPS_COUNTER"]; - this.ShowShutdownButton = environment["SHOW_SHUTDOWN_BUTTON"]; - this.IsMenuFixed = environment["IS_MENU_FIXED"]; - this.IsDarpa = environment["IS_DARPA"]; - this.IsIGT = environment["IS_IGT"]; - this.DegreeOfParallelism = environment["DEGREE_OF_PARALLISM"]; + this.ServerUrl = environment.SERVER_URL ? environment.SERVER_URL : document.URL; + this.ServerApiPath = environment.SERVER_API_PATH; + this.SampleSize = environment.SAMPLE_SIZE; + this.XBins = environment.X_BINS; + this.YBins = environment.Y_BINS; + this.SplashTimeInMS = environment.SPLASH_TIME_IN_MS; + this.ShowFpsCounter = environment.SHOW_FPS_COUNTER; + this.ShowShutdownButton = environment.SHOW_SHUTDOWN_BUTTON; + this.IsMenuFixed = environment.IS_MENU_FIXED; + this.IsDarpa = environment.IS_DARPA; + this.IsIGT = environment.IS_IGT; + this.DegreeOfParallelism = environment.DEGREE_OF_PARALLISM; } public static get Instance(): Settings { diff --git a/src/client/northstar/model/ModelExtensions.ts b/src/client/northstar/model/ModelExtensions.ts index 9fcba7f1c..e4bf77ed8 100644 --- a/src/client/northstar/model/ModelExtensions.ts +++ b/src/client/northstar/model/ModelExtensions.ts @@ -3,23 +3,23 @@ import { Utils } from '../utils/Utils' import { FilterModel } from '../core/filter/FilterModel' -(SingleDimensionAggregateParameters as any).prototype["Equals"] = function (other: Object) { +(SingleDimensionAggregateParameters as any).prototype.Equals = function (other: Object) { if (!Utils.EqualityHelper(this, other)) return false; if (!Utils.EqualityHelper((this as SingleDimensionAggregateParameters).attributeParameters!, (other as SingleDimensionAggregateParameters).attributeParameters!)) return false; - if (!((this as SingleDimensionAggregateParameters).attributeParameters! as any)["Equals"]((other as SingleDimensionAggregateParameters).attributeParameters)) return false; + if (!((this as SingleDimensionAggregateParameters).attributeParameters! as any).Equals((other as SingleDimensionAggregateParameters).attributeParameters)) return false; return true; } { - (AttributeParameters as any).prototype["Equals"] = function (other: AttributeParameters) { + (AttributeParameters as any).prototype.Equals = function (other: AttributeParameters) { return (<any>this).constructor.name === (<any>other).constructor.name && this.rawName === other.rawName; } } { - (Solution as any).prototype["Equals"] = function (other: Object) { + (Solution as any).prototype.Equals = function (other: Object) { if (!Utils.EqualityHelper(this, other)) return false; if ((this as Solution).solutionId !== (other as Solution).solutionId) return false; return true; @@ -27,11 +27,11 @@ import { FilterModel } from '../core/filter/FilterModel' } { - (MarginAggregateParameters as any).prototype["Equals"] = function (other: Object) { + (MarginAggregateParameters as any).prototype.Equals = function (other: Object) { if (!Utils.EqualityHelper(this, other)) return false; if (!Utils.EqualityHelper((this as SingleDimensionAggregateParameters).attributeParameters!, (other as SingleDimensionAggregateParameters).attributeParameters!)) return false; - if (!((this as SingleDimensionAggregateParameters).attributeParameters! as any)["Equals"]((other as SingleDimensionAggregateParameters).attributeParameters!)) return false; + if (!((this as SingleDimensionAggregateParameters).attributeParameters! as any).Equals((other as SingleDimensionAggregateParameters).attributeParameters!)) return false; if ((this as MarginAggregateParameters).aggregateFunction !== (other as MarginAggregateParameters).aggregateFunction) return false; return true; @@ -39,7 +39,7 @@ import { FilterModel } from '../core/filter/FilterModel' } { - (Brush as any).prototype["Equals"] = function (other: Object) { + (Brush as any).prototype.Equals = function (other: Object) { if (!Utils.EqualityHelper(this, other)) return false; if ((this as Brush).brushEnum !== (other as Brush).brushEnum) return false; if ((this as Brush).brushIndex !== (other as Brush).brushIndex) return false; diff --git a/src/client/northstar/model/ModelHelpers.ts b/src/client/northstar/model/ModelHelpers.ts index d0711fb69..1a58e6180 100644 --- a/src/client/northstar/model/ModelHelpers.ts +++ b/src/client/northstar/model/ModelHelpers.ts @@ -16,7 +16,7 @@ export class ModelHelpers { public static CreateAggregateKey(distinctAttributeParameters: AttributeParameters | undefined, atm: AttributeTransformationModel, histogramResult: HistogramResult, brushIndex: number, aggParameters?: SingleDimensionAggregateParameters): AggregateKey { { - if (aggParameters == undefined) { + if (aggParameters === undefined) { aggParameters = ModelHelpers.GetAggregateParameter(distinctAttributeParameters, atm); } else { @@ -146,7 +146,7 @@ export class ModelHelpers { } public static GetAggregateResult(bin: Bin, aggregateKey: AggregateKey) { - if (aggregateKey.aggregateParameterIndex == -1 || aggregateKey.brushIndex == -1) { + if (aggregateKey.aggregateParameterIndex === -1 || aggregateKey.brushIndex === -1) { return null; } return bin.aggregateResults![aggregateKey.aggregateParameterIndex! * bin.ySize! + aggregateKey.brushIndex!]; @@ -157,9 +157,9 @@ export class ModelHelpers { var ret = new Array<AggregateFunction>(); ret.push(AggregateFunction.None); ret.push(AggregateFunction.Count); - if (atm.AttributeModel.DataType == DataType.Float || - atm.AttributeModel.DataType == DataType.Double || - atm.AttributeModel.DataType == DataType.Int) { + if (atm.AttributeModel.DataType === DataType.Float || + atm.AttributeModel.DataType === DataType.Double || + atm.AttributeModel.DataType === DataType.Int) { ret.push(AggregateFunction.Avg); ret.push(AggregateFunction.Sum); } diff --git a/src/client/northstar/model/binRanges/DateTimeVisualBinRange.ts b/src/client/northstar/model/binRanges/DateTimeVisualBinRange.ts index 9313fb1a7..f5872aa4c 100644 --- a/src/client/northstar/model/binRanges/DateTimeVisualBinRange.ts +++ b/src/client/northstar/model/binRanges/DateTimeVisualBinRange.ts @@ -39,24 +39,24 @@ export class DateTimeVisualBinRange extends VisualBinRange { public GetLabel(value: number): string { var dt = DateTimeVisualBinRange.TicksToDate(value); - if (this.DataBinRange.step!.dateTimeStepGranularity == DateTimeStepGranularity.Second || - this.DataBinRange.step!.dateTimeStepGranularity == DateTimeStepGranularity.Minute) { + if (this.DataBinRange.step!.dateTimeStepGranularity === DateTimeStepGranularity.Second || + this.DataBinRange.step!.dateTimeStepGranularity === DateTimeStepGranularity.Minute) { return ("" + this.pad(dt.getMinutes(), 2) + ":" + this.pad(dt.getSeconds(), 2)); //return dt.ToString("mm:ss"); } - else if (this.DataBinRange.step!.dateTimeStepGranularity == DateTimeStepGranularity.Hour) { + else if (this.DataBinRange.step!.dateTimeStepGranularity === DateTimeStepGranularity.Hour) { return (this.pad(dt.getHours(), 2) + ":" + this.pad(dt.getMinutes(), 2)); //return dt.ToString("HH:mm"); } - else if (this.DataBinRange.step!.dateTimeStepGranularity == DateTimeStepGranularity.Day) { + else if (this.DataBinRange.step!.dateTimeStepGranularity === DateTimeStepGranularity.Day) { return ((dt.getMonth() + 1) + "/" + dt.getDate() + "/" + dt.getFullYear()); //return dt.ToString("MM/dd/yyyy"); } - else if (this.DataBinRange.step!.dateTimeStepGranularity == DateTimeStepGranularity.Month) { + else if (this.DataBinRange.step!.dateTimeStepGranularity === DateTimeStepGranularity.Month) { //return dt.ToString("MM/yyyy"); return ((dt.getMonth() + 1) + "/" + dt.getFullYear()); } - else if (this.DataBinRange.step!.dateTimeStepGranularity == DateTimeStepGranularity.Year) { + else if (this.DataBinRange.step!.dateTimeStepGranularity === DateTimeStepGranularity.Year) { return "" + dt.getFullYear(); } return "n/a"; @@ -82,22 +82,22 @@ export class DateTimeVisualBinRange extends VisualBinRange { public static AddToDateTimeTicks(ticks: number, dateTimeStep: DateTimeStep): number { var copiedDate = DateTimeVisualBinRange.TicksToDate(ticks); var returnDate: Date = new Date(Date.now()); - if (dateTimeStep.dateTimeStepGranularity == DateTimeStepGranularity.Second) { + if (dateTimeStep.dateTimeStepGranularity === DateTimeStepGranularity.Second) { returnDate = new Date(copiedDate.setSeconds(copiedDate.getSeconds() + dateTimeStep.dateTimeStepValue!)); } - else if (dateTimeStep.dateTimeStepGranularity == DateTimeStepGranularity.Minute) { + else if (dateTimeStep.dateTimeStepGranularity === DateTimeStepGranularity.Minute) { returnDate = new Date(copiedDate.setMinutes(copiedDate.getMinutes() + dateTimeStep.dateTimeStepValue!)); } - else if (dateTimeStep.dateTimeStepGranularity == DateTimeStepGranularity.Hour) { + else if (dateTimeStep.dateTimeStepGranularity === DateTimeStepGranularity.Hour) { returnDate = new Date(copiedDate.setHours(copiedDate.getHours() + dateTimeStep.dateTimeStepValue!)); } - else if (dateTimeStep.dateTimeStepGranularity == DateTimeStepGranularity.Day) { + else if (dateTimeStep.dateTimeStepGranularity === DateTimeStepGranularity.Day) { returnDate = new Date(copiedDate.setDate(copiedDate.getDate() + dateTimeStep.dateTimeStepValue!)); } - else if (dateTimeStep.dateTimeStepGranularity == DateTimeStepGranularity.Month) { + else if (dateTimeStep.dateTimeStepGranularity === DateTimeStepGranularity.Month) { returnDate = new Date(copiedDate.setMonth(copiedDate.getMonth() + dateTimeStep.dateTimeStepValue!)); } - else if (dateTimeStep.dateTimeStepGranularity == DateTimeStepGranularity.Year) { + else if (dateTimeStep.dateTimeStepGranularity === DateTimeStepGranularity.Year) { returnDate = new Date(copiedDate.setFullYear(copiedDate.getFullYear() + dateTimeStep.dateTimeStepValue!)); } return DateTimeVisualBinRange.DateToTicks(returnDate); diff --git a/src/client/northstar/model/binRanges/VisualBinRange.ts b/src/client/northstar/model/binRanges/VisualBinRange.ts index f53008f9a..a0766e494 100644 --- a/src/client/northstar/model/binRanges/VisualBinRange.ts +++ b/src/client/northstar/model/binRanges/VisualBinRange.ts @@ -2,10 +2,6 @@ import { BinLabel } from '../../model/idea/idea' export abstract class VisualBinRange { - constructor() { - - } - public abstract AddStep(value: number): number; public abstract GetValueFromIndex(index: number): number; diff --git a/src/client/northstar/model/binRanges/VisualBinRangeHelper.ts b/src/client/northstar/model/binRanges/VisualBinRangeHelper.ts index 53d585bb4..63ee61909 100644 --- a/src/client/northstar/model/binRanges/VisualBinRangeHelper.ts +++ b/src/client/northstar/model/binRanges/VisualBinRangeHelper.ts @@ -39,8 +39,7 @@ export class VisualBinRangeHelper { var aggregateKey = ModelHelpers.CreateAggregateKey(distinctAttributeParameters, attr, histoResult, ModelHelpers.AllBrushIndex(histoResult)); var minValue = Number.MAX_VALUE; var maxValue = Number.MIN_VALUE; - for (var b = 0; b < histoResult.brushes!.length; b++) { - var brush = histoResult.brushes![b]; + for (const brush of histoResult.brushes!) { aggregateKey.brushIndex = brush.brushIndex; for (var key in histoResult.bins) { if (histoResult.bins.hasOwnProperty(key)) { @@ -56,12 +55,12 @@ export class VisualBinRangeHelper { let visualBinRange = QuantitativeVisualBinRange.Initialize(minValue, maxValue, 10, false); - if (chartType == ChartType.HorizontalBar || chartType == ChartType.VerticalBar) { + if (chartType === ChartType.HorizontalBar || chartType === ChartType.VerticalBar) { visualBinRange = QuantitativeVisualBinRange.Initialize(Math.min(0, minValue), Math.max(0, (visualBinRange as QuantitativeVisualBinRange).DataBinRange.maxValue!), SETTINGS_X_BINS, false); } - else if (chartType == ChartType.SinglePoint) { + else if (chartType === ChartType.SinglePoint) { visualBinRange = QuantitativeVisualBinRange.Initialize(Math.min(0, minValue), Math.max(0, maxValue), SETTINGS_X_BINS, false); } diff --git a/src/client/northstar/model/idea/MetricTypeMapping.ts b/src/client/northstar/model/idea/MetricTypeMapping.ts index 11e0c871a..e9759cf16 100644 --- a/src/client/northstar/model/idea/MetricTypeMapping.ts +++ b/src/client/northstar/model/idea/MetricTypeMapping.ts @@ -5,20 +5,20 @@ import { Dictionary } from 'typescript-collections'; export class MetricTypeMapping { public static GetMetricInterpretation(metricType: MetricType): MetricInterpretation { - if (metricType == MetricType.Accuracy || - metricType == MetricType.F1 || - metricType == MetricType.F1Macro || - metricType == MetricType.F1Micro || - metricType == MetricType.JaccardSimilarityScore || - metricType == MetricType.ObjectDetectionAveragePrecision || - metricType == MetricType.Precision || - metricType == MetricType.PrecisionAtTopK || - metricType == MetricType.NormalizedMutualInformation || - metricType == MetricType.Recall || - metricType == MetricType.RocAucMacro || - metricType == MetricType.RocAuc || - metricType == MetricType.RocAucMicro || - metricType == MetricType.RSquared) { + if (metricType === MetricType.Accuracy || + metricType === MetricType.F1 || + metricType === MetricType.F1Macro || + metricType === MetricType.F1Micro || + metricType === MetricType.JaccardSimilarityScore || + metricType === MetricType.ObjectDetectionAveragePrecision || + metricType === MetricType.Precision || + metricType === MetricType.PrecisionAtTopK || + metricType === MetricType.NormalizedMutualInformation || + metricType === MetricType.Recall || + metricType === MetricType.RocAucMacro || + metricType === MetricType.RocAuc || + metricType === MetricType.RocAucMicro || + metricType === MetricType.RSquared) { return MetricInterpretation.HigherIsBetter; } return MetricInterpretation.LowerIsBetter; diff --git a/src/client/northstar/operations/BaseOperation.ts b/src/client/northstar/operations/BaseOperation.ts index f545b2c58..a14337763 100644 --- a/src/client/northstar/operations/BaseOperation.ts +++ b/src/client/northstar/operations/BaseOperation.ts @@ -29,11 +29,11 @@ export abstract class BaseOperation { // let filterModels: FilterModel[] = []; // return FilterModel.GetFilterModelsRecursive(this, new Set<GraphNode<BaseOperationViewModel, FilterLinkViewModel>>(), filterModels, true) // if (this.OverridingFilters.length > 0) { - // return "(" + this.OverridingFilters.filter(fm => fm != null).map(fm => fm.ToPythonString()).join(" || ") + ")"; + // return "(" + this.OverridingFilters.filter(fm => fm !== null).map(fm => fm.ToPythonString()).join(" || ") + ")"; // } // let rdg = MainManager.Instance.MainViewModel.FilterReverseDependencyGraph; // let sliceModel = this.TypedViewModel.IncomingSliceModel; - // if (sliceModel != null && sliceModel.Source != null && instanceOfIBaseFilterProvider(sliceModel.Source) && rdg.has(sliceModel.Source)) { + // if (sliceModel !== null && sliceModel.Source !== null && instanceOfIBaseFilterProvider(sliceModel.Source) && rdg.has(sliceModel.Source)) { // let filterModels = sliceModel.Source.FilterModels.map(f => f); // return FilterModel.GetFilterModelsRecursive(rdg.get(sliceModel.Source), new Set<GraphNode<BaseOperationViewModel, FilterLinkViewModel>>(), filterModels, false); // } @@ -99,8 +99,8 @@ export abstract class BaseOperation { if (result instanceof ErrorResult) { throw new Error((result as ErrorResult).message); } - if (this.RequestSalt == pollPromise.RequestSalt) { - if (result && (!this.Result || this.Result.progress != result.progress)) { + if (this.RequestSalt === pollPromise.RequestSalt) { + if (result && (!this.Result || this.Result.progress !== result.progress)) { /*if (operationViewModel.Result !== null && operationViewModel.Result !== undefined) { let t1 = performance.now(); console.log((t1 - start) + " milliseconds."); diff --git a/src/client/northstar/operations/HistogramOperation.ts b/src/client/northstar/operations/HistogramOperation.ts index 840520235..a3ddc1c98 100644 --- a/src/client/northstar/operations/HistogramOperation.ts +++ b/src/client/northstar/operations/HistogramOperation.ts @@ -71,7 +71,7 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons let brushes: string[] = []; this.BrushLinks.map(brushLink => { let brushHistogram = brushLink.b.GetT(KeyStore.Data, HistogramField); - if (brushHistogram && brushHistogram != FieldWaiting) { + if (brushHistogram && brushHistogram !== FieldWaiting) { let filterModels: FilterModel[] = []; brushes.push(FilterModel.GetFilterModelsRecursive(brushHistogram.Data, new Set<IBaseFilterProvider>(), filterModels, false)); } diff --git a/src/client/northstar/utils/ArrayUtil.ts b/src/client/northstar/utils/ArrayUtil.ts index f35c98317..a52ca6d96 100644 --- a/src/client/northstar/utils/ArrayUtil.ts +++ b/src/client/northstar/utils/ArrayUtil.ts @@ -7,14 +7,14 @@ export class ArrayUtil { return false; } let isComplex = typeof arr1[0] === "object"; - for (let i = 0; i < arr1.length; i++) { - if (isComplex && "Equals" in arr1[i]) { - if (arr1[i].Equals(arr2)) { + for (const ele of arr1) { + if (isComplex && "Equals" in ele) { + if (ele.Equals(arr2)) { return true; } } else { - if (arr1[i] === arr2) { + if (ele === arr2) { return true; } } @@ -63,9 +63,9 @@ export class ArrayUtil { public static Distinct(arr: any[]): any[] { let ret = []; - for (let i = 0; i < arr.length; i++) { - if (!ArrayUtil.Contains(ret, arr[i])) { - ret.push(arr[i]); + for (const ele of arr) { + if (!ArrayUtil.Contains(ret, ele)) { + ret.push(ele); } } return ret; diff --git a/src/client/northstar/utils/GeometryUtil.ts b/src/client/northstar/utils/GeometryUtil.ts index d5f3ba631..6d8acea20 100644 --- a/src/client/northstar/utils/GeometryUtil.ts +++ b/src/client/northstar/utils/GeometryUtil.ts @@ -85,7 +85,7 @@ export class GeometryUtil { // var xi = vs[i].x, yi = vs[i].y; // var xj = vs[j].x, yj = vs[j].y; - // var intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); + // var intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); // if (intersect) // inside = !inside; // } diff --git a/src/client/northstar/utils/MathUtil.ts b/src/client/northstar/utils/MathUtil.ts index bb7e73871..7aa255096 100644 --- a/src/client/northstar/utils/MathUtil.ts +++ b/src/client/northstar/utils/MathUtil.ts @@ -93,7 +93,7 @@ export class MathUtil { public static DistToLineSegment(v: PIXIPoint, w: PIXIPoint, p: PIXIPoint) { // Return minimum distance between line segment vw and point p var l2 = MathUtil.DistSquared(v, w); // i.e. |w-v|^2 - avoid a sqrt - if (l2 == 0.0) return MathUtil.Dist(p, v); // v == w case + if (l2 === 0.0) return MathUtil.Dist(p, v); // v === w case // Consider the line extending the segment, parameterized as v + t (w - v). // We find projection of point p onto the line. // It falls where t = [(p-v) . (w-v)] / |w-v|^2 @@ -117,7 +117,7 @@ export class MathUtil { var b2 = ps2.x - pe2.x; var delta = a1 * b2 - a2 * b1; - if (delta == 0) { + if (delta === 0) { return undefined; } var c2 = a2 * ps2.x + b2 * ps2.y; @@ -147,19 +147,19 @@ export class MathUtil { var ret = new Array<PIXIPoint>(); var dist = this.Dist(lineFrom, lineTo) var inter = this.LineSegmentIntersection(lineFrom, lineTo, r1, r2); - if (inter != null && this.PointInPIXIRectangle(inter, rect) && + if (inter && this.PointInPIXIRectangle(inter, rect) && this.Dist(inter, lineFrom) < dist && this.Dist(inter, lineTo) < dist) ret.push(inter); inter = this.LineSegmentIntersection(lineFrom, lineTo, r2, r3); - if (inter != null && this.PointInPIXIRectangle(inter, rect) && + if (inter && this.PointInPIXIRectangle(inter, rect) && this.Dist(inter, lineFrom) < dist && this.Dist(inter, lineTo) < dist) ret.push(inter); inter = this.LineSegmentIntersection(lineFrom, lineTo, r3, r4); - if (inter != null && this.PointInPIXIRectangle(inter, rect) && + if (inter && this.PointInPIXIRectangle(inter, rect) && this.Dist(inter, lineFrom) < dist && this.Dist(inter, lineTo) < dist) ret.push(inter); inter = this.LineSegmentIntersection(lineFrom, lineTo, r4, r1); - if (inter != null && this.PointInPIXIRectangle(inter, rect) && + if (inter && this.PointInPIXIRectangle(inter, rect) && this.Dist(inter, lineFrom) < dist && this.Dist(inter, lineTo) < dist) ret.push(inter); return ret; diff --git a/src/client/northstar/utils/SizeConverter.ts b/src/client/northstar/utils/SizeConverter.ts index bb91ed4a7..b5c4a16ab 100644 --- a/src/client/northstar/utils/SizeConverter.ts +++ b/src/client/northstar/utils/SizeConverter.ts @@ -54,7 +54,7 @@ export class SizeConverter { } public DataToScreenNormalizedRange(dataValue: number, normalization: number, axis: number, binBrushMaxAxis: number) { - var value = normalization != 1 - axis || binBrushMaxAxis == 0 ? dataValue : (dataValue - 0) / (binBrushMaxAxis - 0) * this.DataRanges[axis]; + var value = normalization !== 1 - axis || binBrushMaxAxis === 0 ? dataValue : (dataValue - 0) / (binBrushMaxAxis - 0) * this.DataRanges[axis]; var from = this.DataToScreenCoord(Math.min(0, value), axis); var to = this.DataToScreenCoord(Math.max(0, value), axis); return [from, value, to]; @@ -85,7 +85,7 @@ export class SizeConverter { return flip ? (this.RenderDimension) - retY : retY; } public DataToScreenCoord(v: number, axis: number) { - if (axis == 0) + if (axis === 0) return this.DataToScreenX(v); return this.DataToScreenY(v); } diff --git a/src/client/northstar/utils/Utils.ts b/src/client/northstar/utils/Utils.ts index b35dce820..c96b4cbd9 100644 --- a/src/client/northstar/utils/Utils.ts +++ b/src/client/northstar/utils/Utils.ts @@ -27,17 +27,17 @@ export class Utils { public static isBaseBrushable<T>(obj: Object): obj is IBaseBrushable<T> { let typed = <IBaseBrushable<T>>obj; - return typed != null && typed.BrusherModels !== undefined; + return typed !== null && typed.BrusherModels !== undefined; } public static isBaseFilterProvider(obj: Object): obj is IBaseFilterProvider { let typed = <IBaseFilterProvider>obj; - return typed != null && typed.FilterModels !== undefined; + return typed !== null && typed.FilterModels !== undefined; } public static isBaseFilterConsumer(obj: Object): obj is IBaseFilterConsumer { let typed = <IBaseFilterConsumer>obj; - return typed != null && typed.FilterOperand !== undefined; + return typed !== null && typed.FilterOperand !== undefined; } public static EncodeQueryData(data: any): string { @@ -63,9 +63,9 @@ export class Utils { public static GetQueryVariable(variable: string) { let query = window.location.search.substring(1); let vars = query.split("&"); - for (let i = 0; i < vars.length; i++) { - let pair = vars[i].split("="); - if (decodeURIComponent(pair[0]) == variable) { + for (const variable of vars) { + let pair = variable.split("="); + if (decodeURIComponent(pair[0]) === variable) { return decodeURIComponent(pair[1]); } } diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts index 341959936..fb489edb6 100644 --- a/src/client/util/DocumentManager.ts +++ b/src/client/util/DocumentManager.ts @@ -29,7 +29,7 @@ export class DocumentManager { public getAllDocumentViews(collection: Document) { return this.DocumentViews.filter(dv => - dv.props.ContainingCollectionView && dv.props.ContainingCollectionView.props.Document.Id === collection.Id); + dv.props.ContainingCollectionView && dv.props.ContainingCollectionView.props.Document === collection); } public getDocumentView(toFind: Document): DocumentView | null { @@ -42,12 +42,12 @@ export class DocumentManager { let doc = view.props.Document; // if (view.props.ContainingCollectionView instanceof CollectionFreeFormView) { - if (Object.is(doc, toFind)) { + if (doc === toFind) { toReturn = view; return; } let docSrc = doc.GetT(KeyStore.Prototype, Document); - if (docSrc && docSrc != FieldWaiting && Object.is(docSrc, toFind)) { + if (docSrc && docSrc !== FieldWaiting && Object.is(docSrc, toFind)) { toReturn = view; } }) @@ -63,11 +63,11 @@ export class DocumentManager { let doc = view.props.Document; // if (view.props.ContainingCollectionView instanceof CollectionFreeFormView) { - if (Object.is(doc, toFind)) { + if (doc === toFind) { toReturn.push(view); } else { let docSrc = doc.GetT(KeyStore.Prototype, Document); - if (docSrc && docSrc != FieldWaiting && Object.is(docSrc, toFind)) { + if (docSrc && docSrc !== FieldWaiting && Object.is(docSrc, toFind)) { toReturn.push(view); } } @@ -80,11 +80,11 @@ export class DocumentManager { public get LinkedDocumentViews() { return DocumentManager.Instance.DocumentViews.reduce((pairs, dv) => { let linksList = dv.props.Document.GetT(KeyStore.LinkedToDocs, ListField); - if (linksList && linksList != FieldWaiting && linksList.Data.length) { + if (linksList && linksList !== FieldWaiting && linksList.Data.length) { pairs.push(...linksList.Data.reduce((pairs, link) => { if (link instanceof Document) { let linkToDoc = link.GetT(KeyStore.LinkedToDocs, Document); - if (linkToDoc && linkToDoc != FieldWaiting) { + if (linkToDoc && linkToDoc !== FieldWaiting) { DocumentManager.Instance.getDocumentViews(linkToDoc).map(docView1 => { pairs.push({ a: dv, b: docView1, l: link }) }) diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index 0ee7ed2b3..f95b2c29d 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -4,36 +4,27 @@ import { CollectionDockingView } from "../views/collections/CollectionDockingVie import { CollectionView } from "../views/collections/CollectionView"; import { DocumentDecorations } from "../views/DocumentDecorations"; import { DocumentView } from "../views/nodes/DocumentView"; +import { returnFalse } from "../../Utils"; -export function setupDrag( - _reference: React.RefObject<HTMLDivElement>, - docFunc: () => Document, - removeFunc: (containingCollection: CollectionView) => void = () => { }, - copyOnDrop: boolean = false -) { - let onRowMove = action( - (e: PointerEvent): void => { - e.stopPropagation(); - e.preventDefault(); +export function setupDrag(_reference: React.RefObject<HTMLDivElement>, docFunc: () => Document, moveFunc?: DragManager.MoveFunction, copyOnDrop: boolean = false) { + let onRowMove = action((e: PointerEvent): void => { + e.stopPropagation(); + e.preventDefault(); - // TODO: bcz -- this needs to have a drag threshold so that it doesn't trigger when just selecting. - document.removeEventListener("pointermove", onRowMove); - document.removeEventListener("pointerup", onRowUp); - var dragData = new DragManager.DocumentDragData([docFunc()]); - dragData.copyOnDrop = copyOnDrop; - dragData.removeDocument = removeFunc; - DragManager.StartDocumentDrag([_reference.current!], dragData, e.x, e.y); - } - ); - let onRowUp = action( - (e: PointerEvent): void => { - document.removeEventListener("pointermove", onRowMove); - document.removeEventListener("pointerup", onRowUp); - } - ); + document.removeEventListener("pointermove", onRowMove); + document.removeEventListener('pointerup', onRowUp); + var dragData = new DragManager.DocumentDragData([docFunc()]); + dragData.copyOnDrop = copyOnDrop; + dragData.moveDocument = moveFunc; + DragManager.StartDocumentDrag([_reference.current!], dragData, e.x, e.y); + }); + let onRowUp = action((e: PointerEvent): void => { + document.removeEventListener("pointermove", onRowMove); + document.removeEventListener('pointerup', onRowUp); + }); let onItemDown = (e: React.PointerEvent) => { // if (this.props.isSelected() || this.props.isTopMost) { - if (e.button == 0) { + if (e.button === 0) { e.stopPropagation(); if (e.shiftKey) { CollectionDockingView.Instance.StartOtherDrag([docFunc()], e); @@ -104,7 +95,7 @@ export namespace DragManager { "Element is already droppable, can't make it droppable again" ); } - element.dataset["canDrop"] = "true"; + element.dataset.canDrop = "true"; const handler = (e: Event) => { const ce = e as CustomEvent<DropEvent>; options.handlers.drop(e, ce.detail); @@ -112,10 +103,11 @@ export namespace DragManager { element.addEventListener("dashOnDrop", handler); return () => { element.removeEventListener("dashOnDrop", handler); - delete element.dataset["canDrop"]; + delete element.dataset.canDrop }; } + export type MoveFunction = (document: Document, targetCollection: Document, addDocument: (document: Document) => boolean) => boolean; export class DocumentDragData { constructor(dragDoc: Document[]) { this.draggedDocuments = dragDoc; @@ -127,24 +119,13 @@ export namespace DragManager { yOffset?: number; aliasOnDrop?: boolean; copyOnDrop?: boolean; - removeDocument?: (collectionDrop: CollectionView) => void; + moveDocument?: MoveFunction; [id: string]: any; } - export function StartDocumentDrag( - eles: HTMLElement[], - dragData: DocumentDragData, - downX: number, - downY: number, - options?: DragOptions - ) { + export function StartDocumentDrag(eles: HTMLElement[], dragData: DocumentDragData, downX: number, downY: number, options?: DragOptions) { StartDrag(eles, dragData, downX, downY, options, - (dropData: { [id: string]: any }) => - (dropData.droppedDocuments = dragData.aliasOnDrop - ? dragData.draggedDocuments.map(d => d.CreateAlias()) - : dragData.copyOnDrop ? dragData.draggedDocuments.map(d => d.Copy(true) as Document) : - dragData.draggedDocuments) - ); + (dropData: { [id: string]: any }) => (dropData.droppedDocuments = dragData.aliasOnDrop ? dragData.draggedDocuments.map(d => d.CreateAlias()) : dragData.copyOnDrop ? dragData.draggedDocuments.map(d => d.Copy(true) as Document) : dragData.draggedDocuments)); } export class LinkDragData { @@ -155,21 +136,12 @@ export namespace DragManager { linkSourceDocumentView: DocumentView; [id: string]: any; } - export function StartLinkDrag( - ele: HTMLElement, - dragData: LinkDragData, - downX: number, downY: number, - options?: DragOptions - ) { + + export function StartLinkDrag(ele: HTMLElement, dragData: LinkDragData, downX: number, downY: number, options?: DragOptions) { StartDrag([ele], dragData, downX, downY, options); } - function StartDrag( - eles: HTMLElement[], - dragData: { [id: string]: any }, - downX: number, downY: number, - options?: DragOptions, - finishDrag?: (dropData: { [id: string]: any }) => void - ) { + + function StartDrag(eles: HTMLElement[], dragData: { [id: string]: any }, downX: number, downY: number, options?: DragOptions, finishDrag?: (dropData: { [id: string]: any }) => void) { if (!dragDiv) { dragDiv = document.createElement("div"); dragDiv.className = "dragManager-dragDiv"; @@ -217,11 +189,11 @@ export namespace DragManager { // let thumbnail = docs[0].GetT(KeyStore.Thumbnail, ImageField); // if (pdfBox && pdfBox.childElementCount && thumbnail) { // let img = new Image(); - // img!.src = thumbnail.toString(); - // img!.style.position = "absolute"; - // img!.style.width = `${rect.width / scaleX}px`; - // img!.style.height = `${rect.height / scaleY}px`; - // pdfBox.replaceChild(img!, pdfBox.children[0]); + // img.src = thumbnail.toString(); + // img.style.position = "absolute"; + // img.style.width = `${rect.width / scaleX}px`; + // img.style.height = `${rect.height / scaleY}px`; + // pdfBox.replaceChild(img, pdfBox.children[0]) // } // } @@ -255,6 +227,7 @@ export namespace DragManager { button: 0 }); } + //TODO: Why can't we use e.movementX and e.movementY? let moveX = e.pageX - lastX; let moveY = e.pageY - lastY; lastX = e.pageX; @@ -279,13 +252,7 @@ export namespace DragManager { document.addEventListener("pointerup", upHandler); } - function FinishDrag( - dragEles: HTMLElement[], - e: PointerEvent, - dragData: { [index: string]: any }, - options?: DragOptions, - finishDrag?: (dragData: { [index: string]: any }) => void - ) { + function FinishDrag(dragEles: HTMLElement[], e: PointerEvent, dragData: { [index: string]: any }, options?: DragOptions, finishDrag?: (dragData: { [index: string]: any }) => void) { let removed = dragEles.map(dragEle => { let parent = dragEle.parentElement; if (parent) parent.removeChild(dragEle); @@ -293,9 +260,9 @@ export namespace DragManager { }); const target = document.elementFromPoint(e.x, e.y); removed.map(r => { - let dragEle: HTMLElement = r[0]!; - let parent: HTMLElement | null = r[1]; - if (parent) parent.appendChild(dragEle); + let dragEle = r[0]; + let parent = r[1]; + if (parent && dragEle) parent.appendChild(dragEle); }); if (target) { if (finishDrag) finishDrag(dragData); diff --git a/src/client/util/Scripting.ts b/src/client/util/Scripting.ts index 7c0649a6a..bf9b8266f 100644 --- a/src/client/util/Scripting.ts +++ b/src/client/util/Scripting.ts @@ -43,7 +43,7 @@ export interface CompileError { export type CompiledScript = CompileSuccess | CompileError; function Run(script: string | undefined, customParams: string[], diagnostics: any[]): CompiledScript { - const errors = diagnostics.some(diag => diag.category == ts.DiagnosticCategory.Error); + const errors = diagnostics.some(diag => diag.category === ts.DiagnosticCategory.Error); if (errors || !script) { return { compiled: false, errors: diagnostics }; } @@ -60,7 +60,7 @@ function Run(script: string | undefined, customParams: string[], diagnostics: an } argsArray.push(args[name]); } - let thisParam = args["this"]; + let thisParam = args.this; try { const result = compiledFunction.apply(thisParam, params).apply(thisParam, argsArray); return { success: true, result }; @@ -160,9 +160,9 @@ export function OrLiteralType(returnType: string): string { } export function ToField(data: any): Opt<Field> { - if (typeof data == "string") { + if (typeof data === "string") { return new TextField(data); - } else if (typeof data == "number") { + } else if (typeof data === "number") { return new NumberField(data); } return undefined; diff --git a/src/client/util/SelectionManager.ts b/src/client/util/SelectionManager.ts index 79d4ceb25..1bb15c86a 100644 --- a/src/client/util/SelectionManager.ts +++ b/src/client/util/SelectionManager.ts @@ -12,13 +12,20 @@ export namespace SelectionManager { SelectDoc(doc: DocumentView, ctrlPressed: boolean): void { // if doc is not in SelectedDocuments, add it if (!ctrlPressed) { - manager.SelectedDocuments = []; + this.DeselectAll(); } if (manager.SelectedDocuments.indexOf(doc) === -1) { manager.SelectedDocuments.push(doc); + doc.props.onActiveChanged(true); } } + + @action + DeselectAll(): void { + manager.SelectedDocuments.map(dv => dv.props.onActiveChanged(false)) + manager.SelectedDocuments = []; + } } const manager = new Manager(); @@ -34,13 +41,13 @@ export namespace SelectionManager { export function DeselectAll(except?: Document): void { let found: DocumentView | undefined = undefined; if (except) { - for (let i = 0; i < manager.SelectedDocuments.length; i++) { - let view = manager.SelectedDocuments[i]; - if (view.props.Document == except) found = view; + for (const view of manager.SelectedDocuments) { + if (view.props.Document === except) found = view; } } - manager.SelectedDocuments.length = 0; - if (found) manager.SelectedDocuments.push(found); + + manager.DeselectAll() + if (found) manager.SelectDoc(found, false); Main.Instance.SetTextDoc(undefined, undefined); } diff --git a/src/client/util/Transform.ts b/src/client/util/Transform.ts index 060c5da82..ed4282874 100644 --- a/src/client/util/Transform.ts +++ b/src/client/util/Transform.ts @@ -3,7 +3,7 @@ export class Transform { private _translateY: number = 0; private _scale: number = 1; - static get Identity(): Transform { + static Identity(): Transform { return new Transform(0, 0, 1); } @@ -62,33 +62,19 @@ export class Transform { return this; } - translated = (x: number, y: number): Transform => { - return this.copy().translate(x, y); - } + translated = (x: number, y: number): Transform => this.copy().translate(x, y) - preTranslated = (x: number, y: number): Transform => { - return this.copy().preTranslate(x, y); - } + preTranslated = (x: number, y: number): Transform => this.copy().preTranslate(x, y) - scaled = (scale: number): Transform => { - return this.copy().scale(scale); - } + scaled = (scale: number): Transform => this.copy().scale(scale) - scaledAbout = (scale: number, x: number, y: number): Transform => { - return this.copy().scaleAbout(scale, x, y); - } + scaledAbout = (scale: number, x: number, y: number): Transform => this.copy().scaleAbout(scale, x, y) - preScaled = (scale: number): Transform => { - return this.copy().preScale(scale); - } + preScaled = (scale: number): Transform => this.copy().preScale(scale) - transformed = (transform: Transform): Transform => { - return this.copy().transform(transform); - } + transformed = (transform: Transform): Transform => this.copy().transform(transform) - preTransformed = (transform: Transform): Transform => { - return this.copy().preTransform(transform); - } + preTransformed = (transform: Transform): Transform => this.copy().preTransform(transform) transformPoint = (x: number, y: number): [number, number] => { x *= this._scale; @@ -98,9 +84,7 @@ export class Transform { return [x, y]; } - transformDirection = (x: number, y: number): [number, number] => { - return [x * this._scale, y * this._scale]; - } + transformDirection = (x: number, y: number): [number, number] => [x * this._scale, y * this._scale] transformBounds(x: number, y: number, width: number, height: number): { x: number, y: number, width: number, height: number } { [x, y] = this.transformPoint(x, y); @@ -108,12 +92,8 @@ export class Transform { return { x, y, width, height }; } - inverse = () => { - return new Transform(-this._translateX / this._scale, -this._translateY / this._scale, 1 / this._scale) - } + inverse = () => new Transform(-this._translateX / this._scale, -this._translateY / this._scale, 1 / this._scale) - copy = () => { - return new Transform(this._translateX, this._translateY, this._scale); - } + copy = () => new Transform(this._translateX, this._translateY, this._scale) }
\ No newline at end of file diff --git a/src/client/util/TypedEvent.ts b/src/client/util/TypedEvent.ts index 0714a7f5c..1b251da25 100644 --- a/src/client/util/TypedEvent.ts +++ b/src/client/util/TypedEvent.ts @@ -36,7 +36,5 @@ export class TypedEvent<T> { this.listenersOncer = []; } - pipe = (te: TypedEvent<T>): Disposable => { - return this.on((e) => te.emit(e)); - } + pipe = (te: TypedEvent<T>): Disposable => this.on((e) => te.emit(e)) }
\ No newline at end of file diff --git a/src/client/util/UndoManager.ts b/src/client/util/UndoManager.ts index eb13ff1ee..bdc77f1ba 100644 --- a/src/client/util/UndoManager.ts +++ b/src/client/util/UndoManager.ts @@ -163,8 +163,8 @@ export namespace UndoManager { } undoing = true; - for (let i = 0; i < commands.length; i++) { - commands[i].redo(); + for (const command of commands) { + command.redo(); } undoing = false; diff --git a/src/client/util/type_decls.d b/src/client/util/type_decls.d index 4f69053b1..47c3481b2 100644 --- a/src/client/util/type_decls.d +++ b/src/client/util/type_decls.d @@ -181,7 +181,7 @@ declare class Key extends Field { Copy(): Field; ToScriptString(): string; } -declare type FIELD_WAITING = "<Waiting>"; +declare type FIELD_WAITING = null; declare type Opt<T> = T | undefined; declare type FieldValue<T> = Opt<T> | FIELD_WAITING; // @ts-ignore diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index c7e4a269a..deed0fa7c 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -55,15 +55,15 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> enterPressed = (e: any) => { var key = e.keyCode || e.which; // enter pressed - if (key == 13) { + if (key === 13) { var text = e.target.value; - if (text[0] == '#') { + if (text[0] === '#') { let command = text.slice(1, text.length); this._fieldKey = new Key(command) - // if (command == "Title" || command == "title") { + // if (command === "Title" || command === "title") { // this._fieldKey = KeyStore.Title; // } - // else if (command == "Width" || command == "width") { + // else if (command === "Width" || command === "width") { // this._fieldKey = KeyStore.Width; // } this._title = "changed" @@ -117,23 +117,17 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> dragData.aliasOnDrop = false; dragData.xOffset = e.x - left; dragData.yOffset = e.y - top; - dragData.removeDocument = (dropCollectionView: CollectionView) => - dragData.draggedDocuments.map(d => { - if (dragDocView.props.RemoveDocument && dragDocView.props.ContainingCollectionView !== dropCollectionView) { - dragDocView.props.RemoveDocument(d); - } - }); + let move = SelectionManager.SelectedDocuments()[0].props.moveDocument; + dragData.moveDocument = move; this._dragging = true; document.removeEventListener("pointermove", this.onBackgroundMove); document.removeEventListener("pointerup", this.onBackgroundUp); - DragManager.StartDocumentDrag(SelectionManager.SelectedDocuments().map(docView => (docView as any)._mainCont!.current!), dragData, - e.x, e.y, - { - handlers: { - dragComplete: action(() => this._dragging = false), - }, - hideSource: true - }) + DragManager.StartDocumentDrag(SelectionManager.SelectedDocuments().map(docView => docView.ContentRef.current!), dragData, e.x, e.y, { + handlers: { + dragComplete: action(() => this._dragging = false), + }, + hideSource: true + }) e.stopPropagation(); } @@ -162,7 +156,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> onCloseUp = (e: PointerEvent): void => { e.stopPropagation(); if (e.button === 0) { - SelectionManager.SelectedDocuments().map(dv => dv.props.RemoveDocument && dv.props.RemoveDocument(dv.props.Document)); + SelectionManager.SelectedDocuments().map(dv => dv.props.removeDocument && dv.props.removeDocument(dv.props.Document)); SelectionManager.DeselectAll(); document.removeEventListener("pointermove", this.onCloseMove); document.removeEventListener("pointerup", this.onCloseUp); @@ -217,7 +211,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> } onLinkerButtonMoved = (e: PointerEvent): void => { - if (this._linkerButton.current != null) { + if (this._linkerButton.current !== null) { document.removeEventListener("pointermove", this.onLinkerButtonMoved) document.removeEventListener("pointerup", this.onLinkerButtonUp) let dragData = new DragManager.LinkDragData(SelectionManager.SelectedDocuments()[0]); @@ -246,25 +240,24 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> } onLinkButtonMoved = async (e: PointerEvent) => { - if (this._linkButton.current != null) { + if (this._linkButton.current !== null) { document.removeEventListener("pointermove", this.onLinkButtonMoved) document.removeEventListener("pointerup", this.onLinkButtonUp); let sourceDoc = SelectionManager.SelectedDocuments()[0].props.Document; let srcTarg = sourceDoc.GetT(KeyStore.Prototype, Document) - let draggedDocs = (srcTarg && srcTarg != FieldWaiting) ? + let draggedDocs = (srcTarg && srcTarg !== FieldWaiting) ? srcTarg.GetList(KeyStore.LinkedToDocs, [] as Document[]).map(linkDoc => (linkDoc.GetT(KeyStore.LinkedToDocs, Document)) as Document) : []; - let draggedFromDocs = (srcTarg && srcTarg != FieldWaiting) ? + let draggedFromDocs = (srcTarg && srcTarg !== FieldWaiting) ? srcTarg.GetList(KeyStore.LinkedFromDocs, [] as Document[]).map(linkDoc => (linkDoc.GetT(KeyStore.LinkedFromDocs, Document)) as Document) : []; draggedDocs.push(...draggedFromDocs); if (draggedDocs.length) { let moddrag = [] as Document[]; - for (let i = 0; i < draggedDocs.length; i++) { - let doc = await draggedDocs[i].GetTAsync(KeyStore.AnnotationOn, Document); - if (doc) - moddrag.push(doc); + for (const draggedDoc of draggedDocs) { + let doc = await draggedDoc.GetTAsync(KeyStore.AnnotationOn, Document); + if (doc) moddrag.push(doc); } let dragData = new DragManager.DocumentDragData(moddrag); DragManager.StartDocumentDrag([this._linkButton.current], dragData, e.x, e.y, { diff --git a/src/client/views/EditableView.tsx b/src/client/views/EditableView.tsx index 29bf6add7..982aacdea 100644 --- a/src/client/views/EditableView.tsx +++ b/src/client/views/EditableView.tsx @@ -38,7 +38,7 @@ export class EditableView extends React.Component<EditableProps> { @action onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => { - if (e.key == "Enter") { + if (e.key === "Enter") { if (!e.ctrlKey) { if (this.props.SetValue(e.currentTarget.value)) { this.editing = false; @@ -47,7 +47,7 @@ export class EditableView extends React.Component<EditableProps> { this.props.OnFillDown(e.currentTarget.value); this.editing = false; } - } else if (e.key == "Escape") { + } else if (e.key === "Escape") { this.editing = false; } } diff --git a/src/client/views/InkingCanvas.tsx b/src/client/views/InkingCanvas.tsx index 45ca52d00..4b3ea48c5 100644 --- a/src/client/views/InkingCanvas.tsx +++ b/src/client/views/InkingCanvas.tsx @@ -56,7 +56,7 @@ export class InkingCanvas extends React.Component<InkCanvasProps> { @action onPointerDown = (e: React.PointerEvent): void => { - if (e.button != 0 || e.altKey || e.ctrlKey || InkingControl.Instance.selectedTool === InkTool.None) { + if (e.button !== 0 || e.altKey || e.ctrlKey || InkingControl.Instance.selectedTool === InkTool.None) { return; } document.addEventListener("pointermove", this.onPointerMove, true); @@ -64,7 +64,7 @@ export class InkingCanvas extends React.Component<InkCanvasProps> { e.stopPropagation(); e.preventDefault(); - if (InkingControl.Instance.selectedTool != InkTool.Eraser) { + if (InkingControl.Instance.selectedTool !== InkTool.Eraser) { // start the new line, saves a uuid to represent the field of the stroke this._currentStrokeId = Utils.GenerateGuid(); this.inkData.set(this._currentStrokeId, { @@ -94,7 +94,7 @@ export class InkingCanvas extends React.Component<InkCanvasProps> { onPointerMove = (e: PointerEvent): void => { e.stopPropagation() e.preventDefault(); - if (InkingControl.Instance.selectedTool != InkTool.Eraser) { + if (InkingControl.Instance.selectedTool !== InkTool.Eraser) { let data = this.inkData; // add points to new line as it is being drawn let strokeData = data.get(this._currentStrokeId); if (strokeData) { @@ -121,7 +121,7 @@ export class InkingCanvas extends React.Component<InkCanvasProps> { get drawnPaths() { let curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1) let paths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { - if (strokeData.page == -1 || strokeData.page == curPage) + if (strokeData.page === -1 || strokeData.page === curPage) paths.push(<InkingStroke key={id} id={id} line={strokeData.pathData} offsetX={this.maxCanvasDim - this.inkMidX} offsetY={this.maxCanvasDim - this.inkMidY} @@ -131,16 +131,16 @@ export class InkingCanvas extends React.Component<InkCanvasProps> { }, [] as JSX.Element[]); return [<svg className={`inkingCanvas-paths-markers`} key="Markers" style={{ left: `${this.inkMidX - this.maxCanvasDim}px`, top: `${this.inkMidY - this.maxCanvasDim}px` }} > - {paths.filter(path => path.props.tool == InkTool.Highlighter)} + {paths.filter(path => path.props.tool === InkTool.Highlighter)} </svg>, <svg className={`inkingCanvas-paths-ink`} key="Pens" style={{ left: `${this.inkMidX - this.maxCanvasDim}px`, top: `${this.inkMidY - this.maxCanvasDim}px` }}> - {paths.filter(path => path.props.tool != InkTool.Highlighter)} + {paths.filter(path => path.props.tool !== InkTool.Highlighter)} </svg>]; } render() { - let svgCanvasStyle = InkingControl.Instance.selectedTool != InkTool.None ? "canSelect" : "noSelect"; + let svgCanvasStyle = InkingControl.Instance.selectedTool !== InkTool.None ? "canSelect" : "noSelect"; return ( <div className="inkingCanvas" > <div className={`inkingCanvas-${svgCanvasStyle}`} onPointerDown={this.onPointerDown} /> diff --git a/src/client/views/InkingControl.tsx b/src/client/views/InkingControl.tsx index c1519dff8..13f0a0acc 100644 --- a/src/client/views/InkingControl.tsx +++ b/src/client/views/InkingControl.tsx @@ -36,9 +36,9 @@ export class InkingControl extends React.Component { @action switchColor = (color: ColorResult): void => { this._selectedColor = color.hex; - if (SelectionManager.SelectedDocuments().length == 1) { + if (SelectionManager.SelectedDocuments().length === 1) { var sdoc = SelectionManager.SelectedDocuments()[0]; - if (sdoc.props.ContainingCollectionView && sdoc.props.ContainingCollectionView) { + if (sdoc.props.ContainingCollectionView) { sdoc.props.Document.SetDataOnPrototype(KeyStore.BackgroundColor, color.hex, TextField); } } diff --git a/src/client/views/InkingStroke.tsx b/src/client/views/InkingStroke.tsx index 615f8af7e..12b15a3f0 100644 --- a/src/client/views/InkingStroke.tsx +++ b/src/client/views/InkingStroke.tsx @@ -30,7 +30,7 @@ export class InkingStroke extends React.Component<StrokeProps> { } parseData = (line: Array<{ x: number, y: number }>): string => { - return !line.length ? "" : "M " + line.map(p => (p.x + this.props.offsetX) + " " + (p.y + this.props.offsetY)).join(" L "); + return !line.length ? "" : "M " + line.map(p => (p.x + this.props.offsetX) + " " + (p.y + this.props.offsetY)).join(" L ") } createStyle() { @@ -49,7 +49,7 @@ export class InkingStroke extends React.Component<StrokeProps> { let pathStyle = this.createStyle(); let pathData = this.parseData(this.props.line); - let pointerEvents: any = InkingControl.Instance.selectedTool == InkTool.Eraser ? "all" : "none"; + let pointerEvents: any = InkingControl.Instance.selectedTool === InkTool.Eraser ? "all" : "none"; return ( <path d={pathData} style={{ ...pathStyle, pointerEvents: pointerEvents }} strokeLinejoin="round" strokeLinecap="round" onPointerOver={this.deleteStroke} onPointerDown={this.deleteStroke} /> diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index c9467e130..9868f6c74 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -15,9 +15,10 @@ import { ListField } from '../../fields/ListField'; import { WorkspacesMenu } from '../../server/authentication/controllers/WorkspacesMenu'; import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils'; import { MessageStore } from '../../server/Message'; +import { Utils, returnTrue, emptyFunction } from '../../Utils'; +import * as rp from 'request-promise' import { RouteStore } from '../../server/RouteStore'; import { ServerUtils } from '../../server/ServerUtil'; -import { Utils } from '../../Utils'; import { Documents } from '../documents/Documents'; import { ColumnAttributeModel } from '../northstar/core/attribute/AttributeModel'; import { AttributeTransformationModel } from '../northstar/core/attribute/AttributeTransformationModel'; @@ -48,7 +49,7 @@ export class Main extends React.Component { @computed private get mainContainer(): Document | undefined { let doc = this.userDocument.GetT(KeyStore.ActiveWorkspace, Document); - return doc == FieldWaiting ? undefined : doc; + return doc === FieldWaiting ? undefined : doc; } private set mainContainer(doc: Document | undefined) { @@ -70,7 +71,7 @@ export class Main extends React.Component { configure({ enforceActions: "observed" }); if (window.location.pathname !== RouteStore.home) { let pathname = window.location.pathname.split("/"); - if (pathname.length > 1 && pathname[pathname.length - 2] == 'doc') { + if (pathname.length > 1 && pathname[pathname.length - 2] === 'doc') { CurrentUserUtils.MainDocId = pathname[pathname.length - 1]; } }; @@ -190,15 +191,12 @@ export class Main extends React.Component { @observable workspacesShown: boolean = false; - areWorkspacesShown = () => { - return this.workspacesShown; - } + areWorkspacesShown = () => this.workspacesShown @action toggleWorkspaces = () => { this.workspacesShown = !this.workspacesShown; } - screenToLocalTransform = () => Transform.Identity pwidthFunc = () => this.pwidth; pheightFunc = () => this.pheight; focusDocument = (doc: Document) => { } @@ -222,7 +220,7 @@ export class Main extends React.Component { let w: number = this._textRect.width; let h: number = this._textRect.height; return <div className="mainDiv-textInput" style={{ transform: `translate(${x}px, ${y}px)`, width: `${w}px`, height: `${h}px` }} > - <FormattedTextBox fieldKey={KeyStore.Archives} doc={this._textDoc} isSelected={() => true} select={() => { }} isTopMost={true} selectOnLoad={true} bindings={undefined} /> + <FormattedTextBox fieldKey={KeyStore.Archives} Document={this._textDoc} isSelected={returnTrue} select={emptyFunction} isTopMost={true} selectOnLoad={true} onActiveChanged={emptyFunction} active={returnTrue} ScreenToLocalTransform={Transform.Identity} focus={(doc) => { }} /> </ div> } else return (null); @@ -232,15 +230,17 @@ export class Main extends React.Component { get mainContent() { return !this.mainContainer ? (null) : <DocumentView Document={this.mainContainer} - AddDocument={undefined} - RemoveDocument={undefined} - ScreenToLocalTransform={this.screenToLocalTransform} + addDocument={undefined} + removeDocument={undefined} + ScreenToLocalTransform={Transform.Identity} ContentScaling={this.noScaling} PanelWidth={this.pwidthFunc} PanelHeight={this.pheightFunc} isTopMost={true} - SelectOnLoad={false} + selectOnLoad={false} focus={this.focusDocument} + parentActive={returnTrue} + onActiveChanged={emptyFunction} ContainingCollectionView={undefined} /> } @@ -385,8 +385,8 @@ export class Main extends React.Component { } } -Documents.initProtos().then(() => { - return CurrentUserUtils.loadCurrentUser() -}).then(() => { +(async () => { + await Documents.initProtos() + await CurrentUserUtils.loadCurrentUser() ReactDOM.render(<Main />, document.getElementById('root')); -}); +})() diff --git a/src/client/views/collections/CollectionBaseView.tsx b/src/client/views/collections/CollectionBaseView.tsx new file mode 100644 index 000000000..7a5ab6e3c --- /dev/null +++ b/src/client/views/collections/CollectionBaseView.tsx @@ -0,0 +1,166 @@ +import * as React from 'react'; +import { FieldViewProps } from '../nodes/FieldView'; +import { KeyStore } from '../../../fields/KeyStore'; +import { NumberField } from '../../../fields/NumberField'; +import { FieldWaiting, Field, FieldValue } from '../../../fields/Field'; +import { ContextMenu } from '../ContextMenu'; +import { SelectionManager } from '../../util/SelectionManager'; +import { Document } from '../../../fields/Document'; +import { ListField } from '../../../fields/ListField'; +import { action } from 'mobx'; +import { Transform } from '../../util/Transform'; +import { observer } from 'mobx-react'; + +export enum CollectionViewType { + Invalid, + Freeform, + Schema, + Docking, + Tree, +} + +export interface CollectionRenderProps { + addDocument: (document: Document, allowDuplicates?: boolean) => boolean; + removeDocument: (document: Document) => boolean; + moveDocument: (document: Document, targetCollection: Document, addDocument: (document: Document) => boolean) => boolean; + active: () => boolean; + onActiveChanged: (isActive: boolean) => void; +} + +export interface CollectionViewProps extends FieldViewProps { + onContextMenu?: (e: React.MouseEvent) => void; + children: (type: CollectionViewType, props: CollectionRenderProps) => JSX.Element | JSX.Element[] | null; + className?: string; + contentRef?: React.Ref<HTMLDivElement>; +} + +export const COLLECTION_BORDER_WIDTH = 1; + +@observer +export class CollectionBaseView extends React.Component<CollectionViewProps> { + get collectionViewType(): CollectionViewType { + let Document = this.props.Document; + let viewField = Document.GetT(KeyStore.ViewType, NumberField); + if (viewField === FieldWaiting) { + return CollectionViewType.Invalid; + } else if (viewField) { + return viewField.Data; + } else { + return CollectionViewType.Freeform; + } + } + + active = (): boolean => { + var isSelected = this.props.isSelected(); + var topMost = this.props.isTopMost; + return isSelected || this._isChildActive || topMost; + } + + //TODO should this be observable? + private _isChildActive = false; + onActiveChanged = (isActive: boolean) => { + this._isChildActive = isActive; + this.props.onActiveChanged(isActive); + } + + createsCycle(documentToAdd: Document, containerDocument: Document): boolean { + let data = documentToAdd.GetList<Document>(KeyStore.Data, []); + for (const doc of data) { + if (this.createsCycle(doc, containerDocument)) + return true; + } + let annots = documentToAdd.GetList<Document>(KeyStore.Annotations, []); + for (const annot of annots) { + if (this.createsCycle(annot, containerDocument)) + return true; + } + for (let containerProto: FieldValue<Document> = containerDocument; containerProto && containerProto !== FieldWaiting; containerProto = containerProto.GetPrototype()) { + if (containerProto.Id === documentToAdd.Id) + return true; + } + return false; + } + + @action.bound + addDocument(doc: Document, allowDuplicates: boolean = false): boolean { + let props = this.props; + var curPage = props.Document.GetNumber(KeyStore.CurPage, -1); + doc.SetOnPrototype(KeyStore.Page, new NumberField(curPage)); + if (curPage >= 0) { + doc.SetOnPrototype(KeyStore.AnnotationOn, props.Document); + } + if (props.Document.Get(props.fieldKey) instanceof Field) { + //TODO This won't create the field if it doesn't already exist + const value = props.Document.GetData(props.fieldKey, ListField, new Array<Document>()) + if (!this.createsCycle(doc, props.Document)) { + if (!value.some(v => v.Id === doc.Id) || allowDuplicates) + value.push(doc); + } + else + return false; + } else { + let proto = props.Document.GetPrototype(); + if (!proto || proto === FieldWaiting || !this.createsCycle(proto, doc)) { + props.Document.SetOnPrototype(props.fieldKey, new ListField([doc])); + } + else + return false; + } + return true; + } + + @action.bound + removeDocument(doc: Document): boolean { + const props = this.props; + //TODO This won't create the field if it doesn't already exist + const value = props.Document.GetData(props.fieldKey, ListField, new Array<Document>()) + let index = -1; + for (let i = 0; i < value.length; i++) { + if (value[i].Id === doc.Id) { + index = i; + break; + } + } + doc.GetTAsync(KeyStore.AnnotationOn, Document).then((annotationOn) => { + if (annotationOn === props.Document) { + doc.Set(KeyStore.AnnotationOn, undefined, true); + } + }) + + if (index !== -1) { + value.splice(index, 1) + + // SelectionManager.DeselectAll() + ContextMenu.Instance.clearItems() + return true; + } + return false + } + + @action.bound + moveDocument(doc: Document, targetCollection: Document, addDocument: (doc: Document) => boolean): boolean { + if (this.props.Document === targetCollection) { + return true; + } + if (this.removeDocument(doc)) { + return addDocument(doc); + } + return false; + } + + render() { + const props: CollectionRenderProps = { + addDocument: this.addDocument, + removeDocument: this.removeDocument, + moveDocument: this.moveDocument, + active: this.active, + onActiveChanged: this.onActiveChanged, + } + return ( + <div className={this.props.className || "collectionView-cont"} onContextMenu={this.props.onContextMenu} ref={this.props.contentRef}> + {this.props.children(this.collectionViewType, props)} + </div> + ) + } + +}
\ No newline at end of file diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 921ee4591..6640c843e 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -8,12 +8,12 @@ import { Document } from "../../../fields/Document"; import { KeyStore } from "../../../fields/KeyStore"; import Measure from "react-measure"; import { FieldId, Opt, Field } from "../../../fields/Field"; -import { Utils } from "../../../Utils"; +import { Utils, returnTrue, emptyFunction } from "../../../Utils"; import { Server } from "../../Server"; import { undoBatch } from "../../util/UndoManager"; import { DocumentView } from "../nodes/DocumentView"; import "./CollectionDockingView.scss"; -import { COLLECTION_BORDER_WIDTH } from "./CollectionView"; +import { COLLECTION_BORDER_WIDTH } from "./CollectionBaseView"; import React = require("react"); import { SubCollectionViewProps } from "./CollectionViewBase"; import { ServerUtils } from "../../../server/ServerUtil"; @@ -101,12 +101,12 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp newRow.addChild(newContentItem, undefined, true); newRow.addChild(collayout, 0, true); - collayout.config["width"] = 50; - newContentItem.config["width"] = 50; + collayout.config.width = 50; + newContentItem.config.width = 50; } if (minimize) { - newContentItem.config["width"] = 10; - newContentItem.config["height"] = 10; + newContentItem.config.width = 10; + newContentItem.config.height = 10; } newContentItem.callDownwards('_$init'); this._goldenLayout.root.callDownwards('setSize', [this._goldenLayout.width, this._goldenLayout.height]); @@ -124,7 +124,7 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp this._goldenLayout = new GoldenLayout(JSON.parse(config)); } else { - if (config == JSON.stringify(this._goldenLayout.toConfig())) + if (config === JSON.stringify(this._goldenLayout.toConfig())) return; try { this._goldenLayout.unbind('itemDropped', this.itemDropped); @@ -154,7 +154,7 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp reaction( () => this.props.Document.GetText(KeyStore.Data, ""), () => { - if (!this._goldenLayout || this._ignoreStateChange != JSON.stringify(this._goldenLayout.toConfig())) { + if (!this._goldenLayout || this._ignoreStateChange !== JSON.stringify(this._goldenLayout.toConfig())) { setTimeout(() => this.setupGoldenLayout(), 1); } this._ignoreStateChange = ""; @@ -193,7 +193,7 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp @action onPointerDown = (e: React.PointerEvent): void => { var className = (e.target as any).className; - if ((className == "lm_title" || className == "lm_tab lm_active") && (e.ctrlKey || e.altKey)) { + if ((className === "lm_title" || className === "lm_tab lm_active") && (e.ctrlKey || e.altKey)) { e.stopPropagation(); e.preventDefault(); let docid = (e.target as any).DashDocId; @@ -209,7 +209,7 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp }) })); } - if (className == "lm_drag_handle" || className == "lm_close" || className == "lm_maximise" || className == "lm_minimise" || className == "lm_close_tab") { + if (className === "lm_drag_handle" || className === "lm_close" || className === "lm_maximise" || className === "lm_minimise" || className === "lm_close_tab") { this._flush = true; } if (this.props.active()) { @@ -227,12 +227,12 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp this.stateChanged(); } tabCreated = (tab: any) => { - if (tab.hasOwnProperty("contentItem") && tab.contentItem.config.type != "stack") { - if (tab.titleElement[0].textContent.indexOf("-waiting") != -1) { + if (tab.hasOwnProperty("contentItem") && tab.contentItem.config.type !== "stack") { + if (tab.titleElement[0].textContent.indexOf("-waiting") !== -1) { Server.GetField(tab.contentItem.config.props.documentId, action((f: Opt<Field>) => { - if (f != undefined && f instanceof Document) { + if (f !== undefined && f instanceof Document) { f.GetTAsync(KeyStore.Title, TextField, (tfield) => { - if (tfield != undefined) { + if (tfield !== undefined) { tab.titleElement[0].textContent = f.Title; } }) @@ -296,9 +296,9 @@ export class DockedFrameRenderer extends React.Component<DockedFrameProps> { Server.GetField(this.props.documentId, action((f: Opt<Field>) => this._document = f as Document)); } - private _nativeWidth = () => { return this._document!.GetNumber(KeyStore.NativeWidth, this._panelWidth); } - private _nativeHeight = () => { return this._document!.GetNumber(KeyStore.NativeHeight, this._panelHeight); } - private _contentScaling = () => { return this._panelWidth / (this._nativeWidth() ? this._nativeWidth() : this._panelWidth); } + private _nativeWidth = () => this._document!.GetNumber(KeyStore.NativeWidth, this._panelWidth) + private _nativeHeight = () => this._document!.GetNumber(KeyStore.NativeHeight, this._panelHeight) + private _contentScaling = () => this._panelWidth / (this._nativeWidth() ? this._nativeWidth() : this._panelWidth) ScreenToLocalTransform = () => { let { scale, translateX, translateY } = Utils.GetScreenTransform(this._mainCont.current!); @@ -311,14 +311,16 @@ export class DockedFrameRenderer extends React.Component<DockedFrameProps> { var content = <div className="collectionDockingView-content" ref={this._mainCont}> <DocumentView key={this._document.Id} Document={this._document} - AddDocument={undefined} - RemoveDocument={undefined} + addDocument={undefined} + removeDocument={undefined} ContentScaling={this._contentScaling} PanelWidth={this._nativeWidth} PanelHeight={this._nativeHeight} ScreenToLocalTransform={this.ScreenToLocalTransform} isTopMost={true} - SelectOnLoad={false} + selectOnLoad={false} + parentActive={returnTrue} + onActiveChanged={emptyFunction} focus={(doc: Document) => { }} ContainingCollectionView={undefined} /> </div> diff --git a/src/client/views/collections/CollectionPDFView.tsx b/src/client/views/collections/CollectionPDFView.tsx index 4d2daf149..1f2e71f6e 100644 --- a/src/client/views/collections/CollectionPDFView.tsx +++ b/src/client/views/collections/CollectionPDFView.tsx @@ -1,22 +1,20 @@ import { action, computed, observable } from "mobx"; import { observer } from "mobx-react"; -import { Document } from "../../../fields/Document"; import { KeyStore } from "../../../fields/KeyStore"; import { ContextMenu } from "../ContextMenu"; -import { CollectionView, CollectionViewType } from "./CollectionView"; import { CollectionViewProps } from "./CollectionViewBase"; import "./CollectionPDFView.scss" import React = require("react"); -import { FieldId } from "../../../fields/Field"; +import { CollectionFreeFormView } from "./collectionFreeForm/CollectionFreeFormView"; +import { FieldView } from "../nodes/FieldView"; +import { CollectionRenderProps, CollectionBaseView, CollectionViewType } from "./CollectionBaseView"; @observer export class CollectionPDFView extends React.Component<CollectionViewProps> { public static LayoutString(fieldKey: string = "DataKey") { - return `<${CollectionPDFView.name} Document={Document} - ScreenToLocalTransform={ScreenToLocalTransform} fieldKey={${fieldKey}} panelWidth={PanelWidth} panelHeight={PanelHeight} isSelected={isSelected} select={select} bindings={bindings} - isTopMost={isTopMost} SelectOnLoad={selectOnLoad} BackgroundView={BackgroundView} focus={focus}/>`; + return FieldView.LayoutString(CollectionPDFView, fieldKey); } private get curPage() { return this.props.Document.GetNumber(KeyStore.CurPage, -1); } @@ -30,30 +28,31 @@ export class CollectionPDFView extends React.Component<CollectionViewProps> { <div className="collectionPdfView-buttonTray" key="tray" style={{ transform: `scale(${scaling}, ${scaling})` }}> <button className="collectionPdfView-backward" onClick={this.onPageBack}>{"<"}</button> <button className="collectionPdfView-forward" onClick={this.onPageForward}>{">"}</button> - </div>); + </div> + ); } - // "inherited" CollectionView API starts here... - @observable - public SelectedDocs: FieldId[] = [] - public active: () => boolean = () => CollectionView.Active(this); - - addDocument = (doc: Document, allowDuplicates: boolean): boolean => { return CollectionView.AddDocument(this.props, doc, allowDuplicates); } - removeDocument = (doc: Document): boolean => { return CollectionView.RemoveDocument(this.props, doc); } - - specificContextMenu = (e: React.MouseEvent): void => { - if (!e.isPropagationStopped() && this.props.Document.Id != "mainDoc") { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7 + onContextMenu = (e: React.MouseEvent): void => { + if (!e.isPropagationStopped() && this.props.Document.Id !== "mainDoc") { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7 ContextMenu.Instance.addItem({ description: "PDFOptions", event: () => { } }); } } - get collectionViewType(): CollectionViewType { return CollectionViewType.Freeform; } - get subView(): any { return CollectionView.SubView(this); } + private subView = (_type: CollectionViewType, renderProps: CollectionRenderProps) => { + let props = { ...renderProps, ...this.props }; + return ( + <> + <CollectionFreeFormView {...props} /> + {this.props.isSelected() ? this.uIButtons : (null)} + </> + ) + } render() { - return (<div className="collectionPdfView-cont" onContextMenu={this.specificContextMenu}> - {this.subView} - {this.props.isSelected() ? this.uIButtons : (null)} - </div>) + return ( + <CollectionBaseView {...this.props} className="collectionPdfView-cont" onContextMenu={this.onContextMenu}> + {this.subView} + </CollectionBaseView> + ) } }
\ No newline at end of file diff --git a/src/client/views/collections/CollectionSchemaView.tsx b/src/client/views/collections/CollectionSchemaView.tsx index b10aaba98..4604945d1 100644 --- a/src/client/views/collections/CollectionSchemaView.tsx +++ b/src/client/views/collections/CollectionSchemaView.tsx @@ -22,9 +22,11 @@ import { EditableView } from "../EditableView"; import { DocumentView } from "../nodes/DocumentView"; import { FieldView, FieldViewProps } from "../nodes/FieldView"; import "./CollectionSchemaView.scss"; -import { CollectionView, COLLECTION_BORDER_WIDTH } from "./CollectionView"; +import { CollectionView } from "./CollectionView"; import { CollectionViewBase } from "./CollectionViewBase"; import { TextField } from "../../../fields/TextField"; +import { COLLECTION_BORDER_WIDTH } from "./CollectionBaseView"; +import { emptyFunction, returnFalse } from "../../../Utils"; // bcz: need to add drag and drop of rows and columns. This seems like it might work for rows: https://codesandbox.io/s/l94mn1q657 @@ -73,19 +75,22 @@ export class CollectionSchemaView extends CollectionViewBase { renderCell = (rowProps: CellInfo) => { let props: FieldViewProps = { - doc: rowProps.value[0], + Document: rowProps.value[0], fieldKey: rowProps.value[1], isSelected: () => false, select: () => { }, isTopMost: false, - bindings: {}, selectOnLoad: false, + ScreenToLocalTransform: Transform.Identity, + focus: emptyFunction, + active: returnFalse, + onActiveChanged: emptyFunction, } let contents = ( <FieldView {...props} /> ) let reference = React.createRef<HTMLDivElement>(); - let onItemDown = setupDrag(reference, () => props.doc, (containingCollection: CollectionView) => this.props.removeDocument(props.doc)); + let onItemDown = setupDrag(reference, () => props.Document, this.props.moveDocument); let applyToDoc = (doc: Document, run: (args?: { [name: string]: any }) => any) => { const res = run({ this: doc }); if (!res.success) return false; @@ -103,13 +108,13 @@ export class CollectionSchemaView extends CollectionViewBase { return false; } return ( - <div className="collectionSchemaView-cellContents" onPointerDown={onItemDown} style={{ height: "56px" }} key={props.doc.Id} ref={reference}> + <div className="collectionSchemaView-cellContents" onPointerDown={onItemDown} style={{ height: "56px" }} key={props.Document.Id} ref={reference}> <EditableView display={"inline"} contents={contents} height={56} GetValue={() => { - let field = props.doc.Get(props.fieldKey); + let field = props.Document.Get(props.fieldKey); if (field && field instanceof Field) { return field.ToScriptString(); } @@ -120,7 +125,7 @@ export class CollectionSchemaView extends CollectionViewBase { if (!script.compiled) { return false; } - return applyToDoc(props.doc, script.run); + return applyToDoc(props.Document, script.run); }} OnFillDown={(value: string) => { let script = CompileScript(value, { addReturn: true, params: { this: "Document" } }); @@ -155,8 +160,8 @@ export class CollectionSchemaView extends CollectionViewBase { } }), style: { - background: rowInfo.index == this._selectedIndex ? "lightGray" : "white", - //color: rowInfo.index == this._selectedIndex ? "white" : "black" + background: rowInfo.index === this._selectedIndex ? "lightGray" : "white", + //color: rowInfo.index === this._selectedIndex ? "white" : "black" } }; } @@ -184,8 +189,8 @@ export class CollectionSchemaView extends CollectionViewBase { @action toggleExpander = (event: React.ChangeEvent<HTMLInputElement>) => { this._startSplitPercent = this.splitPercentage; - if (this._startSplitPercent == this.splitPercentage) { - this.props.Document.SetNumber(KeyStore.SchemaSplitPercentage, this.splitPercentage == 0 ? 33 : 0); + if (this._startSplitPercent === this.splitPercentage) { + this.props.Document.SetNumber(KeyStore.SchemaSplitPercentage, this.splitPercentage === 0 ? 33 : 0); } } @@ -214,8 +219,8 @@ export class CollectionSchemaView extends CollectionViewBase { onDividerUp = (e: PointerEvent): void => { document.removeEventListener("pointermove", this.onDividerMove); document.removeEventListener('pointerup', this.onDividerUp); - if (this._startSplitPercent == this.splitPercentage) { - this.props.Document.SetNumber(KeyStore.SchemaSplitPercentage, this.splitPercentage == 0 ? 33 : 0); + if (this._startSplitPercent === this.splitPercentage) { + this.props.Document.SetNumber(KeyStore.SchemaSplitPercentage, this.splitPercentage === 0 ? 33 : 0); } } onDividerDown = (e: React.PointerEvent) => { @@ -243,12 +248,8 @@ export class CollectionSchemaView extends CollectionViewBase { getContentScaling = (): number => this._contentScaling; getPanelWidth = (): number => this._panelWidth; getPanelHeight = (): number => this._panelHeight; - getTransform = (): Transform => { - return this.props.ScreenToLocalTransform().translate(- COLLECTION_BORDER_WIDTH - this.DIVIDER_WIDTH - this._dividerX, - COLLECTION_BORDER_WIDTH).scale(1 / this._contentScaling); - } - getPreviewTransform = (): Transform => { - return this.props.ScreenToLocalTransform().translate(- COLLECTION_BORDER_WIDTH - this.DIVIDER_WIDTH - this._dividerX - this._tableWidth, - COLLECTION_BORDER_WIDTH).scale(1 / this._contentScaling); - } + getTransform = (): Transform => this.props.ScreenToLocalTransform().translate(- COLLECTION_BORDER_WIDTH - this.DIVIDER_WIDTH - this._dividerX, - COLLECTION_BORDER_WIDTH).scale(1 / this._contentScaling) + getPreviewTransform = (): Transform => this.props.ScreenToLocalTransform().translate(- COLLECTION_BORDER_WIDTH - this.DIVIDER_WIDTH - this._dividerX - this._tableWidth, - COLLECTION_BORDER_WIDTH).scale(1 / this._contentScaling) focusDocument = (doc: Document) => { } @@ -299,28 +300,30 @@ export class CollectionSchemaView extends CollectionViewBase { let doc: any = selected ? selected.Get(new Key(this.previewScript)) : undefined; // let doc = CompileScript(this.previewScript, { this: selected }, true)(); - let content = this._selectedIndex == -1 || !selected ? (null) : ( + let content = this._selectedIndex === -1 || !selected ? (null) : ( <Measure onResize={this.setScaling}> {({ measureRef }) => <div className="collectionSchemaView-content" ref={measureRef}> - {doc instanceof Document ? <DocumentView Document={doc} - AddDocument={this.props.addDocument} RemoveDocument={this.props.removeDocument} - isTopMost={false} - SelectOnLoad={false} - ScreenToLocalTransform={this.getPreviewTransform} - ContentScaling={this.getContentScaling} - PanelWidth={this.getPanelWidth} - PanelHeight={this.getPanelHeight} - ContainingCollectionView={this.props.CollectionView} - focus={this.focusDocument} - /> : null} + {doc instanceof Document ? + <DocumentView Document={doc} + addDocument={this.props.addDocument} removeDocument={this.props.removeDocument} + isTopMost={false} + selectOnLoad={false} + ScreenToLocalTransform={this.getPreviewTransform} + ContentScaling={this.getContentScaling} + PanelWidth={this.getPanelWidth} + PanelHeight={this.getPanelHeight} + ContainingCollectionView={undefined} + focus={this.focusDocument} + parentActive={this.props.active} + onActiveChanged={this.props.onActiveChanged} /> : null} <input value={this.previewScript} onChange={this.onPreviewScriptChange} style={{ position: 'absolute', bottom: '0px' }} /> </div> } </Measure> ) - let dividerDragger = this.splitPercentage == 0 ? (null) : + let dividerDragger = this.splitPercentage === 0 ? (null) : <div className="collectionSchemaView-dividerDragger" onPointerDown={this.onDividerDown} style={{ width: `${this.DIVIDER_WIDTH}px` }} /> //options button and menu @@ -330,12 +333,11 @@ export class CollectionSchemaView extends CollectionViewBase { <div id="schema-options-header"><h5><b>Options</b></h5></div> <div id="options-flyout-div"> <h6 className="schema-options-subHeader">Preview Window</h6> - <div id="preview-schema-checkbox-div"><input type="checkbox" key={"Show Preview"} checked={this.splitPercentage != 0} onChange={this.toggleExpander} /> Show Preview </div> + <div id="preview-schema-checkbox-div"><input type="checkbox" key={"Show Preview"} checked={this.splitPercentage !== 0} onChange={this.toggleExpander} /> Show Preview </div> <h6 className="schema-options-subHeader" >Displayed Columns</h6> <ul id="schema-col-checklist" > - {Array.from(Object.keys(allKeys)).map(item => { - return (<KeyToggle checked={allKeys[item]} key={item} keyId={item} toggle={this.toggleKey} />) - })} + {Array.from(Object.keys(allKeys)).map(item => + (<KeyToggle checked={allKeys[item]} key={item} keyId={item} toggle={this.toggleKey} />))} </ul> <input value={this.newKeyName} onChange={this.newKeyChange} /> <button onClick={this.addColumn}><FontAwesomeIcon style={{ color: "white" }} icon="plus" size="lg" /></button> diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index 0b12f11fd..dce35868e 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -7,17 +7,20 @@ import { Document } from "../../../fields/Document"; import { FieldWaiting } from "../../../fields/Field"; import { KeyStore } from "../../../fields/KeyStore"; import { ListField } from "../../../fields/ListField"; -import { setupDrag } from "../../util/DragManager"; +import { setupDrag, DragManager } from "../../util/DragManager"; import { EditableView } from "../EditableView"; import "./CollectionTreeView.scss"; -import { CollectionView, COLLECTION_BORDER_WIDTH } from "./CollectionView"; +import { CollectionView } from "./CollectionView"; import { CollectionViewBase } from "./CollectionViewBase"; import React = require("react") +import { COLLECTION_BORDER_WIDTH } from './CollectionBaseView'; +import { props } from 'bluebird'; export interface TreeViewProps { document: Document; deleteDoc: (doc: Document) => void; + moveDocument: DragManager.MoveFunction; copyOnDrag: boolean; } @@ -49,6 +52,16 @@ class TreeView extends React.Component<TreeViewProps> { } } + @action + move: DragManager.MoveFunction = (document, target, addDoc) => { + if (this.props.document === target) { + return true; + } + //TODO This should check if it was removed + this.remove(document) + return addDoc(document); + } + renderBullet(type: BulletType) { let onClicked = action(() => this._collapsed = !this._collapsed); let bullet: IconProp | undefined = undefined; @@ -64,7 +77,7 @@ class TreeView extends React.Component<TreeViewProps> { */ renderTitle() { let reference = React.createRef<HTMLDivElement>(); - let onItemDown = setupDrag(reference, () => this.props.document, (containingCollection: CollectionView) => this.props.deleteDoc(this.props.document), this.props.copyOnDrag); + let onItemDown = setupDrag(reference, () => this.props.document, this.props.moveDocument, this.props.copyOnDrag); let editableView = (titleString: string) => (<EditableView display={"inline"} @@ -91,8 +104,8 @@ class TreeView extends React.Component<TreeViewProps> { if (!this._collapsed) { bulletType = BulletType.Collapsible; childElements = <ul> - {children.Data.map(value => <TreeView key={value.Id} document={value} deleteDoc={this.remove} copyOnDrag={this.props.copyOnDrag} />)} - </ul> + {children.Data.map(value => <TreeView key={value.Id} document={value} deleteDoc={this.remove} moveDocument={this.move} copyOnDrag={this.props.copyOnDrag} />)} + </ul > } else bulletType = BulletType.Collapsed; } @@ -122,7 +135,7 @@ export class CollectionTreeView extends CollectionViewBase { let copyOnDrag = this.props.Document.GetBoolean(KeyStore.CopyDraggedItems, false); let childrenElement = !children || children === FieldWaiting ? (null) : (children.Data.map(value => - <TreeView document={value} key={value.Id} deleteDoc={this.remove} copyOnDrag={copyOnDrag} />) + <TreeView document={value} key={value.Id} deleteDoc={this.remove} moveDocument={this.props.moveDocument} copyOnDrag={copyOnDrag} />) ) return ( diff --git a/src/client/views/collections/CollectionVideoView.tsx b/src/client/views/collections/CollectionVideoView.tsx index 470a853e3..afadfeefb 100644 --- a/src/client/views/collections/CollectionVideoView.tsx +++ b/src/client/views/collections/CollectionVideoView.tsx @@ -3,11 +3,14 @@ import { observer } from "mobx-react"; import { Document } from "../../../fields/Document"; import { KeyStore } from "../../../fields/KeyStore"; import { ContextMenu } from "../ContextMenu"; -import { CollectionView, CollectionViewType } from "./CollectionView"; +import { CollectionView } from "./CollectionView"; +import { CollectionViewType, CollectionBaseView, CollectionRenderProps } from "./CollectionBaseView"; import { CollectionViewProps } from "./CollectionViewBase"; import React = require("react"); import { FieldId } from "../../../fields/Field"; import "./CollectionVideoView.scss" +import { CollectionFreeFormView } from "./collectionFreeForm/CollectionFreeFormView"; +import { FieldView } from "../nodes/FieldView"; @observer @@ -19,9 +22,7 @@ export class CollectionVideoView extends React.Component<CollectionViewProps> { @observable _isPlaying: boolean = false; public static LayoutString(fieldKey: string = "DataKey") { - return `<${CollectionVideoView.name} Document={Document} - ScreenToLocalTransform={ScreenToLocalTransform} fieldKey={${fieldKey}} panelWidth={PanelWidth} panelHeight={PanelHeight} isSelected={isSelected} select={select} bindings={bindings} - isTopMost={isTopMost} SelectOnLoad={selectOnLoad} BackgroundView={BackgroundView} focus={focus}/>`; + return FieldView.LayoutString(CollectionVideoView, fieldKey); } private get uIButtons() { let scaling = Math.min(1.8, this.props.ScreenToLocalTransform().transformDirection(1, 1)[0]); @@ -42,7 +43,7 @@ export class CollectionVideoView extends React.Component<CollectionViewProps> { @action mainCont = (ele: HTMLDivElement | null) => { if (ele) { - this._player = ele!.getElementsByTagName("video")[0]; + this._player = ele.getElementsByTagName("video")[0]; if (this.props.Document.GetNumber(KeyStore.CurPage, -1) >= 0) { this._currentTimecode = this.props.Document.GetNumber(KeyStore.CurPage, -1); } @@ -60,7 +61,7 @@ export class CollectionVideoView extends React.Component<CollectionViewProps> { @action updateTimecode = () => { if (this._player) { - if ((this._player as any).AHackBecauseSomethingResetsTheVideoToZero != -1) { + if ((this._player as any).AHackBecauseSomethingResetsTheVideoToZero !== -1) { this._player.currentTime = (this._player as any).AHackBecauseSomethingResetsTheVideoToZero; (this._player as any).AHackBecauseSomethingResetsTheVideoToZero = -1; } else { @@ -101,30 +102,27 @@ export class CollectionVideoView extends React.Component<CollectionViewProps> { } - // "inherited" CollectionView API starts here... - - @observable - public SelectedDocs: FieldId[] = [] - public active: () => boolean = () => CollectionView.Active(this); - - addDocument = (doc: Document, allowDuplicates: boolean): boolean => { return CollectionView.AddDocument(this.props, doc, allowDuplicates); } - removeDocument = (doc: Document): boolean => { return CollectionView.RemoveDocument(this.props, doc); } - - specificContextMenu = (e: React.MouseEvent): void => { - if (!e.isPropagationStopped() && this.props.Document.Id != "mainDoc") { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7 + onContextMenu = (e: React.MouseEvent): void => { + if (!e.isPropagationStopped() && this.props.Document.Id !== "mainDoc") { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7 ContextMenu.Instance.addItem({ description: "VideoOptions", event: () => { } }); } } - get collectionViewType(): CollectionViewType { return CollectionViewType.Freeform; } - get subView(): any { return CollectionView.SubView(this); } - + private subView = (_type: CollectionViewType, renderProps: CollectionRenderProps) => { + let props = { ...renderProps, ...this.props }; + return ( + <> + <CollectionFreeFormView {...props} /> + {this.props.isSelected() ? this.uIButtons : (null)} + </> + ) + } render() { trace(); - return (<div className="collectionVideoView-cont" ref={this.mainCont} onContextMenu={this.specificContextMenu}> - {this.subView} - {this.props.isSelected() ? this.uIButtons : (null)} - </div>) + return ( + <CollectionBaseView {...this.props} className="collectionVideoView-cont" contentRef={this.mainCont} onContextMenu={this.onContextMenu}> + {this.subView} + </CollectionBaseView>) } }
\ No newline at end of file diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 014aa1d8f..1b0cfd57b 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -1,159 +1,45 @@ -import { action, computed, observable } from "mobx"; -import { observer } from "mobx-react"; -import { Document } from "../../../fields/Document"; -import { ListField } from "../../../fields/ListField"; -import { SelectionManager } from "../../util/SelectionManager"; -import { ContextMenu } from "../ContextMenu"; -import React = require("react"); -import { KeyStore } from "../../../fields/KeyStore"; -import { NumberField } from "../../../fields/NumberField"; -import { CollectionFreeFormView } from "./collectionFreeForm/CollectionFreeFormView"; -import { CollectionDockingView } from "./CollectionDockingView"; -import { CollectionSchemaView } from "./CollectionSchemaView"; -import { CollectionViewProps } from "./CollectionViewBase"; -import { CollectionTreeView } from "./CollectionTreeView"; -import { Field, FieldId, FieldWaiting } from "../../../fields/Field"; -import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; - -export enum CollectionViewType { - Invalid, - Freeform, - Schema, - Docking, - Tree -} - -export const COLLECTION_BORDER_WIDTH = 1; +import * as React from 'react' +import { FieldViewProps, FieldView } from '../nodes/FieldView'; +import { CollectionBaseView, CollectionViewType, CollectionRenderProps } from './CollectionBaseView'; +import { CollectionFreeFormView } from './collectionFreeForm/CollectionFreeFormView'; +import { CollectionSchemaView } from './CollectionSchemaView'; +import { CollectionDockingView } from './CollectionDockingView'; +import { CollectionTreeView } from './CollectionTreeView'; +import { ContextMenu } from '../ContextMenu'; +import { CurrentUserUtils } from '../../../server/authentication/models/current_user_utils'; +import { KeyStore } from '../../../fields/KeyStore'; +import { observer } from 'mobx-react'; @observer -export class CollectionView extends React.Component<CollectionViewProps> { - - public static LayoutString(fieldKey: string = "DataKey") { - return `<${CollectionView.name} Document={Document} - ScreenToLocalTransform={ScreenToLocalTransform} fieldKey={${fieldKey}} panelWidth={PanelWidth} panelHeight={PanelHeight} isSelected={isSelected} select={select} bindings={bindings} - isTopMost={isTopMost} SelectOnLoad={selectOnLoad} BackgroundView={BackgroundView} focus={focus}/>`; - } - - @observable - public SelectedDocs: FieldId[] = []; - public active: () => boolean = () => CollectionView.Active(this); - addDocument = (doc: Document, allowDuplicates: boolean): boolean => { return CollectionView.AddDocument(this.props, doc, allowDuplicates); } - removeDocument = (doc: Document): boolean => { return CollectionView.RemoveDocument(this.props, doc); } - get subView() { return CollectionView.SubView(this); } - - public static Active(self: CollectionView): boolean { - var isSelected = self.props.isSelected(); - var childSelected = SelectionManager.SelectedDocuments().some(view => view.props.ContainingCollectionView == self); - var topMost = self.props.isTopMost; - return isSelected || childSelected || topMost; - } - - static createsCycle(documentToAdd: Document, containerDocument: Document): boolean { - let data = documentToAdd.GetList<Document>(KeyStore.Data, []); - for (let i = 0; i < data.length; i++) { - if (CollectionView.createsCycle(data[i], containerDocument)) - return true; - } - let annots = documentToAdd.GetList<Document>(KeyStore.Annotations, []); - for (let i = 0; i < annots.length; i++) { - if (CollectionView.createsCycle(annots[i], containerDocument)) - return true; - } - for (let containerProto: any = containerDocument; containerProto && containerProto != FieldWaiting; containerProto = containerProto.GetPrototype()) { - if (containerProto.Id == documentToAdd.Id) - return true; - } - return false; - } - - @action - public static AddDocument(props: CollectionViewProps, doc: Document, allowDuplicates: boolean): boolean { - var curPage = props.Document.GetNumber(KeyStore.CurPage, -1); - doc.SetOnPrototype(KeyStore.Page, new NumberField(curPage)); - if (curPage >= 0) { - doc.SetOnPrototype(KeyStore.AnnotationOn, props.Document); - } - if (props.Document.Get(props.fieldKey) instanceof Field) { - //TODO This won't create the field if it doesn't already exist - const value = props.Document.GetData(props.fieldKey, ListField, new Array<Document>()) - if (!CollectionView.createsCycle(doc, props.Document)) { - if (!value.some(v => v.Id == doc.Id) || allowDuplicates) - value.push(doc); - } - else - return false; - } else { - let proto = props.Document.GetPrototype(); - if (!proto || proto == FieldWaiting || !CollectionView.createsCycle(proto, doc)) { - props.Document.SetOnPrototype(props.fieldKey, new ListField([doc])); - } - else - return false; - } - return true; - } - - @action - public static RemoveDocument(props: CollectionViewProps, doc: Document): boolean { - //TODO This won't create the field if it doesn't already exist - const value = props.Document.GetData(props.fieldKey, ListField, new Array<Document>()) - let index = -1; - for (let i = 0; i < value.length; i++) { - if (value[i].Id == doc.Id) { - index = i; - break; - } - } - doc.GetTAsync(KeyStore.AnnotationOn, Document).then((annotationOn) => { - if (annotationOn == props.Document) { - doc.Set(KeyStore.AnnotationOn, undefined, true); - } - }) - - if (index !== -1) { - value.splice(index, 1) - - //SelectionManager.DeselectAll() - ContextMenu.Instance.clearItems() - return true; - } - return false - } - - get collectionViewType(): CollectionViewType { - let Document = this.props.Document; - let viewField = Document.GetT(KeyStore.ViewType, NumberField); - if (viewField === FieldWaiting) { - return CollectionViewType.Invalid; - } else if (viewField) { - return viewField.Data; - } else { - return CollectionViewType.Freeform; +export class CollectionView extends React.Component<FieldViewProps> { + public static LayoutString(fieldStr: string = "DataKey") { return FieldView.LayoutString(CollectionView, fieldStr) } + + private SubView = (type: CollectionViewType, renderProps: CollectionRenderProps) => { + let props = { ...this.props, ...renderProps }; + switch (type) { + case CollectionViewType.Schema: return (<CollectionSchemaView {...props} />) + case CollectionViewType.Docking: return (<CollectionDockingView {...props} />) + case CollectionViewType.Tree: return (<CollectionTreeView {...props} />) + case CollectionViewType.Freeform: + default: + return (<CollectionFreeFormView {...props} />) } + return (null); } - specificContextMenu = (e: React.MouseEvent): void => { - if (!e.isPropagationStopped() && this.props.Document.Id != CurrentUserUtils.MainDocId) { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7 + onContextMenu = (e: React.MouseEvent): void => { + if (!e.isPropagationStopped() && this.props.Document.Id !== CurrentUserUtils.MainDocId) { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7 ContextMenu.Instance.addItem({ description: "Freeform", event: () => this.props.Document.SetNumber(KeyStore.ViewType, CollectionViewType.Freeform) }) ContextMenu.Instance.addItem({ description: "Schema", event: () => this.props.Document.SetNumber(KeyStore.ViewType, CollectionViewType.Schema) }) ContextMenu.Instance.addItem({ description: "Treeview", event: () => this.props.Document.SetNumber(KeyStore.ViewType, CollectionViewType.Tree) }) } } - public static SubView(self: CollectionView) { - let subProps = { ...self.props, addDocument: self.addDocument, removeDocument: self.removeDocument, active: self.active, CollectionView: self } - switch (self.collectionViewType) { - case CollectionViewType.Freeform: return (<CollectionFreeFormView {...subProps} />) - case CollectionViewType.Schema: return (<CollectionSchemaView {...subProps} />) - case CollectionViewType.Docking: return (<CollectionDockingView {...subProps} />) - case CollectionViewType.Tree: return (<CollectionTreeView {...subProps} />) - } - return (null); - } - render() { - return (<div className="collectionView-cont" onContextMenu={this.specificContextMenu}> - {this.subView} - </div>) + return ( + <CollectionBaseView {...this.props} onContextMenu={this.onContextMenu}> + {this.SubView} + </CollectionBaseView> + ) } -} +}
\ No newline at end of file diff --git a/src/client/views/collections/CollectionViewBase.tsx b/src/client/views/collections/CollectionViewBase.tsx index 7cf49e215..84d378e1c 100644 --- a/src/client/views/collections/CollectionViewBase.tsx +++ b/src/client/views/collections/CollectionViewBase.tsx @@ -17,27 +17,15 @@ import { NumberField } from "../../../fields/NumberField"; import request = require("request"); import { ServerUtils } from "../../../server/ServerUtil"; import { Server } from "../../Server"; -import { CollectionDockingView } from "./CollectionDockingView"; -import { runReactions } from "mobx/lib/internal"; +import { FieldViewProps } from "../nodes/FieldView"; -export interface CollectionViewProps { - fieldKey: Key; - Document: Document; - ScreenToLocalTransform: () => Transform; - isSelected: () => boolean; - isTopMost: boolean; - select: (ctrlPressed: boolean) => void; - bindings: any; - panelWidth: () => number; - panelHeight: () => number; - focus: (doc: Document) => void; +export interface CollectionViewProps extends FieldViewProps { + addDocument: (document: Document, allowDuplicates?: boolean) => boolean; + removeDocument: (document: Document) => boolean; + moveDocument: (document: Document, targetCollection: Document, addDocument: (document: Document) => boolean) => boolean; } export interface SubCollectionViewProps extends CollectionViewProps { - active: () => boolean; - addDocument: (doc: Document, allowDuplicates: boolean) => boolean; - removeDocument: (doc: Document) => boolean; - CollectionView: CollectionView; } export type CursorEntry = TupleField<[string, string], [number, number]>; @@ -87,9 +75,14 @@ export class CollectionViewBase extends React.Component<SubCollectionViewProps> de.data.draggedDocuments.map((draggedDocument: Document, i: number) => draggedDocument.GetTAsync(key, NumberField, (f: Opt<NumberField>) => f ? de.data.droppedDocuments[i].SetNumber(key, f.Data) : null))); } - let added = de.data.droppedDocuments.reduce((added, d) => this.props.addDocument(d, false), true); - if (added && de.data.removeDocument && !de.data.aliasOnDrop && !de.data.copyOnDrop) { - de.data.removeDocument(this.props.CollectionView); + let added = false; + if (de.data.aliasOnDrop) { + added = de.data.droppedDocuments.reduce((added: boolean, d) => added || this.props.addDocument(d), false); + } else if (de.data.moveDocument) { + const move = de.data.moveDocument; + added = de.data.droppedDocuments.reduce((added: boolean, d) => added || move(d, this.props.Document, this.props.addDocument), false) + } else { + added = de.data.droppedDocuments.reduce((added: boolean, d) => added || this.props.addDocument(d), false) } e.stopPropagation(); return added; @@ -98,11 +91,11 @@ export class CollectionViewBase extends React.Component<SubCollectionViewProps> let sourceDoc: Document = de.data.linkSourceDocumentView.props.Document; if (sourceDoc) runInAction(() => { let srcTarg = sourceDoc.GetT(KeyStore.Prototype, Document) - if (srcTarg && srcTarg != FieldWaiting) { + if (srcTarg && srcTarg !== FieldWaiting) { let linkDocs = srcTarg.GetList(KeyStore.LinkedToDocs, [] as Document[]); linkDocs.map(linkDoc => { let targDoc = linkDoc.GetT(KeyStore.LinkedToDocs, Document); - if (targDoc && targDoc != FieldWaiting) { + if (targDoc && targDoc !== FieldWaiting) { let dropdoc = targDoc.MakeDelegate(); de.data.droppedDocuments.push(dropdoc); this.props.addDocument(dropdoc, false); @@ -154,8 +147,6 @@ export class CollectionViewBase extends React.Component<SubCollectionViewProps> @action protected onDrop(e: React.DragEvent, options: DocumentOptions): void { - let that = this; - let html = e.dataTransfer.getData("text/html"); let text = e.dataTransfer.getData("text/plain"); @@ -165,7 +156,7 @@ export class CollectionViewBase extends React.Component<SubCollectionViewProps> e.stopPropagation() e.preventDefault() - if (html && html.indexOf("<img") != 0 && !html.startsWith("<a")) { + if (html && html.indexOf("<img") !== 0 && !html.startsWith("<a")) { console.log("not good"); let htmlDoc = Documents.HtmlDocument(html, { ...options, width: 300, height: 300 }); htmlDoc.SetText(KeyStore.DocumentText, text); @@ -173,10 +164,11 @@ export class CollectionViewBase extends React.Component<SubCollectionViewProps> return; } + // tslint:disable-next-line:prefer-for-of for (let i = 0; i < e.dataTransfer.items.length; i++) { const upload = window.location.origin + RouteStore.upload; let item = e.dataTransfer.items[i]; - if (item.kind === "string" && item.type.indexOf("uri") != -1) { + if (item.kind === "string" && item.type.indexOf("uri") !== -1) { e.dataTransfer.items[i].getAsString(action((s: string) => { request.head(ServerUtils.prepend(RouteStore.corsProxy + "/" + s), (err, res, body) => { let type = res.headers["content-type"]; @@ -191,7 +183,7 @@ export class CollectionViewBase extends React.Component<SubCollectionViewProps> })) } let type = item.type - if (item.kind == "file") { + if (item.kind === "file") { let file = item.getAsFile(); let formData = new FormData() @@ -202,19 +194,18 @@ export class CollectionViewBase extends React.Component<SubCollectionViewProps> fetch(upload, { method: 'POST', body: formData - }).then((res: Response) => { - return res.json() - }).then(json => { + }).then(async (res: Response) => { + const json = await res.json(); json.map((file: any) => { let path = window.location.origin + file runInAction(() => { let doc = this.getDocumentFromType(type, path, { ...options, nativeWidth: 300, width: 300 }) - let docs = that.props.Document.GetT(KeyStore.Data, ListField); - if (docs != FieldWaiting) { + let docs = this.props.Document.GetT(KeyStore.Data, ListField); + if (docs !== FieldWaiting) { if (!docs) { docs = new ListField<Document>(); - that.props.Document.Set(KeyStore.Data, docs) + this.props.Document.Set(KeyStore.Data, docs) } if (doc) { docs.Data.push(doc); diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx index 1189dd4e8..abc6cecff 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx @@ -31,17 +31,17 @@ export class CollectionFreeFormLinksView extends React.Component<CollectionViewP let x1w = srcDoc.GetNumber(KeyStore.Width, -1); let x2 = dstDoc.GetNumber(KeyStore.X, 0); let x2w = dstDoc.GetNumber(KeyStore.Width, -1); - if (x1w < 0 || x2w < 0 || i == j) + if (x1w < 0 || x2w < 0 || i === j) continue; let dstTarg = dstDoc; let srcTarg = srcDoc; let findBrush = (field: ListField<Document>) => field.Data.findIndex(brush => { let bdocs = brush ? brush.GetList(KeyStore.BrushingDocs, [] as Document[]) : []; - return (bdocs.length && ((bdocs[0] == dstTarg && bdocs[1] == srcTarg)) ? true : false) + return (bdocs.length && ((bdocs[0] === dstTarg && bdocs[1] === srcTarg)) ? true : false) }); let brushAction = (field: ListField<Document>) => { let found = findBrush(field); - if (found != -1) { + if (found !== -1) { console.log("REMOVE BRUSH " + srcTarg.Title + " " + dstTarg.Title); field.Data.splice(found, 1); } @@ -53,9 +53,9 @@ export class CollectionFreeFormLinksView extends React.Component<CollectionViewP linkDoc.SetData(KeyStore.BrushingDocs, [dstTarg, srcTarg], ListField); brushAction = brushAction = (field: ListField<Document>) => { - if (findBrush(field) == -1) { + if (findBrush(field) === -1) { console.log("ADD BRUSH " + srcTarg.Title + " " + dstTarg.Title); - (findBrush(field) == -1) && field.Data.push(linkDoc); + (findBrush(field) === -1) && field.Data.push(linkDoc); } }; } @@ -69,10 +69,10 @@ export class CollectionFreeFormLinksView extends React.Component<CollectionViewP documentAnchors(view: DocumentView) { let equalViews = [view]; let containerDoc = view.props.Document.GetT(KeyStore.AnnotationOn, Document); - if (containerDoc && containerDoc != FieldWaiting && containerDoc instanceof Document) { - equalViews = DocumentManager.Instance.getDocumentViews(containerDoc.GetPrototype() as Document) + if (containerDoc && containerDoc instanceof Document) { + equalViews = DocumentManager.Instance.getDocumentViews(containerDoc.GetPrototype()!) } - return equalViews.filter(sv => sv.props.ContainingCollectionView && sv.props.ContainingCollectionView.props.Document == this.props.Document); + return equalViews.filter(sv => sv.props.ContainingCollectionView && sv.props.ContainingCollectionView.props.Document === this.props.Document); } @computed @@ -84,14 +84,14 @@ export class CollectionFreeFormLinksView extends React.Component<CollectionViewP srcViews.map(sv => targetViews.map(tv => possiblePairs.push({ a: sv.props.Document, b: tv.props.Document }))); possiblePairs.map(possiblePair => { if (!drawnPairs.reduce((found, drawnPair) => { - let match = (possiblePair.a == drawnPair.a && possiblePair.b == drawnPair.b); + let match = (possiblePair.a === drawnPair.a && possiblePair.b === drawnPair.b); if (match) { - if (!drawnPair.l.reduce((found, link) => found || link.Id == connection.l.Id, false)) + if (!drawnPair.l.reduce((found, link) => found || link.Id === connection.l.Id, false)) drawnPair.l.push(connection.l); } return match || found; }, false)) { - drawnPairs.push({ a: possiblePair.a, b: possiblePair.b, l: [connection.l] as Document[] }); + drawnPairs.push({ a: possiblePair.a, b: possiblePair.b, l: [connection.l] }); } }) return drawnPairs diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx index 19382e66f..f664f4e65 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx @@ -1,21 +1,8 @@ -import { action, computed, observable } from "mobx"; +import { computed } from "mobx"; import { observer } from "mobx-react"; -import { Document } from "../../../../fields/Document"; -import { FieldWaiting } from "../../../../fields/Field"; import { KeyStore } from "../../../../fields/KeyStore"; -import { TextField } from "../../../../fields/TextField"; -import { DragManager } from "../../../util/DragManager"; -import { Transform } from "../../../util/Transform"; -import { undoBatch } from "../../../util/UndoManager"; -import { InkingCanvas } from "../../InkingCanvas"; -import { CollectionFreeFormDocumentView } from "../../nodes/CollectionFreeFormDocumentView"; -import { DocumentContentsView } from "../../nodes/DocumentContentsView"; -import { DocumentViewProps } from "../../nodes/DocumentView"; -import { COLLECTION_BORDER_WIDTH } from "../CollectionView"; -import { CollectionViewBase, CollectionViewProps, CursorEntry } from "../CollectionViewBase"; -import { CollectionFreeFormLinksView } from "./CollectionFreeFormLinksView"; +import { CollectionViewProps, CursorEntry } from "../CollectionViewBase"; import "./CollectionFreeFormView.scss"; -import { MarqueeView } from "./MarqueeView"; import React = require("react"); import v5 = require("uuid/v5"); import { CurrentUserUtils } from "../../../../server/authentication/models/current_user_utils"; diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 2a86d0ee1..d542b8bc2 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -11,7 +11,7 @@ import { InkingCanvas } from "../../InkingCanvas"; import { CollectionFreeFormDocumentView } from "../../nodes/CollectionFreeFormDocumentView"; import { DocumentContentsView } from "../../nodes/DocumentContentsView"; import { DocumentViewProps } from "../../nodes/DocumentView"; -import { COLLECTION_BORDER_WIDTH } from "../CollectionView"; +import { COLLECTION_BORDER_WIDTH } from "../CollectionBaseView"; import { CollectionViewBase } from "../CollectionViewBase"; import { CollectionFreeFormLinksView } from "./CollectionFreeFormLinksView"; import "./CollectionFreeFormView.scss"; @@ -20,6 +20,8 @@ import React = require("react"); import v5 = require("uuid/v5"); import { CollectionFreeFormRemoteCursors } from "./CollectionFreeFormRemoteCursors"; import { PreviewCursor } from "./PreviewCursor"; +import { DocumentManager } from "../../../util/DocumentManager"; +import { SelectionManager } from "../../../util/SelectionManager"; import { NumberField } from "../../../../fields/NumberField"; import { Main } from "../../Main"; @@ -41,15 +43,20 @@ export class CollectionFreeFormView extends CollectionViewBase { } public selectDocuments = (docs: Document[]) => { - this.props.CollectionView.SelectedDocs.length = 0; - docs.map(d => this.props.CollectionView.SelectedDocs.push(d.Id)); + SelectionManager.DeselectAll; + docs.map(doc => { + const dv = DocumentManager.Instance.getDocumentView(doc); + if (dv) { + SelectionManager.SelectDoc(dv, true); + } + }) } public getActiveDocuments = () => { var curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1); return this.props.Document.GetList(this.props.fieldKey, [] as Document[]).reduce((active, doc) => { var page = doc.GetNumber(KeyStore.Page, -1); - if (page == curPage || page == -1) { + if (page === curPage || page === -1) { active.push(doc); } return active; @@ -61,6 +68,8 @@ export class CollectionFreeFormView extends CollectionViewBase { @observable private _lastX: number = 0; @observable private _lastY: number = 0; + private outerElement?: HTMLDivElement; + @computed get panX(): number { return this.props.Document.GetNumber(KeyStore.PanX, 0) } @computed get panY(): number { return this.props.Document.GetNumber(KeyStore.PanY, 0) } @computed get scale(): number { return this.props.Document.GetNumber(KeyStore.Scale, 1); } @@ -68,38 +77,40 @@ export class CollectionFreeFormView extends CollectionViewBase { @computed get nativeWidth() { return this.props.Document.GetNumber(KeyStore.NativeWidth, 0); } @computed get nativeHeight() { return this.props.Document.GetNumber(KeyStore.NativeHeight, 0); } @computed get zoomScaling() { return this.props.Document.GetNumber(KeyStore.Scale, 1); } - @computed get centeringShiftX() { return !this.props.Document.GetNumber(KeyStore.NativeWidth, 0) ? this.props.panelWidth() / 2 : 0; } // shift so pan position is at center of window for non-overlay collections - @computed get centeringShiftY() { return !this.props.Document.GetNumber(KeyStore.NativeHeight, 0) ? this.props.panelHeight() / 2 : 0; }// shift so pan position is at center of window for non-overlay collections + @computed get centeringShiftX() { return !this.props.Document.GetNumber(KeyStore.NativeWidth, 0) && this.outerElement ? this.outerElement.clientWidth / 2 : 0; } // shift so pan position is at center of window for non-overlay collections + @computed get centeringShiftY() { return !this.props.Document.GetNumber(KeyStore.NativeHeight, 0) && this.outerElement ? this.outerElement.clientHeight / 2 : 0; }// shift so pan position is at center of window for non-overlay collections @undoBatch @action drop = (e: Event, de: DragManager.DropEvent) => { if (super.drop(e, de)) { - let droppedDocs = de.data.droppedDocuments as Document[]; - let xoff = de.data.xOffset as number || 0; - let yoff = de.data.yOffset as number || 0; - if (droppedDocs && droppedDocs.length) { - let screenX = de.x - xoff; - let screenY = de.y - yoff; - const [x, y] = this.getTransform().transformPoint(screenX, screenY); - let dragDoc = de.data.droppedDocuments[0]; - let dragX = dragDoc.GetNumber(KeyStore.X, 0); - let dragY = dragDoc.GetNumber(KeyStore.Y, 0); - droppedDocs.map(async d => { - let docX = d.GetNumber(KeyStore.X, 0); - let docY = d.GetNumber(KeyStore.Y, 0); - d.SetNumber(KeyStore.X, x + (docX - dragX)); - d.SetNumber(KeyStore.Y, y + (docY - dragY)); - let docW = await d.GetTAsync(KeyStore.Width, NumberField); - let docH = await d.GetTAsync(KeyStore.Height, NumberField); - if (!docW) { - d.SetNumber(KeyStore.Width, 300); - } - if (!docH) { - d.SetNumber(KeyStore.Height, 300); - } - this.bringToFront(d); - }) + if (de.data instanceof DragManager.DocumentDragData) { + let droppedDocs = de.data.droppedDocuments; + let xoff = de.data.xOffset as number || 0; + let yoff = de.data.yOffset as number || 0; + if (droppedDocs.length) { + let screenX = de.x - xoff; + let screenY = de.y - yoff; + const [x, y] = this.getTransform().transformPoint(screenX, screenY); + let dragDoc = droppedDocs[0]; + let dragX = dragDoc.GetNumber(KeyStore.X, 0); + let dragY = dragDoc.GetNumber(KeyStore.Y, 0); + droppedDocs.map(async d => { + let docX = d.GetNumber(KeyStore.X, 0); + let docY = d.GetNumber(KeyStore.Y, 0); + d.SetNumber(KeyStore.X, x + (docX - dragX)); + d.SetNumber(KeyStore.Y, y + (docY - dragY)); + let docW = await d.GetTAsync(KeyStore.Width, NumberField); + let docH = await d.GetTAsync(KeyStore.Height, NumberField); + if (!docW) { + d.SetNumber(KeyStore.Width, 300); + } + if (!docH) { + d.SetNumber(KeyStore.Height, 300); + } + this.bringToFront(d); + }) + } } return true; } @@ -115,7 +126,7 @@ export class CollectionFreeFormView extends CollectionViewBase { @action onPointerDown = (e: React.PointerEvent): void => { - if (((e.button === 2 && (!this.isAnnotationOverlay || this.zoomScaling != 1)) || e.button == 0) && this.props.active()) { + if (((e.button === 2 && (!this.isAnnotationOverlay || this.zoomScaling !== 1)) || e.button === 0) && this.props.active()) { document.removeEventListener("pointermove", this.onPointerMove); document.addEventListener("pointermove", this.onPointerMove); document.removeEventListener("pointerup", this.onPointerUp); @@ -137,7 +148,7 @@ export class CollectionFreeFormView extends CollectionViewBase { @action onPointerMove = (e: PointerEvent): void => { if (!e.cancelBubble && this.props.active()) { - if ((!this.isAnnotationOverlay || this.zoomScaling != 1) && !e.shiftKey) { + if ((!this.isAnnotationOverlay || this.zoomScaling !== 1) && !e.shiftKey) { let x = this.props.Document.GetNumber(KeyStore.PanX, 0); let y = this.props.Document.GetNumber(KeyStore.PanY, 0); let [dx, dy] = this.getTransform().transformDirection(e.clientX - this._lastX, e.clientY - this._lastY); @@ -166,8 +177,8 @@ export class CollectionFreeFormView extends CollectionViewBase { e.stopPropagation(); e.preventDefault(); } else { - // if (modes[e.deltaMode] == 'pixels') coefficient = 50; - // else if (modes[e.deltaMode] == 'lines') coefficient = 1000; // This should correspond to line-height?? + // if (modes[e.deltaMode] === 'pixels') coefficient = 50; + // else if (modes[e.deltaMode] === 'lines') coefficient = 1000; // This should correspond to line-height?? let transform = this.getTransform(); let deltaScale = (1 - (e.deltaY / coefficient)); @@ -244,16 +255,19 @@ export class CollectionFreeFormView extends CollectionViewBase { getDocumentViewProps(document: Document): DocumentViewProps { return { Document: document, - AddDocument: this.props.addDocument, - RemoveDocument: this.props.removeDocument, + addDocument: this.props.addDocument, + removeDocument: this.props.removeDocument, + moveDocument: this.props.moveDocument, ScreenToLocalTransform: this.getTransform, isTopMost: false, - SelectOnLoad: document.Id == this._selectOnLoaded, + selectOnLoad: document.Id === this._selectOnLoaded, PanelWidth: document.Width, PanelHeight: document.Height, ContentScaling: this.noScaling, - ContainingCollectionView: this.props.CollectionView, - focus: this.focusDocument + ContainingCollectionView: undefined, + focus: this.focusDocument, + parentActive: this.props.active, + onActiveChanged: this.props.active, } } @@ -262,7 +276,7 @@ export class CollectionFreeFormView extends CollectionViewBase { var curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1); return this.props.Document.GetList(this.props.fieldKey, [] as Document[]).filter(doc => doc).reduce((prev, doc) => { var page = doc.GetNumber(KeyStore.Page, -1); - if (page == curPage || page == -1) + if (page === curPage || page === -1) prev.push(<CollectionFreeFormDocumentView key={doc.Id} {...this.getDocumentViewProps(doc)} />); return prev; }, [] as JSX.Element[]) @@ -283,7 +297,7 @@ export class CollectionFreeFormView extends CollectionViewBase { getTransform = (): Transform => this.props.ScreenToLocalTransform().translate(-COLLECTION_BORDER_WIDTH, -COLLECTION_BORDER_WIDTH).translate(-this.centeringShiftX, -this.centeringShiftY).transform(this.getLocalTransform()) getContainerTransform = (): Transform => this.props.ScreenToLocalTransform().translate(-COLLECTION_BORDER_WIDTH, -COLLECTION_BORDER_WIDTH) - getLocalTransform = (): Transform => Transform.Identity.scale(1 / this.scale).translate(this.panX, this.panY); + getLocalTransform = (): Transform => Transform.Identity().scale(1 / this.scale).translate(this.panX, this.panY); noScaling = () => 1; childViews = () => this.views; diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index df150a045..704db1d4a 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -48,7 +48,7 @@ export class MarqueeView extends React.Component<MarqueeViewProps> @action onPointerDown = (e: React.PointerEvent): void => { - if (e.buttons == 1 && !e.altKey && !e.metaKey && this.props.container.props.active()) { + if (e.buttons === 1 && !e.altKey && !e.metaKey && this.props.container.props.active()) { this._downX = this._lastX = e.pageX; this._downY = this._lastY = e.pageY; this._used = false; @@ -63,7 +63,7 @@ export class MarqueeView extends React.Component<MarqueeViewProps> this._lastX = e.pageX; this._lastY = e.pageY; if (!e.cancelBubble) { - if (!this._used && e.buttons == 1 && !e.altKey && !e.metaKey && + if (!this._used && e.buttons === 1 && !e.altKey && !e.metaKey && (Math.abs(this._lastX - this._downX) > MarqueeView.DRAG_THRESHOLD || Math.abs(this._lastY - this._downY) > MarqueeView.DRAG_THRESHOLD)) { this._visible = true; } @@ -99,15 +99,15 @@ export class MarqueeView extends React.Component<MarqueeViewProps> @action marqueeCommand = (e: KeyboardEvent) => { - if (e.key == "Backspace" || e.key == "Delete") { + if (e.key === "Backspace" || e.key === "Delete") { this.marqueeSelect().map(d => this.props.removeDocument(d)); let ink = this.props.container.props.Document.GetT(KeyStore.Ink, InkField); - if (ink && ink != FieldWaiting) { + if (ink && ink !== FieldWaiting) { this.marqueeInkDelete(ink.Data); } this.cleanupInteractions(); } - if (e.key == "c") { + if (e.key === "c") { let bounds = this.Bounds; let selected = this.marqueeSelect().map(d => { this.props.removeDocument(d); @@ -118,7 +118,7 @@ export class MarqueeView extends React.Component<MarqueeViewProps> return d; }); let ink = this.props.container.props.Document.GetT(KeyStore.Ink, InkField); - let inkData = ink && ink != FieldWaiting ? ink.Data : undefined; + let inkData = ink && ink !== FieldWaiting ? ink.Data : undefined; //setTimeout(() => { let newCollection = Documents.FreeformDocument(selected, { x: bounds.left, @@ -147,7 +147,7 @@ export class MarqueeView extends React.Component<MarqueeViewProps> if (InkingCanvas.IntersectStrokeRect(value, this.Bounds)) { idata.set(key, { - pathData: value.pathData.map(val => { return { x: val.x + centerShiftX, y: val.y + centerShiftY } }), + pathData: value.pathData.map(val => ({ x: val.x + centerShiftX, y: val.y + centerShiftY })), color: value.color, width: value.width, tool: value.tool, diff --git a/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx b/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx index 93c98f7b0..599461f85 100644 --- a/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx +++ b/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx @@ -33,7 +33,7 @@ export class PreviewCursor extends React.Component<PreviewCursorProps> { @action onPointerDown = (e: React.PointerEvent) => { - if (e.button == 0 && this.props.container.props.active()) { + if (e.button === 0 && this.props.container.props.active()) { document.removeEventListener("keypress", this.onKeyPress, false); this._showOnUp = true; this.DownX = e.pageX; diff --git a/src/client/views/nodes/Annotation.tsx b/src/client/views/nodes/Annotation.tsx index a2c7be1a8..e4f17940c 100644 --- a/src/client/views/nodes/Annotation.tsx +++ b/src/client/views/nodes/Annotation.tsx @@ -4,13 +4,13 @@ import { observer } from "mobx-react" import { observable, action } from 'mobx'; import 'react-pdf/dist/Page/AnnotationLayer.css' -interface IProps{ +interface IProps { Span: HTMLSpanElement; - X: number; - Y: number; - Highlights: any[]; - Annotations: any[]; - CurrAnno: any[]; + X: number; + Y: number; + Highlights: any[]; + Annotations: any[]; + CurrAnno: any[]; } @@ -23,95 +23,95 @@ interface IProps{ */ @observer export class Annotation extends React.Component<IProps> { - + /** * changes color of the span (highlighted section) */ - onColorChange = (e:React.PointerEvent) => { - if (e.currentTarget.innerHTML == "r"){ + onColorChange = (e: React.PointerEvent) => { + if (e.currentTarget.innerHTML === "r") { this.props.Span.style.backgroundColor = "rgba(255,0,0, 0.3)" - } else if (e.currentTarget.innerHTML == "b"){ + } else if (e.currentTarget.innerHTML === "b") { this.props.Span.style.backgroundColor = "rgba(0,255, 255, 0.3)" - } else if (e.currentTarget.innerHTML == "y"){ + } else if (e.currentTarget.innerHTML === "y") { this.props.Span.style.backgroundColor = "rgba(255,255,0, 0.3)" - } else if (e.currentTarget.innerHTML == "g"){ + } else if (e.currentTarget.innerHTML === "g") { this.props.Span.style.backgroundColor = "rgba(76, 175, 80, 0.3)" } - + } /** * removes the highlighted span. Supposed to remove Annotation too, but I don't know how to unmount this */ @action - onRemove = (e:any) => { - let index:number = -1; + onRemove = (e: any) => { + let index: number = -1; //finding the highlight in the highlight array this.props.Highlights.forEach((e) => { - for (let i = 0; i < e.spans.length; i++){ - if (e.spans[i] == this.props.Span){ - index = this.props.Highlights.indexOf(e); - this.props.Highlights.splice(index, 1); + for (const span of e.spans) { + if (span === this.props.Span) { + index = this.props.Highlights.indexOf(e); + this.props.Highlights.splice(index, 1); } } }) //removing from CurrAnno and Annotation array - this.props.Annotations.splice(index, 1); + this.props.Annotations.splice(index, 1); this.props.CurrAnno.pop() - + //removing span from div - if(this.props.Span.parentElement){ - let nodesArray = this.props.Span.parentElement.childNodes; + if (this.props.Span.parentElement) { + let nodesArray = this.props.Span.parentElement.childNodes; nodesArray.forEach((e) => { - if (e == this.props.Span){ - if (this.props.Span.parentElement){ + if (e === this.props.Span) { + if (this.props.Span.parentElement) { this.props.Highlights.forEach((item) => { - if (item == e){ - item.remove(); + if (item === e) { + item.remove(); } }) - e.remove(); + e.remove(); } } - }) + }) } - - + + } render() { return ( - <div - style = {{ - position: "absolute", - top: "20px", - left: "0px", - zIndex: 1, - transform: `translate(${this.props.X}px, ${this.props.Y}px)`, - - }}> - <div style = {{width:"200px", height:"50px", backgroundColor: "orange"}}> + <div + style={{ + position: "absolute", + top: "20px", + left: "0px", + zIndex: 1, + transform: `translate(${this.props.X}px, ${this.props.Y}px)`, + + }}> + <div style={{ width: "200px", height: "50px", backgroundColor: "orange" }}> <button - style = {{borderRadius: "25px", width:"25%", height:"100%"}} - onClick = {this.onRemove} + style={{ borderRadius: "25px", width: "25%", height: "100%" }} + onClick={this.onRemove} >x</button> - <div style = {{width:"75%", height: "100%" , display:"inline-block"}}> - <button onPointerDown = {this.onColorChange} style = {{backgroundColor:"red", borderRadius:"50%", color: "transparent"}}>r</button> - <button onPointerDown = {this.onColorChange} style = {{backgroundColor:"blue", borderRadius:"50%", color: "transparent"}}>b</button> - <button onPointerDown = {this.onColorChange} style = {{backgroundColor:"yellow", borderRadius:"50%", color:"transparent"}}>y</button> - <button onPointerDown = {this.onColorChange} style = {{backgroundColor:"green", borderRadius:"50%", color:"transparent"}}>g</button> + <div style={{ width: "75%", height: "100%", display: "inline-block" }}> + <button onPointerDown={this.onColorChange} style={{ backgroundColor: "red", borderRadius: "50%", color: "transparent" }}>r</button> + <button onPointerDown={this.onColorChange} style={{ backgroundColor: "blue", borderRadius: "50%", color: "transparent" }}>b</button> + <button onPointerDown={this.onColorChange} style={{ backgroundColor: "yellow", borderRadius: "50%", color: "transparent" }}>y</button> + <button onPointerDown={this.onColorChange} style={{ backgroundColor: "green", borderRadius: "50%", color: "transparent" }}>g</button> </div> - + </div> - <div style = {{width:"200px", height:"200"}}> - <textarea style = {{width: "100%", height: "100%"}} - defaultValue = "Enter Text Here..." - + <div style={{ width: "200px", height: "200" }}> + <textarea style={{ width: "100%", height: "100%" }} + defaultValue="Enter Text Here..." + ></textarea> </div> </div> - + ); } }
\ No newline at end of file diff --git a/src/client/views/nodes/AudioBox.tsx b/src/client/views/nodes/AudioBox.tsx index 6daf15f5f..1bd934c25 100644 --- a/src/client/views/nodes/AudioBox.tsx +++ b/src/client/views/nodes/AudioBox.tsx @@ -28,8 +28,8 @@ export class AudioBox extends React.Component<FieldViewProps> { render() { - let field = this.props.doc.Get(this.props.fieldKey) - let path = field == FieldWaiting ? "http://techslides.com/demos/samples/sample.mp3" : + let field = this.props.Document.Get(this.props.fieldKey) + let path = field === FieldWaiting ? "http://techslides.com/demos/samples/sample.mp3" : field instanceof AudioField ? field.Data.href : "http://techslides.com/demos/samples/sample.mp3"; return ( diff --git a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx index 1a0f0cbbd..dcf82ccd4 100644 --- a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx +++ b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx @@ -52,14 +52,12 @@ export class CollectionFreeFormDocumentView extends React.Component<DocumentView this.props.Document.SetData(KeyStore.ZIndex, h, NumberField) } - contentScaling = () => { - return this.nativeWidth > 0 ? this.width / this.nativeWidth : 1; - } + contentScaling = () => this.nativeWidth > 0 ? this.width / this.nativeWidth : 1 - getTransform = (): Transform => { - return this.props.ScreenToLocalTransform(). - translate(-this.props.Document.GetNumber(KeyStore.X, 0), -this.props.Document.GetNumber(KeyStore.Y, 0)).scale(1 / this.contentScaling()); - } + getTransform = (): Transform => + this.props.ScreenToLocalTransform() + .translate(-this.props.Document.GetNumber(KeyStore.X, 0), -this.props.Document.GetNumber(KeyStore.Y, 0)) + .scale(1 / this.contentScaling()) @computed get docView() { diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index 77551649c..34cc326aa 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -1,6 +1,6 @@ import { computed } from "mobx"; import { observer } from "mobx-react"; -import { FieldWaiting } from "../../../fields/Field"; +import { FieldWaiting, Field } from "../../../fields/Field"; import { Key } from "../../../fields/Key"; import { KeyStore } from "../../../fields/KeyStore"; import { ListField } from "../../../fields/ListField"; @@ -11,7 +11,7 @@ import { CollectionSchemaView } from "../collections/CollectionSchemaView"; import { CollectionVideoView } from "../collections/CollectionVideoView"; import { CollectionView } from "../collections/CollectionView"; import { AudioBox } from "./AudioBox"; -import { DocumentViewProps, JsxBindings } from "./DocumentView"; +import { DocumentViewProps } from "./DocumentView"; import "./DocumentView.scss"; import { FormattedTextBox } from "./FormattedTextBox"; import { ImageBox } from "./ImageBox"; @@ -21,8 +21,16 @@ import { VideoBox } from "./VideoBox"; import { WebBox } from "./WebBox"; import { HistogramBox } from "../../northstar/dash-nodes/HistogramBox"; import React = require("react"); +import { Document } from "../../../fields/Document"; +import { FieldViewProps } from "./FieldView"; +import { Without } from "../../../Utils"; const JsxParser = require('react-jsx-parser').default; //TODO Why does this need to be imported like this? +type BindingProps = Without<FieldViewProps, 'fieldKey'> +export interface JsxBindings { + props: BindingProps; + [keyName: string]: BindingProps | Field; +} @observer export class DocumentContentsView extends React.Component<DocumentViewProps & { @@ -36,13 +44,40 @@ export class DocumentContentsView extends React.Component<DocumentViewProps & { CreateBindings(): JsxBindings { - let bindings: JsxBindings = { ...this.props, }; + let + { + Document, + isSelected, + select, + isTopMost, + selectOnLoad, + ScreenToLocalTransform, + addDocument, + removeDocument, + onActiveChanged, + parentActive: active, + } = this.props; + let bindings: JsxBindings = { + props: { + Document, + isSelected, + select, + isTopMost, + selectOnLoad, + ScreenToLocalTransform, + active, + onActiveChanged, + addDocument, + removeDocument, + focus, + } + }; for (const key of this.layoutKeys) { bindings[key.Name + "Key"] = key; // this maps string values of the form <keyname>Key to an actual key Kestore.keyname e.g, "DataKey" => KeyStore.Data } for (const key of this.layoutFields) { let field = this.props.Document.Get(key); - bindings[key.Name] = field && field != FieldWaiting ? field.GetValue() : field; + bindings[key.Name] = field && field !== FieldWaiting ? field.GetValue() : field; } return bindings; } diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 7514e782d..ab9cd2d53 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -15,24 +15,28 @@ import { DragManager } from "../../util/DragManager"; import { SelectionManager } from "../../util/SelectionManager"; import { Transform } from "../../util/Transform"; import { CollectionDockingView } from "../collections/CollectionDockingView"; -import { CollectionView, CollectionViewType } from "../collections/CollectionView"; +import { CollectionView } from "../collections/CollectionView"; import { ContextMenu } from "../ContextMenu"; import { DocumentContentsView } from "./DocumentContentsView"; import "./DocumentView.scss"; import React = require("react"); + export interface DocumentViewProps { ContainingCollectionView: Opt<CollectionView>; Document: Document; - AddDocument?: (doc: Document, allowDuplicates: boolean) => boolean; - RemoveDocument?: (doc: Document) => boolean; + addDocument?: (doc: Document, allowDuplicates?: boolean) => boolean; + removeDocument?: (doc: Document) => boolean; + moveDocument?: (doc: Document, targetCollection: Document, addDocument: (document: Document) => boolean) => boolean; ScreenToLocalTransform: () => Transform; isTopMost: boolean; ContentScaling: () => number; PanelWidth: () => number; PanelHeight: () => number; focus: (doc: Document) => void; - SelectOnLoad: boolean; + selectOnLoad: boolean; + parentActive: () => boolean; + onActiveChanged: (isActive: boolean) => void; } export interface JsxArgs extends DocumentViewProps { Keys: { [name: string]: Key }; @@ -76,60 +80,20 @@ export function FakeJsxArgs(keys: string[], fields: string[] = []): JsxArgs { return args; } -export interface JsxBindings { - Document: Document; - isSelected: () => boolean; - select: (isCtrlPressed: boolean) => void; - isTopMost: boolean; - SelectOnLoad: boolean; - [prop: string]: any; -} - @observer export class DocumentView extends React.Component<DocumentViewProps> { private _mainCont = React.createRef<HTMLDivElement>(); + public get ContentRef() { + return this._mainCont; + } private _downX: number = 0; private _downY: number = 0; - - private _reactionDisposer: Opt<IReactionDisposer>; - @computed get active(): boolean { - return ( - SelectionManager.IsSelected(this) || - !this.props.ContainingCollectionView || - this.props.ContainingCollectionView.active() - ); - } - @computed get topMost(): boolean { - return ( - !this.props.ContainingCollectionView || - this.props.ContainingCollectionView.collectionViewType == - CollectionViewType.Docking - ); - } - @computed get layout(): string { - return this.props.Document.GetText( - KeyStore.Layout, - "<p>Error loading layout data</p>" - ); - } - @computed get layoutKeys(): Key[] { - return this.props.Document.GetData( - KeyStore.LayoutKeys, - ListField, - new Array<Key>() - ); - } - @computed get layoutFields(): Key[] { - return this.props.Document.GetData( - KeyStore.LayoutFields, - ListField, - new Array<Key>() - ); - } - screenRect = (): ClientRect | DOMRect => - this._mainCont.current - ? this._mainCont.current.getBoundingClientRect() - : new DOMRect(); + @computed get active(): boolean { return SelectionManager.IsSelected(this) || this.props.parentActive(); } + @computed get topMost(): boolean { return this.props.isTopMost; } + @computed get layout(): string { return this.props.Document.GetText(KeyStore.Layout, "<p>Error loading layout data</p>"); } + @computed get layoutKeys(): Key[] { return this.props.Document.GetData(KeyStore.LayoutKeys, ListField, new Array<Key>()); } + @computed get layoutFields(): Key[] { return this.props.Document.GetData(KeyStore.LayoutFields, ListField, new Array<Key>()); } + screenRect = (): ClientRect | DOMRect => this._mainCont.current ? this._mainCont.current.getBoundingClientRect() : new DOMRect(); onPointerDown = (e: React.PointerEvent): void => { this._downX = e.clientX; this._downY = e.clientY; @@ -159,20 +123,6 @@ export class DocumentView extends React.Component<DocumentViewProps> { }); } runInAction(() => DocumentManager.Instance.DocumentViews.push(this)); - this._reactionDisposer = reaction( - () => - this.props.ContainingCollectionView && - this.props.ContainingCollectionView.SelectedDocs.slice(), - () => { - if ( - this.props.ContainingCollectionView && - this.props.ContainingCollectionView.SelectedDocs.indexOf( - this.props.Document.Id - ) != -1 - ) - SelectionManager.SelectDoc(this, true); - } - ); } componentDidUpdate() { @@ -190,15 +140,7 @@ export class DocumentView extends React.Component<DocumentViewProps> { if (this.dropDisposer) { this.dropDisposer(); } - runInAction(() => - DocumentManager.Instance.DocumentViews.splice( - DocumentManager.Instance.DocumentViews.indexOf(this), - 1 - ) - ); - if (this._reactionDisposer) { - this._reactionDisposer(); - } + runInAction(() => DocumentManager.Instance.DocumentViews.splice(DocumentManager.Instance.DocumentViews.indexOf(this), 1)); } startDragging(x: number, y: number, dropAliasOfDraggedDoc: boolean) { @@ -211,14 +153,7 @@ export class DocumentView extends React.Component<DocumentViewProps> { dragData.aliasOnDrop = dropAliasOfDraggedDoc; dragData.xOffset = x - left; dragData.yOffset = y - top; - dragData.removeDocument = (dropCollectionView: CollectionView) => { - if ( - this.props.RemoveDocument && - this.props.ContainingCollectionView !== dropCollectionView - ) { - this.props.RemoveDocument(this.props.Document); - } - }; + dragData.moveDocument = this.props.moveDocument; DragManager.StartDocumentDrag([this._mainCont.current], dragData, x, y, { handlers: { dragComplete: action(() => { }) @@ -238,7 +173,7 @@ export class DocumentView extends React.Component<DocumentViewProps> { ) { document.removeEventListener("pointermove", this.onPointerMove); document.removeEventListener("pointerup", this.onPointerUp); - if (!this.topMost || e.buttons == 2 || e.altKey) { + if (!this.topMost || e.buttons === 2 || e.altKey) { this.startDragging(this._downX, this._downY, e.ctrlKey || e.altKey); } } @@ -261,17 +196,14 @@ export class DocumentView extends React.Component<DocumentViewProps> { }; deleteClicked = (): void => { - if (this.props.RemoveDocument) { - this.props.RemoveDocument(this.props.Document); + if (this.props.removeDocument) { + this.props.removeDocument(this.props.Document); } }; fieldsClicked = (e: React.MouseEvent): void => { - if (this.props.AddDocument) { - this.props.AddDocument( - Documents.KVPDocument(this.props.Document, { width: 300, height: 300 }), - false - ); + if (this.props.addDocument) { + this.props.addDocument(Documents.KVPDocument(this.props.Document, { width: 300, height: 300 }), false); } }; fullScreenClicked = (e: React.MouseEvent): void => { @@ -438,9 +370,7 @@ export class DocumentView extends React.Component<DocumentViewProps> { ); }; - isSelected = () => { - return SelectionManager.IsSelected(this); - }; + isSelected = () => SelectionManager.IsSelected(this) select = (ctrlPressed: boolean) => { SelectionManager.SelectDoc(this, ctrlPressed); diff --git a/src/client/views/nodes/FieldView.tsx b/src/client/views/nodes/FieldView.tsx index 4e83ec7b9..d9422ae9b 100644 --- a/src/client/views/nodes/FieldView.tsx +++ b/src/client/views/nodes/FieldView.tsx @@ -19,6 +19,7 @@ import { ListField } from "../../../fields/ListField"; import { DocumentContentsView } from "./DocumentContentsView"; import { Transform } from "../../util/Transform"; import { KeyStore } from "../../../fields/KeyStore"; +import { returnFalse } from "../../../Utils"; // @@ -28,23 +29,29 @@ import { KeyStore } from "../../../fields/KeyStore"; // export interface FieldViewProps { fieldKey: Key; - doc: Document; + Document: Document; isSelected: () => boolean; - select: () => void; + select: (isCtrlPressed: boolean) => void; isTopMost: boolean; selectOnLoad: boolean; - bindings: any; + addDocument?: (document: Document, allowDuplicates?: boolean) => boolean; + removeDocument?: (document: Document) => boolean; + moveDocument?: (document: Document, targetCollection: Document, addDocument: (document: Document) => boolean) => boolean; + ScreenToLocalTransform: () => Transform; + active: () => boolean; + onActiveChanged: (isActive: boolean) => void; + focus: (doc: Document) => void; } @observer export class FieldView extends React.Component<FieldViewProps> { public static LayoutString(fieldType: { name: string }, fieldStr: string = "DataKey") { - return `<${fieldType.name} doc={Document} DocumentViewForField={DocumentView} bindings={bindings} fieldKey={${fieldStr}} isSelected={isSelected} select={select} selectOnLoad={SelectOnLoad} isTopMost={isTopMost} />`; + return `<${fieldType.name} {...props} fieldKey={${fieldStr}} />`; } @computed get field(): FieldValue<Field> { - const { doc, fieldKey } = this.props; + const { Document: doc, fieldKey } = this.props; return doc.Get(fieldKey); } render() { @@ -68,26 +75,28 @@ export class FieldView extends React.Component<FieldViewProps> { return <AudioBox {...this.props} /> } else if (field instanceof Document) { - return (<DocumentContentsView Document={field} - AddDocument={undefined} - RemoveDocument={undefined} - ScreenToLocalTransform={() => Transform.Identity} - ContentScaling={() => 1} - PanelWidth={() => 100} - PanelHeight={() => 100} - isTopMost={true} - SelectOnLoad={false} - focus={() => { }} - isSelected={() => false} - select={() => false} - layoutKey={KeyStore.Layout} - ContainingCollectionView={undefined} />) + return ( + <DocumentContentsView Document={field} + addDocument={undefined} + removeDocument={undefined} + ScreenToLocalTransform={Transform.Identity} + ContentScaling={() => 1} + PanelWidth={() => 100} + PanelHeight={() => 100} + isTopMost={true} //TODO Why is this top most? + selectOnLoad={false} + focus={() => { }} + isSelected={() => false} + select={() => false} + layoutKey={KeyStore.Layout} + ContainingCollectionView={undefined} + parentActive={this.props.active} + onActiveChanged={this.props.onActiveChanged} /> + ) } else if (field instanceof ListField) { return (<div> - {(field as ListField<Field>).Data.map(f => { - return f instanceof Document ? f.Title : f.GetValue().toString(); - }).join(", ")} + {(field as ListField<Field>).Data.map(f => f instanceof Document ? f.Title : f.GetValue().toString()).join(", ")} </div>) } // bcz: this belongs here, but it doesn't render well so taking it out for now @@ -97,7 +106,7 @@ export class FieldView extends React.Component<FieldViewProps> { else if (field instanceof NumberField) { return <p>{field.Data}</p> } - else if (field != FieldWaiting) { + else if (field !== FieldWaiting) { return <p>{JSON.stringify(field.GetValue())}</p> } else diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index e59179874..ebac61c78 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -63,7 +63,7 @@ export class FormattedTextBox extends React.Component<FieldViewProps> { } }; - get FieldDoc() { return this.props.fieldKey === KeyStore.Archives ? Main.Instance._textDoc! : this.props.doc; } + get FieldDoc() { return this.props.fieldKey === KeyStore.Archives ? Main.Instance._textDoc! : this.props.Document; } get FieldKey() { return this.props.fieldKey === KeyStore.Archives ? KeyStore.Data : this.props.fieldKey; } componentDidMount() { @@ -92,7 +92,7 @@ export class FormattedTextBox extends React.Component<FieldViewProps> { this._reactionDisposer = reaction( () => { const field = this.FieldDoc.GetT(this.FieldKey, RichTextField); - return field && field != FieldWaiting ? field.Data : undefined; + return field && field !== FieldWaiting ? field.Data : undefined; }, field => { if (field && this._editorView) { @@ -109,7 +109,7 @@ export class FormattedTextBox extends React.Component<FieldViewProps> { let state: EditorState; let field = this.FieldDoc.GetT(this.FieldKey, RichTextField); - if (field && field != FieldWaiting && field.Data) { + if (field && field !== FieldWaiting && field.Data) { state = EditorState.fromJSON(config, JSON.parse(field.Data)); } else { state = EditorState.create(config); @@ -122,7 +122,7 @@ export class FormattedTextBox extends React.Component<FieldViewProps> { } if (this.props.selectOnLoad) { - this.props.select(); + this.props.select(false); this._editorView!.focus(); } } @@ -145,8 +145,8 @@ export class FormattedTextBox extends React.Component<FieldViewProps> { @action onChange(e: React.ChangeEvent<HTMLInputElement>) { - const { fieldKey, doc } = this.props; - doc.SetOnPrototype(fieldKey, new RichTextField(e.target.value)); + const { fieldKey, Document } = this.props; + Document.SetOnPrototype(fieldKey, new RichTextField(e.target.value)); // doc.SetData(fieldKey, e.target.value, RichTextField); } onPointerDown = (e: React.PointerEvent): void => { @@ -162,13 +162,13 @@ export class FormattedTextBox extends React.Component<FieldViewProps> { } if (this.props.fieldKey !== KeyStore.Archives) { e.preventDefault(); - Main.Instance.SetTextDoc(this.props.doc, this._ref.current!); + Main.Instance.SetTextDoc(this.props.Document, this._ref.current!); } }; onFocused = (e: React.FocusEvent): void => { if (this.props.fieldKey !== KeyStore.Archives) { - Main.Instance.SetTextDoc(this.props.doc, this._ref.current!); + Main.Instance.SetTextDoc(this.props.Document, this._ref.current!); } } diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index 60d1f7214..c5f29f7b0 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -39,7 +39,7 @@ export class ImageBox extends React.Component<FieldViewProps> { onLoad = (target: any) => { var h = this._imgRef.current!.naturalHeight; var w = this._imgRef.current!.naturalWidth; - this.props.doc.SetNumber(KeyStore.NativeHeight, this.props.doc.GetNumber(KeyStore.NativeWidth, 0) * h / w) + this.props.Document.SetNumber(KeyStore.NativeHeight, this.props.Document.GetNumber(KeyStore.NativeWidth, 0) * h / w) } componentDidMount() { @@ -91,7 +91,7 @@ export class ImageBox extends React.Component<FieldViewProps> { } specificContextMenu = (e: React.MouseEvent): void => { - let field = this.props.doc.GetT(this.props.fieldKey, ImageField); + let field = this.props.Document.GetT(this.props.fieldKey, ImageField); if (field && field !== FieldWaiting) { let url = field.Data.href; ContextMenu.Instance.addItem({ @@ -103,10 +103,10 @@ export class ImageBox extends React.Component<FieldViewProps> { } render() { - let field = this.props.doc.Get(this.props.fieldKey); - let path = field == FieldWaiting ? "https://image.flaticon.com/icons/svg/66/66163.svg" : + let field = this.props.Document.Get(this.props.fieldKey); + let path = field === FieldWaiting ? "https://image.flaticon.com/icons/svg/66/66163.svg" : field instanceof ImageField ? field.Data.href : "http://www.cs.brown.edu/~bcz/face.gif"; - let nativeWidth = this.props.doc.GetNumber(KeyStore.NativeWidth, 1); + let nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 1); return ( <div className="imageBox-cont" onPointerDown={this.onPointerDown} ref={this._ref} onContextMenu={this.specificContextMenu}> <img src={path} width={nativeWidth} alt="Image not found" ref={this._imgRef} onLoad={this.onLoad} /> diff --git a/src/client/views/nodes/KeyValueBox.tsx b/src/client/views/nodes/KeyValueBox.tsx index 9bd6c1052..8a7f32e6d 100644 --- a/src/client/views/nodes/KeyValueBox.tsx +++ b/src/client/views/nodes/KeyValueBox.tsx @@ -32,10 +32,10 @@ export class KeyValueBox extends React.Component<FieldViewProps> { @action onEnterKey = (e: React.KeyboardEvent): void => { - if (e.key == 'Enter') { + if (e.key === 'Enter') { if (this._keyInput && this._valueInput) { - let doc = this.props.doc.GetT(KeyStore.Data, Document); - if (!doc || doc == FieldWaiting) { + let doc = this.props.Document.GetT(KeyStore.Data, Document); + if (!doc || doc === FieldWaiting) { return } let realDoc = doc; @@ -71,8 +71,8 @@ export class KeyValueBox extends React.Component<FieldViewProps> { } createTable = () => { - let doc = this.props.doc.GetT(KeyStore.Data, Document); - if (!doc || doc == FieldWaiting) { + let doc = this.props.Document.GetT(KeyStore.Data, Document); + if (!doc || doc === FieldWaiting) { return <tr><td>Loading...</td></tr> } let realDoc = doc; @@ -105,14 +105,13 @@ export class KeyValueBox extends React.Component<FieldViewProps> { this._valueInput = e.currentTarget.value; } - newKeyValue = () => { - return ( + newKeyValue = () => + ( <tr> <td><input type="text" value={this._keyInput} placeholder="Key" onChange={this.keyChanged} /></td> <td><input type="text" value={this._valueInput} placeholder="Value" onChange={this.valueChanged} onKeyPress={this.onEnterKey} /></td> </tr> ) - } render() { return (<div className="keyValueBox-cont" onWheel={this.onPointerWheel}> diff --git a/src/client/views/nodes/KeyValuePair.tsx b/src/client/views/nodes/KeyValuePair.tsx index 5647f45bf..c6a0a7296 100644 --- a/src/client/views/nodes/KeyValuePair.tsx +++ b/src/client/views/nodes/KeyValuePair.tsx @@ -11,6 +11,8 @@ import { Key } from '../../../fields/Key'; import { Server } from "../../Server" import { EditableView } from "../EditableView"; import { CompileScript, ToField } from "../../util/Scripting"; +import { Transform } from '../../util/Transform'; +import { returnFalse, emptyFunction } from '../../../Utils'; // Represents one row in a key value plane @@ -43,13 +45,16 @@ export class KeyValuePair extends React.Component<KeyValuePairProps> { } let props: FieldViewProps = { - doc: this.props.doc, + Document: this.props.doc, fieldKey: this.key, - isSelected: () => false, - select: () => { }, + isSelected: returnFalse, + select: emptyFunction, isTopMost: false, - bindings: {}, selectOnLoad: false, + active: returnFalse, + onActiveChanged: emptyFunction, + ScreenToLocalTransform: Transform.Identity, + focus: emptyFunction, } let contents = ( <FieldView {...props} /> @@ -61,15 +66,15 @@ export class KeyValuePair extends React.Component<KeyValuePairProps> { <div className="container"> <div>{this.key.Name}</div> <button className="delete" onClick={() => { - let field = props.doc.Get(props.fieldKey); + let field = props.Document.Get(props.fieldKey); if (field && field instanceof Field) { - props.doc.Set(props.fieldKey, undefined); + props.Document.Set(props.fieldKey, undefined); } }}>X</button> </div> </td> <td><EditableView contents={contents} height={36} GetValue={() => { - let field = props.doc.Get(props.fieldKey); + let field = props.Document.Get(props.fieldKey); if (field && field instanceof Field) { return field.ToScriptString(); } @@ -84,12 +89,12 @@ export class KeyValuePair extends React.Component<KeyValuePairProps> { if (!res.success) return false; const field = res.result; if (field instanceof Field) { - props.doc.Set(props.fieldKey, field); + props.Document.Set(props.fieldKey, field); return true; } else { let dataField = ToField(field); if (dataField) { - props.doc.Set(props.fieldKey, dataField); + props.Document.Set(props.fieldKey, dataField); return true; } } diff --git a/src/client/views/nodes/LinkBox.tsx b/src/client/views/nodes/LinkBox.tsx index e81f8fec7..4791d6029 100644 --- a/src/client/views/nodes/LinkBox.tsx +++ b/src/client/views/nodes/LinkBox.tsx @@ -49,7 +49,7 @@ export class LinkBox extends React.Component<Props> { } else if (contextDoc instanceof Document) { this.props.pairedDoc.GetTAsync(KeyStore.Page, NumberField).then((pfield: any) => { contextDoc.GetTAsync(KeyStore.CurPage, NumberField).then((cfield: any) => { - if (pfield != cfield) + if (pfield !== cfield) contextDoc.SetNumber(KeyStore.CurPage, pfield.Data); let contextView = DocumentManager.Instance.getDocumentView(contextDoc); if (contextView) { diff --git a/src/client/views/nodes/LinkMenu.tsx b/src/client/views/nodes/LinkMenu.tsx index 5eeb40772..6c2d24630 100644 --- a/src/client/views/nodes/LinkMenu.tsx +++ b/src/client/views/nodes/LinkMenu.tsx @@ -24,7 +24,7 @@ export class LinkMenu extends React.Component<Props> { renderLinkItems(links: Document[], key: Key, type: string) { return links.map(link => { let doc = link.GetT(key, Document); - if (doc && doc != FieldWaiting) { + if (doc && doc !== FieldWaiting) { return <LinkBox key={doc.Id} linkDoc={link} linkName={link.Title} pairedDoc={doc} showEditor={action(() => this._editingLink = link)} type={type} /> } }) diff --git a/src/client/views/nodes/PDFBox.tsx b/src/client/views/nodes/PDFBox.tsx index 7039b0c41..774d9be3e 100644 --- a/src/client/views/nodes/PDFBox.tsx +++ b/src/client/views/nodes/PDFBox.tsx @@ -89,14 +89,14 @@ export class PDFBox extends React.Component<FieldViewProps> { @observable private _interactive: boolean = false; @observable private _loaded: boolean = false; - @computed private get curPage() { return this.props.doc.GetNumber(KeyStore.CurPage, 1); } - @computed private get thumbnailPage() { return this.props.doc.GetNumber(KeyStore.ThumbnailPage, -1); } + @computed private get curPage() { return this.props.Document.GetNumber(KeyStore.CurPage, 1); } + @computed private get thumbnailPage() { return this.props.Document.GetNumber(KeyStore.ThumbnailPage, -1); } componentDidMount() { this._reactionDisposer = reaction( () => [SelectionManager.SelectedDocuments().slice()], () => { - if (this.curPage > 0 && this.thumbnailPage > 0 && this.curPage != this.thumbnailPage && !this.props.isSelected()) { + if (this.curPage > 0 && this.thumbnailPage > 0 && this.curPage !== this.thumbnailPage && !this.props.isSelected()) { this.saveThumbnail(); this._interactive = true; } @@ -167,16 +167,16 @@ export class PDFBox extends React.Component<FieldViewProps> { let obj: Object = { parentDivs: [], spans: [] }; //@ts-ignore - if (range.commonAncestorContainer.className == 'react-pdf__Page__textContent') { //multiline highlighting case + if (range.commonAncestorContainer.className === 'react-pdf__Page__textContent') { //multiline highlighting case obj = this.highlightNodes(range.commonAncestorContainer.childNodes) } else { //single line highlighting case let parentDiv = range.commonAncestorContainer.parentElement if (parentDiv) { - if (parentDiv.className == 'react-pdf__Page__textContent') { //when highlight is overwritten + if (parentDiv.className === 'react-pdf__Page__textContent') { //when highlight is overwritten obj = this.highlightNodes(parentDiv.childNodes) } else { parentDiv.childNodes.forEach((child) => { - if (child.nodeName == 'SPAN') { + if (child.nodeName === 'SPAN') { //@ts-ignore obj.parentDivs.push(parentDiv) //@ts-ignore @@ -199,7 +199,7 @@ export class PDFBox extends React.Component<FieldViewProps> { let temp = { parentDivs: [], spans: [] } nodes.forEach((div) => { div.childNodes.forEach((child) => { - if (child.nodeName == 'SPAN') { + if (child.nodeName === 'SPAN') { //@ts-ignore temp.parentDivs.push(div) //@ts-ignore @@ -223,7 +223,7 @@ export class PDFBox extends React.Component<FieldViewProps> { let index: any; this._pageInfo.divs.forEach((obj: any) => { obj.spans.forEach((element: any) => { - if (element == span) { + if (element === span) { if (!index) { index = this._pageInfo.divs.indexOf(obj); } @@ -232,11 +232,11 @@ export class PDFBox extends React.Component<FieldViewProps> { }) if (this._pageInfo.anno.length >= index + 1) { - if (this._currAnno.length == 0) { + if (this._currAnno.length === 0) { this._currAnno.push(this._pageInfo.anno[index]); } } else { - if (this._currAnno.length == 0) { //if there are no current annotation + if (this._currAnno.length === 0) { //if there are no current annotation let div = span.offsetParent; //@ts-ignore let divX = div.style.left @@ -317,7 +317,7 @@ export class PDFBox extends React.Component<FieldViewProps> { * starts drawing the line when user presses down. */ onDraw = () => { - if (this._currTool != null) { + if (this._currTool !== null) { this._currTool.style.backgroundColor = "grey"; } @@ -342,13 +342,13 @@ export class PDFBox extends React.Component<FieldViewProps> { * for changing color (for ink/pen) */ onColorChange = (e: React.PointerEvent) => { - if (e.currentTarget.innerHTML == "Red") { + if (e.currentTarget.innerHTML === "Red") { this._currColor = "red"; - } else if (e.currentTarget.innerHTML == "Blue") { + } else if (e.currentTarget.innerHTML === "Blue") { this._currColor = "blue"; - } else if (e.currentTarget.innerHTML == "Green") { + } else if (e.currentTarget.innerHTML === "Green") { this._currColor = "green"; - } else if (e.currentTarget.innerHTML == "Black") { + } else if (e.currentTarget.innerHTML === "Black") { this._currColor = "black"; } @@ -360,7 +360,7 @@ export class PDFBox extends React.Component<FieldViewProps> { */ onHighlight = () => { this._drawToolOn = false; - if (this._currTool != null) { + if (this._currTool !== null) { this._currTool.style.backgroundColor = "grey"; } if (this._highlightTool.current) { @@ -381,12 +381,12 @@ export class PDFBox extends React.Component<FieldViewProps> { this._renderAsSvg = false; setTimeout(() => { var me = this; - let nwidth = me.props.doc.GetNumber(KeyStore.NativeWidth, 0); - let nheight = me.props.doc.GetNumber(KeyStore.NativeHeight, 0); + let nwidth = me.props.Document.GetNumber(KeyStore.NativeWidth, 0); + let nheight = me.props.Document.GetNumber(KeyStore.NativeHeight, 0); htmlToImage.toPng(this._mainDiv.current!, { width: nwidth, height: nheight, quality: 1 }) .then(action((dataUrl: string) => { - me.props.doc.SetData(KeyStore.Thumbnail, new URL(dataUrl), ImageField); - me.props.doc.SetNumber(KeyStore.ThumbnailPage, me.props.doc.GetNumber(KeyStore.CurPage, -1)); + me.props.Document.SetData(KeyStore.Thumbnail, new URL(dataUrl), ImageField); + me.props.Document.SetNumber(KeyStore.ThumbnailPage, me.props.Document.GetNumber(KeyStore.CurPage, -1)); me._renderAsSvg = true; })) .catch(function (error: any) { @@ -399,7 +399,7 @@ export class PDFBox extends React.Component<FieldViewProps> { onLoaded = (page: any) => { if (this._mainDiv.current) { this._mainDiv.current.childNodes.forEach((element) => { - if (element.nodeName == "DIV") { + if (element.nodeName === "DIV") { element.childNodes[0].childNodes.forEach((e) => { if (e instanceof HTMLCanvasElement) { @@ -414,8 +414,8 @@ export class PDFBox extends React.Component<FieldViewProps> { } // bcz: the number of pages should really be set when the document is imported. - this.props.doc.SetNumber(KeyStore.NumPages, page._transport.numPages); - if (this._perPageInfo.length == 0) { //Makes sure it only runs once + this.props.Document.SetNumber(KeyStore.NumPages, page._transport.numPages); + if (this._perPageInfo.length === 0) { //Makes sure it only runs once this._perPageInfo = [...Array(page._transport.numPages)] } this._loaded = true; @@ -426,11 +426,11 @@ export class PDFBox extends React.Component<FieldViewProps> { // bcz: the nativeHeight should really be set when the document is imported. // also, the native dimensions could be different for different pages of the PDF // so this design is flawed. - var nativeWidth = this.props.doc.GetNumber(KeyStore.NativeWidth, 0); - if (!this.props.doc.GetNumber(KeyStore.NativeHeight, 0)) { + var nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 0); + if (!this.props.Document.GetNumber(KeyStore.NativeHeight, 0)) { var nativeHeight = nativeWidth * r.entry.height / r.entry.width; - this.props.doc.SetNumber(KeyStore.Height, nativeHeight / nativeWidth * this.props.doc.GetNumber(KeyStore.Width, 0)); - this.props.doc.SetNumber(KeyStore.NativeHeight, nativeHeight); + this.props.Document.SetNumber(KeyStore.Height, nativeHeight / nativeWidth * this.props.Document.GetNumber(KeyStore.Width, 0)); + this.props.Document.SetNumber(KeyStore.NativeHeight, nativeHeight); } } @@ -438,8 +438,8 @@ export class PDFBox extends React.Component<FieldViewProps> { get pdfContent() { let page = this.curPage; const renderHeight = 2400; - let pdfUrl = this.props.doc.GetT(this.props.fieldKey, PDFField); - let xf = this.props.doc.GetNumber(KeyStore.NativeHeight, 0) / renderHeight; + let pdfUrl = this.props.Document.GetT(this.props.fieldKey, PDFField); + let xf = this.props.Document.GetNumber(KeyStore.NativeHeight, 0) / renderHeight; return <div className="pdfBox-contentContainer" key="container" style={{ transform: `scale(${xf}, ${xf})` }}> <Document file={window.origin + RouteStore.corsProxy + `/${pdfUrl}`} renderMode={this._renderAsSvg ? "svg" : ""}> <Measure onResize={this.setScaling}> @@ -456,8 +456,8 @@ export class PDFBox extends React.Component<FieldViewProps> { @computed get pdfRenderer() { let proxy = this._loaded ? (null) : this.imageProxyRenderer; - let pdfUrl = this.props.doc.GetT(this.props.fieldKey, PDFField); - if ((!this._interactive && proxy) || !pdfUrl || pdfUrl == FieldWaiting) { + let pdfUrl = this.props.Document.GetT(this.props.fieldKey, PDFField); + if ((!this._interactive && proxy) || !pdfUrl || pdfUrl === FieldWaiting) { return proxy; } return [ @@ -470,9 +470,9 @@ export class PDFBox extends React.Component<FieldViewProps> { @computed get imageProxyRenderer() { - let thumbField = this.props.doc.Get(KeyStore.Thumbnail); + let thumbField = this.props.Document.Get(KeyStore.Thumbnail); if (thumbField) { - let path = thumbField == FieldWaiting || this.thumbnailPage != this.curPage ? "https://image.flaticon.com/icons/svg/66/66163.svg" : + let path = thumbField === FieldWaiting || this.thumbnailPage !== this.curPage ? "https://image.flaticon.com/icons/svg/66/66163.svg" : thumbField instanceof ImageField ? thumbField.Data.href : "http://cs.brown.edu/people/bcz/prairie.jpg"; return <img src={path} width="100%" />; } diff --git a/src/client/views/nodes/VideoBox.tsx b/src/client/views/nodes/VideoBox.tsx index 7c0db83a8..a08b320e8 100644 --- a/src/client/views/nodes/VideoBox.tsx +++ b/src/client/views/nodes/VideoBox.tsx @@ -20,7 +20,7 @@ export class VideoBox extends React.Component<FieldViewProps> { super(props); } - @computed private get curPage() { return this.props.doc.GetNumber(KeyStore.CurPage, -1); } + @computed private get curPage() { return this.props.Document.GetNumber(KeyStore.CurPage, -1); } _loaded: boolean = false; @@ -31,12 +31,12 @@ export class VideoBox extends React.Component<FieldViewProps> { // bcz: the nativeHeight should really be set when the document is imported. // also, the native dimensions could be different for different pages of the PDF // so this design is flawed. - var nativeWidth = this.props.doc.GetNumber(KeyStore.NativeWidth, 0); - var nativeHeight = this.props.doc.GetNumber(KeyStore.NativeHeight, 0); + var nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 0); + var nativeHeight = this.props.Document.GetNumber(KeyStore.NativeHeight, 0); var newNativeHeight = nativeWidth * r.entry.height / r.entry.width; - if (!nativeHeight && newNativeHeight != nativeHeight && !isNaN(newNativeHeight)) { - this.props.doc.SetNumber(KeyStore.Height, newNativeHeight / nativeWidth * this.props.doc.GetNumber(KeyStore.Width, 0)); - this.props.doc.SetNumber(KeyStore.NativeHeight, newNativeHeight); + if (!nativeHeight && newNativeHeight !== nativeHeight && !isNaN(newNativeHeight)) { + this.props.Document.SetNumber(KeyStore.Height, newNativeHeight / nativeWidth * this.props.Document.GetNumber(KeyStore.Width, 0)); + this.props.Document.SetNumber(KeyStore.NativeHeight, newNativeHeight); } } else { this._loaded = true; @@ -50,13 +50,13 @@ export class VideoBox extends React.Component<FieldViewProps> { @action setVideoRef = (vref: HTMLVideoElement | null) => { if (this.curPage >= 0 && vref) { - vref!.currentTime = this.curPage; - (vref! as any).AHackBecauseSomethingResetsTheVideoToZero = this.curPage; + vref.currentTime = this.curPage; + (vref as any).AHackBecauseSomethingResetsTheVideoToZero = this.curPage; } } render() { - let field = this.props.doc.GetT(this.props.fieldKey, VideoField); + let field = this.props.Document.GetT(this.props.fieldKey, VideoField); if (!field || field === FieldWaiting) { return <div>Loading</div> } diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx index 2ca8d49ce..c1d389001 100644 --- a/src/client/views/nodes/WebBox.tsx +++ b/src/client/views/nodes/WebBox.tsx @@ -16,11 +16,11 @@ export class WebBox extends React.Component<FieldViewProps> { super(props); } - @computed get html(): string { return this.props.doc.GetHtml(KeyStore.Data, ""); } + @computed get html(): string { return this.props.Document.GetHtml(KeyStore.Data, ""); } render() { - let field = this.props.doc.Get(this.props.fieldKey); - let path = field == FieldWaiting ? "https://image.flaticon.com/icons/svg/66/66163.svg" : + let field = this.props.Document.Get(this.props.fieldKey); + let path = field === FieldWaiting ? "https://image.flaticon.com/icons/svg/66/66163.svg" : field instanceof WebField ? field.Data.href : "https://crossorigin.me/" + "https://cs.brown.edu"; let content = this.html ? diff --git a/src/debug/Viewer.tsx b/src/debug/Viewer.tsx index 7fdd77bf3..f13cccd24 100644 --- a/src/debug/Viewer.tsx +++ b/src/debug/Viewer.tsx @@ -87,7 +87,7 @@ class DocumentViewer extends React.Component<{ field: Document }> { return ( <div key={kv[0]}> <b>({key ? key.Name : kv[0]}): </b> - <DebugViewer fieldId={kv[1]!}></DebugViewer> + <DebugViewer fieldId={kv[1]}></DebugViewer> </div> ) }) @@ -177,9 +177,7 @@ class Viewer extends React.Component { onChange={this.inputOnChange} onKeyDown={this.onKeyPress} /> <div> - {this.ids.map(id => { - return <DebugViewer fieldId={id} key={id}></DebugViewer> - })} + {this.ids.map(id => <DebugViewer fieldId={id} key={id}></DebugViewer>)} </div> </> ) diff --git a/src/fields/AudioField.ts b/src/fields/AudioField.ts index 8864471ae..252a5b74e 100644 --- a/src/fields/AudioField.ts +++ b/src/fields/AudioField.ts @@ -4,7 +4,7 @@ import { Types } from "../server/Message"; export class AudioField extends BasicField<URL> { constructor(data: URL | undefined = undefined, id?: FieldId, save: boolean = true) { - super(data == undefined ? new URL("http://techslides.com/demos/samples/sample.mp3") : data, save, id); + super(data === undefined ? new URL("http://techslides.com/demos/samples/sample.mp3") : data, save, id); } toString(): string { diff --git a/src/fields/BasicField.ts b/src/fields/BasicField.ts index a92c4a236..3083a1937 100644 --- a/src/fields/BasicField.ts +++ b/src/fields/BasicField.ts @@ -46,7 +46,7 @@ export abstract class BasicField<T> extends Field { @action TrySetValue(value: any): boolean { - if (typeof value == typeof this.data) { + if (typeof value === typeof this.data) { this.Data = value; return true; } diff --git a/src/fields/Document.ts b/src/fields/Document.ts index 02004678d..4fa478f32 100644 --- a/src/fields/Document.ts +++ b/src/fields/Document.ts @@ -37,33 +37,20 @@ export class Document extends Field { } } - public Width = () => { - return this.GetNumber(KeyStore.Width, 0); - }; - public Height = () => { - return this.GetNumber( - KeyStore.Height, - this.GetNumber(KeyStore.NativeWidth, 0) - ? (this.GetNumber(KeyStore.NativeHeight, 0) / - this.GetNumber(KeyStore.NativeWidth, 0)) * - this.GetNumber(KeyStore.Width, 0) - : 0 - ); - }; - public Scale = () => { - return this.GetNumber(KeyStore.Scale, 1); - }; + public Width = () => this.GetNumber(KeyStore.Width, 0) + public Height = () => this.GetNumber(KeyStore.Height, this.GetNumber(KeyStore.NativeWidth, 0) ? (this.GetNumber(KeyStore.NativeHeight, 0) / this.GetNumber(KeyStore.NativeWidth, 0)) * this.GetNumber(KeyStore.Width, 0) : 0); + public Scale = () => this.GetNumber(KeyStore.Scale, 1) @computed public get Title(): string { let title = this.Get(KeyStore.Title, true); if (title) - if (title != FieldWaiting && title instanceof TextField) + if (title !== FieldWaiting && title instanceof TextField) return title.Data; else return "-waiting-"; let parTitle = this.GetT(KeyStore.Title, TextField); if (parTitle) - if (parTitle != FieldWaiting) return parTitle.Data + ".alias"; + if (parTitle !== FieldWaiting) return parTitle.Data + ".alias"; else return "-waiting-.alias"; return "-untitled-"; } @@ -109,7 +96,7 @@ export class Document extends Field { } } else { let doc: FieldValue<Document> = this; - while (doc && doc != FieldWaiting && field != FieldWaiting) { + while (doc && field !== FieldWaiting) { let curField = doc.fields.get(key.Id); let curProxy = doc._proxies.get(key.Id); if (!curField || (curProxy && curField.field.Id !== curProxy)) { @@ -140,7 +127,7 @@ export class Document extends Field { break; } } - if (doc == FieldWaiting) field = FieldWaiting; + if (doc === FieldWaiting) field = FieldWaiting; } return field; @@ -194,7 +181,7 @@ export class Document extends Field { if (callback) { fn(callback); } else { - return new Promise(res => fn(res)); + return new Promise(fn); } } @@ -240,7 +227,7 @@ export class Document extends Field { ignoreProto: boolean = false ): FieldValue<T> { var getfield = this.Get(key, ignoreProto); - if (getfield != FieldWaiting) { + if (getfield !== FieldWaiting) { return Cast(getfield, ctor); } return FieldWaiting; @@ -252,7 +239,7 @@ export class Document extends Field { ignoreProto: boolean = false ): T { const field = this.GetT(key, ctor, ignoreProto); - if (field && field != FieldWaiting) { + if (field && field !== FieldWaiting) { return field; } const newField = new ctor(); @@ -362,7 +349,7 @@ export class Document extends Field { GetAllPrototypes(): Document[] { let protos: Document[] = []; let doc: FieldValue<Document> = this; - while (doc && doc != FieldWaiting) { + while (doc && doc !== FieldWaiting) { protos.push(doc); doc = doc.GetPrototype(); } @@ -425,7 +412,7 @@ export class Document extends Field { let fields: [string, string][] = []; this._proxies.forEach((field, key) => { if (field) { - fields.push([key, field as string]); + fields.push([key, field]); } }); diff --git a/src/fields/Field.ts b/src/fields/Field.ts index d48509a47..0d0e56f77 100644 --- a/src/fields/Field.ts +++ b/src/fields/Field.ts @@ -12,8 +12,8 @@ export function Cast<T extends Field>(field: FieldValue<Field>, ctor: { new(): T return undefined; } -export const FieldWaiting: FIELD_WAITING = "<Waiting>"; -export type FIELD_WAITING = "<Waiting>"; +export const FieldWaiting: FIELD_WAITING = null; +export type FIELD_WAITING = null; export type FieldId = string; export type Opt<T> = T | undefined; export type FieldValue<T> = Opt<T> | FIELD_WAITING; diff --git a/src/fields/ImageField.ts b/src/fields/ImageField.ts index a9ece7d7b..ef616b2ad 100644 --- a/src/fields/ImageField.ts +++ b/src/fields/ImageField.ts @@ -4,7 +4,7 @@ import { Types } from "../server/Message"; export class ImageField extends BasicField<URL> { constructor(data: URL | undefined = undefined, id?: FieldId, save: boolean = true) { - super(data == undefined ? new URL("http://cs.brown.edu/~bcz/bob_fettucine.jpg") : data, save, id); + super(data === undefined ? new URL("http://cs.brown.edu/~bcz/bob_fettucine.jpg") : data, save, id); } toString(): string { diff --git a/src/fields/KeyStore.ts b/src/fields/KeyStore.ts index 42dc34c51..e24e9c8ec 100644 --- a/src/fields/KeyStore.ts +++ b/src/fields/KeyStore.ts @@ -55,11 +55,10 @@ export namespace KeyStore { Archives, Workspaces, Minimized, CopyDraggedItems ]; export function KeyLookup(keyid: string) { - for (let i = 0; i < KeyList.length; i++) { - let keylistid = KeyList[i].Id; - if (keylistid === keyid) - return KeyList[i]; + for (const key of KeyList) { + if (key.Id === keyid) + return key; } - return null; + return undefined; } } diff --git a/src/fields/ListField.ts b/src/fields/ListField.ts index c4008bd12..815a3df73 100644 --- a/src/fields/ListField.ts +++ b/src/fields/ListField.ts @@ -26,7 +26,7 @@ export class ListField<T extends Field> extends BasicField<T[]> { } this.observeDisposer = observe(this.Data as IObservableArray<T>, (change: IArrayChange<T> | IArraySplice<T>) => { this.updateProxies() - if (change.type == "splice") { + if (change.type === "splice") { UndoManager.AddEvent({ undo: () => this.Data.splice(change.index, change.addedCount, ...change.removed), redo: () => this.Data.splice(change.index, change.removedCount, ...change.added) @@ -57,8 +57,8 @@ export class ListField<T extends Field> extends BasicField<T[]> { } private arraysEqual(a: any[], b: any[]) { if (a === b) return true; - if (a == null || b == null) return false; - if (a.length != b.length) return false; + if (a === null || b === null) return false; + if (a.length !== b.length) return false; // If you don't care about the order of the elements inside // the array, you should sort both arrays here. @@ -79,9 +79,9 @@ export class ListField<T extends Field> extends BasicField<T[]> { var added = this.data.length < this._proxies.length; var deleted = this.data.length > this._proxies.length; for (let i = 0; i < dataids.length && added; i++) - added = proxies.indexOf(dataids[i]) != -1; + added = proxies.indexOf(dataids[i]) !== -1; for (let i = 0; i < this._proxies.length && deleted; i++) - deleted = dataids.indexOf(proxies[i]) != -1; + deleted = dataids.indexOf(proxies[i]) !== -1; this._processingServerUpdate = true; for (let i = 0; i < proxies.length && added; i++) { diff --git a/src/fields/PDFField.ts b/src/fields/PDFField.ts index b6625387e..436c1cf2b 100644 --- a/src/fields/PDFField.ts +++ b/src/fields/PDFField.ts @@ -7,7 +7,7 @@ import { Types } from "../server/Message"; export class PDFField extends BasicField<URL> { constructor(data: URL | undefined = undefined, id?: FieldId, save: boolean = true) { - super(data == undefined ? new URL("http://cs.brown.edu/~bcz/bob_fettucine.jpg") : data, save, id); + super(data === undefined ? new URL("http://cs.brown.edu/~bcz/bob_fettucine.jpg") : data, save, id); } toString(): string { diff --git a/src/fields/VideoField.ts b/src/fields/VideoField.ts index 626e4ec83..992cc1641 100644 --- a/src/fields/VideoField.ts +++ b/src/fields/VideoField.ts @@ -4,7 +4,7 @@ import { Types } from "../server/Message"; export class VideoField extends BasicField<URL> { constructor(data: URL | undefined = undefined, id?: FieldId, save: boolean = true) { - super(data == undefined ? new URL("http://techslides.com/demos/sample-videos/small.mp4") : data, save, id); + super(data === undefined ? new URL("http://techslides.com/demos/sample-videos/small.mp4") : data, save, id); } toString(): string { diff --git a/src/fields/WebField.ts b/src/fields/WebField.ts index 6c4de5000..0cbcc6d33 100644 --- a/src/fields/WebField.ts +++ b/src/fields/WebField.ts @@ -4,7 +4,7 @@ import { Types } from "../server/Message"; export class WebField extends BasicField<URL> { constructor(data: URL | undefined = undefined, id?: FieldId, save: boolean = true) { - super(data == undefined ? new URL("https://crossorigin.me/" + "https://cs.brown.edu/") : data, save, id); + super(data === undefined ? new URL("https://crossorigin.me/" + "https://cs.brown.edu/") : data, save, id); } toString(): string { diff --git a/src/mobile/ImageUpload.tsx b/src/mobile/ImageUpload.tsx index ae48dd2c6..c3684a0eb 100644 --- a/src/mobile/ImageUpload.tsx +++ b/src/mobile/ImageUpload.tsx @@ -9,6 +9,7 @@ import { RouteStore } from '../server/RouteStore'; import { ServerUtils } from '../server/ServerUtil'; import "./ImageUpload.scss"; import React = require('react'); +import { Opt } from '../fields/Field'; @@ -20,48 +21,44 @@ import React = require('react'); // } // } -const onFileLoad = (file: any) => { +const onFileLoad = async (file: any) => { let imgPrev = document.getElementById("img_preview") if (imgPrev) { let files: File[] = file.target.files; - if (files.length != 0) { + if (files.length !== 0) { console.log(files[0]); let formData = new FormData(); formData.append("file", files[0]); const upload = window.location.origin + "/upload" - fetch(upload, { + const res = await fetch(upload, { method: 'POST', body: formData - }).then((res: Response) => { - return res.json() - }).then(json => { - json.map((file: any) => { - let path = window.location.origin + file - var doc: Document = Documents.ImageDocument(path, { nativeWidth: 200, width: 200 }) + }); + const json = await res.json(); + json.map(async (file: any) => { + let path = window.location.origin + file + var doc: Document = Documents.ImageDocument(path, { nativeWidth: 200, width: 200 }) - rp.get(ServerUtils.prepend(RouteStore.getUserDocumentId)).then(res => { - if (res) { - return Server.GetField(res); - } - throw new Error("No user id returned"); - }).then(field => { - if (field instanceof Document) { - return field.GetTAsync(KeyStore.OptionalRightCollection, Document) - } - }).then(pending => { - if (pending) { - pending.GetOrCreateAsync(KeyStore.Data, ListField, list => { - list.Data.push(doc); - }) - } - }); + const res = await rp.get(ServerUtils.prepend(RouteStore.getUserDocumentId)); + if (!res) { + throw new Error("No user id returned"); + } + const field = await Server.GetField(res); + let pending: Opt<Document>; + if (field instanceof Document) { + pending = await field.GetTAsync(KeyStore.OptionalRightCollection, Document) + } + if (pending) { + pending.GetOrCreateAsync(KeyStore.Data, ListField, list => { + list.Data.push(doc); + }) + } + }); - // console.log(window.location.origin + file[0]) + // console.log(window.location.origin + file[0]) - //imgPrev.setAttribute("src", window.location.origin + files[0].name) - }) - }) + //imgPrev.setAttribute("src", window.location.origin + files[0].name) } } } diff --git a/src/server/authentication/controllers/WorkspacesMenu.tsx b/src/server/authentication/controllers/WorkspacesMenu.tsx index 8e14cf98e..835432c8e 100644 --- a/src/server/authentication/controllers/WorkspacesMenu.tsx +++ b/src/server/authentication/controllers/WorkspacesMenu.tsx @@ -73,7 +73,7 @@ export class WorkspacesMenu extends React.Component<WorkspaceMenuProps> { <span>{i + 1} - </span> <EditableView display={"inline"} - GetValue={() => { return s.Title }} + GetValue={() => s.Title} SetValue={(title: string): boolean => { s.SetText(KeyStore.Title, title); return true; diff --git a/src/server/authentication/controllers/user_controller.ts b/src/server/authentication/controllers/user_controller.ts index e365b8dce..2bbb334b5 100644 --- a/src/server/authentication/controllers/user_controller.ts +++ b/src/server/authentication/controllers/user_controller.ts @@ -4,7 +4,7 @@ import * as passport from "passport"; import { IVerifyOptions } from "passport-local"; import "../config/passport"; import * as request from "express-validator"; -const flash = require("express-flash"); +import flash = require("express-flash"); import * as session from "express-session"; import * as pug from 'pug'; import * as async from 'async'; @@ -109,12 +109,12 @@ export let postLogin = (req: Request, res: Response, next: NextFunction) => { } passport.authenticate("local", (err: Error, user: DashUserModel, info: IVerifyOptions) => { - if (err) { return next(err); } + if (err) { next(err); return } if (!user) { return res.redirect(RouteStore.signup); } req.logIn(user, (err) => { - if (err) { return next(err); } + if (err) { next(err); return } res.redirect(RouteStore.home); }); })(req, res, next); @@ -158,7 +158,8 @@ export let postForgot = function (req: Request, res: Response, next: NextFunctio User.findOne({ email }, function (err, user: DashUserModel) { if (!user) { // NO ACCOUNT WITH SUBMITTED EMAIL - return res.redirect(RouteStore.forgot); + res.redirect(RouteStore.forgot); + return } user.passwordResetToken = token; user.passwordResetExpires = new Date(Date.now() + 3600000); // 1 HOUR @@ -228,7 +229,8 @@ export let postReset = function (req: Request, res: Response) { user.save(function (err) { if (err) { - return res.redirect(RouteStore.login); + res.redirect(RouteStore.login); + return; } req.logIn(user, function (err) { if (err) { diff --git a/src/server/index.ts b/src/server/index.ts index 17d7432e0..f60e6e293 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -143,7 +143,7 @@ addSecureRoute( Method.GET, (user, res, req) => { let detector = new mobileDetect(req.headers['user-agent'] || ""); - if (detector.mobile() != null) { + if (detector.mobile() !== null) { res.sendFile(path.join(__dirname, '../../deploy/mobile/image.html')); } else { res.sendFile(path.join(__dirname, '../../deploy/index.html')); @@ -263,12 +263,10 @@ function deleteFields() { return Database.Instance.deleteAll(); } -function deleteAll() { - return Database.Instance.deleteAll().then(() => { - return Database.Instance.deleteAll('sessions') - }).then(() => { - return Database.Instance.deleteAll('users') - }); +async function deleteAll() { + await Database.Instance.deleteAll(); + await Database.Instance.deleteAll('sessions'); + await Database.Instance.deleteAll('users'); } function barReceived(guid: String) { diff --git a/src/server/public/files/upload_a6a70d84ebb65febf7900e29f52cc86d.pdf b/src/server/public/files/upload_a6a70d84ebb65febf7900e29f52cc86d.pdf Binary files differdeleted file mode 100644 index dfd6ab339..000000000 --- a/src/server/public/files/upload_a6a70d84ebb65febf7900e29f52cc86d.pdf +++ /dev/null diff --git a/test/test.ts b/test/test.ts index 0fa1ea15b..db24cae5f 100644 --- a/test/test.ts +++ b/test/test.ts @@ -152,7 +152,7 @@ describe("Reference", () => { let ran = false; reaction(() => { let field = doc2.GetT(key, NumberField); - if (field && field != FieldWaiting) { + if (field && field !== FieldWaiting) { return field.Data; } return undefined; diff --git a/tslint.json b/tslint.json new file mode 100644 index 000000000..54876916e --- /dev/null +++ b/tslint.json @@ -0,0 +1,56 @@ +{ + "rules": { + // "no-non-null-assertion": true, + "no-return-await": true, + "no-string-literal": true, + // "no-var-keyword": true, + // "no-var-requires": true, + "prefer-object-spread": true, + "prefer-for-of": true, + "no-unnecessary-type-assertion": true, + // "no-void-expression": [ + // true, + // "ignore-arrow-function-shorthand" + // ], + "triple-equals": true, + // "prefer-const": true, + "no-unnecessary-callback-wrapper": true, + // "align": [ + // true, + // "parameters", + // "arguments", + // "statements", + // "members", + // "elements" + // ], + "class-name": true, + "arrow-return-shorthand": true, + // "object-literal-shorthand": true, + // "object-literal-sort-keys": true, + // "semicolon": [ + // true, + // "always" + // ], + // "curly": [ + // true, + // "ignore-same-line" + // ], + // "quotemark": [ + // true, + // "double", + // "jsx-double", + // "avoid-template", + // "avoid-escape" + // ], + "no-tautology-expression": true, + "unnecessary-constructor": true + // "trailing-comma": [ + // true, + // { + // "multiline": "always", + // "singleline": "never" + // } + // ], + // "ordered-imports": true + } +}
\ No newline at end of file diff --git a/webpack.config.js b/webpack.config.js index 5ba9dd4b5..50079255f 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -28,44 +28,53 @@ module.exports = { extensions: ['.js', '.ts', '.tsx'] }, module: { - rules: [{ - test: [/\.tsx?$/, /\.ts?$/,], - loader: "awesome-typescript-loader", - include: path.join(__dirname, 'src') - }, - { - test: /\.scss|css$/, - use: [ - { - loader: "style-loader" - }, - { - loader: "css-loader" - }, - { - loader: "sass-loader" - } - ] - }, - { - test: /\.(jpg|png|pdf)$/, - use: [ - { - loader: 'file-loader' - } - ] - }, - { - test: /\.(png|jpg|gif)$/i, - use: [ - { - loader: 'url-loader', - options: { - limit: 8192 + rules: [ + { + test: [/\.tsx?$/, /\.ts?$/,], + enforce: 'pre', + use: [ + { + loader: "tslint-loader", } - } - ] - }] + ] + }, { + test: [/\.tsx?$/, /\.ts?$/,], + loader: "awesome-typescript-loader", + include: path.join(__dirname, 'src') + }, + { + test: /\.scss|css$/, + use: [ + { + loader: "style-loader" + }, + { + loader: "css-loader" + }, + { + loader: "sass-loader" + } + ] + }, + { + test: /\.(jpg|png|pdf)$/, + use: [ + { + loader: 'file-loader' + } + ] + }, + { + test: /\.(png|jpg|gif)$/i, + use: [ + { + loader: 'url-loader', + options: { + limit: 8192 + } + } + ] + }] }, plugins: [ new CopyWebpackPlugin([{ from: "deploy", to: path.join(__dirname, "build") }]), |