From 17b27d3575d3f91f461262e5ad72a457238d198a Mon Sep 17 00:00:00 2001 From: ab Date: Wed, 7 Aug 2019 16:28:51 -0400 Subject: correlation matrix completed --- src/client/views/MainView.tsx | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'src/client/views/MainView.tsx') diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 2ecf5fd85..97964166a 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -39,6 +39,7 @@ import { FilterBox } from './search/FilterBox'; import { CollectionTreeView } from './collections/CollectionTreeView'; import { ClientUtils } from '../util/ClientUtils'; import { SchemaHeaderField, RandomPastel } from '../../new_fields/SchemaHeaderField'; +//import { DocumentManager } from '../util/DocumentManager'; @observer export class MainView extends React.Component { @@ -435,6 +436,12 @@ export class MainView extends React.Component { ; } + // clusterDocuments = () => { + // DocumentManager.Instance.DocumentViews(); + // } + + + @action -- cgit v1.2.3-70-g09d2 From e03a1b2cc90e0fdb7789f4826e482e9040aa7075 Mon Sep 17 00:00:00 2001 From: ab Date: Tue, 13 Aug 2019 17:26:49 -0400 Subject: 80% done, garbage collection is much needed --- src/Recommendations.scss | 21 --- src/Recommendations.tsx | 28 ---- src/client/util/SearchUtil.ts | 7 +- src/client/views/MainView.tsx | 2 + src/client/views/Recommendations.scss | 65 ++++++++ src/client/views/Recommendations.tsx | 169 +++++++++++++++++++++ .../collectionFreeForm/CollectionFreeFormView.tsx | 13 +- src/client/views/nodes/DocumentView.tsx | 34 ++++- src/client/views/nodes/ImageBox.tsx | 21 ++- 9 files changed, 297 insertions(+), 63 deletions(-) delete mode 100644 src/Recommendations.scss delete mode 100644 src/Recommendations.tsx create mode 100644 src/client/views/Recommendations.scss create mode 100644 src/client/views/Recommendations.tsx (limited to 'src/client/views/MainView.tsx') diff --git a/src/Recommendations.scss b/src/Recommendations.scss deleted file mode 100644 index 5129a59d9..000000000 --- a/src/Recommendations.scss +++ /dev/null @@ -1,21 +0,0 @@ -.recommendation-content *{ - display: inline-block; - margin: auto; - border: 1px dashed grey; - padding: 2px 2px; -} - -.recommendation-content { - float: left; - border: 1px solid green; - width: 200px; - align-content: center; -} - -.rec-scroll { - overflow-y: scroll; - height: 300px; - width: auto; - position: absolute; - background: #cdcdcd; -} \ No newline at end of file diff --git a/src/Recommendations.tsx b/src/Recommendations.tsx deleted file mode 100644 index ca1123ef9..000000000 --- a/src/Recommendations.tsx +++ /dev/null @@ -1,28 +0,0 @@ -import { observer } from "mobx-react"; -import React = require("react"); -import { Doc } from "./new_fields/Doc"; -import { NumCast } from "./new_fields/Types"; - -export interface RecProps { - documents: { preview: string, similarity: number }[], - node: Doc; -} - -@observer -export class Recommendations extends React.Component { - render() { - const transform = "translate(" + (NumCast(this.props.node.x) + 350) + "px, " + NumCast(this.props.node.y) + "px" - return ( -
- {this.props.documents.map(doc => { - return ( -
- -
{doc.similarity}
-
- ) - })} -
- ) - } -} \ No newline at end of file diff --git a/src/client/util/SearchUtil.ts b/src/client/util/SearchUtil.ts index 1fce995d7..85e593529 100644 --- a/src/client/util/SearchUtil.ts +++ b/src/client/util/SearchUtil.ts @@ -81,12 +81,13 @@ export namespace SearchUtil { export async function GetAllDocs() { const query = "*"; let response = await rp.get(Utils.prepend('/search'), { - qs: { - q: query - } + qs: + { start: 0, rows: 10000, q: query }, + }); let result: IdSearchResult = JSON.parse(response); const { ids, numFound, highlighting } = result; + console.log(ids.length); const docMap = await DocServer.GetRefFields(ids); const docs: Doc[] = []; for (const id of ids) { diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 419b15697..0b6fe3876 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -41,6 +41,7 @@ import { ClientUtils } from '../util/ClientUtils'; import { SchemaHeaderField, RandomPastel } from '../../new_fields/SchemaHeaderField'; //import { DocumentManager } from '../util/DocumentManager'; import { DictationManager } from '../util/DictationManager'; +import { Recommendations } from './Recommendations'; @observer export class MainView extends React.Component { @@ -581,6 +582,7 @@ export class MainView extends React.Component { {this.mainContent} + {this.nodesMenu()} {this.miscButtons} diff --git a/src/client/views/Recommendations.scss b/src/client/views/Recommendations.scss new file mode 100644 index 000000000..5d8f17e37 --- /dev/null +++ b/src/client/views/Recommendations.scss @@ -0,0 +1,65 @@ +@import "globalCssVariables"; + +.rec-content *{ + display: inline-block; + margin: auto; + width: 50; + height: 30px; + border: 1px dashed grey; + padding: 10px 10px; +} + +.rec-content { + float: left; + width: inherit; + align-content: center; +} + +.rec-scroll { + overflow-y: scroll; + overflow-x: hidden; + position: absolute; + // display: flex; + z-index: 10000; + box-shadow: gray 0.2vw 0.2vw 0.4vw; + // flex-direction: column; + background: whitesmoke; + padding-bottom: 10px; + border-radius: 15px; + border: solid #BBBBBBBB 1px; + width: 200px; + text-align: center; + max-height: 250px; + text-transform: uppercase; + color: grey; + letter-spacing: 2px; +} + +.content { + padding: 10px; + display: flex; + flex-direction: row; + align-items: center; + justify-content: center; +} + +.image-background { + pointer-events: none; + background-color: transparent; + width: 50%; + text-align: center; + height: 35px; + margin-left: 5px; +} + +img{ + width: 100%; + height: 100%; +} + +.score { + // margin-left: 15px; + width: 50%; + height: 100%; + text-align: center; +} diff --git a/src/client/views/Recommendations.tsx b/src/client/views/Recommendations.tsx new file mode 100644 index 000000000..8569996b3 --- /dev/null +++ b/src/client/views/Recommendations.tsx @@ -0,0 +1,169 @@ +import { observer } from "mobx-react"; +import React = require("react"); +import { observable, action } from "mobx"; +import Measure from "react-measure"; +import "./Recommendations.scss"; +import { Doc, DocListCast, WidthSym, HeightSym } from "../../new_fields/Doc"; +import { DocumentIcon } from "./nodes/DocumentIcon"; +import { StrCast, NumCast } from "../../new_fields/Types"; +import { returnFalse, emptyFunction, returnEmptyString, returnOne } from "../../Utils"; +import { Transform } from "../util/Transform"; +import { ObjectField } from "../../new_fields/ObjectField"; +import { DocumentView } from "./nodes/DocumentView"; +import { DocumentType } from "../documents/Documents"; + + +export interface RecProps { + documents: { preview: Doc, similarity: number }[]; + node: Doc; +} + +@observer +export class Recommendations extends React.Component<{}> { + + static Instance: Recommendations; + @observable private _display: boolean = false; + @observable private _pageX: number = 0; + @observable private _pageY: number = 0; + @observable private _width: number = 0; + @observable private _height: number = 0; + @observable private _documents: { preview: Doc, score: number }[] = []; + + constructor(props: {}) { + super(props); + Recommendations.Instance = this; + } + + private DocumentIcon(doc: Doc) { + let layoutresult = StrCast(doc.type); + let renderDoc = doc; + //let box: number[] = []; + if (layoutresult.indexOf(DocumentType.COL) !== -1) { + renderDoc = Doc.MakeDelegate(renderDoc); + let bounds = DocListCast(renderDoc.data).reduce((bounds, doc) => { + var [sptX, sptY] = [NumCast(doc.x), NumCast(doc.y)]; + let [bptX, bptY] = [sptX + doc[WidthSym](), sptY + doc[HeightSym]()]; + return { + x: Math.min(sptX, bounds.x), y: Math.min(sptY, bounds.y), + r: Math.max(bptX, bounds.r), b: Math.max(bptY, bounds.b) + }; + }, { x: Number.MAX_VALUE, y: Number.MAX_VALUE, r: Number.MIN_VALUE, b: Number.MIN_VALUE }); + } + let returnXDimension = () => 50; + let returnYDimension = () => 50; + let scale = () => returnXDimension() / NumCast(renderDoc.nativeWidth, returnXDimension()); + let newRenderDoc = Doc.MakeDelegate(renderDoc); /// newRenderDoc -> renderDoc -> render"data"Doc -> TextProt + const docview =
+ {/* onPointerDown={action(() => { + this._useIcons = !this._useIcons; + this._displayDim = this._useIcons ? 50 : Number(SEARCH_THUMBNAIL_SIZE); + })} + onPointerEnter={action(() => this._displayDim = this._useIcons ? 50 : Number(SEARCH_THUMBNAIL_SIZE))} + onPointerLeave={action(() => this._displayDim = 50)} > */} + +
; + const data = renderDoc.data; + if (data instanceof ObjectField) newRenderDoc.data = ObjectField.MakeCopy(data); + newRenderDoc.preview = true; + return docview; + + } + + @action + closeMenu = () => { + this._display = false; + } + + @action + resetDocuments = () => { + this._documents = []; + } + + @action + addDocuments = (documents: { preview: Doc, score: number }[]) => { + this._documents = documents; + } + + @action + displayRecommendations(x: number, y: number) { + this._pageX = x; + this._pageY = y; + this._display = true; + } + + static readonly buffer = 20; + + get pageX() { + const x = this._pageX; + if (x < 0) { + return 0; + } + const width = this._width; + if (x + width > window.innerWidth - Recommendations.buffer) { + return window.innerWidth - Recommendations.buffer - width; + } + return x; + } + + get pageY() { + const y = this._pageY; + if (y < 0) { + return 0; + } + const height = this._height; + if (y + height > window.innerHeight - Recommendations.buffer) { + return window.innerHeight - Recommendations.buffer - height; + } + return y; + } + + render() { + if (!this._display) { + return null; + } + let style = { left: this.pageX, top: this.pageY }; + //const transform = "translate(" + (NumCast(this.props.node.x) + 350) + "px, " + NumCast(this.props.node.y) + "px" + return ( + { this._width = r.offset.width; this._height = r.offset.height; })}> + {({ measureRef }) => ( +
+

Recommendations

+ {this._documents.map(doc => { + return ( +
+ + {this.DocumentIcon(doc.preview)} + + {doc.score} +
+ ); + })} + +
+ ) + } + +
+ ); + } +} \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index d1e8031fd..50f7e2dc8 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -896,10 +896,13 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { allDocs.forEach(doc => console.log(doc.title)); // clears internal representation of documents as vectors ClientRecommender.Instance.reset_docs(); - await Promise.all(activedocs.map((doc: Doc) => { - //console.log(StrCast(doc.title)); - const extdoc = doc.data_ext as Doc; - return ClientRecommender.Instance.extractText(doc, extdoc ? extdoc : doc); + await Promise.all(allDocs.map((doc: Doc) => { + console.log(StrCast(doc.title)); + if (doc.type === DocumentType.IMG) { + console.log(doc.title); + const extdoc = doc.data_ext as Doc; + return ClientRecommender.Instance.extractText(doc, extdoc ? extdoc : doc); + } })); console.log(ClientRecommender.Instance.createDistanceMatrix()); }, @@ -1013,7 +1016,7 @@ class CollectionFreeFormViewPannableContents extends React.Component otherwise, reactions won't fire return
{this.props.children} - + {/* */}
; } } \ No newline at end of file diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 24bcc0217..3ce4dbd4f 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -40,9 +40,13 @@ import React = require("react"); import { DictationManager } from '../../util/DictationManager'; import { MainView } from '../MainView'; import requestPromise = require('request-promise'); -import { Recommendations } from '../../../Recommendations'; +import { Recommendations } from '../Recommendations'; +import { SearchUtil } from '../../util/SearchUtil'; +import { ClientRecommender } from '../../ClientRecommender'; +import { DocumentType } from '../../documents/Documents'; const JsxParser = require('react-jsx-parser').default; //TODO Why does this need to be imported like this? +library.add(fa.faBrain); library.add(fa.faTrash); library.add(fa.faShare); library.add(fa.faDownload); @@ -610,6 +614,33 @@ export class DocumentView extends DocComponent(Docu a.click(); } }); + cm.addItem({ + description: "Recommender System", + event: async () => { + if (!ClientRecommender.Instance) new ClientRecommender({ title: "Client Recommender" }); + let documents: Doc[] = []; + let allDocs = await SearchUtil.GetAllDocs(); + allDocs.forEach(doc => console.log(doc.title)); + // clears internal representation of documents as vectors + ClientRecommender.Instance.reset_docs(); + await Promise.all(allDocs.map((doc: Doc) => { + if (doc.type === DocumentType.IMG) { + console.log(StrCast(doc.title)); + documents.push(doc); + const extdoc = doc.data_ext as Doc; + return ClientRecommender.Instance.extractText(doc, extdoc ? extdoc : doc); + } + })); + console.log(ClientRecommender.Instance.createDistanceMatrix()); + let recDocs: { preview: Doc, score: number }[] = []; + for (let i = 0; i < documents.length; i++) { + recDocs.push({ preview: documents[i], score: i }); + } + Recommendations.Instance.addDocuments(recDocs); + Recommendations.Instance.displayRecommendations(e.pageX + 100, e.pageY); + }, + icon: "brain" + }); cm.addItem({ description: "Delete", event: this.deleteClicked, icon: "trash" }); type User = { email: string, userDocumentId: string }; let usersMenu: ContextMenuProps[] = []; @@ -758,7 +789,6 @@ export class DocumentView extends DocComponent(Docu } - ); } diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index 73b892e26..45d389ba6 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -28,6 +28,9 @@ import FaceRectangles from './FaceRectangles'; import { FieldView, FieldViewProps } from './FieldView'; import "./ImageBox.scss"; import React = require("react"); +import { SearchUtil } from '../../util/SearchUtil'; +import { ClientRecommender } from '../../ClientRecommender'; +import { DocumentType } from '../../documents/Documents'; var requestImageSize = require('../../util/request-image-size'); var path = require('path'); const { Howl } = require('howler'); @@ -240,10 +243,20 @@ export class ImageBox extends DocComponent(ImageD } } - extractText = () => { - //Recommender.Instance.extractText(this.dataDoc, this.extensionDoc); - // request recommender - //fetch(Utils.prepend("/recommender"), { body: body, method: "POST", headers: { "content-type": "application/json" } }).then((value) => console.log(value)); + extractText = async () => { + //let activedocs = this.getActiveDocuments(); + let allDocs = await SearchUtil.GetAllDocs(); + allDocs.forEach(doc => console.log(doc.title)); + // clears internal representation of documents as vectors + ClientRecommender.Instance.reset_docs(); + await Promise.all(allDocs.map((doc: Doc) => { + //console.log(StrCast(doc.title)); + if (doc.type === DocumentType.IMG) { + const extdoc = doc.data_ext as Doc; + return ClientRecommender.Instance.extractText(doc, extdoc ? extdoc : doc); + } + })); + console.log(ClientRecommender.Instance.createDistanceMatrix()); } generateMetadata = (threshold: Confidence = Confidence.Excellent) => { -- cgit v1.2.3-70-g09d2 From e0bfe978e029268b3901b5d098f946b1a6fc7d0d Mon Sep 17 00:00:00 2001 From: ab Date: Thu, 29 Aug 2019 18:43:32 -0400 Subject: ui fixes, datadoc resolved --- src/client/ClientRecommender.tsx | 83 +++++++++++++++------- src/client/cognitive_services/CognitiveServices.ts | 24 ++++--- src/client/views/MainView.tsx | 1 + src/client/views/Recommendations.tsx | 21 ++++-- .../collectionFreeForm/CollectionFreeFormView.tsx | 21 ------ src/client/views/nodes/DocumentView.tsx | 26 ++++--- src/client/views/nodes/ImageBox.tsx | 16 ----- 7 files changed, 104 insertions(+), 88 deletions(-) (limited to 'src/client/views/MainView.tsx') diff --git a/src/client/ClientRecommender.tsx b/src/client/ClientRecommender.tsx index 63f85c737..a6d1a32b3 100644 --- a/src/client/ClientRecommender.tsx +++ b/src/client/ClientRecommender.tsx @@ -1,5 +1,5 @@ import { Doc } from "../new_fields/Doc"; -import { StrCast } from "../new_fields/Types"; +import { StrCast, Cast } from "../new_fields/Types"; import { List } from "../new_fields/List"; import { CognitiveServices } from "./cognitive_services/CognitiveServices"; import React = require("react"); @@ -8,30 +8,42 @@ import { observable, action, computed, reaction } from "mobx"; var assert = require('assert'); import "./ClientRecommender.scss"; import { JSXElement } from "babel-types"; +import { ToPlainText, RichTextField } from "../new_fields/RichTextField"; export interface RecommenderProps { title: string; } +export interface RecommenderDocument { + actualDoc: Doc; + vectorDoc: number[]; + score: number; +} + @observer export class ClientRecommender extends React.Component { static Instance: ClientRecommender; - private docVectors: Set; + private mainDoc?: RecommenderDocument; + private docVectors: Set = new Set(); @observable private corr_matrix = [[0, 0], [0, 0]]; constructor(props: RecommenderProps) { //console.log("creating client recommender..."); super(props); if (!ClientRecommender.Instance) ClientRecommender.Instance = this; - this.docVectors = new Set(); - //this.corr_matrix = [[0, 0], [0, 0]]; + ClientRecommender.Instance.docVectors = new Set(); + //ClientRecommender.Instance.corr_matrix = [[0, 0], [0, 0]]; } @action public reset_docs() { - this.docVectors = new Set(); - this.corr_matrix = [[0, 0], [0, 0]]; + ClientRecommender.Instance.docVectors = new Set(); + ClientRecommender.Instance.corr_matrix = [[0, 0], [0, 0]]; + } + + public deleteDocs() { + console.log("deleting previews..."); } /*** @@ -67,11 +79,24 @@ export class ClientRecommender extends React.Component { } } + public computeSimilarities() { + ClientRecommender.Instance.docVectors.forEach((doc: RecommenderDocument) => { + if (ClientRecommender.Instance.mainDoc) { + const distance = ClientRecommender.Instance.distance(ClientRecommender.Instance.mainDoc.vectorDoc, doc.vectorDoc, "euclidian"); + doc.score = distance; + } + } + ); + let doclist = Array.from(ClientRecommender.Instance.docVectors); + doclist.sort((a: RecommenderDocument, b: RecommenderDocument) => a.score - b.score); + return doclist; + } + /*** * Computes the mean of a set of vectors */ - public mean(paragraph: Set) { + public mean(paragraph: Set, dataDoc: Doc, mainDoc: boolean) { const n = 200; const num_words = paragraph.size; let meanVector = new Array(n).fill(0); // mean vector @@ -82,14 +107,16 @@ export class ClientRecommender extends React.Component { } }); meanVector = meanVector.map(x => x / num_words); - this.addToDocSet(meanVector); + const internalDoc: RecommenderDocument = { actualDoc: dataDoc, vectorDoc: meanVector, score: 0 }; + if (mainDoc) ClientRecommender.Instance.mainDoc = internalDoc; + ClientRecommender.Instance.addToDocSet(internalDoc); } return meanVector; } - private addToDocSet(vector: number[]) { - if (this.docVectors) { - this.docVectors.add(vector); + private addToDocSet(internalDoc: RecommenderDocument) { + if (ClientRecommender.Instance.docVectors) { + ClientRecommender.Instance.docVectors.add(internalDoc); } } @@ -97,9 +124,11 @@ export class ClientRecommender extends React.Component { * Uses Cognitive Services to extract keywords from a document */ - public async extractText(dataDoc: Doc, extDoc: Doc) { - let data = StrCast(dataDoc.title); - //console.log(data); + public async extractText(dataDoc: Doc, extDoc: Doc, mainDoc: boolean = false) { + let fielddata = Cast(dataDoc.data, RichTextField); + let data: string; + fielddata ? data = fielddata[ToPlainText]() : data = ""; + console.log(data); let converter = (results: any) => { let keyterms = new List(); results.documents.forEach((doc: any) => { @@ -108,7 +137,7 @@ export class ClientRecommender extends React.Component { }); return keyterms; }; - await CognitiveServices.Text.Appliers.analyzer(extDoc, ["key words"], data, converter); + await CognitiveServices.Text.Appliers.analyzer(dataDoc, extDoc, ["key words"], data, converter, mainDoc); } /*** @@ -116,7 +145,7 @@ export class ClientRecommender extends React.Component { */ @action - public createDistanceMatrix(documents: Set = this.docVectors) { + public createDistanceMatrix(documents: Set = ClientRecommender.Instance.docVectors) { const documents_list = Array.from(documents); const n = documents_list.length; var matrix = new Array(n).fill(0).map(() => new Array(n).fill(0)); @@ -124,22 +153,22 @@ export class ClientRecommender extends React.Component { var doc1 = documents_list[i]; for (let j = 0; j < n; j++) { var doc2 = documents_list[j]; - matrix[i][j] = this.distance(doc1, doc2, "euclidian"); + matrix[i][j] = ClientRecommender.Instance.distance(doc1.vectorDoc, doc2.vectorDoc, "euclidian"); } } - this.corr_matrix = matrix; + ClientRecommender.Instance.corr_matrix = matrix; return matrix; } @computed private get generateRows() { - const n = this.corr_matrix.length; + const n = ClientRecommender.Instance.corr_matrix.length; let rows: JSX.Element[] = []; for (let i = 0; i < n; i++) { let children: JSX.Element[] = []; for (let j = 0; j < n; j++) { - //let cell = React.createElement("td", this.corr_matrix[i][j]); - let cell = {this.corr_matrix[i][j].toFixed(4)}; + //let cell = React.createElement("td", ClientRecommender.Instance.corr_matrix[i][j]); + let cell = {ClientRecommender.Instance.corr_matrix[i][j].toFixed(4)}; children.push(cell); } //let row = React.createElement("tr", { children: children, key: i }); @@ -151,22 +180,22 @@ export class ClientRecommender extends React.Component { render() { return (
-

{this.props.title ? this.props.title : "hello"}

+

{ClientRecommender.Instance.props.title ? ClientRecommender.Instance.props.title : "hello"}

{/* - - + + - - + +
{this.corr_matrix[0][0].toFixed(4)}{this.corr_matrix[0][1].toFixed(4)}{ClientRecommender.Instance.corr_matrix[0][0].toFixed(4)}{ClientRecommender.Instance.corr_matrix[0][1].toFixed(4)}
{this.corr_matrix[1][0].toFixed(4)}{this.corr_matrix[1][1].toFixed(4)}{ClientRecommender.Instance.corr_matrix[1][0].toFixed(4)}{ClientRecommender.Instance.corr_matrix[1][1].toFixed(4)}
*/} - {this.generateRows} + {ClientRecommender.Instance.generateRows}
); diff --git a/src/client/cognitive_services/CognitiveServices.ts b/src/client/cognitive_services/CognitiveServices.ts index 75d0760ed..874ee433d 100644 --- a/src/client/cognitive_services/CognitiveServices.ts +++ b/src/client/cognitive_services/CognitiveServices.ts @@ -263,29 +263,35 @@ export namespace CognitiveServices { export namespace Appliers { - export async function vectorize(keyterms: any) { + export async function vectorize(keyterms: any, dataDoc: Doc, mainDoc: boolean = false) { console.log("vectorizing..."); //keyterms = ["father", "king"]; let args = { method: 'POST', uri: Utils.prepend("/recommender"), body: { keyphrases: keyterms }, json: true }; await requestPromise.post(args).then(async (wordvecs) => { - var vectorValues = new Set(); - wordvecs.forEach((wordvec: any) => { - //console.log(wordvec.word); - vectorValues.add(wordvec.values as number[]); - }); - ClientRecommender.Instance.mean(vectorValues); + if (wordvecs.length > 0) { + console.log("successful vectorization!"); + var vectorValues = new Set(); + wordvecs.forEach((wordvec: any) => { + //console.log(wordvec.word); + vectorValues.add(wordvec.values as number[]); + }); + ClientRecommender.Instance.mean(vectorValues, dataDoc, mainDoc); + } // adds document to internal doc set + else { + console.log("unsuccessful :( word(s) not in vocabulary"); + } //console.log(vectorValues.size); }); } - export const analyzer = async (target: Doc, keys: string[], data: string, converter: Converter) => { + export const analyzer = async (dataDoc: Doc, target: Doc, keys: string[], data: string, converter: Converter, mainDoc: boolean = false) => { let results = await ExecuteQuery(Service.Text, Manager, data); console.log(results); let keyterms = converter(results); //target[keys[0]] = Docs.Get.DocumentHierarchyFromJson(results, "Key Word Analysis"); target[keys[0]] = keyterms; console.log("analyzed!"); - await vectorize(keyterms); + await vectorize(keyterms, dataDoc, mainDoc); }; } diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 57eb30439..3a5795077 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -204,6 +204,7 @@ export class MainView extends React.Component { const targets = document.elementsFromPoint(e.x, e.y); if (targets && targets.length && targets[0].className.toString().indexOf("contextMenu") === -1) { ContextMenu.Instance.closeMenu(); + Recommendations.Instance.closeMenu(); } }); diff --git a/src/client/views/Recommendations.tsx b/src/client/views/Recommendations.tsx index 8569996b3..cf1974c69 100644 --- a/src/client/views/Recommendations.tsx +++ b/src/client/views/Recommendations.tsx @@ -10,8 +10,10 @@ import { returnFalse, emptyFunction, returnEmptyString, returnOne } from "../../ import { Transform } from "../util/Transform"; import { ObjectField } from "../../new_fields/ObjectField"; import { DocumentView } from "./nodes/DocumentView"; -import { DocumentType } from "../documents/Documents"; - +import { DocumentType } from '../documents/DocumentTypes'; +import { ClientRecommender } from "../ClientRecommender"; +import { DocServer } from "../DocServer"; +import { Id } from "../../new_fields/FieldSymbols"; export interface RecProps { documents: { preview: Doc, similarity: number }[]; @@ -28,6 +30,7 @@ export class Recommendations extends React.Component<{}> { @observable private _width: number = 0; @observable private _height: number = 0; @observable private _documents: { preview: Doc, score: number }[] = []; + private previewDocs: Doc[] = []; constructor(props: {}) { super(props); @@ -52,7 +55,8 @@ export class Recommendations extends React.Component<{}> { let returnXDimension = () => 50; let returnYDimension = () => 50; let scale = () => returnXDimension() / NumCast(renderDoc.nativeWidth, returnXDimension()); - let newRenderDoc = Doc.MakeDelegate(renderDoc); /// newRenderDoc -> renderDoc -> render"data"Doc -> TextProt + //let scale = () => 1; + //let newRenderDoc = Doc.MakeDelegate(renderDoc); /// newRenderDoc -> renderDoc -> render"data"Doc -> TextProt const docview =
{/* onPointerDown={action(() => { this._useIcons = !this._useIcons; @@ -62,7 +66,7 @@ export class Recommendations extends React.Component<{}> { onPointerLeave={action(() => this._displayDim = 50)} > */} { ContentScaling={scale} />
; - const data = renderDoc.data; - if (data instanceof ObjectField) newRenderDoc.data = ObjectField.MakeCopy(data); - newRenderDoc.preview = true; + // const data = renderDoc.data; + // if (data instanceof ObjectField) newRenderDoc.data = ObjectField.MakeCopy(data); + // newRenderDoc.preview = true; + // this.previewDocs.push(newRenderDoc); return docview; } @@ -92,6 +97,8 @@ export class Recommendations extends React.Component<{}> { @action closeMenu = () => { this._display = false; + this.previewDocs.forEach(doc => DocServer.DeleteDocument(doc[Id])); + this.previewDocs = []; } @action diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 2d4775070..3cef93383 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -857,27 +857,6 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { input.click(); } }); - ContextMenu.Instance.addItem({ - description: "Recommender System", - event: async () => { - // if (!ClientRecommender.Instance) new ClientRecommender({ title: "Client Recommender" }); - let activedocs = this.getActiveDocuments(); - let allDocs = await SearchUtil.GetAllDocs(); - allDocs.forEach(doc => console.log(doc.title)); - // clears internal representation of documents as vectors - ClientRecommender.Instance.reset_docs(); - await Promise.all(allDocs.map((doc: Doc) => { - console.log(StrCast(doc.title)); - if (doc.type === DocumentType.IMG) { - console.log(doc.title); - const extdoc = doc.data_ext as Doc; - return ClientRecommender.Instance.extractText(doc, extdoc ? extdoc : doc); - } - })); - console.log(ClientRecommender.Instance.createDistanceMatrix()); - }, - icon: "brain" - }); layoutItems.push({ description: `${this.fitToBox ? "Unset" : "Set"} Fit To Container`, event: this.fitToContainer, icon: !this.fitToBox ? "expand-arrows-alt" : "compress-arrows-alt" }); layoutItems.push({ description: "reset view", event: () => { this.props.Document.panX = this.props.Document.panY = 0; this.props.Document.scale = 1; }, icon: "compress-arrows-alt" }); layoutItems.push({ diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 2a6e91272..f708a7a3a 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -648,21 +648,31 @@ export class DocumentView extends DocComponent(Docu if (!ClientRecommender.Instance) new ClientRecommender({ title: "Client Recommender" }); let documents: Doc[] = []; let allDocs = await SearchUtil.GetAllDocs(); - allDocs.forEach(doc => console.log(doc.title)); + //allDocs.forEach(doc => console.log(doc.title)); // clears internal representation of documents as vectors ClientRecommender.Instance.reset_docs(); await Promise.all(allDocs.map((doc: Doc) => { - if (doc.type === DocumentType.IMG) { - console.log(StrCast(doc.title)); - documents.push(doc); - const extdoc = doc.data_ext as Doc; - return ClientRecommender.Instance.extractText(doc, extdoc ? extdoc : doc); + let mainDoc: boolean = false; + const dataDoc = Doc.GetDataDoc(doc); + if (doc.type === DocumentType.TEXT) { + if (dataDoc === Doc.GetDataDoc(this.props.Document)) { + mainDoc = true; + console.log(StrCast(doc.title)); + } + if (!documents.includes(dataDoc)) { + documents.push(dataDoc); + const extdoc = doc.data_ext as Doc; + return ClientRecommender.Instance.extractText(doc, extdoc ? extdoc : doc, mainDoc); + } } })); console.log(ClientRecommender.Instance.createDistanceMatrix()); + const doclist = ClientRecommender.Instance.computeSimilarities(); let recDocs: { preview: Doc, score: number }[] = []; - for (let i = 0; i < documents.length; i++) { - recDocs.push({ preview: documents[i], score: i }); + // tslint:disable-next-line: prefer-for-of + for (let i = 0; i < doclist.length; i++) { + console.log(doclist[i].score); + recDocs.push({ preview: doclist[i].actualDoc, score: doclist[i].score }); } Recommendations.Instance.addDocuments(recDocs); Recommendations.Instance.displayRecommendations(e.pageX + 100, e.pageY); diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index ec35465eb..d94e92847 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -240,22 +240,6 @@ export class ImageBox extends DocComponent(ImageD } } - extractText = async () => { - //let activedocs = this.getActiveDocuments(); - let allDocs = await SearchUtil.GetAllDocs(); - allDocs.forEach(doc => console.log(doc.title)); - // clears internal representation of documents as vectors - ClientRecommender.Instance.reset_docs(); - await Promise.all(allDocs.map((doc: Doc) => { - //console.log(StrCast(doc.title)); - if (doc.type === DocumentType.IMG) { - const extdoc = doc.data_ext as Doc; - return ClientRecommender.Instance.extractText(doc, extdoc ? extdoc : doc); - } - })); - console.log(ClientRecommender.Instance.createDistanceMatrix()); - } - generateMetadata = (threshold: Confidence = Confidence.Excellent) => { let converter = (results: any) => { let tagDoc = new Doc; -- cgit v1.2.3-70-g09d2 From af59d641022119e25402f1f13ae2c3f3eb4c20a2 Mon Sep 17 00:00:00 2001 From: ab Date: Mon, 16 Sep 2019 14:39:44 -0400 Subject: initial commit --- src/client/documents/DocumentTypes.ts | 1 + src/client/documents/Documents.ts | 9 ++ src/client/views/GlobalKeyHandler.ts | 2 + src/client/views/MainView.tsx | 5 +- src/client/views/Recommendations.scss | 12 +- src/client/views/Recommendations.tsx | 172 +++++++++++++----------- src/client/views/nodes/DocumentContentsView.tsx | 3 +- src/client/views/nodes/DocumentView.tsx | 20 ++- 8 files changed, 132 insertions(+), 92 deletions(-) (limited to 'src/client/views/MainView.tsx') diff --git a/src/client/documents/DocumentTypes.ts b/src/client/documents/DocumentTypes.ts index 1578e49fe..08f64fc8e 100644 --- a/src/client/documents/DocumentTypes.ts +++ b/src/client/documents/DocumentTypes.ts @@ -19,4 +19,5 @@ export enum DocumentType { YOUTUBE = "youtube", DRAGBOX = "dragbox", PRES = "presentation", + RECOMMENDATION = "recommendation" } \ No newline at end of file diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 1e9d1687f..89358d773 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -45,6 +45,7 @@ import { PresBox } from "../views/nodes/PresBox"; import { ComputedField } from "../../new_fields/ScriptField"; import { ProxyField } from "../../new_fields/Proxy"; import { DocumentType } from "./DocumentTypes"; +import { RecommendationsBox } from "../views/Recommendations"; //import { PresBox } from "../views/nodes/PresBox"; //import { PresField } from "../../new_fields/PresField"; var requestImageSize = require('../util/request-image-size'); @@ -170,6 +171,10 @@ export namespace Docs { [DocumentType.DRAGBOX, { layout: { view: DragBox }, options: { width: 40, height: 40 }, + }], + [DocumentType.RECOMMENDATION, { + layout: { view: RecommendationsBox }, + options: { width: 200, height: 200 }, }] ]); @@ -451,6 +456,10 @@ export namespace Docs { return InstanceFromProto(Prototypes.get(DocumentType.IMPORT), new List(), options); } + export function RecommendationsDocument(data: Doc[], options: DocumentOptions = {}) { + return InstanceFromProto(Prototypes.get(DocumentType.RECOMMENDATION), new List(data), options); + } + export type DocConfig = { doc: Doc, initialWidth?: number diff --git a/src/client/views/GlobalKeyHandler.ts b/src/client/views/GlobalKeyHandler.ts index d0464bd5f..4135afcb8 100644 --- a/src/client/views/GlobalKeyHandler.ts +++ b/src/client/views/GlobalKeyHandler.ts @@ -6,6 +6,7 @@ import { DragManager } from "../util/DragManager"; import { action, runInAction } from "mobx"; import { Doc } from "../../new_fields/Doc"; import { DictationManager } from "../util/DictationManager"; +import { RecommendationsBox } from "./Recommendations"; const modifiers = ["control", "meta", "shift", "alt"]; type KeyHandler = (keycode: string, e: KeyboardEvent) => KeyControlInfo | Promise; @@ -72,6 +73,7 @@ export default class KeyManager { main.toggleColorPicker(true); SelectionManager.DeselectAll(); DictationManager.Controls.stop(); + // RecommendationsBox.Instance.closeMenu(); break; case "delete": case "backspace": diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 3a5795077..0bc539dca 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -40,7 +40,7 @@ import { PreviewCursor } from './PreviewCursor'; import { FilterBox } from './search/FilterBox'; import { SchemaHeaderField, RandomPastel } from '../../new_fields/SchemaHeaderField'; //import { DocumentManager } from '../util/DocumentManager'; -import { Recommendations } from './Recommendations'; +import { RecommendationsBox } from './Recommendations'; import PresModeMenu from './presentationview/PresentationModeMenu'; import { PresBox } from './nodes/PresBox'; @@ -204,7 +204,6 @@ export class MainView extends React.Component { const targets = document.elementsFromPoint(e.x, e.y); if (targets && targets.length && targets[0].className.toString().indexOf("contextMenu") === -1) { ContextMenu.Instance.closeMenu(); - Recommendations.Instance.closeMenu(); } }); @@ -567,7 +566,7 @@ export class MainView extends React.Component { {this.miniPresentation} - + {/* */} {this.nodesMenu()} {this.miscButtons} diff --git a/src/client/views/Recommendations.scss b/src/client/views/Recommendations.scss index 6619d8df3..dd8a105f6 100644 --- a/src/client/views/Recommendations.scss +++ b/src/client/views/Recommendations.scss @@ -4,7 +4,7 @@ display: inline-block; margin: auto; width: 50; - height: 30px; + height: 150px; border: 1px dashed grey; padding: 10px 10px; } @@ -19,17 +19,20 @@ overflow-y: scroll; overflow-x: hidden; position: absolute; + pointer-events: all; // display: flex; z-index: 10000; box-shadow: gray 0.2vw 0.2vw 0.4vw; // flex-direction: column; background: whitesmoke; padding-bottom: 10px; - border-radius: 15px; + padding-top: 20px; + // border-radius: 15px; border: solid #BBBBBBBB 1px; - width: 250px; + width: 100%; text-align: center; - max-height: 250px; + // max-height: 250px; + height: 100%; text-transform: uppercase; color: grey; letter-spacing: 2px; @@ -48,7 +51,6 @@ background-color: transparent; width: 50%; text-align: center; - height: 35px; margin-left: 5px; } diff --git a/src/client/views/Recommendations.tsx b/src/client/views/Recommendations.tsx index d0105ee18..ff6e66492 100644 --- a/src/client/views/Recommendations.tsx +++ b/src/client/views/Recommendations.tsx @@ -14,27 +14,37 @@ import { DocumentType } from '../documents/DocumentTypes'; import { ClientRecommender } from "../ClientRecommender"; import { DocServer } from "../DocServer"; import { Id } from "../../new_fields/FieldSymbols"; +import { FieldView, FieldViewProps } from "./nodes/FieldView"; +import { DocumentManager } from "../util/DocumentManager"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { library } from "@fortawesome/fontawesome-svg-core"; +import { faBullseye, faLink } from "@fortawesome/free-solid-svg-icons"; +import { DocUtils } from "../documents/Documents"; export interface RecProps { documents: { preview: Doc, similarity: number }[]; node: Doc; } +library.add(faBullseye, faLink); + @observer -export class Recommendations extends React.Component<{}> { +export class RecommendationsBox extends React.Component { + + public static LayoutString(fieldKey?: string) { return FieldView.LayoutString(RecommendationsBox, fieldKey); } - static Instance: Recommendations; - @observable private _display: boolean = false; + static Instance: RecommendationsBox; + // @observable private _display: boolean = false; @observable private _pageX: number = 0; @observable private _pageY: number = 0; @observable private _width: number = 0; @observable private _height: number = 0; - @observable private _documents: { preview: Doc, score: number }[] = []; + // @observable private _documents: { preview: Doc, score: number }[] = []; private previewDocs: Doc[] = []; - constructor(props: {}) { + constructor(props: FieldViewProps) { super(props); - Recommendations.Instance = this; + RecommendationsBox.Instance = this; } private DocumentIcon(doc: Doc) { @@ -52,12 +62,12 @@ export class Recommendations extends React.Component<{}> { }; }, { x: Number.MAX_VALUE, y: Number.MAX_VALUE, r: Number.MIN_VALUE, b: Number.MIN_VALUE }); } - let returnXDimension = () => 50; - let returnYDimension = () => 50; + let returnXDimension = () => 150; + let returnYDimension = () => 150; let scale = () => returnXDimension() / NumCast(renderDoc.nativeWidth, returnXDimension()); //let scale = () => 1; let newRenderDoc = Doc.MakeAlias(renderDoc); /// newRenderDoc -> renderDoc -> render"data"Doc -> TextProt - newRenderDoc.height = 50; + newRenderDoc.height = NumCast(this.props.Document.documentIconHeight); newRenderDoc.autoHeight = false; const docview =
{/* onPointerDown={action(() => { @@ -78,7 +88,8 @@ export class Recommendations extends React.Component<{}> { PanelHeight={returnYDimension} focus={emptyFunction} backgroundColor={returnEmptyString} - selectOnLoad={false} + // selectOnLoad={false} + pinToPres={emptyFunction} parentActive={returnFalse} whenActiveChanged={returnFalse} bringToFront={emptyFunction} @@ -96,83 +107,84 @@ export class Recommendations extends React.Component<{}> { } - @action - closeMenu = () => { - this._display = false; - this.previewDocs.forEach(doc => DocServer.DeleteDocument(doc[Id])); - this.previewDocs = []; - } - - @action - resetDocuments = () => { - this._documents = []; - } - - @action - addDocuments = (documents: { preview: Doc, score: number }[]) => { - this._documents = documents; - } - - @action - displayRecommendations(x: number, y: number) { - this._pageX = x; - this._pageY = y; - this._display = true; - } + // @action + // closeMenu = () => { + // this._display = false; + // this.previewDocs.forEach(doc => DocServer.DeleteDocument(doc[Id])); + // this.previewDocs = []; + // } + + // @action + // resetDocuments = () => { + // this._documents = []; + // } + + // @action + // displayRecommendations(x: number, y: number) { + // this._pageX = x; + // this._pageY = y; + // this._display = true; + // } static readonly buffer = 20; - get pageX() { - const x = this._pageX; - if (x < 0) { - return 0; - } - const width = this._width; - if (x + width > window.innerWidth - Recommendations.buffer) { - return window.innerWidth - Recommendations.buffer - width; - } - return x; - } - - get pageY() { - const y = this._pageY; - if (y < 0) { - return 0; - } - const height = this._height; - if (y + height > window.innerHeight - Recommendations.buffer) { - return window.innerHeight - Recommendations.buffer - height; - } - return y; - } + // get pageX() { + // const x = this._pageX; + // if (x < 0) { + // return 0; + // } + // const width = this._width; + // if (x + width > window.innerWidth - RecommendationsBox.buffer) { + // return window.innerWidth - RecommendationsBox.buffer - width; + // } + // return x; + // } + + // get pageY() { + // const y = this._pageY; + // if (y < 0) { + // return 0; + // } + // const height = this._height; + // if (y + height > window.innerHeight - RecommendationsBox.buffer) { + // return window.innerHeight - RecommendationsBox.buffer - height; + // } + // return y; + // } render() { - if (!this._display) { - return null; - } - let style = { left: this.pageX, top: this.pageY }; + // if (!this._display) { + // return null; + // } + // let style = { left: this.pageX, top: this.pageY }; //const transform = "translate(" + (NumCast(this.props.node.x) + 350) + "px, " + NumCast(this.props.node.y) + "px" return ( - { this._width = r.offset.width; this._height = r.offset.height; })}> - {({ measureRef }) => ( -
-

Recommendations

- {this._documents.map(doc => { - return ( -
- - {this.DocumentIcon(doc.preview)} - - {doc.score.toFixed(4)} -
- ); - })} - -
- ) - } - -
+ // { this._width = r.offset.width; this._height = r.offset.height; })}> + // {({ measureRef }) => ( +
+

Recommendations

+ {DocListCast(this.props.Document.data).map(doc => { + return ( +
+ + {this.DocumentIcon(doc)} + + {NumCast(doc.score).toFixed(4)} +
DocumentManager.Instance.jumpToDocument(doc, true, undefined, undefined, undefined, this.props.Document.sourceDocContext as Doc)}> + +
+
DocUtils.MakeLink(this.props.Document.sourceDoc as Doc, doc, undefined, "User Selected Link", "Generated from Recommender", undefined)}> + +
+
+ ); + })} + +
+ // ); + // } + + //
); } } \ No newline at end of file diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index d77662355..c8a636727 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -29,6 +29,7 @@ import { Cast, StrCast, NumCast } from "../../../new_fields/Types"; import { List } from "../../../new_fields/List"; import { Doc } from "../../../new_fields/Doc"; import DirectoryImportBox from "../../util/Import & Export/DirectoryImportBox"; +import { RecommendationsBox } from "../../views/Recommendations"; import { ScriptField } from "../../../new_fields/ScriptField"; const JsxParser = require('react-jsx-parser').default; //TODO Why does this need to be imported like this? @@ -108,7 +109,7 @@ export class DocumentContentsView extends React.Component(Docu for (let i = 0; i < doclist.length; i++) { recDocs.push({ preview: doclist[i].actualDoc, score: doclist[i].score }); } - Recommendations.Instance.addDocuments(recDocs); - Recommendations.Instance.displayRecommendations(e.pageX + 100, e.pageY); + + const data = recDocs.map(unit => { + unit.preview.score = unit.score; + return unit.preview; + }); + + console.log(recDocs.map(doc => doc.score)); + + const title = `Showing ${data.length} recommendations for "${StrCast(this.props.Document.title)}"`; + const recommendations = Docs.Create.RecommendationsDocument(data, { title }); + recommendations.documentIconHeight = 150; + recommendations.sourceDoc = this.props.Document; + recommendations.sourceDocContext = this.props.ContainingCollectionView!.props.Document; + CollectionDockingView.Instance.AddRightSplit(recommendations, undefined); + + // RecommendationsBox.Instance.displayRecommendations(e.pageX + 100, e.pageY); } onPointerEnter = (e: React.PointerEvent): void => { Doc.BrushDoc(this.props.Document); }; -- cgit v1.2.3-70-g09d2 From c6e2eee8e5b035ed4cab1e7bb1315a36d43255c5 Mon Sep 17 00:00:00 2001 From: ab Date: Tue, 8 Oct 2019 16:02:25 -0400 Subject: switching out --- src/client/views/MainView.tsx | 1 - src/client/views/Recommendations.tsx | 2 +- .../collectionFreeForm/CollectionFreeFormView.tsx | 3 --- src/client/views/nodes/DocumentContentsView.tsx | 6 ------ src/client/views/nodes/DocumentView.tsx | 4 ++-- src/client/views/nodes/ImageBox.tsx | 1 - src/new_fields/RichTextField.ts | 17 ++++++++++++++++- 7 files changed, 19 insertions(+), 15 deletions(-) (limited to 'src/client/views/MainView.tsx') diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 17de708a2..e6f500e75 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -41,7 +41,6 @@ import { FilterBox } from './search/FilterBox'; import { SchemaHeaderField, RandomPastel } from '../../new_fields/SchemaHeaderField'; //import { DocumentManager } from '../util/DocumentManager'; import { RecommendationsBox } from './Recommendations'; -import PresModeMenu from './presentationview/PresentationModeMenu'; import { PresBox } from './nodes/PresBox'; import { OverlayView } from './OverlayView'; diff --git a/src/client/views/Recommendations.tsx b/src/client/views/Recommendations.tsx index b7b1d84d0..c44dfc032 100644 --- a/src/client/views/Recommendations.tsx +++ b/src/client/views/Recommendations.tsx @@ -174,7 +174,7 @@ export class RecommendationsBox extends React.Component { {this.DocumentIcon(doc)} {NumCast(doc.score).toFixed(4)} -
DocumentManager.Instance.jumpToDocument(doc, true, undefined, undefined, undefined, this.props.Document.sourceDocContext as Doc)}> +
DocumentManager.Instance.jumpToDocument(doc, false)}>
DocUtils.MakeLink(this.props.Document.sourceDoc as Doc, doc, undefined, "User Selected Link", "Generated from Recommender", undefined)}> diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 3ee069e4c..d2b8afa02 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -12,7 +12,6 @@ import { BoolCast, Cast, DateCast, NumCast, StrCast } from "../../../../new_fiel import { CurrentUserUtils } from "../../../../server/authentication/models/current_user_utils"; import { aggregateBounds, emptyFunction, intersectRect, returnEmptyString, returnOne, Utils } from "../../../../Utils"; import { CognitiveServices } from "../../../cognitive_services/CognitiveServices"; -import { DocServer } from "../../../DocServer"; import { Docs } from "../../../documents/Documents"; import { DocumentType } from "../../../documents/DocumentTypes"; import { DocumentManager } from "../../../util/DocumentManager"; @@ -28,7 +27,6 @@ import { InkingCanvas } from "../../InkingCanvas"; import { CollectionFreeFormDocumentView, positionSchema } from "../../nodes/CollectionFreeFormDocumentView"; import { DocumentContentsView } from "../../nodes/DocumentContentsView"; import { documentSchema, DocumentViewProps } from "../../nodes/DocumentView"; -import { FormattedTextBox } from "../../nodes/FormattedTextBox"; import { pageSchema } from "../../nodes/ImageBox"; import PDFMenu from "../../pdf/PDFMenu"; import { CollectionSubView } from "../CollectionSubView"; @@ -41,7 +39,6 @@ import React = require("react"); import v5 = require("uuid/v5"); import { ClientRecommender } from "../../../ClientRecommender"; import { SearchUtil } from "../../../util/SearchUtil"; -import { SearchBox } from "../../SearchBox"; import { RouteStore } from "../../../../server/RouteStore"; import { string, number, elementType } from "prop-types"; import { DocServer } from "../../../DocServer"; diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index e5eb8dbce..919c13055 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -2,8 +2,6 @@ import { computed } from "mobx"; import { observer } from "mobx-react"; import { Doc } from "../../../new_fields/Doc"; import { ScriptField } from "../../../new_fields/ScriptField"; -import { Cast } from "../../../new_fields/Types"; -import { OmitKeys, Without } from "../../../Utils"; import { HistogramBox } from "../../northstar/dash-nodes/HistogramBox"; import DirectoryImportBox from "../../util/Import & Export/DirectoryImportBox"; import { CollectionDockingView } from "../collections/CollectionDockingView"; @@ -30,14 +28,10 @@ import { PresElementBox } from "../presentationview/PresElementBox"; import { VideoBox } from "./VideoBox"; import { WebBox } from "./WebBox"; import React = require("react"); -import { FieldViewProps } from "./FieldView"; import { Without, OmitKeys } from "../../../Utils"; import { Cast, StrCast, NumCast } from "../../../new_fields/Types"; import { List } from "../../../new_fields/List"; -import { Doc } from "../../../new_fields/Doc"; -import DirectoryImportBox from "../../util/Import & Export/DirectoryImportBox"; import { RecommendationsBox } from "../../views/Recommendations"; -import { ScriptField } from "../../../new_fields/ScriptField"; const JsxParser = require('react-jsx-parser').default; //TODO Why does this need to be imported like this? type BindingProps = Without; diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 0064b98c3..070b1f426 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -621,7 +621,7 @@ export class DocumentView extends DocComponent(Docu recommendations.documentIconHeight = 150; recommendations.sourceDoc = this.props.Document; recommendations.sourceDocContext = this.props.ContainingCollectionView!.props.Document; - CollectionDockingView.Instance.AddRightSplit(recommendations, undefined); + CollectionDockingView.AddRightSplit(recommendations, undefined); // RecommendationsBox.Instance.displayRecommendations(e.pageX + 100, e.pageY); } @@ -641,7 +641,7 @@ export class DocumentView extends DocComponent(Docu body.href = urls[i]; bodies.push(body); } - CollectionDockingView.Instance.AddRightSplit(Docs.Create.SchemaDocument(headers, bodies, { title: `Showing External Recommendations for "${StrCast(doc.title)}"` }), undefined); + CollectionDockingView.AddRightSplit(Docs.Create.SchemaDocument(headers, bodies, { title: `Showing External Recommendations for "${StrCast(doc.title)}"` }), undefined); } onPointerEnter = (e: React.PointerEvent): void => { Doc.BrushDoc(this.props.Document); }; diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index f36b9895f..7ffe64b9b 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -29,7 +29,6 @@ import "./ImageBox.scss"; import React = require("react"); import { SearchUtil } from '../../util/SearchUtil'; import { ClientRecommender } from '../../ClientRecommender'; -import { DocumentType } from '../../documents/Documents'; var requestImageSize = require('../../util/request-image-size'); var path = require('path'); const { Howl } = require('howler'); diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts index 390045ee1..f41ea0350 100644 --- a/src/new_fields/RichTextField.ts +++ b/src/new_fields/RichTextField.ts @@ -4,6 +4,9 @@ import { Deserializable } from "../client/util/SerializationHelper"; import { Copy, ToScriptString, ToPlainText } from "./FieldSymbols"; import { scriptingGlobal } from "../client/util/Scripting"; +const delimiter = "\n"; +const joiner = ""; + @scriptingGlobal @Deserializable("RichTextField") export class RichTextField extends ObjectField { @@ -24,7 +27,19 @@ export class RichTextField extends ObjectField { } [ToPlainText]() { - return this.Data; + // Because we're working with plain text, just concatenate all paragraphs + let content = JSON.parse(this.Data).doc.content; + let paragraphs = content.filter((item: any) => item.type === "paragraph"); + + // Functions to flatten ProseMirror paragraph objects (and their components) to plain text + // While this function already exists in state.doc.textBeteen(), it doesn't account for newlines + let blockText = (block: any) => block.text; + let concatenateParagraph = (p: any) => (p.content ? p.content.map(blockText).join(joiner) : "") + delimiter; + + // Concatentate paragraphs and string the result together + let textParagraphs: string[] = paragraphs.map(concatenateParagraph); + let plainText = textParagraphs.join(joiner); + return plainText.substring(0, plainText.length - 1); } } \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 301784883375860a7c693db97fe8f279e5380caf Mon Sep 17 00:00:00 2001 From: ab Date: Sat, 19 Oct 2019 16:51:45 -0400 Subject: image stuff --- src/client/ClientRecommender.tsx | 3 +- src/client/documents/Documents.ts | 2 +- src/client/views/GlobalKeyHandler.ts | 2 +- src/client/views/MainView.tsx | 2 +- src/client/views/Recommendations.scss | 68 --------- src/client/views/Recommendations.tsx | 185 ------------------------ src/client/views/RecommendationsBox.scss | 68 +++++++++ src/client/views/RecommendationsBox.tsx | 185 ++++++++++++++++++++++++ src/client/views/nodes/DocumentContentsView.tsx | 4 +- src/client/views/nodes/DocumentView.tsx | 2 +- 10 files changed, 261 insertions(+), 260 deletions(-) delete mode 100644 src/client/views/Recommendations.scss delete mode 100644 src/client/views/Recommendations.tsx create mode 100644 src/client/views/RecommendationsBox.scss create mode 100644 src/client/views/RecommendationsBox.tsx (limited to 'src/client/views/MainView.tsx') diff --git a/src/client/ClientRecommender.tsx b/src/client/ClientRecommender.tsx index 73b05cf1a..97efedd89 100644 --- a/src/client/ClientRecommender.tsx +++ b/src/client/ClientRecommender.tsx @@ -12,6 +12,7 @@ import "./ClientRecommender.scss"; import { JSXElement } from "babel-types"; import { RichTextField } from "../new_fields/RichTextField"; import { ToPlainText } from "../new_fields/FieldSymbols"; +import { listSpec } from "../new_fields/Schema"; export interface RecommenderProps { title: string; @@ -148,7 +149,7 @@ export class ClientRecommender extends React.Component { public async extractText(dataDoc: Doc, extDoc: Doc, internal: boolean = true, isMainDoc: boolean = false, image: boolean = false) { let fielddata = Cast(dataDoc.data, RichTextField); if (image && extDoc.generatedTags) { - console.log(StrCast(extDoc.generatedTags)); + console.log(Cast(extDoc.generatedTags, listSpec("string"))); } let data: string; fielddata ? data = fielddata[ToPlainText]() : data = ""; diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 1179f0238..36f20199c 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -43,7 +43,7 @@ import { PresBox } from "../views/nodes/PresBox"; import { ComputedField, ScriptField } from "../../new_fields/ScriptField"; import { ProxyField } from "../../new_fields/Proxy"; import { DocumentType } from "./DocumentTypes"; -import { RecommendationsBox } from "../views/Recommendations"; +import { RecommendationsBox } from "../views/RecommendationsBox"; //import { PresBox } from "../views/nodes/PresBox"; //import { PresField } from "../../new_fields/PresField"; import { LinkFollowBox } from "../views/linking/LinkFollowBox"; diff --git a/src/client/views/GlobalKeyHandler.ts b/src/client/views/GlobalKeyHandler.ts index 189e2bbe0..b0d0a0d28 100644 --- a/src/client/views/GlobalKeyHandler.ts +++ b/src/client/views/GlobalKeyHandler.ts @@ -6,7 +6,7 @@ import { DragManager } from "../util/DragManager"; import { action, runInAction } from "mobx"; import { Doc } from "../../new_fields/Doc"; import { DictationManager } from "../util/DictationManager"; -import { RecommendationsBox } from "./Recommendations"; +import { RecommendationsBox } from "./RecommendationsBox"; import SharingManager from "../util/SharingManager"; import { CurrentUserUtils } from "../../server/authentication/models/current_user_utils"; import { Cast, PromiseValue } from "../../new_fields/Types"; diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index bfd9c2163..2b47c2534 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -38,7 +38,7 @@ import { PreviewCursor } from './PreviewCursor'; import { FilterBox } from './search/FilterBox'; import { SchemaHeaderField, RandomPastel } from '../../new_fields/SchemaHeaderField'; //import { DocumentManager } from '../util/DocumentManager'; -import { RecommendationsBox } from './Recommendations'; +import { RecommendationsBox } from './RecommendationsBox'; import { PresBox } from './nodes/PresBox'; import { OverlayView } from './OverlayView'; diff --git a/src/client/views/Recommendations.scss b/src/client/views/Recommendations.scss deleted file mode 100644 index dd8a105f6..000000000 --- a/src/client/views/Recommendations.scss +++ /dev/null @@ -1,68 +0,0 @@ -@import "globalCssVariables"; - -.rec-content *{ - display: inline-block; - margin: auto; - width: 50; - height: 150px; - border: 1px dashed grey; - padding: 10px 10px; -} - -.rec-content { - float: left; - width: inherit; - align-content: center; -} - -.rec-scroll { - overflow-y: scroll; - overflow-x: hidden; - position: absolute; - pointer-events: all; - // display: flex; - z-index: 10000; - box-shadow: gray 0.2vw 0.2vw 0.4vw; - // flex-direction: column; - background: whitesmoke; - padding-bottom: 10px; - padding-top: 20px; - // border-radius: 15px; - border: solid #BBBBBBBB 1px; - width: 100%; - text-align: center; - // max-height: 250px; - height: 100%; - text-transform: uppercase; - color: grey; - letter-spacing: 2px; -} - -.content { - padding: 10px; - display: flex; - flex-direction: row; - align-items: center; - justify-content: center; -} - -.image-background { - pointer-events: none; - background-color: transparent; - width: 50%; - text-align: center; - margin-left: 5px; -} - -img{ - width: 100%; - height: 100%; -} - -.score { - // margin-left: 15px; - width: 50%; - height: 100%; - text-align: center; - margin-left: 10px; -} diff --git a/src/client/views/Recommendations.tsx b/src/client/views/Recommendations.tsx deleted file mode 100644 index f965d655b..000000000 --- a/src/client/views/Recommendations.tsx +++ /dev/null @@ -1,185 +0,0 @@ -import { observer } from "mobx-react"; -import React = require("react"); -import { observable, action } from "mobx"; -import Measure from "react-measure"; -import "./Recommendations.scss"; -import { Doc, DocListCast, WidthSym, HeightSym } from "../../new_fields/Doc"; -import { DocumentIcon } from "./nodes/DocumentIcon"; -import { StrCast, NumCast } from "../../new_fields/Types"; -import { returnFalse, emptyFunction, returnEmptyString, returnOne } from "../../Utils"; -import { Transform } from "../util/Transform"; -import { ObjectField } from "../../new_fields/ObjectField"; -import { DocumentView } from "./nodes/DocumentView"; -import { DocumentType } from '../documents/DocumentTypes'; -import { ClientRecommender } from "../ClientRecommender"; -import { DocServer } from "../DocServer"; -import { Id } from "../../new_fields/FieldSymbols"; -import { FieldView, FieldViewProps } from "./nodes/FieldView"; -import { DocumentManager } from "../util/DocumentManager"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { library } from "@fortawesome/fontawesome-svg-core"; -import { faBullseye, faLink } from "@fortawesome/free-solid-svg-icons"; -import { DocUtils } from "../documents/Documents"; - -export interface RecProps { - documents: { preview: Doc, similarity: number }[]; - node: Doc; -} - -library.add(faBullseye, faLink); - -@observer -export class RecommendationsBox extends React.Component { - - public static LayoutString(fieldKey?: string) { return FieldView.LayoutString(RecommendationsBox, fieldKey); } - - static Instance: RecommendationsBox; - // @observable private _display: boolean = false; - @observable private _pageX: number = 0; - @observable private _pageY: number = 0; - @observable private _width: number = 0; - @observable private _height: number = 0; - // @observable private _documents: { preview: Doc, score: number }[] = []; - private previewDocs: Doc[] = []; - - constructor(props: FieldViewProps) { - super(props); - RecommendationsBox.Instance = this; - } - - private DocumentIcon(doc: Doc) { - let layoutresult = StrCast(doc.type); - let renderDoc = doc; - //let box: number[] = []; - if (layoutresult.indexOf(DocumentType.COL) !== -1) { - renderDoc = Doc.MakeDelegate(renderDoc); - let bounds = DocListCast(renderDoc.data).reduce((bounds, doc) => { - var [sptX, sptY] = [NumCast(doc.x), NumCast(doc.y)]; - let [bptX, bptY] = [sptX + doc[WidthSym](), sptY + doc[HeightSym]()]; - return { - x: Math.min(sptX, bounds.x), y: Math.min(sptY, bounds.y), - r: Math.max(bptX, bounds.r), b: Math.max(bptY, bounds.b) - }; - }, { x: Number.MAX_VALUE, y: Number.MAX_VALUE, r: Number.MIN_VALUE, b: Number.MIN_VALUE }); - } - let returnXDimension = () => 150; - let returnYDimension = () => 150; - let scale = () => returnXDimension() / NumCast(renderDoc.nativeWidth, returnXDimension()); - //let scale = () => 1; - let newRenderDoc = Doc.MakeAlias(renderDoc); /// newRenderDoc -> renderDoc -> render"data"Doc -> TextProt - newRenderDoc.height = NumCast(this.props.Document.documentIconHeight); - newRenderDoc.autoHeight = false; - const docview =
- -
; - return docview; - - } - - // @action - // closeMenu = () => { - // this._display = false; - // this.previewDocs.forEach(doc => DocServer.DeleteDocument(doc[Id])); - // this.previewDocs = []; - // } - - // @action - // resetDocuments = () => { - // this._documents = []; - // } - - // @action - // displayRecommendations(x: number, y: number) { - // this._pageX = x; - // this._pageY = y; - // this._display = true; - // } - - static readonly buffer = 20; - - // get pageX() { - // const x = this._pageX; - // if (x < 0) { - // return 0; - // } - // const width = this._width; - // if (x + width > window.innerWidth - RecommendationsBox.buffer) { - // return window.innerWidth - RecommendationsBox.buffer - width; - // } - // return x; - // } - - // get pageY() { - // const y = this._pageY; - // if (y < 0) { - // return 0; - // } - // const height = this._height; - // if (y + height > window.innerHeight - RecommendationsBox.buffer) { - // return window.innerHeight - RecommendationsBox.buffer - height; - // } - // return y; - // } - - render() { - // if (!this._display) { - // return null; - // } - // let style = { left: this.pageX, top: this.pageY }; - //const transform = "translate(" + (NumCast(this.props.node.x) + 350) + "px, " + NumCast(this.props.node.y) + "px" - let title = StrCast((this.props.Document.sourceDoc as Doc).title); - if (title.length > 15) { - title = title.substring(0, 15) + "..."; - } - return ( - // { this._width = r.offset.width; this._height = r.offset.height; })}> - // {({ measureRef }) => ( -
-

Recommendations for "{title}"

- {DocListCast(this.props.Document.data).map(doc => { - return ( -
- - {this.DocumentIcon(doc)} - - {NumCast(doc.score).toFixed(4)} -
DocumentManager.Instance.jumpToDocument(doc, false)}> - -
-
DocUtils.MakeLink({ doc: this.props.Document.sourceDoc as Doc }, { doc: doc }, "User Selected Link", "Generated from Recommender", undefined)}> - -
-
- ); - })} - -
- // ); - // } - - //
- ); - } -} \ No newline at end of file diff --git a/src/client/views/RecommendationsBox.scss b/src/client/views/RecommendationsBox.scss new file mode 100644 index 000000000..dd8a105f6 --- /dev/null +++ b/src/client/views/RecommendationsBox.scss @@ -0,0 +1,68 @@ +@import "globalCssVariables"; + +.rec-content *{ + display: inline-block; + margin: auto; + width: 50; + height: 150px; + border: 1px dashed grey; + padding: 10px 10px; +} + +.rec-content { + float: left; + width: inherit; + align-content: center; +} + +.rec-scroll { + overflow-y: scroll; + overflow-x: hidden; + position: absolute; + pointer-events: all; + // display: flex; + z-index: 10000; + box-shadow: gray 0.2vw 0.2vw 0.4vw; + // flex-direction: column; + background: whitesmoke; + padding-bottom: 10px; + padding-top: 20px; + // border-radius: 15px; + border: solid #BBBBBBBB 1px; + width: 100%; + text-align: center; + // max-height: 250px; + height: 100%; + text-transform: uppercase; + color: grey; + letter-spacing: 2px; +} + +.content { + padding: 10px; + display: flex; + flex-direction: row; + align-items: center; + justify-content: center; +} + +.image-background { + pointer-events: none; + background-color: transparent; + width: 50%; + text-align: center; + margin-left: 5px; +} + +img{ + width: 100%; + height: 100%; +} + +.score { + // margin-left: 15px; + width: 50%; + height: 100%; + text-align: center; + margin-left: 10px; +} diff --git a/src/client/views/RecommendationsBox.tsx b/src/client/views/RecommendationsBox.tsx new file mode 100644 index 000000000..3938a8690 --- /dev/null +++ b/src/client/views/RecommendationsBox.tsx @@ -0,0 +1,185 @@ +import { observer } from "mobx-react"; +import React = require("react"); +import { observable, action } from "mobx"; +import Measure from "react-measure"; +import "./RecommendationsBox.scss"; +import { Doc, DocListCast, WidthSym, HeightSym } from "../../new_fields/Doc"; +import { DocumentIcon } from "./nodes/DocumentIcon"; +import { StrCast, NumCast } from "../../new_fields/Types"; +import { returnFalse, emptyFunction, returnEmptyString, returnOne } from "../../Utils"; +import { Transform } from "../util/Transform"; +import { ObjectField } from "../../new_fields/ObjectField"; +import { DocumentView } from "./nodes/DocumentView"; +import { DocumentType } from '../documents/DocumentTypes'; +import { ClientRecommender } from "../ClientRecommender"; +import { DocServer } from "../DocServer"; +import { Id } from "../../new_fields/FieldSymbols"; +import { FieldView, FieldViewProps } from "./nodes/FieldView"; +import { DocumentManager } from "../util/DocumentManager"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { library } from "@fortawesome/fontawesome-svg-core"; +import { faBullseye, faLink } from "@fortawesome/free-solid-svg-icons"; +import { DocUtils } from "../documents/Documents"; + +export interface RecProps { + documents: { preview: Doc, similarity: number }[]; + node: Doc; +} + +library.add(faBullseye, faLink); + +@observer +export class RecommendationsBox extends React.Component { + + public static LayoutString(fieldKey?: string) { return FieldView.LayoutString(RecommendationsBox, fieldKey); } + + static Instance: RecommendationsBox; + // @observable private _display: boolean = false; + @observable private _pageX: number = 0; + @observable private _pageY: number = 0; + @observable private _width: number = 0; + @observable private _height: number = 0; + // @observable private _documents: { preview: Doc, score: number }[] = []; + private previewDocs: Doc[] = []; + + constructor(props: FieldViewProps) { + super(props); + RecommendationsBox.Instance = this; + } + + private DocumentIcon(doc: Doc) { + let layoutresult = StrCast(doc.type); + let renderDoc = doc; + //let box: number[] = []; + if (layoutresult.indexOf(DocumentType.COL) !== -1) { + renderDoc = Doc.MakeDelegate(renderDoc); + let bounds = DocListCast(renderDoc.data).reduce((bounds, doc) => { + var [sptX, sptY] = [NumCast(doc.x), NumCast(doc.y)]; + let [bptX, bptY] = [sptX + doc[WidthSym](), sptY + doc[HeightSym]()]; + return { + x: Math.min(sptX, bounds.x), y: Math.min(sptY, bounds.y), + r: Math.max(bptX, bounds.r), b: Math.max(bptY, bounds.b) + }; + }, { x: Number.MAX_VALUE, y: Number.MAX_VALUE, r: Number.MIN_VALUE, b: Number.MIN_VALUE }); + } + let returnXDimension = () => 150; + let returnYDimension = () => 150; + let scale = () => returnXDimension() / NumCast(renderDoc.nativeWidth, returnXDimension()); + //let scale = () => 1; + let newRenderDoc = Doc.MakeAlias(renderDoc); /// newRenderDoc -> renderDoc -> render"data"Doc -> TextProt + newRenderDoc.height = NumCast(this.props.Document.documentIconHeight); + newRenderDoc.autoHeight = false; + const docview =
+ +
; + return docview; + + } + + // @action + // closeMenu = () => { + // this._display = false; + // this.previewDocs.forEach(doc => DocServer.DeleteDocument(doc[Id])); + // this.previewDocs = []; + // } + + // @action + // resetDocuments = () => { + // this._documents = []; + // } + + // @action + // displayRecommendations(x: number, y: number) { + // this._pageX = x; + // this._pageY = y; + // this._display = true; + // } + + static readonly buffer = 20; + + // get pageX() { + // const x = this._pageX; + // if (x < 0) { + // return 0; + // } + // const width = this._width; + // if (x + width > window.innerWidth - RecommendationsBox.buffer) { + // return window.innerWidth - RecommendationsBox.buffer - width; + // } + // return x; + // } + + // get pageY() { + // const y = this._pageY; + // if (y < 0) { + // return 0; + // } + // const height = this._height; + // if (y + height > window.innerHeight - RecommendationsBox.buffer) { + // return window.innerHeight - RecommendationsBox.buffer - height; + // } + // return y; + // } + + render() { + // if (!this._display) { + // return null; + // } + // let style = { left: this.pageX, top: this.pageY }; + //const transform = "translate(" + (NumCast(this.props.node.x) + 350) + "px, " + NumCast(this.props.node.y) + "px" + let title = StrCast((this.props.Document.sourceDoc as Doc).title); + if (title.length > 15) { + title = title.substring(0, 15) + "..."; + } + return ( + // { this._width = r.offset.width; this._height = r.offset.height; })}> + // {({ measureRef }) => ( +
+

Recommendations for "{title}"

+ {DocListCast(this.props.Document.data).map(doc => { + return ( +
+ + {this.DocumentIcon(doc)} + + {NumCast(doc.score).toFixed(4)} +
DocumentManager.Instance.jumpToDocument(doc, false)}> + +
+
DocUtils.MakeLink({ doc: this.props.Document.sourceDoc as Doc }, { doc: doc }, "User Selected Link", "Generated from Recommender", undefined)}> + +
+
+ ); + })} + +
+ // ); + // } + + //
+ ); + } +} \ No newline at end of file diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index 32d74b193..01096e5e5 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -31,7 +31,7 @@ import { WebBox } from "./WebBox"; import React = require("react"); import { Without, OmitKeys } from "../../../Utils"; import { Cast } from "../../../new_fields/Types"; -import { RecommendationsBox } from "../../views/Recommendations"; +import { RecommendationsBox } from "../RecommendationsBox"; const JsxParser = require('react-jsx-parser').default; //TODO Why does this need to be imported like this? type BindingProps = Without; @@ -96,7 +96,7 @@ export class DocumentContentsView extends React.Component Date: Wed, 15 Jan 2020 16:08:48 -0500 Subject: mobile interface emits events when switched to inking view and when strokes are drawn, currently with dummy callbacks --- src/client/DocServer.ts | 22 ++++++++++++++++++- src/client/views/GestureOverlay.tsx | 21 ++++++++++++++++++ src/client/views/MainView.tsx | 13 +++++++++-- .../collectionFreeForm/CollectionFreeFormView.tsx | 3 --- src/mobile/MobileInterface.tsx | 25 +++++++++++++++------- src/server/Message.ts | 13 +++++++++++ src/server/Websocket/Websocket.ts | 12 ++++++++++- 7 files changed, 94 insertions(+), 15 deletions(-) (limited to 'src/client/views/MainView.tsx') diff --git a/src/client/DocServer.ts b/src/client/DocServer.ts index ed7fbd7ba..cfd9612ed 100644 --- a/src/client/DocServer.ts +++ b/src/client/DocServer.ts @@ -1,10 +1,11 @@ import * as OpenSocket from 'socket.io-client'; -import { MessageStore, YoutubeQueryTypes } from "./../server/Message"; +import { MessageStore, YoutubeQueryTypes, GestureContent } from "./../server/Message"; import { Opt, Doc } from '../new_fields/Doc'; import { Utils, emptyFunction } from '../Utils'; import { SerializationHelper } from './util/SerializationHelper'; import { RefField } from '../new_fields/RefField'; import { Id, HandleUpdate } from '../new_fields/FieldSymbols'; +import GestureOverlay from './views/GestureOverlay'; /** * This class encapsulates the transfer and cross-client synchronization of @@ -64,6 +65,19 @@ export namespace DocServer { } } + export namespace Mobile { + + export function dispatchGesturePoints(content: GestureContent) { + Utils.Emit(_socket, MessageStore.GesturePoints, content); + } + + export function dispatchBoxTrigger(enableBox: boolean) { + // _socket.emit("dispatchBoxTrigger"); + Utils.Emit(_socket, MessageStore.MobileInkBoxTrigger, enableBox); + } + + } + export function init(protocol: string, hostname: string, port: number, identifier: string) { _cache = {}; GUID = identifier; @@ -85,6 +99,12 @@ export namespace DocServer { Utils.AddServerHandler(_socket, MessageStore.ConnectionTerminated, () => { alert("Your connection to the server has been terminated."); }); + _socket.addEventListener("receiveGesturePoints", (content: GestureContent) => { + GestureOverlay.Instance.manualDispatch(content); + }); + _socket.addEventListener("receiveBoxTrigger", (enableBox: boolean) => { + GestureOverlay.Instance.showBox(enableBox); + }); } function errorFunc(): never { diff --git a/src/client/views/GestureOverlay.tsx b/src/client/views/GestureOverlay.tsx index 4d487c032..4b8dfa119 100644 --- a/src/client/views/GestureOverlay.tsx +++ b/src/client/views/GestureOverlay.tsx @@ -16,6 +16,10 @@ import { Scripting } from "../util/Scripting"; import { FieldValue, Cast } from "../../new_fields/Types"; import { CurrentUserUtils } from "../../server/authentication/models/current_user_utils"; import Palette from "./Palette"; +import MobileInterface from "../../mobile/MobileInterface"; +import { MainView } from "./MainView"; +import { DocServer } from "../DocServer"; +import { GestureContent } from "../../server/Message"; @observer export default class GestureOverlay extends Touchable { @@ -35,6 +39,14 @@ export default class GestureOverlay extends Touchable { GestureOverlay.Instance = this; } + manualDispatch = (content: GestureContent) => { + console.log(content); + } + + showBox = (enableBox: boolean) => { + console.log("enable box?", enableBox); + } + @action handleHandDown = (e: React.TouchEvent) => { const fingers = InteractionUtils.GetMyTargetTouches(e, this.prevPoints, true); @@ -139,6 +151,15 @@ export default class GestureOverlay extends Touchable { const B = this.svgBounds; const points = this._points.map(p => ({ X: p.X - B.left, Y: p.Y - B.top })); + if (MobileInterface.Instance.drawingInk) { + const { selectedColor, selectedWidth } = InkingControl.Instance; + DocServer.Mobile.dispatchGesturePoints({ + points: this._points, + color: selectedColor, + width: selectedWidth + }); + } + const result = GestureUtils.GestureRecognizer.Recognize(new Array(points)); let actionPerformed = false; if (result && result.Score > 0.7) { diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 93fb0a07c..f1f7c37a3 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -49,6 +49,7 @@ export class MainView extends React.Component { private _flyoutSizeOnDown = 0; private _urlState: HistoryUtil.DocUrl; private _docBtnRef = React.createRef(); + private _mainViewRef = React.createRef(); @observable private _panelWidth: number = 0; @observable private _panelHeight: number = 0; @@ -507,8 +508,16 @@ export class MainView extends React.Component { return (null); } + get mainViewElement() { + return document.getElementById("mainView-container"); + } + + get mainViewRef() { + return this._mainViewRef; + } + render() { - return (
+ return (
@@ -518,7 +527,7 @@ export class MainView extends React.Component { - + diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 8d376fb57..bbfd22f50 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -114,7 +114,6 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { } private addDocument = (newBox: Doc) => { const added = this.props.addDocument(newBox); - console.log("adding doc from freeform", added); added && this.bringToFront(newBox); added && this.updateCluster(newBox); return added; @@ -362,7 +361,6 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { const points = ge.points; const B = this.getTransform().transformBounds(ge.bounds.left, ge.bounds.top, ge.bounds.width, ge.bounds.height); const inkDoc = Docs.Create.InkDocument(InkingControl.Instance.selectedColor, InkingControl.Instance.selectedTool, parseInt(InkingControl.Instance.selectedWidth), points, { x: B.x, y: B.y, width: B.width, height: B.height }); - console.log("make stroke", inkDoc); this.addDocument(inkDoc); e.stopPropagation(); break; @@ -991,7 +989,6 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { // otherwise, they are stored in fieldKey. All annotations to this document are stored in the extension document if (!this.extensionDoc) return (null); // let lodarea = this.Document[WidthSym]() * this.Document[HeightSym]() / this.props.ScreenToLocalTransform().Scale / this.props.ScreenToLocalTransform().Scale; - console.log("height freeform", this.isAnnotationOverlay, this.Document.scrollHeight, this.props.PanelHeight()); return
diff --git a/src/mobile/MobileInterface.tsx b/src/mobile/MobileInterface.tsx index 3cb08afa7..1429226b4 100644 --- a/src/mobile/MobileInterface.tsx +++ b/src/mobile/MobileInterface.tsx @@ -2,7 +2,7 @@ import React = require('react'); import { observer } from 'mobx-react'; import { computed, action, observable } from 'mobx'; import { CurrentUserUtils } from '../server/authentication/models/current_user_utils'; -import { FieldValue, Cast } from '../new_fields/Types'; +import { FieldValue, Cast, StrCast } from '../new_fields/Types'; import { Doc } from '../new_fields/Doc'; import { Docs } from '../client/documents/Documents'; import { CollectionView } from '../client/views/collections/CollectionView'; @@ -18,6 +18,10 @@ import { InkingControl } from '../client/views/InkingControl'; import { InkTool } from '../new_fields/InkField'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import "./MobileInterface.scss"; +import { SelectionManager } from '../client/util/SelectionManager'; +import { DateField } from '../new_fields/DateField'; +import { GestureUtils } from '../pen-gestures/GestureUtils'; +import { DocServer } from '../client/DocServer'; library.add(faTrash, faCheck); @@ -30,6 +34,7 @@ export default class MobileInterface extends React.Component { private mainDoc = CurrentUserUtils.setupMobileDoc(this.userDoc); private inkDoc?: Doc; + public drawingInk: boolean = false; constructor(props: Readonly<{}>) { super(props); @@ -61,6 +66,10 @@ export default class MobileInterface extends React.Component { this.inkDoc = CurrentUserUtils.setupMobileInkingDoc(this.userDoc); this.userDoc.activeMobile = this.inkDoc; InkingControl.Instance.switchTool(InkTool.Pen); + this.drawingInk = true; + + DocServer.Mobile.dispatchBoxTrigger(true); + break; } } @@ -100,17 +109,17 @@ export default class MobileInterface extends React.Component { } onClick = (e: React.MouseEvent) => { - // insert ink as collection into active displayed doc view - // reset ink collection - this.inkDoc = undefined; - console.log("clicked"); this.switchCurrentView("main"); InkingControl.Instance.switchTool(InkTool.None); // TODO: switch to previous tool + + DocServer.Mobile.dispatchBoxTrigger(false); + + this.inkDoc = undefined; + this.drawingInk = false; } @computed get inkContent() { - // TODO: get props from active collection and pass to the new freeform if (this.mainContainer) { return ( @@ -128,9 +137,9 @@ export default class MobileInterface extends React.Component { PanelHeight={() => window.innerHeight} PanelWidth={() => window.innerWidth} focus={emptyFunction} - isSelected={returnTrue} + isSelected={returnFalse} select={emptyFunction} - active={returnTrue} + active={returnFalse} ContentScaling={returnOne} whenActiveChanged={returnFalse} ScreenToLocalTransform={Transform.Identity} diff --git a/src/server/Message.ts b/src/server/Message.ts index 621abfd1e..fe74dafa5 100644 --- a/src/server/Message.ts +++ b/src/server/Message.ts @@ -1,4 +1,5 @@ import { Utils } from "../Utils"; +import { Point } from "../pen-gestures/ndollar"; export class Message { private _name: string; @@ -42,6 +43,16 @@ export interface Diff extends Reference { readonly diff: any; } +export interface GestureContent { + readonly points: Array; + readonly width?: string; + readonly color?: string; +} + +export interface MobileInkBoxTriggerContent { + readonly enableBox: boolean; +} + export namespace MessageStore { export const Foo = new Message("Foo"); export const Bar = new Message("Bar"); @@ -51,6 +62,8 @@ export namespace MessageStore { export const GetDocument = new Message("Get Document"); export const DeleteAll = new Message("Delete All"); export const ConnectionTerminated = new Message("Connection Terminated"); + export const GesturePoints = new Message("Gesture Points"); + export const MobileInkBoxTrigger = new Message("Trigger Mobile Ink Box"); export const GetRefField = new Message("Get Ref Field"); export const GetRefFields = new Message("Get Ref Fields"); diff --git a/src/server/Websocket/Websocket.ts b/src/server/Websocket/Websocket.ts index 578147d60..67777f023 100644 --- a/src/server/Websocket/Websocket.ts +++ b/src/server/Websocket/Websocket.ts @@ -1,5 +1,5 @@ import { Utils } from "../../Utils"; -import { MessageStore, Transferable, Types, Diff, YoutubeQueryInput, YoutubeQueryTypes } from "../Message"; +import { MessageStore, Transferable, Types, Diff, YoutubeQueryInput, YoutubeQueryTypes, GestureContent } from "../Message"; import { Client } from "../Client"; import { Socket } from "socket.io"; import { Database } from "../database"; @@ -54,6 +54,8 @@ export namespace WebSocket { Utils.AddServerHandler(socket, MessageStore.UpdateField, diff => UpdateField(socket, diff)); Utils.AddServerHandler(socket, MessageStore.DeleteField, id => DeleteField(socket, id)); Utils.AddServerHandler(socket, MessageStore.DeleteFields, ids => DeleteFields(socket, ids)); + Utils.AddServerHandler(socket, MessageStore.GesturePoints, content => processGesturePoints(socket, content)); + Utils.AddServerHandler(socket, MessageStore.MobileInkBoxTrigger, enableBox => processBoxTrigger(socket, enableBox)); Utils.AddServerHandlerCallback(socket, MessageStore.GetRefField, GetRefField); Utils.AddServerHandlerCallback(socket, MessageStore.GetRefFields, GetRefFields); @@ -68,6 +70,14 @@ export namespace WebSocket { logPort("websocket", socketPort); } + function processGesturePoints(socket: Socket, content: GestureContent) { + socket.broadcast.emit("receiveGesturePoints", content); + } + + function processBoxTrigger(socket: Socket, enableBox: boolean) { + socket.broadcast.emit("receiveBoxTrigger", enableBox); + } + function HandleYoutubeQuery([query, callback]: [YoutubeQueryInput, (result?: any[]) => void]) { const { ProjectCredentials } = GoogleCredentialsLoader; switch (query.type) { -- cgit v1.2.3-70-g09d2 From 87167fd126e161b29d8d798a5f04e3cf159aae16 Mon Sep 17 00:00:00 2001 From: Stanley Yip Date: Sat, 8 Feb 2020 15:58:07 -0500 Subject: some fixes to thumb movements --- package-lock.json | 27 +++++--- src/client/views/GestureOverlay.scss | 2 +- src/client/views/GestureOverlay.tsx | 107 +++++++++++++++++++------------- src/client/views/MainView.tsx | 2 +- src/client/views/nodes/DocumentView.tsx | 4 +- 5 files changed, 86 insertions(+), 56 deletions(-) (limited to 'src/client/views/MainView.tsx') diff --git a/package-lock.json b/package-lock.json index 31524932c..825890038 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5391,7 +5391,8 @@ }, "ansi-regex": { "version": "2.1.1", - "bundled": true + "bundled": true, + "optional": true }, "aproba": { "version": "1.2.0", @@ -5428,7 +5429,8 @@ }, "code-point-at": { "version": "1.1.0", - "bundled": true + "bundled": true, + "optional": true }, "concat-map": { "version": "0.0.1", @@ -5437,7 +5439,8 @@ }, "console-control-strings": { "version": "1.1.0", - "bundled": true + "bundled": true, + "optional": true }, "core-util-is": { "version": "1.0.2", @@ -5551,6 +5554,7 @@ "is-fullwidth-code-point": { "version": "1.0.0", "bundled": true, + "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -5576,6 +5580,7 @@ "minipass": { "version": "2.9.0", "bundled": true, + "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" @@ -5592,6 +5597,7 @@ "mkdirp": { "version": "0.5.1", "bundled": true, + "optional": true, "requires": { "minimist": "0.0.8" } @@ -5683,6 +5689,7 @@ "once": { "version": "1.4.0", "bundled": true, + "optional": true, "requires": { "wrappy": "1" } @@ -5758,7 +5765,8 @@ }, "safe-buffer": { "version": "5.1.2", - "bundled": true + "bundled": true, + "optional": true }, "safer-buffer": { "version": "2.1.2", @@ -5788,6 +5796,7 @@ "string-width": { "version": "1.0.2", "bundled": true, + "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -5805,6 +5814,7 @@ "strip-ansi": { "version": "3.0.1", "bundled": true, + "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -5843,7 +5853,8 @@ }, "wrappy": { "version": "1.0.2", - "bundled": true + "bundled": true, + "optional": true }, "yallist": { "version": "3.1.1", @@ -13826,7 +13837,7 @@ }, "readable-stream": { "version": "2.3.6", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", "requires": { "core-util-is": "~1.0.0", @@ -15742,7 +15753,7 @@ }, "strip-ansi": { "version": "3.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "requires": { "ansi-regex": "^2.0.0" @@ -18314,4 +18325,4 @@ } } } -} \ No newline at end of file +} diff --git a/src/client/views/GestureOverlay.scss b/src/client/views/GestureOverlay.scss index 2fad87ee0..7474ca839 100644 --- a/src/client/views/GestureOverlay.scss +++ b/src/client/views/GestureOverlay.scss @@ -26,7 +26,7 @@ .menuItem-cont { width: 100%; - height: 20px; + height: 25px; padding: 2.5px; border-bottom: .5px solid black; } diff --git a/src/client/views/GestureOverlay.tsx b/src/client/views/GestureOverlay.tsx index cd535bd53..b23d4d020 100644 --- a/src/client/views/GestureOverlay.tsx +++ b/src/client/views/GestureOverlay.tsx @@ -130,7 +130,7 @@ export default class GestureOverlay extends Touchable { if (nts.nt.length < 5) { const target = document.elementFromPoint(te.changedTouches.item(0).clientX, te.changedTouches.item(0).clientY); - target ?.dispatchEvent( + target?.dispatchEvent( new CustomEvent>("dashOnTouchStart", { bubbles: true, @@ -144,34 +144,34 @@ export default class GestureOverlay extends Touchable { } ) ); - if (this.prevPoints.size === 1 && this._holdTimer === undefined) { - console.log("started"); - this._holdTimer = setTimeout(() => { - console.log("hold"); - const target = document.elementFromPoint(te.changedTouches.item(0).clientX, te.changedTouches.item(0).clientY); - target ?.dispatchEvent( - new CustomEvent>("dashOnTouchHoldStart", - { - bubbles: true, - detail: { - fingers: this.prevPoints.size, - targetTouches: nts.ntt, - touches: nts.nt, - changedTouches: nts.nct, - touchEvent: te - } - } - ) - ); - this._holdTimer = undefined; - document.removeEventListener("touchmove", this.onReactTouchMove); - document.removeEventListener("touchend", this.onReactTouchEnd); - document.removeEventListener("touchmove", this.onReactHoldTouchMove); - document.removeEventListener("touchend", this.onReactHoldTouchEnd); - document.addEventListener("touchmove", this.onReactHoldTouchMove); - document.addEventListener("touchend", this.onReactHoldTouchEnd); - }, (1000)); - } + // if (this.prevPoints.size === 1 && this._holdTimer === undefined) { + // console.log("started"); + // this._holdTimer = setTimeout(() => { + // console.log("hold"); + // const target = document.elementFromPoint(te.changedTouches.item(0).clientX, te.changedTouches.item(0).clientY); + // target?.dispatchEvent( + // new CustomEvent>("dashOnTouchHoldStart", + // { + // bubbles: true, + // detail: { + // fingers: this.prevPoints.size, + // targetTouches: nts.ntt, + // touches: nts.nt, + // changedTouches: nts.nct, + // touchEvent: te + // } + // } + // ) + // ); + // this._holdTimer = undefined; + // document.removeEventListener("touchmove", this.onReactTouchMove); + // document.removeEventListener("touchend", this.onReactTouchEnd); + // document.removeEventListener("touchmove", this.onReactHoldTouchMove); + // document.removeEventListener("touchend", this.onReactHoldTouchEnd); + // document.addEventListener("touchmove", this.onReactHoldTouchMove); + // document.addEventListener("touchend", this.onReactHoldTouchEnd); + // }, (1000)); + // } document.removeEventListener("touchmove", this.onReactTouchMove); document.removeEventListener("touchend", this.onReactTouchEnd); document.addEventListener("touchmove", this.onReactTouchMove); @@ -304,7 +304,7 @@ export default class GestureOverlay extends Touchable { if (pt.radiusX > 1 && pt.radiusY > 1) { for (let j = 0; j < e.targetTouches.length; j++) { const tPt = e.targetTouches.item(j); - if (tPt ?.screenX === pt ?.screenX && tPt ?.screenY === pt ?.screenY) { + if (tPt?.screenX === pt?.screenX && tPt?.screenY === pt?.screenY) { if (pt && this.prevPoints.has(pt.identifier)) { fingers.push(pt); } @@ -392,17 +392,32 @@ export default class GestureOverlay extends Touchable { for (let i = 0; i < e.changedTouches.length; i++) { const pt = e.changedTouches.item(i); if (pt && pt.identifier === this.thumbIdentifier && this._thumbY) { - if (this._thumbX && this._thumbDoc) { - if (Math.abs(pt.clientX - this._thumbX) > 30) { - this._thumbDoc.selectedIndex = Math.max(0, NumCast(this._thumbDoc.selectedIndex) - Math.sign(pt.clientX - this._thumbX)); - this._thumbX = pt.clientX; + if (this._thumbX && this._thumbY) { + const yOverX = Math.abs(pt.clientX - this._thumbX) < Math.abs(pt.clientY - this._thumbY); + if ((yOverX && this._inkToTextDoc) || this._selectedIndex > 0) { + if (Math.abs(pt.clientY - this._thumbY) > 20) { + this._selectedIndex = Math.min(Math.max(0, -Math.ceil((pt.clientY - this._thumbY) / 20)), this._possibilities.length - 1); + } } - } - if (this._thumbY && this._inkToTextDoc) { - if (Math.abs(pt.clientY - this._thumbY) > 20) { - this._selectedIndex = Math.max(0, -Math.floor((pt.clientY - this._thumbY) / 20)); + else if (this._thumbDoc) { + if (Math.abs(pt.clientX - this._thumbX) > 30) { + this._thumbDoc.selectedIndex = Math.max(0, NumCast(this._thumbDoc.selectedIndex) - Math.sign(pt.clientX - this._thumbX)); + this._thumbX = pt.clientX; + } } } + + // if (this._thumbX && this._thumbDoc) { + // if (Math.abs(pt.clientX - this._thumbX) > 30) { + // this._thumbDoc.selectedIndex = Math.max(0, NumCast(this._thumbDoc.selectedIndex) - Math.sign(pt.clientX - this._thumbX)); + // this._thumbX = pt.clientX; + // } + // } + // if (this._thumbY && this._inkToTextDoc) { + // if (Math.abs(pt.clientY - this._thumbY) > 20) { + // this._selectedIndex = Math.min(Math.max(0, -Math.ceil((pt.clientY - this._thumbY) / 20)), this._possibilities.length - 1); + // } + // } } if (pt && pt.identifier === this.pointerIdentifier) { this._pointerY = pt.clientY; @@ -506,8 +521,8 @@ export default class GestureOverlay extends Touchable { callbackFn: callback } }); - target1 ?.dispatchEvent(ge); - target2 ?.dispatchEvent(ge); + target1?.dispatchEvent(ge); + target2?.dispatchEvent(ge); return actionPerformed; } @@ -529,12 +544,16 @@ export default class GestureOverlay extends Touchable { this._strokes.push(new Array(...this._points)); this._points = []; CognitiveServices.Inking.Appliers.InterpretStrokes(this._strokes).then((results) => { - const wordResults = results.filter((r: any) => r.category === "inkWord" || r.category === "paragraph"); + console.log(results); + const wordResults = results.filter((r: any) => r.category === "line"); const possibilities: string[] = []; - if (wordResults[0]?.recognizedText) { - possibilities.push(wordResults[0]?.recognizedText) + for (const wR of wordResults) { + console.log(wR); + if (wR?.recognizedText) { + possibilities.push(wR?.recognizedText) + } + possibilities.push(...wR?.alternates?.map((a: any) => a.recognizedString)); } - possibilities.push(...wordResults[0]?.alternates?.map((a: any) => a.recognizedString)); console.log(possibilities); const r = Math.max(this.svgBounds.right, ...this._strokes.map(s => this.getBounds(s).right)); const l = Math.min(this.svgBounds.left, ...this._strokes.map(s => this.getBounds(s).left)); diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 87a81504c..4e81f528a 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -526,7 +526,7 @@ export class MainView extends React.Component { - + {/* */} diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 925a590ca..4a5613428 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -170,7 +170,7 @@ export class DocumentView extends DocComponent(Docu this._mainCont.current && (this._dropDisposer = DragManager.MakeDropTarget(this._mainCont.current, this.drop.bind(this))); this._mainCont.current && (this._gestureEventDisposer = GestureUtils.MakeGestureTarget(this._mainCont.current, this.onGesture.bind(this))); this._mainCont.current && (this.multiTouchDisposer = InteractionUtils.MakeMultiTouchTarget(this._mainCont.current, this.onTouchStart.bind(this))); - this._mainCont.current && (this.holdDisposer = InteractionUtils.MakeHoldTouchTarget(this._mainCont.current, this.handle1PointerHoldStart.bind(this))); + // this._mainCont.current && (this.holdDisposer = InteractionUtils.MakeHoldTouchTarget(this._mainCont.current, this.handle1PointerHoldStart.bind(this))); !this.props.dontRegisterView && DocumentManager.Instance.DocumentViews.push(this); } @@ -184,7 +184,7 @@ export class DocumentView extends DocComponent(Docu this._mainCont.current && (this._dropDisposer = DragManager.MakeDropTarget(this._mainCont.current, this.drop.bind(this))); this._mainCont.current && (this._gestureEventDisposer = GestureUtils.MakeGestureTarget(this._mainCont.current, this.onGesture.bind(this))); this._mainCont.current && (this.multiTouchDisposer = InteractionUtils.MakeMultiTouchTarget(this._mainCont.current, this.onTouchStart.bind(this))); - this._mainCont.current && (this.holdDisposer = InteractionUtils.MakeHoldTouchTarget(this._mainCont.current, this.handle1PointerHoldStart.bind(this))); + // this._mainCont.current && (this.holdDisposer = InteractionUtils.MakeHoldTouchTarget(this._mainCont.current, this.handle1PointerHoldStart.bind(this))); } @action -- cgit v1.2.3-70-g09d2 From 1e6d81d5f3019a6407ed764e3725611e0228489b Mon Sep 17 00:00:00 2001 From: eeng5 Date: Sun, 9 Feb 2020 15:52:40 -0500 Subject: :asdkfjl --- package.json | 2 +- src/client/views/GestureOverlay.tsx | 56 ++++++++++++++++----------------- src/client/views/MainView.tsx | 2 +- src/client/views/nodes/DocumentView.tsx | 2 +- 4 files changed, 31 insertions(+), 31 deletions(-) (limited to 'src/client/views/MainView.tsx') diff --git a/package.json b/package.json index 67b9b1630..7e0adfba6 100644 --- a/package.json +++ b/package.json @@ -253,4 +253,4 @@ "xoauth2": "^1.2.0", "youtube": "^0.1.0" } -} \ No newline at end of file +} diff --git a/src/client/views/GestureOverlay.tsx b/src/client/views/GestureOverlay.tsx index 4e9b87eea..b85f35fe4 100644 --- a/src/client/views/GestureOverlay.tsx +++ b/src/client/views/GestureOverlay.tsx @@ -144,34 +144,34 @@ export default class GestureOverlay extends Touchable { } ) ); - // if (this.prevPoints.size === 1 && this._holdTimer === undefined) { - // console.log("started"); - // this._holdTimer = setTimeout(() => { - // console.log("hold"); - // const target = document.elementFromPoint(te.changedTouches.item(0).clientX, te.changedTouches.item(0).clientY); - // target?.dispatchEvent( - // new CustomEvent>("dashOnTouchHoldStart", - // { - // bubbles: true, - // detail: { - // fingers: this.prevPoints.size, - // targetTouches: nts.ntt, - // touches: nts.nt, - // changedTouches: nts.nct, - // touchEvent: te - // } - // } - // ) - // ); - // this._holdTimer = undefined; - // document.removeEventListener("touchmove", this.onReactTouchMove); - // document.removeEventListener("touchend", this.onReactTouchEnd); - // document.removeEventListener("touchmove", this.onReactHoldTouchMove); - // document.removeEventListener("touchend", this.onReactHoldTouchEnd); - // document.addEventListener("touchmove", this.onReactHoldTouchMove); - // document.addEventListener("touchend", this.onReactHoldTouchEnd); - // }, (1000)); - // } + if (this.prevPoints.size === 1 && this._holdTimer === undefined) { + console.log("started"); + this._holdTimer = setTimeout(() => { + console.log("hold"); + const target = document.elementFromPoint(te.changedTouches.item(0).clientX, te.changedTouches.item(0).clientY); + target?.dispatchEvent( + new CustomEvent>("dashOnTouchHoldStart", + { + bubbles: true, + detail: { + fingers: this.prevPoints.size, + targetTouches: nts.ntt, + touches: nts.nt, + changedTouches: nts.nct, + touchEvent: te + } + } + ) + ); + this._holdTimer = undefined; + document.removeEventListener("touchmove", this.onReactTouchMove); + document.removeEventListener("touchend", this.onReactTouchEnd); + document.removeEventListener("touchmove", this.onReactHoldTouchMove); + document.removeEventListener("touchend", this.onReactHoldTouchEnd); + document.addEventListener("touchmove", this.onReactHoldTouchMove); + document.addEventListener("touchend", this.onReactHoldTouchEnd); + }, (1000)); + } document.removeEventListener("touchmove", this.onReactTouchMove); document.removeEventListener("touchend", this.onReactTouchEnd); document.addEventListener("touchmove", this.onReactTouchMove); diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 92b26b9bc..997266266 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -531,7 +531,7 @@ export class MainView extends React.Component { - {/* */} + diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 765077c4d..6b400113b 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -189,7 +189,7 @@ export class DocumentView extends DocComponent(Docu this._mainCont.current && (this._dropDisposer = DragManager.MakeDropTarget(this._mainCont.current, this.drop.bind(this))); this._mainCont.current && (this._gestureEventDisposer = GestureUtils.MakeGestureTarget(this._mainCont.current, this.onGesture.bind(this))); this._mainCont.current && (this.multiTouchDisposer = InteractionUtils.MakeMultiTouchTarget(this._mainCont.current, this.onTouchStart.bind(this))); - // this._mainCont.current && (this.holdDisposer = InteractionUtils.MakeHoldTouchTarget(this._mainCont.current, this.handle1PointerHoldStart.bind(this))); + this._mainCont.current && (this.holdDisposer = InteractionUtils.MakeHoldTouchTarget(this._mainCont.current, this.handle1PointerHoldStart.bind(this))); } @action -- cgit v1.2.3-70-g09d2 From 4859d4e3f5827c3341d43d19a5309d2ec25ab67b Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Wed, 1 Apr 2020 17:15:14 -0400 Subject: fixed warnings and some compile errors. Made a key value layout and extened DocumentBox to have a childLayoutKey field --- src/client/ClientRecommender.tsx | 54 +++++----- src/client/cognitive_services/CognitiveServices.ts | 36 +++---- src/client/documents/Documents.ts | 3 +- src/client/util/RichTextSchema.tsx | 18 ++-- src/client/views/DocumentButtonBar.tsx | 2 +- src/client/views/EditableView.tsx | 22 ++-- src/client/views/GestureOverlay.tsx | 8 +- src/client/views/GlobalKeyHandler.ts | 4 +- src/client/views/MainView.tsx | 2 + src/client/views/RecommendationsBox.tsx | 16 +-- src/client/views/TemplateMenu.tsx | 8 +- src/client/views/TouchScrollableMenu.tsx | 4 +- .../views/collections/CollectionDockingView.tsx | 2 +- .../views/collections/CollectionSchemaCells.tsx | 2 + .../views/collections/CollectionSchemaView.tsx | 8 +- .../views/collections/CollectionStackingView.tsx | 2 +- .../CollectionStackingViewFieldColumn.tsx | 3 +- .../views/collections/CollectionStaffView.tsx | 12 +-- src/client/views/collections/CollectionSubView.tsx | 3 +- .../views/collections/CollectionTimeView.tsx | 2 +- src/client/views/collections/CollectionView.tsx | 2 +- .../views/collections/CollectionViewChromes.tsx | 10 +- .../CollectionFreeFormLinksView.tsx | 116 ++++++++++----------- .../collections/collectionFreeForm/MarqueeView.tsx | 4 +- src/client/views/nodes/ButtonBox.tsx | 2 +- .../views/nodes/ContentFittingDocumentView.tsx | 2 + src/client/views/nodes/DocumentBox.tsx | 3 +- src/client/views/nodes/DocumentContentsView.tsx | 24 +++-- src/client/views/nodes/KeyValuePair.tsx | 2 + src/client/views/nodes/RadialMenuItem.tsx | 30 +++--- src/client/views/nodes/ScreenshotBox.tsx | 2 +- src/client/views/nodes/WebBox.tsx | 2 +- src/client/views/pdf/PDFViewer.tsx | 2 +- src/client/views/webcam/DashWebRTCVideo.tsx | 8 +- src/mobile/MobileInterface.tsx | 2 + src/new_fields/Doc.ts | 4 +- src/new_fields/util.ts | 2 +- .../Session/agents/applied_session_agent.ts | 2 +- src/server/DashSession/Session/agents/monitor.ts | 2 +- .../Session/agents/promisified_ipc_manager.ts | 6 +- src/server/Websocket/Websocket.ts | 8 +- src/server/database.ts | 2 +- src/server/server_Initialization.ts | 2 +- 43 files changed, 232 insertions(+), 218 deletions(-) (limited to 'src/client/views/MainView.tsx') diff --git a/src/client/ClientRecommender.tsx b/src/client/ClientRecommender.tsx index 0e67a6e57..537e331ab 100644 --- a/src/client/ClientRecommender.tsx +++ b/src/client/ClientRecommender.tsx @@ -69,7 +69,7 @@ export class ClientRecommender extends React.Component { */ private distance(vector1: number[], vector2: number[], metric: string = "cosine") { - assert(vector1.length === vector2.length, "Vectors are not the same length"); + // assert(vector1.length === vector2.length, "Vectors are not the same length"); let similarity: number; switch (metric) { case "cosine": @@ -113,7 +113,7 @@ export class ClientRecommender extends React.Component { } } ); - let doclist = Array.from(ClientRecommender.Instance.docVectors); + const doclist = Array.from(ClientRecommender.Instance.docVectors); if (distance_metric === "euclidian") { doclist.sort((a: RecommenderDocument, b: RecommenderDocument) => a.score - b.score); } @@ -169,12 +169,12 @@ export class ClientRecommender extends React.Component { */ generateMetadata = async (dataDoc: Doc, extDoc: Doc, threshold: Confidence = Confidence.Excellent) => { - let converter = (results: any) => { - let tagDoc = new Doc; - let tagsList = new List(); + const converter = (results: any) => { + const tagDoc = new Doc; + const tagsList = new List(); results.tags.map((tag: Tag) => { tagsList.push(tag.name); - let sanitized = tag.name.replace(" ", "_"); + const sanitized = tag.name.replace(" ", "_"); tagDoc[sanitized] = ComputedField.MakeFunction(`(${tag.confidence} >= this.confidence) ? ${tag.confidence} : "${ComputedField.undefined}"`); }); extDoc.generatedTags = tagsList; @@ -193,7 +193,7 @@ export class ClientRecommender extends React.Component { */ private url(dataDoc: Doc) { - let data = Cast(Doc.GetProto(dataDoc)[fieldkey], ImageField); + const data = Cast(Doc.GetProto(dataDoc)[fieldkey], ImageField); return data ? data.url.href : undefined; } @@ -215,14 +215,14 @@ export class ClientRecommender extends React.Component { } } else { - let fielddata = Cast(dataDoc.data, RichTextField); - fielddata ? data = fielddata[ToPlainText]() : data = ""; + const fielddata = Cast(dataDoc.data, RichTextField, null); + data = fielddata?.Text || ""; } // STEP 2. Upon receiving response from Text Cognitive Services, do additional processing on keywords. // Currently we are still using Cognitive Services for internal recommendations, but in the future this might not be necessary. - let converter = async (results: any, data: string, isImage: boolean = false) => { + const converter = async (results: any, data: string, isImage: boolean = false) => { let keyterms = new List(); // raw keywords let kp_string: string = ""; // keywords*frequency concatenated into a string. input into TF let highKP: string[] = [""]; // most frequent keyphrase @@ -237,7 +237,7 @@ export class ClientRecommender extends React.Component { } else { // text processing results.documents.forEach((doc: any) => { - let keyPhrases = doc.keyPhrases; // returned by Cognitive Services + const keyPhrases = doc.keyPhrases; // returned by Cognitive Services keyPhrases.map((kp: string) => { keyterms.push(kp); const frequency = this.countFrequencies(kp, data); // frequency of keyphrase in paragraph @@ -308,10 +308,10 @@ export class ClientRecommender extends React.Component { */ private countFrequencies(keyphrase: string, paragraph: string) { - let data = paragraph.split(/ |\n/); // splits by new lines and spaces - let kp_array = keyphrase.split(" "); - let num_keywords = kp_array.length; - let par_length = data.length; + const data = paragraph.split(/ |\n/); // splits by new lines and spaces + const kp_array = keyphrase.split(" "); + const num_keywords = kp_array.length; + const par_length = data.length; let frequency = 0; // slides keyphrase windows across paragraph and checks if it matches with corresponding paragraph slice for (let i = 0; i <= par_length - num_keywords; i++) { @@ -353,8 +353,8 @@ export class ClientRecommender extends React.Component { bingWebSearch = async (query: string) => { const converter = async (results: any) => { - let title_vals: string[] = []; - let url_vals: string[] = []; + const title_vals: string[] = []; + const url_vals: string[] = []; results.webPages.value.forEach((doc: any) => { title_vals.push(doc.name); url_vals.push(doc.url); @@ -369,23 +369,23 @@ export class ClientRecommender extends React.Component { */ arxivrequest = async (query: string) => { - let xhttp = new XMLHttpRequest(); - let serveraddress = "http://export.arxiv.org/api"; + const xhttp = new XMLHttpRequest(); + const serveraddress = "http://export.arxiv.org/api"; const maxresults = 5; - let endpoint = serveraddress + "/query?search_query=all:" + query + "&start=0&max_results=" + maxresults.toString(); - let promisified = (resolve: any, reject: any) => { + const endpoint = serveraddress + "/query?search_query=all:" + query + "&start=0&max_results=" + maxresults.toString(); + const promisified = (resolve: any, reject: any) => { xhttp.onreadystatechange = function () { if (this.readyState === 4) { - let result = xhttp.response; - let xml = xhttp.responseXML; + const result = xhttp.response; + const xml = xhttp.responseXML; console.log("arXiv Result: ", xml); switch (this.status) { case 200: - let title_vals: string[] = []; - let url_vals: string[] = []; + const title_vals: string[] = []; + const url_vals: string[] = []; //console.log(result); if (xml) { - let titles = xml.getElementsByTagName("title"); + const titles = xml.getElementsByTagName("title"); let counter = 1; if (titles && titles.length > 1) { while (counter <= maxresults) { @@ -394,7 +394,7 @@ export class ClientRecommender extends React.Component { counter++; } } - let ids = xml.getElementsByTagName("id"); + const ids = xml.getElementsByTagName("id"); counter = 1; if (ids && ids.length > 1) { while (counter <= maxresults) { diff --git a/src/client/cognitive_services/CognitiveServices.ts b/src/client/cognitive_services/CognitiveServices.ts index 542ccf04d..3f3726621 100644 --- a/src/client/cognitive_services/CognitiveServices.ts +++ b/src/client/cognitive_services/CognitiveServices.ts @@ -208,7 +208,7 @@ export namespace CognitiveServices { results.recognitionUnits && (results = results.recognitionUnits); } return results; - } + }; } export interface AzureStrokeData { @@ -232,13 +232,13 @@ export namespace CognitiveServices { return data; }, requester: async (apiKey: string, query: string) => { - let xhttp = new XMLHttpRequest(); - let serverAddress = "https://api.cognitive.microsoft.com"; - let endpoint = serverAddress + '/bing/v5.0/search?q=' + encodeURIComponent(query); - let promisified = (resolve: any, reject: any) => { + const xhttp = new XMLHttpRequest(); + const serverAddress = "https://api.cognitive.microsoft.com"; + const endpoint = serverAddress + '/bing/v5.0/search?q=' + encodeURIComponent(query); + const promisified = (resolve: any, reject: any) => { xhttp.onreadystatechange = function () { if (this.readyState === 4) { - let result = xhttp.responseText; + const result = xhttp.responseText; switch (this.status) { case 200: return resolve(result); @@ -266,7 +266,7 @@ export namespace CognitiveServices { export namespace Appliers { export const analyzer = async (query: string, converter: BingConverter) => { - let results = await ExecuteQuery(Service.Bing, Manager, query); + const results = await ExecuteQuery(Service.Bing, Manager, query); console.log("Bing results: ", results); const { title_vals, url_vals } = await converter(results); return { title_vals, url_vals }; @@ -281,13 +281,13 @@ export namespace CognitiveServices { return data; }, requester: async (apiKey: string, query: string) => { - let xhttp = new XMLHttpRequest(); - let serverAddress = "https://babel.hathitrust.org/cgi/htd/​"; - let endpoint = serverAddress + '/bing/v5.0/search?q=' + encodeURIComponent(query); - let promisified = (resolve: any, reject: any) => { + const xhttp = new XMLHttpRequest(); + const serverAddress = "https://babel.hathitrust.org/cgi/htd/​"; + const endpoint = serverAddress + '/bing/v5.0/search?q=' + encodeURIComponent(query); + const promisified = (resolve: any, reject: any) => { xhttp.onreadystatechange = function () { if (this.readyState === 4) { - let result = xhttp.responseText; + const result = xhttp.responseText; switch (this.status) { case 200: return resolve(result); @@ -315,7 +315,7 @@ export namespace CognitiveServices { export namespace Appliers { export const analyzer = async (query: string, converter: BingConverter) => { - let results = await ExecuteQuery(Service.Bing, Manager, query); + const results = await ExecuteQuery(Service.Bing, Manager, query); console.log("Bing results: ", results); const { title_vals, url_vals } = await converter(results); return { title_vals, url_vals }; @@ -337,9 +337,9 @@ export namespace CognitiveServices { }); }, requester: async (apiKey: string, body: string, service: Service) => { - let serverAddress = "https://eastus.api.cognitive.microsoft.com"; - let endpoint = serverAddress + "/text/analytics/v2.1/keyPhrases"; - let sampleBody = { + const serverAddress = "https://eastus.api.cognitive.microsoft.com"; + const endpoint = serverAddress + "/text/analytics/v2.1/keyPhrases"; + const sampleBody = { "documents": [ { "language": "en", @@ -348,7 +348,7 @@ export namespace CognitiveServices { } ] }; - let actualBody = body; + const actualBody = body; const options = { uri: endpoint, body: actualBody, @@ -368,7 +368,7 @@ export namespace CognitiveServices { console.log("vectorizing..."); //keyterms = ["father", "king"]; - let args = { method: 'POST', uri: Utils.prepend("/recommender"), body: { keyphrases: keyterms }, json: true }; + const args = { method: 'POST', uri: Utils.prepend("/recommender"), body: { keyphrases: keyterms }, json: true }; await requestPromise.post(args).then(async (wordvecs) => { if (wordvecs) { const indices = Object.keys(wordvecs); diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index dbea8062e..96425ba30 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -266,7 +266,7 @@ export namespace Docs { options: { _width: 40, _height: 40, borderRounding: "100%" }, }], [DocumentType.RECOMMENDATION, { - layout: { view: RecommendationsBox }, + layout: { view: RecommendationsBox, dataField: data }, options: { width: 200, height: 200 }, }], [DocumentType.WEBCAM, { @@ -365,6 +365,7 @@ export namespace Docs { const options = { title, type, baseProto: true, ...defaultOptions, ...(template.options || {}) }; options.layout = layout.view.LayoutString(layout.dataField); const doc = Doc.assign(new Doc(prototypeId, true), { layoutKey: "layout", ...options }); + doc.layout_keyValue = KeyValueBox.LayoutString(""); return doc; } diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index a2fb7c11b..81ab95ff5 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -810,7 +810,7 @@ export class DashDocView { this._dashSpan.style.height = this._outer.style.height = Math.max(20, dim[1]) + "px"; this._outer.style.border = "1px solid " + StrCast(finalLayout.color, (Cast(Doc.UserDoc().activeWorkspace, Doc, null).darkScheme ? "dimGray" : "lightGray")); }, { fireImmediately: true }); - let doReactRender = (finalLayout: Doc, resolvedDataDoc: Doc) => { + const doReactRender = (finalLayout: Doc, resolvedDataDoc: Doc) => { ReactDOM.unmountComponentAtNode(this._dashSpan); ReactDOM.render( { if (!Doc.AreProtosEqual(finalLayout, dashDoc)) { @@ -939,7 +939,7 @@ export class DashFieldView { this._fieldCheck.style.backgroundColor = "rgba(155, 155, 155, 0.24)"; this._fieldCheck.onchange = function (e: any) { self._dashDoc![self._fieldKey] = e.target.checked; - } + }; this._fieldSpan = document.createElement("div"); this._fieldSpan.id = Utils.GenerateGuid(); @@ -1095,12 +1095,12 @@ export class FootnoteView { "Mod-y": () => redo(this.outerView.state, this.outerView.dispatch), "Mod-b": toggleMark(schema.marks.strong) }), - new Plugin({ - view(newView) { - // TODO -- make this work with RichTextMenu - // return FormattedTextBox.getToolTip(newView); - } - }) + // new Plugin({ + // view(newView) { + // // TODO -- make this work with RichTextMenu + // // return FormattedTextBox.getToolTip(newView); + // } + // }) ], }), diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index e673189f9..c6fb9ad0b 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -39,7 +39,7 @@ library.add(faCheckCircle); library.add(faCloudUploadAlt); library.add(faSyncAlt); library.add(faShare); -library.add(faPhotoVideo) +library.add(faPhotoVideo); const cloud: IconProp = "cloud-upload-alt"; const fetch: IconProp = "sync-alt"; diff --git a/src/client/views/EditableView.tsx b/src/client/views/EditableView.tsx index 4a27425e8..2219966e5 100644 --- a/src/client/views/EditableView.tsx +++ b/src/client/views/EditableView.tsx @@ -4,10 +4,7 @@ import { observer } from 'mobx-react'; import * as Autosuggest from 'react-autosuggest'; import { ObjectField } from '../../new_fields/ObjectField'; import { SchemaHeaderField } from '../../new_fields/SchemaHeaderField'; -import { ContextMenu } from './ContextMenu'; -import { ContextMenuProps } from './ContextMenuItem'; import "./EditableView.scss"; -import { CollectionTreeView } from './collections/CollectionTreeView'; export interface EditableProps { /** @@ -88,12 +85,12 @@ export class EditableView extends React.Component { onKeyDown = (e: React.KeyboardEvent) => { if (e.key === "Tab") { e.stopPropagation(); - this.finalizeEdit(e.currentTarget.value, e.shiftKey); + this.finalizeEdit(e.currentTarget.value, e.shiftKey, false); this.props.OnTab && this.props.OnTab(e.shiftKey); } else if (e.key === "Enter") { e.stopPropagation(); if (!e.ctrlKey) { - this.finalizeEdit(e.currentTarget.value, e.shiftKey); + this.finalizeEdit(e.currentTarget.value, e.shiftKey, false); } else if (this.props.OnFillDown) { this.props.OnFillDown(e.currentTarget.value); this._editing = false; @@ -123,10 +120,17 @@ export class EditableView extends React.Component { } @action - private finalizeEdit(value: string, shiftDown: boolean) { - this._editing = false; + private finalizeEdit(value: string, shiftDown: boolean, lostFocus: boolean) { if (this.props.SetValue(value, shiftDown)) { + this._editing = false; + this.props.isEditingCallback?.(false); + } else { + this._editing = false; this.props.isEditingCallback?.(false); + !lostFocus && setTimeout(action(() => { + this._editing = true; + this.props.isEditingCallback?.(true); + }), 0); } } @@ -151,7 +155,7 @@ export class EditableView extends React.Component { className: "editableView-input", onKeyDown: this.onKeyDown, autoFocus: true, - onBlur: e => this.finalizeEdit(e.currentTarget.value, false), + onBlur: e => this.finalizeEdit(e.currentTarget.value, false, true), onPointerDown: this.stopPropagation, onClick: this.stopPropagation, onPointerUp: this.stopPropagation, @@ -163,7 +167,7 @@ export class EditableView extends React.Component { defaultValue={this.props.GetValue()} onKeyDown={this.onKeyDown} autoFocus={true} - onBlur={e => this.finalizeEdit(e.currentTarget.value, false)} + onBlur={e => this.finalizeEdit(e.currentTarget.value, false, true)} onPointerDown={this.stopPropagation} onClick={this.stopPropagation} onPointerUp={this.stopPropagation} style={{ display: this.props.display, fontSize: this.props.fontSize }} />; diff --git a/src/client/views/GestureOverlay.tsx b/src/client/views/GestureOverlay.tsx index 1eff58948..ea60907f6 100644 --- a/src/client/views/GestureOverlay.tsx +++ b/src/client/views/GestureOverlay.tsx @@ -165,7 +165,7 @@ export default class GestureOverlay extends Touchable { this._holdTimer = setTimeout(() => { console.log("hold"); const target = document.elementFromPoint(te.changedTouches.item(0).clientX, te.changedTouches.item(0).clientY); - let pt: any = te.touches[te.touches.length - 1]; + const pt: any = te.touches[te.touches.length - 1]; if (nts.nt.length === 1 && pt.radiusX > 1 && pt.radiusY > 1) { target?.dispatchEvent( new CustomEvent>("dashOnTouchHoldStart", @@ -589,7 +589,7 @@ export default class GestureOverlay extends Touchable { for (const wR of wordResults) { console.log(wR); if (wR?.recognizedText) { - possibilities.push(wR?.recognizedText) + possibilities.push(wR?.recognizedText); } possibilities.push(...wR?.alternates?.map((a: any) => a.recognizedString)); } @@ -743,16 +743,16 @@ export default class GestureOverlay extends Touchable { {this.elements}
{this._clipboardDoc}
{ - let stopPropagation = false; - let preventDefault = false; + const stopPropagation = false; + const preventDefault = false; switch (keyname) { // case "~": diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index a81e0cc2c..8d9be5980 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -521,7 +521,9 @@ export class MainView extends React.Component { DataDoc={undefined} LibraryPath={emptyPath} fieldKey={"data"} + dropAction={"alias"} annotationsKey={""} + bringToFront={emptyFunction} select={emptyFunction} active={returnFalse} isSelected={returnFalse} diff --git a/src/client/views/RecommendationsBox.tsx b/src/client/views/RecommendationsBox.tsx index 262226bac..5ebba0abb 100644 --- a/src/client/views/RecommendationsBox.tsx +++ b/src/client/views/RecommendationsBox.tsx @@ -6,7 +6,7 @@ import "./RecommendationsBox.scss"; import { Doc, DocListCast, WidthSym, HeightSym } from "../../new_fields/Doc"; import { DocumentIcon } from "./nodes/DocumentIcon"; import { StrCast, NumCast } from "../../new_fields/Types"; -import { returnFalse, emptyFunction, returnEmptyString, returnOne } from "../../Utils"; +import { returnFalse, emptyFunction, returnEmptyString, returnOne, emptyPath } from "../../Utils"; import { Transform } from "../util/Transform"; import { ObjectField } from "../../new_fields/ObjectField"; import { DocumentView } from "./nodes/DocumentView"; @@ -31,7 +31,7 @@ library.add(faBullseye, faLink); @observer export class RecommendationsBox extends React.Component { - public static LayoutString(fieldKey?: string) { return FieldView.LayoutString(RecommendationsBox, fieldKey); } + public static LayoutString(fieldKey: string) { return FieldView.LayoutString(RecommendationsBox, fieldKey); } // @observable private _display: boolean = false; @observable private _pageX: number = 0; @@ -48,17 +48,17 @@ export class RecommendationsBox extends React.Component { @action private DocumentIcon(doc: Doc) { - let layoutresult = StrCast(doc.type); + const layoutresult = StrCast(doc.type); let renderDoc = doc; //let box: number[] = []; if (layoutresult.indexOf(DocumentType.COL) !== -1) { renderDoc = Doc.MakeDelegate(renderDoc); } - let returnXDimension = () => 150; - let returnYDimension = () => 150; - let scale = () => returnXDimension() / NumCast(renderDoc.nativeWidth, returnXDimension()); + const returnXDimension = () => 150; + const returnYDimension = () => 150; + const scale = () => returnXDimension() / NumCast(renderDoc.nativeWidth, returnXDimension()); //let scale = () => 1; - let newRenderDoc = Doc.MakeAlias(renderDoc); /// newRenderDoc -> renderDoc -> render"data"Doc -> TextProt + const newRenderDoc = Doc.MakeAlias(renderDoc); /// newRenderDoc -> renderDoc -> render"data"Doc -> TextProt newRenderDoc.height = NumCast(this.props.Document.documentIconHeight); newRenderDoc.autoHeight = false; const docview =
@@ -66,8 +66,8 @@ export class RecommendationsBox extends React.Component { fitToBox={StrCast(doc.type).indexOf(DocumentType.COL) !== -1} Document={newRenderDoc} addDocument={returnFalse} + LibraryPath={emptyPath} removeDocument={returnFalse} - ruleProvider={undefined} ScreenToLocalTransform={Transform.Identity} addDocTab={returnFalse} pinToPres={returnFalse} diff --git a/src/client/views/TemplateMenu.tsx b/src/client/views/TemplateMenu.tsx index 83dbd3db3..996928cca 100644 --- a/src/client/views/TemplateMenu.tsx +++ b/src/client/views/TemplateMenu.tsx @@ -114,7 +114,7 @@ export class TemplateMenu extends React.Component { const templateName = StrCast(firstDoc.layoutKey, "layout").replace("layout_", ""); const noteTypesDoc = Cast(Doc.UserDoc().noteTypes, Doc, null); const noteTypes = DocListCast(noteTypesDoc?.data); - const addedTypes = DocListCast(Cast(Doc.UserDoc().templateButtons, Doc, null)?.data) + const addedTypes = DocListCast(Cast(Doc.UserDoc().templateButtons, Doc, null)?.data); const layout = Doc.Layout(firstDoc); const templateMenu: Array = []; this.props.templates.forEach((checked, template) => @@ -170,8 +170,8 @@ Scripting.addGlobal(function switchView(doc: Doc, template: Doc) { if (template.dragFactory) { template = Cast(template.dragFactory, Doc, null); } - let templateTitle = StrCast(template?.title); - return templateTitle && DocumentView.makeCustomViewClicked(doc, undefined, Docs.Create.FreeformDocument, templateTitle, template) + const templateTitle = StrCast(template?.title); + return templateTitle && DocumentView.makeCustomViewClicked(doc, undefined, Docs.Create.FreeformDocument, templateTitle, template); }); Scripting.addGlobal(function templateIsUsed(templateDoc: Doc, firstDocTitlte: string) { @@ -180,4 +180,4 @@ Scripting.addGlobal(function templateIsUsed(templateDoc: Doc, firstDocTitlte: st const template = StrCast(templateDoc.dragFactory ? Cast(templateDoc.dragFactory, Doc, null)?.title : templateDoc.title); return StrCast(firstDoc.layoutKey) === "layout_" + template ? 'check' : 'unchecked'; // return SelectionManager.SelectedDocuments().some(view => StrCast(view.props.Document.layoutKey) === "layout_" + template) ? 'check' : 'unchecked' -}) \ No newline at end of file +}); \ No newline at end of file diff --git a/src/client/views/TouchScrollableMenu.tsx b/src/client/views/TouchScrollableMenu.tsx index 4bda0818e..969605be9 100644 --- a/src/client/views/TouchScrollableMenu.tsx +++ b/src/client/views/TouchScrollableMenu.tsx @@ -44,7 +44,7 @@ export default class TouchScrollableMenu extends React.Component
- ) + ); } } @@ -54,6 +54,6 @@ export class TouchScrollableMenuItem extends React.Component {this.props.text}
- ) + ); } } \ No newline at end of file diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 2ee39bc0d..4e1e76f39 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -513,7 +513,7 @@ export class CollectionDockingView extends React.Component ((view: Opt) => view ? [view] : [])(DocumentManager.Instance.getDocumentView(doc)), (views) => { diff --git a/src/client/views/collections/CollectionSchemaCells.tsx b/src/client/views/collections/CollectionSchemaCells.tsx index 79b5d7bb7..f124fe21b 100644 --- a/src/client/views/collections/CollectionSchemaCells.tsx +++ b/src/client/views/collections/CollectionSchemaCells.tsx @@ -157,6 +157,8 @@ export class CollectionSchemaCell extends React.Component { Document: this.props.rowProps.original, DataDoc: this.props.rowProps.original, LibraryPath: [], + dropAction: "alias", + bringToFront: emptyFunction, fieldKey: this.props.rowProps.column.id as string, ContainingCollectionView: this.props.CollectionView, ContainingCollectionDoc: this.props.CollectionView && this.props.CollectionView.props.Document, diff --git a/src/client/views/collections/CollectionSchemaView.tsx b/src/client/views/collections/CollectionSchemaView.tsx index a4502cced..981438513 100644 --- a/src/client/views/collections/CollectionSchemaView.tsx +++ b/src/client/views/collections/CollectionSchemaView.tsx @@ -51,8 +51,7 @@ const columnTypes: Map = new Map([ @observer export class CollectionSchemaView extends CollectionSubView(doc => doc) { - private _mainCont?: HTMLDivElement; - private _startPreviewWidth = 0; + private _previewCont?: HTMLDivElement; private DIVIDER_WIDTH = 4; @observable previewDoc: Doc | undefined = undefined; @@ -64,7 +63,7 @@ export class CollectionSchemaView extends CollectionSubView(doc => doc) { @computed get borderWidth() { return Number(COLLECTION_BORDER_WIDTH); } private createTarget = (ele: HTMLDivElement) => { - this._mainCont = ele; + this._previewCont = ele; super.CreateDropTarget(ele); } @@ -81,12 +80,11 @@ export class CollectionSchemaView extends CollectionSubView(doc => doc) { } onDividerDown = (e: React.PointerEvent) => { - this._startPreviewWidth = this.previewWidth(); setupMoveUpEvents(this, e, this.onDividerMove, emptyFunction, action(() => this.toggleExpander())); } @action onDividerMove = (e: PointerEvent, down: number[], delta: number[]) => { - const nativeWidth = this._mainCont!.getBoundingClientRect(); + const nativeWidth = this._previewCont!.getBoundingClientRect(); const minWidth = 40; const maxWidth = 1000; const movedWidth = this.props.ScreenToLocalTransform().transformDirection(nativeWidth.right - e.clientX, 0)[0]; diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index 086e0842e..076dd3629 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -106,7 +106,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { fields.delete(header); sectionHeaders.splice(sectionHeaders.indexOf(header), 1); changed = true; - }) + }); } changed && setTimeout(action(() => { if (this.sectionHeaders) { this.sectionHeaders.length = 0; this.sectionHeaders.push(...sectionHeaders); } }), 0); return fields; diff --git a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx index 646b433bf..0a48c95e4 100644 --- a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx +++ b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx @@ -131,7 +131,8 @@ export class CollectionStackingViewFieldColumn extends React.Component NumCast(doc.heading) > maxHeading ? NumCast(doc.heading) : maxHeading, 0); const heading = maxHeading === 0 || this.props.docList.length === 0 ? 1 : maxHeading === 1 ? 2 : 3; newDoc.heading = heading; - return this.props.parent.props.addDocument(newDoc); + this.props.parent.props.addDocument(newDoc); + return false; } @action diff --git a/src/client/views/collections/CollectionStaffView.tsx b/src/client/views/collections/CollectionStaffView.tsx index 8c7e113b2..5b9a69bf7 100644 --- a/src/client/views/collections/CollectionStaffView.tsx +++ b/src/client/views/collections/CollectionStaffView.tsx @@ -1,22 +1,20 @@ import { CollectionSubView } from "./CollectionSubView"; -import { Transform } from "../../util/Transform"; import React = require("react"); import { computed, action, IReactionDisposer, reaction, runInAction, observable } from "mobx"; -import { Doc } from "../../../new_fields/Doc"; import { NumCast } from "../../../new_fields/Types"; import "./CollectionStaffView.scss"; import { observer } from "mobx-react"; @observer export class CollectionStaffView extends CollectionSubView(doc => doc) { - private getTransform = (): Transform => this.props.ScreenToLocalTransform().translate(0, -this._mainCont.current!.scrollTop); - private _mainCont = React.createRef(); private _reactionDisposer: IReactionDisposer | undefined; @observable private _staves = NumCast(this.props.Document.staves); + componentWillUnmount() { + this._reactionDisposer?.(); + } componentDidMount = () => { - this._reactionDisposer = reaction( - () => NumCast(this.props.Document.staves), + this._reactionDisposer = reaction(() => NumCast(this.props.Document.staves), (staves) => runInAction(() => this._staves = staves) ); @@ -47,7 +45,7 @@ export class CollectionStaffView extends CollectionSubView(doc => doc) { } render() { - return
+ return
{this.staves} {this.addStaffButton}
; diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index 88cfde0b6..70927cf22 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -1,5 +1,4 @@ import { action, computed, IReactionDisposer, reaction } from "mobx"; -import * as rp from 'request-promise'; import CursorField from "../../../new_fields/CursorField"; import { Doc, DocListCast, Opt, WidthSym, HeightSym } from "../../../new_fields/Doc"; import { Id } from "../../../new_fields/FieldSymbols"; @@ -107,7 +106,7 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T, moreProps?: get childLayoutPairs(): { layout: Doc; data: Doc; }[] { const { Document, DataDoc } = this.props; const validPairs = this.childDocs.map(doc => Doc.GetLayoutDataDocPair(Document, !this.props.annotationsKey ? DataDoc : undefined, doc)).filter(pair => pair.layout); - return validPairs.map(({ data, layout }) => ({ data, layout: layout! })); // this mapping is a bit of a hack to coerce types + return validPairs.map(({ data, layout }) => ({ data: data as Doc, layout: layout! })); // this mapping is a bit of a hack to coerce types } get childDocList() { return Cast(this.dataField, listSpec(Doc)); diff --git a/src/client/views/collections/CollectionTimeView.tsx b/src/client/views/collections/CollectionTimeView.tsx index 64832506b..0d2207b27 100644 --- a/src/client/views/collections/CollectionTimeView.tsx +++ b/src/client/views/collections/CollectionTimeView.tsx @@ -146,7 +146,7 @@ export class CollectionTimeView extends CollectionSubView(doc => doc) { back -
+
; } render() { diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index edb9fd930..b6ce2f3a9 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -299,7 +299,7 @@ export class CollectionView extends Touchable { get childLayoutPairs(): { layout: Doc; data: Doc; }[] { const { Document, DataDoc } = this.props; const validPairs = this.childDocs.map(doc => Doc.GetLayoutDataDocPair(Document, DataDoc, doc)).filter(pair => pair.layout); - return validPairs.map(({ data, layout }) => ({ data, layout: layout! })); // this mapping is a bit of a hack to coerce types + return validPairs.map(({ data, layout }) => ({ data: data as Doc, layout: layout! })); // this mapping is a bit of a hack to coerce types } get childDocList() { return Cast(this.dataField, listSpec(Doc)); diff --git a/src/client/views/collections/CollectionViewChromes.tsx b/src/client/views/collections/CollectionViewChromes.tsx index 960c6554e..2d565d9db 100644 --- a/src/client/views/collections/CollectionViewChromes.tsx +++ b/src/client/views/collections/CollectionViewChromes.tsx @@ -267,10 +267,10 @@ export class CollectionViewBaseChrome extends React.Component); - case CollectionViewType.Schema: return (); - case CollectionViewType.Tree: return (); - case CollectionViewType.Masonry: return (); + case CollectionViewType.Stacking: return (); + case CollectionViewType.Schema: return (); + case CollectionViewType.Tree: return (); + case CollectionViewType.Masonry: return (); default: return null; } } @@ -355,7 +355,7 @@ export class CollectionViewBaseChrome extends React.Component Doc.setChildLayout(this.target, source?.[0]), initialize: emptyFunction, }; - DragManager.StartButtonDrag([this._viewRef.current!], c.script, c.title, + DragManager.StartButtonDrag([this._viewRef.current!], c.script, StrCast(c.title), { target: this.props.CollectionView.props.Document }, c.params, c.initialize, e.clientX, e.clientY); return true; }, emptyFunction, emptyFunction); diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx index a1ec0daef..49ca024a2 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx @@ -1,4 +1,4 @@ -import { computed, IReactionDisposer } from "mobx"; +import { computed } from "mobx"; import { observer } from "mobx-react"; import { Doc } from "../../../../new_fields/Doc"; import { Id } from "../../../../new_fields/FieldSymbols"; @@ -10,67 +10,9 @@ import React = require("react"); import { Utils, emptyFunction } from "../../../../Utils"; import { SelectionManager } from "../../../util/SelectionManager"; import { DocumentType } from "../../../documents/DocumentTypes"; -import { StrCast } from "../../../../new_fields/Types"; @observer export class CollectionFreeFormLinksView extends React.Component { - - _brushReactionDisposer?: IReactionDisposer; - componentDidMount() { - // this._brushReactionDisposer = reaction( - // () => { - // let doclist = DocListCast(this.props.Document[this.props.fieldKey]); - // return { doclist: doclist ? doclist : [], xs: doclist.map(d => d.x) }; - // }, - // () => { - // let doclist = DocListCast(this.props.Document[this.props.fieldKey]); - // let views = doclist ? doclist.filter(doc => StrCast(doc.backgroundLayout).indexOf("istogram") !== -1) : []; - // views.forEach((dstDoc, i) => { - // views.forEach((srcDoc, j) => { - // let dstTarg = dstDoc; - // let srcTarg = srcDoc; - // let x1 = NumCast(srcDoc.x); - // let x2 = NumCast(dstDoc.x); - // let x1w = NumCast(srcDoc.width, -1); - // let x2w = NumCast(dstDoc.width, -1); - // if (x1w < 0 || x2w < 0 || i === j) { } - // else { - // let findBrush = (field: (Doc | Promise)[]) => field.findIndex(brush => { - // let bdocs = brush instanceof Doc ? Cast(brush.brushingDocs, listSpec(Doc), []) : undefined; - // return bdocs && bdocs.length && ((bdocs[0] === dstTarg && bdocs[1] === srcTarg)) ? true : false; - // }); - // let brushAction = (field: (Doc | Promise)[]) => { - // let found = findBrush(field); - // if (found !== -1) { - // field.splice(found, 1); - // } - // }; - // if (Math.abs(x1 + x1w - x2) < 20) { - // let linkDoc: Doc = new Doc(); - // linkDoc.title = "Histogram Brush"; - // linkDoc.linkDescription = "Brush between " + StrCast(srcTarg.title) + " and " + StrCast(dstTarg.Title); - // linkDoc.brushingDocs = new List([dstTarg, srcTarg]); - - // brushAction = (field: (Doc | Promise)[]) => { - // if (findBrush(field) === -1) { - // field.push(linkDoc); - // } - // }; - // } - // if (dstTarg.brushingDocs === undefined) dstTarg.brushingDocs = new List(); - // if (srcTarg.brushingDocs === undefined) srcTarg.brushingDocs = new List(); - // let dstBrushDocs = Cast(dstTarg.brushingDocs, listSpec(Doc), []); - // let srcBrushDocs = Cast(srcTarg.brushingDocs, listSpec(Doc), []); - // brushAction(dstBrushDocs); - // brushAction(srcBrushDocs); - // } - // }); - // }); - // }); - } - componentWillUnmount() { - this._brushReactionDisposer && this._brushReactionDisposer(); - } @computed get uniqueConnections() { const connections = DocumentManager.Instance.LinkedDocumentViews.reduce((drawnPairs, connection) => { @@ -101,4 +43,60 @@ export class CollectionFreeFormLinksView extends React.Component { {this.props.children}
; } + // _brushReactionDisposer?: IReactionDisposer; + // componentDidMount() { + // this._brushReactionDisposer = reaction( + // () => { + // let doclist = DocListCast(this.props.Document[this.props.fieldKey]); + // return { doclist: doclist ? doclist : [], xs: doclist.map(d => d.x) }; + // }, + // () => { + // let doclist = DocListCast(this.props.Document[this.props.fieldKey]); + // let views = doclist ? doclist.filter(doc => StrCast(doc.backgroundLayout).indexOf("istogram") !== -1) : []; + // views.forEach((dstDoc, i) => { + // views.forEach((srcDoc, j) => { + // let dstTarg = dstDoc; + // let srcTarg = srcDoc; + // let x1 = NumCast(srcDoc.x); + // let x2 = NumCast(dstDoc.x); + // let x1w = NumCast(srcDoc.width, -1); + // let x2w = NumCast(dstDoc.width, -1); + // if (x1w < 0 || x2w < 0 || i === j) { } + // else { + // let findBrush = (field: (Doc | Promise)[]) => field.findIndex(brush => { + // let bdocs = brush instanceof Doc ? Cast(brush.brushingDocs, listSpec(Doc), []) : undefined; + // return bdocs && bdocs.length && ((bdocs[0] === dstTarg && bdocs[1] === srcTarg)) ? true : false; + // }); + // let brushAction = (field: (Doc | Promise)[]) => { + // let found = findBrush(field); + // if (found !== -1) { + // field.splice(found, 1); + // } + // }; + // if (Math.abs(x1 + x1w - x2) < 20) { + // let linkDoc: Doc = new Doc(); + // linkDoc.title = "Histogram Brush"; + // linkDoc.linkDescription = "Brush between " + StrCast(srcTarg.title) + " and " + StrCast(dstTarg.Title); + // linkDoc.brushingDocs = new List([dstTarg, srcTarg]); + + // brushAction = (field: (Doc | Promise)[]) => { + // if (findBrush(field) === -1) { + // field.push(linkDoc); + // } + // }; + // } + // if (dstTarg.brushingDocs === undefined) dstTarg.brushingDocs = new List(); + // if (srcTarg.brushingDocs === undefined) srcTarg.brushingDocs = new List(); + // let dstBrushDocs = Cast(dstTarg.brushingDocs, listSpec(Doc), []); + // let srcBrushDocs = Cast(srcTarg.brushingDocs, listSpec(Doc), []); + // brushAction(dstBrushDocs); + // brushAction(srcBrushDocs); + // } + // }); + // }); + // }); + // } + // componentWillUnmount() { + // this._brushReactionDisposer?.(); + // } } \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index 0f94bffd6..276a49570 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -4,7 +4,7 @@ import { Doc, DocListCast, DataSym, WidthSym, HeightSym } from "../../../../new_ import { InkField, InkData } from "../../../../new_fields/InkField"; import { List } from "../../../../new_fields/List"; import { SchemaHeaderField } from "../../../../new_fields/SchemaHeaderField"; -import { Cast, NumCast, FieldValue } from "../../../../new_fields/Types"; +import { Cast, NumCast, FieldValue, StrCast } from "../../../../new_fields/Types"; import { CurrentUserUtils } from "../../../../server/authentication/models/current_user_utils"; import { Utils } from "../../../../Utils"; import { Docs, DocUtils } from "../../../documents/Documents"; @@ -107,7 +107,7 @@ export class MarqueeView extends React.Component(Butt style={{ boxShadow: this.Document.opacity === 0 ? undefined : StrCast(this.Document.boxShadow, "") }}>
{(this.Document.text || this.Document.title)} diff --git a/src/client/views/nodes/ContentFittingDocumentView.tsx b/src/client/views/nodes/ContentFittingDocumentView.tsx index 8632f9c9a..9494a4bc4 100644 --- a/src/client/views/nodes/ContentFittingDocumentView.tsx +++ b/src/client/views/nodes/ContentFittingDocumentView.tsx @@ -22,6 +22,7 @@ interface ContentFittingDocumentViewProps { childDocs?: Doc[]; renderDepth: number; fitToBox?: boolean; + layoutKey?: string; dropAction?: dropActionType; PanelWidth: () => number; PanelHeight: () => number; @@ -88,6 +89,7 @@ export class ContentFittingDocumentView extends React.Componentawaiting layout

"; const layout = Cast(this.layoutDoc[StrCast(this.layoutDoc.layoutKey, this.layoutDoc === this.props.Document ? this.props.layoutKey : "layout")], "string"); - if (layout === undefined) { - return this.props.Document.data ? - "" : - KeyValueBox.LayoutString(this.layoutDoc.proto ? "proto" : ""); - } else if (typeof layout === "string") { - return layout; - } else { - return "

Loading layout

"; - } + if (this.props.layoutKey === "layout_keyValue") { + return StrCast(this.props.Document.layout_keyValue, KeyValueBox.LayoutString("data")); + } else + if (layout === undefined) { + return this.props.Document.data ? + "" : + KeyValueBox.LayoutString(this.layoutDoc.proto ? "proto" : ""); + } else if (typeof layout === "string") { + return layout; + } else { + return "

Loading layout

"; + } } get dataDoc() { @@ -81,7 +84,8 @@ export class DocumentContentsView extends React.Component { fieldKey: this.props.keyName, isSelected: returnFalse, select: emptyFunction, + dropAction:"alias", + bringToFront:emptyFunction, renderDepth: 1, active: returnFalse, whenActiveChanged: emptyFunction, diff --git a/src/client/views/nodes/RadialMenuItem.tsx b/src/client/views/nodes/RadialMenuItem.tsx index fdc732d3f..bd5b3bff4 100644 --- a/src/client/views/nodes/RadialMenuItem.tsx +++ b/src/client/views/nodes/RadialMenuItem.tsx @@ -44,12 +44,12 @@ export class RadialMenuItem extends React.Component { setcircle() { let circlemin = 0; - let circlemax = 1 + let circlemax = 1; this.props.min ? circlemin = this.props.min : null; this.props.max ? circlemax = this.props.max : null; if (document.getElementById("myCanvas") !== null) { - var c: any = document.getElementById("myCanvas"); - let color = "white" + const c: any = document.getElementById("myCanvas"); + let color = "white"; switch (circlemin % 3) { case 1: color = "#c2c2c5"; @@ -70,38 +70,38 @@ export class RadialMenuItem extends React.Component { } if (c.getContext) { - var ctx = c.getContext("2d"); + const ctx = c.getContext("2d"); ctx.beginPath(); ctx.arc(150, 150, 150, (circlemin / circlemax) * 2 * Math.PI, ((circlemin + 1) / circlemax) * 2 * Math.PI); ctx.arc(150, 150, 50, ((circlemin + 1) / circlemax) * 2 * Math.PI, (circlemin / circlemax) * 2 * Math.PI, true); ctx.fillStyle = color; - ctx.fill() + ctx.fill(); } } } calculatorx() { let circlemin = 0; - let circlemax = 1 + let circlemax = 1; this.props.min ? circlemin = this.props.min : null; this.props.max ? circlemax = this.props.max : null; - let avg = ((circlemin / circlemax) + ((circlemin + 1) / circlemax)) / 2; - let degrees = 360 * avg; - let x = 100 * Math.cos(degrees * Math.PI / 180); - let y = -125 * Math.sin(degrees * Math.PI / 180); + const avg = ((circlemin / circlemax) + ((circlemin + 1) / circlemax)) / 2; + const degrees = 360 * avg; + const x = 100 * Math.cos(degrees * Math.PI / 180); + const y = -125 * Math.sin(degrees * Math.PI / 180); return x; } calculatory() { let circlemin = 0; - let circlemax = 1 + let circlemax = 1; this.props.min ? circlemin = this.props.min : null; this.props.max ? circlemax = this.props.max : null; - let avg = ((circlemin / circlemax) + ((circlemin + 1) / circlemax)) / 2; - let degrees = 360 * avg; - let x = 125 * Math.cos(degrees * Math.PI / 180); - let y = -100 * Math.sin(degrees * Math.PI / 180); + const avg = ((circlemin / circlemax) + ((circlemin + 1) / circlemax)) / 2; + const degrees = 360 * avg; + const x = 125 * Math.cos(degrees * Math.PI / 180); + const y = -100 * Math.sin(degrees * Math.PI / 180); return y; } diff --git a/src/client/views/nodes/ScreenshotBox.tsx b/src/client/views/nodes/ScreenshotBox.tsx index 548066f1c..7c58a5148 100644 --- a/src/client/views/nodes/ScreenshotBox.tsx +++ b/src/client/views/nodes/ScreenshotBox.tsx @@ -142,7 +142,7 @@ export class ScreenshotBox extends DocAnnotatableComponent { this._screenCapture = !this._screenCapture; this._videoRef!.srcObject = !this._screenCapture ? undefined : await (navigator.mediaDevices as any).getDisplayMedia({ video: true }); - }) + }); private get uIButtons() { return (
diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx index 591864f2c..838fbefb1 100644 --- a/src/client/views/nodes/WebBox.tsx +++ b/src/client/views/nodes/WebBox.tsx @@ -63,7 +63,7 @@ export class WebBox extends DocAnnotatableComponent this.layoutDoc._height = NumCast(this.layoutDoc._width) / youtubeaspect; } } else if (field?.url) { - var result = await WebRequest.get(Utils.CorsProxy(field.url.href)); + const result = await WebRequest.get(Utils.CorsProxy(field.url.href)); this.dataDoc.text = htmlToText.fromString(result.content); } diff --git a/src/client/views/pdf/PDFViewer.tsx b/src/client/views/pdf/PDFViewer.tsx index a1e7d5c2a..cc187cd67 100644 --- a/src/client/views/pdf/PDFViewer.tsx +++ b/src/client/views/pdf/PDFViewer.tsx @@ -238,7 +238,7 @@ export class PDFViewer extends DocAnnotatableComponent { if (e.keyCode === 13) { - let submittedTitle = this.roomText!.value; + const submittedTitle = this.roomText!.value; this.roomText!.value = ""; this.roomText!.blur(); initialize(submittedTitle, this.changeUILook); @@ -56,7 +56,7 @@ export class DashWebRTCVideo extends React.Component
DashWebRTC
this.roomText = e!} onKeyDown={this.onEnterKeyDown} /> @@ -72,8 +72,8 @@ export class DashWebRTCVideo extends React.Component
; - let frozen = !this.props.isSelected() || DocumentDecorations.Instance.Interacting; - let classname = "webBox-cont" + (this.props.isSelected() && !InkingControl.Instance.selectedTool && !DocumentDecorations.Instance.Interacting ? "-interactive" : ""); + const frozen = !this.props.isSelected() || DocumentDecorations.Instance.Interacting; + const classname = "webBox-cont" + (this.props.isSelected() && !InkingControl.Instance.selectedTool && !DocumentDecorations.Instance.Interacting ? "-interactive" : ""); return ( diff --git a/src/mobile/MobileInterface.tsx b/src/mobile/MobileInterface.tsx index 5d3a517ae..1d2d57b96 100644 --- a/src/mobile/MobileInterface.tsx +++ b/src/mobile/MobileInterface.tsx @@ -199,6 +199,8 @@ export default class MobileInterface extends React.Component { DataDoc={undefined} LibraryPath={emptyPath} fieldKey={""} + dropAction={"alias"} + bringToFront={emptyFunction } addDocTab={returnFalse} pinToPres={emptyFunction} PanelHeight={() => window.innerHeight} diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 25b526168..440f13d6b 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -353,7 +353,7 @@ export namespace Doc { // and returns the document who's proto is undefined or whose proto is marked as a base prototype ('isPrototype'). export function GetProto(doc: Doc): Doc { if (doc instanceof Promise) { - console.log("GetProto: error: got Promise insead of Doc") + console.log("GetProto: error: got Promise insead of Doc"); } const proto = doc && (Doc.GetT(doc, "isPrototype", "boolean", true) ? doc : (doc.proto || doc)); return proto === doc ? proto : Doc.GetProto(proto); @@ -697,7 +697,7 @@ export namespace Doc { // the document containing the view layout information - will be the Document itself unless the Document has // a layout field or 'layout' is given. export function Layout(doc: Doc, layout?: Doc): Doc { - const overrideLayout = layout && Cast(doc["data-layout[" + layout[Id] + "]"], Doc, null); + const overrideLayout = layout && Cast(doc[`${StrCast(layout.isTemplateForField, "data")}-layout[` + layout[Id] + "]"], Doc, null); return overrideLayout || doc[LayoutSym] || doc; } export function SetLayout(doc: Doc, layout: Doc | string) { doc[StrCast(doc.layoutKey, "layout")] = layout; } diff --git a/src/new_fields/util.ts b/src/new_fields/util.ts index 3a1fd41f8..8c719ccd8 100644 --- a/src/new_fields/util.ts +++ b/src/new_fields/util.ts @@ -12,7 +12,7 @@ function _readOnlySetter(): never { throw new Error("Documents can't be modified in read-only mode"); } -let tracing = false; +const tracing = false; export function TraceMobx() { tracing && trace(); } diff --git a/src/server/DashSession/Session/agents/applied_session_agent.ts b/src/server/DashSession/Session/agents/applied_session_agent.ts index 46c9e22ed..12064668b 100644 --- a/src/server/DashSession/Session/agents/applied_session_agent.ts +++ b/src/server/DashSession/Session/agents/applied_session_agent.ts @@ -44,7 +44,7 @@ export abstract class AppliedSessionAgent { if (!this.launched) { this.launched = true; if (isMaster) { - this.sessionMonitorRef = Monitor.Create() + this.sessionMonitorRef = Monitor.Create(); const sessionKey = await this.initializeMonitor(this.sessionMonitorRef); this.sessionMonitorRef.finalize(sessionKey); } else { diff --git a/src/server/DashSession/Session/agents/monitor.ts b/src/server/DashSession/Session/agents/monitor.ts index 6f8d25614..ee8afee65 100644 --- a/src/server/DashSession/Session/agents/monitor.ts +++ b/src/server/DashSession/Session/agents/monitor.ts @@ -167,7 +167,7 @@ export class Monitor extends IPCMessageReceiver { * and pass down any variables the pertinent to the child processes as environment variables. */ private loadAndValidateConfiguration = (): Configuration => { - let config: Configuration; + let config: Configuration | undefined; try { console.log(this.timestamp(), cyan("validating configuration...")); config = JSON.parse(readFileSync('./session.config.json', 'utf8')); diff --git a/src/server/DashSession/Session/agents/promisified_ipc_manager.ts b/src/server/DashSession/Session/agents/promisified_ipc_manager.ts index 9f0db8330..feff568e1 100644 --- a/src/server/DashSession/Session/agents/promisified_ipc_manager.ts +++ b/src/server/DashSession/Session/agents/promisified_ipc_manager.ts @@ -35,8 +35,8 @@ export type MessageHandler = (args: T) => (any | Promise); * When a message is emitted, it is embedded with private metadata * to facilitate the resolution of promises, etc. */ -interface InternalMessage extends Message { metadata: Metadata } -interface Metadata { isResponse: boolean; id: string } +interface InternalMessage extends Message { metadata: Metadata; } +interface Metadata { isResponse: boolean; id: string; } type InternalMessageHandler = (message: InternalMessage) => (any | Promise); /** @@ -133,7 +133,7 @@ export class PromisifiedIPCManager { Object.keys(pendingMessages).forEach(id => { const error: ErrorLike = { name: "ManagerDestroyed", message: "The IPC manager was destroyed before the response could be returned." }; const message: InternalMessage = { name: pendingMessages[id], args: { error }, metadata: { id, isResponse: true } }; - this.target.send?.(message) + this.target.send?.(message); }); this.pendingMessages = {}; } diff --git a/src/server/Websocket/Websocket.ts b/src/server/Websocket/Websocket.ts index c5dc22912..9f9fc9619 100644 --- a/src/server/Websocket/Websocket.ts +++ b/src/server/Websocket/Websocket.ts @@ -55,8 +55,8 @@ export namespace WebSocket { socket.on('create or join', function (room) { console.log('Received request to create or join room ' + room); - var clientsInRoom = socket.adapter.rooms[room]; - var numClients = clientsInRoom ? Object.keys(clientsInRoom.sockets).length : 0; + const clientsInRoom = socket.adapter.rooms[room]; + const numClients = clientsInRoom ? Object.keys(clientsInRoom.sockets).length : 0; console.log('Room ' + room + ' now has ' + numClients + ' client(s)'); if (numClients === 0) { @@ -76,8 +76,8 @@ export namespace WebSocket { }); socket.on('ipaddr', function () { - var ifaces = networkInterfaces(); - for (var dev in ifaces) { + const ifaces = networkInterfaces(); + for (const dev in ifaces) { ifaces[dev].forEach(function (details) { if (details.family === 'IPv4' && details.address !== '127.0.0.1') { socket.emit('ipaddr', details.address); diff --git a/src/server/database.ts b/src/server/database.ts index 055f04c49..fc91ff3a2 100644 --- a/src/server/database.ts +++ b/src/server/database.ts @@ -328,7 +328,7 @@ export namespace Database { export const LogUpload = async (information: Upload.ImageInformation) => { const bundle = { - _id: Utils.GenerateDeterministicGuid(String(information.contentSize!)), + _id: Utils.GenerateDeterministicGuid(String(information.contentSize)), ...information }; return Instance.insert(bundle, AuxiliaryCollections.GooglePhotosUploadHistory); diff --git a/src/server/server_Initialization.ts b/src/server/server_Initialization.ts index 7b2228831..1150118f7 100644 --- a/src/server/server_Initialization.ts +++ b/src/server/server_Initialization.ts @@ -123,7 +123,7 @@ function registerCorsProxy(server: express.Express) { const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/; server.use("/corsProxy", (req, res) => { - let requrl = decodeURIComponent(req.url.substring(1)); + const requrl = decodeURIComponent(req.url.substring(1)); const referer = req.headers.referer ? decodeURIComponent(req.headers.referer) : ""; // cors weirdness here... // if the referer is a cors page and the cors() route (I think) redirected to /corsProxy/ and the requested url path was relative, -- cgit v1.2.3-70-g09d2 From adabfbea2b034beb310530aef9cc8b206e260b67 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Fri, 3 Apr 2020 20:23:15 -0400 Subject: added rootSelected() to make forceActive work better --- src/client/documents/Documents.ts | 2 +- src/client/util/RichTextSchema.tsx | 1 + src/client/views/DocComponent.tsx | 6 +++-- src/client/views/GestureOverlay.tsx | 1 + src/client/views/MainView.tsx | 4 ++++ src/client/views/OverlayView.tsx | 1 + src/client/views/Palette.tsx | 26 +++++++--------------- src/client/views/RecommendationsBox.tsx | 1 + src/client/views/SearchDocBox.tsx | 3 ++- .../views/collections/CollectionDockingView.tsx | 1 + .../views/collections/CollectionLinearView.tsx | 3 ++- .../views/collections/CollectionSchemaView.tsx | 1 + .../views/collections/CollectionStackingView.tsx | 1 + src/client/views/collections/CollectionSubView.tsx | 5 +++++ .../views/collections/CollectionTreeView.tsx | 2 ++ src/client/views/collections/CollectionView.tsx | 2 +- .../collectionFreeForm/CollectionFreeFormView.tsx | 1 + .../collections/collectionFreeForm/MarqueeView.tsx | 1 - src/client/views/nodes/AudioBox.tsx | 12 +++++++--- .../views/nodes/CollectionFreeFormDocumentView.tsx | 7 +++--- .../views/nodes/ContentFittingDocumentView.tsx | 1 + src/client/views/nodes/DocumentBox.tsx | 1 + src/client/views/nodes/DocumentContentsView.tsx | 4 ++-- src/client/views/nodes/DocumentView.tsx | 24 +++++++++++++++----- src/client/views/nodes/FieldView.tsx | 1 + src/client/views/nodes/FormattedTextBoxComment.tsx | 1 + src/client/views/pdf/PDFViewer.tsx | 3 +-- .../views/presentationview/PresElementBox.tsx | 3 ++- src/client/views/search/SearchItem.tsx | 3 ++- src/mobile/MobileInterface.tsx | 2 ++ .../authentication/models/current_user_utils.ts | 2 +- 31 files changed, 83 insertions(+), 43 deletions(-) (limited to 'src/client/views/MainView.tsx') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index a69bfae01..0a2269bac 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -435,7 +435,7 @@ export namespace Docs { Scripting.addGlobal(Buxton); const delegateKeys = ["x", "y", "layoutKey", "_width", "_height", "_panX", "_panY", "_viewType", "_nativeWidth", "_nativeHeight", "dropAction", "childDropAction", "_annotationOn", - "_chromeStatus", "_forceActive", "_autoHeight", "_fitWidth", "_LODdisable", "_itemIndex", "_showSidebar", "_showTitle", "_showCaption", "_showTitleHover", "_backgroundColor", + "_chromeStatus", "_autoHeight", "_fitWidth", "_LODdisable", "_itemIndex", "_showSidebar", "_showTitle", "_showCaption", "_showTitleHover", "_backgroundColor", "_xMargin", "_yMargin", "_xPadding", "_yPadding", "_singleLine", "_scrollTop", "_color", "isButton", "isBackground", "removeDropProperties", "treeViewOpen"]; diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index 094cd58f3..4a930177d 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -818,6 +818,7 @@ export class DashDocView { LibraryPath={this._textBox.props.LibraryPath} fitToBox={BoolCast(dashDoc._fitToBox)} addDocument={returnFalse} + rootSelected={this._textBox.props.isSelected} removeDocument={removeDoc} ScreenToLocalTransform={this.getDocTransform} addDocTab={this._textBox.props.addDocTab} diff --git a/src/client/views/DocComponent.tsx b/src/client/views/DocComponent.tsx index f4e830a48..454c245cc 100644 --- a/src/client/views/DocComponent.tsx +++ b/src/client/views/DocComponent.tsx @@ -29,6 +29,7 @@ interface DocExtendableProps { fieldKey: string; isSelected: (outsideReaction?: boolean) => boolean; renderDepth: number; + rootSelected: () => boolean; } export function DocExtendableComponent

(schemaCtor: (doc: Doc) => T) { class Component extends Touchable

{ @@ -36,7 +37,7 @@ export function DocExtendableComponent

(schemaCt @computed get Document(): T { return schemaCtor(this.props.Document); } @computed get layoutDoc() { return Doc.Layout(this.props.Document); } @computed get dataDoc() { return (this.props.DataDoc && (this.props.Document.isTemplateForField || this.props.Document.isTemplateDoc) ? this.props.DataDoc : Cast(this.props.Document.resolvedDataDoc, Doc, null) || Doc.GetProto(this.props.Document)) as Doc; } - active = (outsideReaction?: boolean) => !this.props.Document.isBackground && (this.props.Document.forceActive || this.props.isSelected(outsideReaction) || this.props.renderDepth === 0);// && !InkingControl.Instance.selectedTool; // bcz: inking state shouldn't affect static tools + active = (outsideReaction?: boolean) => !this.props.Document.isBackground && ((this.props.Document.forceActive && this.props.rootSelected()) || this.props.isSelected(outsideReaction) || this.props.renderDepth === 0);// && !InkingControl.Instance.selectedTool; // bcz: inking state shouldn't affect static tools } return Component; } @@ -50,6 +51,7 @@ export interface DocAnnotatableProps { active: () => boolean; whenActiveChanged: (isActive: boolean) => void; isSelected: (outsideReaction?: boolean) => boolean; + rootSelected: () => boolean; renderDepth: number; } export function DocAnnotatableComponent

(schemaCtor: (doc: Doc) => T) { @@ -86,7 +88,7 @@ export function DocAnnotatableComponent

(schema whenActiveChanged = action((isActive: boolean) => this.props.whenActiveChanged(this._isChildActive = isActive)); active = (outsideReaction?: boolean) => ((InkingControl.Instance.selectedTool === InkTool.None && !this.props.Document.isBackground) && - (this.props.Document.forceActive || this.props.isSelected(outsideReaction) || this._isChildActive || this.props.renderDepth === 0) ? true : false) + ((this.props.Document.forceActive && this.props.rootSelected()) || this.props.isSelected(outsideReaction) || this._isChildActive || this.props.renderDepth === 0) ? true : false) annotationsActive = (outsideReaction?: boolean) => (InkingControl.Instance.selectedTool !== InkTool.None || (this.props.Document.forceActive || this.props.isSelected(outsideReaction) || this._isChildActive || this.props.renderDepth === 0) ? true : false) } diff --git a/src/client/views/GestureOverlay.tsx b/src/client/views/GestureOverlay.tsx index ea60907f6..26bee9a6f 100644 --- a/src/client/views/GestureOverlay.tsx +++ b/src/client/views/GestureOverlay.tsx @@ -705,6 +705,7 @@ export default class GestureOverlay extends Touchable { LibraryPath={emptyPath} addDocument={undefined} addDocTab={returnFalse} + rootSelected={returnTrue} pinToPres={emptyFunction} onClick={undefined} removeDocument={undefined} diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 8d9be5980..fae520e40 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -309,6 +309,7 @@ export class MainView extends React.Component { addDocument={undefined} addDocTab={this.addDocTabFunc} pinToPres={emptyFunction} + rootSelected={returnTrue} onClick={undefined} backgroundColor={this.defaultBackgroundColors} removeDocument={undefined} @@ -407,6 +408,7 @@ export class MainView extends React.Component { DataDoc={undefined} LibraryPath={emptyPath} addDocument={undefined} + rootSelected={returnTrue} addDocTab={this.addDocTabFunc} pinToPres={emptyFunction} removeDocument={undefined} @@ -435,6 +437,7 @@ export class MainView extends React.Component { addDocument={undefined} addDocTab={this.addDocTabFunc} pinToPres={emptyFunction} + rootSelected={returnTrue} removeDocument={returnFalse} onClick={undefined} ScreenToLocalTransform={this.mainContainerXf} @@ -523,6 +526,7 @@ export class MainView extends React.Component { fieldKey={"data"} dropAction={"alias"} annotationsKey={""} + rootSelected={returnTrue} bringToFront={emptyFunction} select={emptyFunction} active={returnFalse} diff --git a/src/client/views/OverlayView.tsx b/src/client/views/OverlayView.tsx index 220efd4a8..7587071db 100644 --- a/src/client/views/OverlayView.tsx +++ b/src/client/views/OverlayView.tsx @@ -174,6 +174,7 @@ export class OverlayView extends React.Component { Document={d} LibraryPath={emptyPath} ChromeHeight={returnZero} + rootSelected={returnTrue} // isSelected={returnFalse} // select={emptyFunction} // layoutKey={"layout"} diff --git a/src/client/views/Palette.tsx b/src/client/views/Palette.tsx index e04f814d1..674b27918 100644 --- a/src/client/views/Palette.tsx +++ b/src/client/views/Palette.tsx @@ -1,23 +1,12 @@ +import { IReactionDisposer, observable, reaction } from "mobx"; +import { observer } from "mobx-react"; import * as React from "react"; -import "./Palette.scss"; -import { PointData } from "../../new_fields/InkField"; import { Doc } from "../../new_fields/Doc"; -import { Docs } from "../documents/Documents"; -import { ScriptField, ComputedField } from "../../new_fields/ScriptField"; -import { List } from "../../new_fields/List"; -import { DocumentView } from "./nodes/DocumentView"; -import { emptyPath, returnFalse, emptyFunction, returnOne, returnEmptyString, returnTrue } from "../../Utils"; -import { CurrentUserUtils } from "../../server/authentication/models/current_user_utils"; +import { NumCast } from "../../new_fields/Types"; +import { emptyFunction, emptyPath, returnEmptyString, returnFalse, returnOne, returnTrue } from "../../Utils"; import { Transform } from "../util/Transform"; -import { computed, action, IReactionDisposer, reaction, observable } from "mobx"; -import { FieldValue, Cast, NumCast } from "../../new_fields/Types"; -import { observer } from "mobx-react"; -import { DocumentContentsView } from "./nodes/DocumentContentsView"; -import { CollectionStackingView } from "./collections/CollectionStackingView"; -import { CollectionView } from "./collections/CollectionView"; -import { CollectionSubView, SubCollectionViewProps } from "./collections/CollectionSubView"; -import { makeInterface } from "../../new_fields/Schema"; -import { documentSchema } from "../../new_fields/documentSchemas"; +import { DocumentView } from "./nodes/DocumentView"; +import "./Palette.scss"; export interface PaletteProps { x: number; @@ -40,7 +29,7 @@ export default class Palette extends React.Component { } componentWillUnmount = () => { - this._selectedDisposer && this._selectedDisposer(); + this._selectedDisposer?.(); } render() { @@ -54,6 +43,7 @@ export default class Palette extends React.Component { LibraryPath={emptyPath} addDocument={undefined} addDocTab={returnFalse} + rootSelected={returnTrue} pinToPres={emptyFunction} removeDocument={undefined} onClick={undefined} diff --git a/src/client/views/RecommendationsBox.tsx b/src/client/views/RecommendationsBox.tsx index 5ebba0abb..bf8de36b4 100644 --- a/src/client/views/RecommendationsBox.tsx +++ b/src/client/views/RecommendationsBox.tsx @@ -68,6 +68,7 @@ export class RecommendationsBox extends React.Component { addDocument={returnFalse} LibraryPath={emptyPath} removeDocument={returnFalse} + rootSelected={returnFalse} ScreenToLocalTransform={Transform.Identity} addDocTab={returnFalse} pinToPres={returnFalse} diff --git a/src/client/views/SearchDocBox.tsx b/src/client/views/SearchDocBox.tsx index c57f9e737..e66de39d4 100644 --- a/src/client/views/SearchDocBox.tsx +++ b/src/client/views/SearchDocBox.tsx @@ -410,8 +410,9 @@ export class SearchDocBox extends React.Component {

- +
{ Document={document} DataDoc={resolvedDataDoc} bringToFront={emptyFunction} + rootSelected={returnTrue} addDocument={undefined} removeDocument={undefined} ContentScaling={this.contentScaling} diff --git a/src/client/views/collections/CollectionLinearView.tsx b/src/client/views/collections/CollectionLinearView.tsx index 344605412..a6ada75b2 100644 --- a/src/client/views/collections/CollectionLinearView.tsx +++ b/src/client/views/collections/CollectionLinearView.tsx @@ -4,7 +4,7 @@ import * as React from 'react'; import { Doc, HeightSym, WidthSym } from '../../../new_fields/Doc'; import { makeInterface } from '../../../new_fields/Schema'; import { BoolCast, NumCast, StrCast, Cast } from '../../../new_fields/Types'; -import { emptyFunction, returnEmptyString, returnOne, returnTrue, Utils } from '../../../Utils'; +import { emptyFunction, returnEmptyString, returnOne, returnTrue, Utils, returnFalse } from '../../../Utils'; import { DragManager } from '../../util/DragManager'; import { Transform } from '../../util/Transform'; import "./CollectionLinearView.scss"; @@ -110,6 +110,7 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { moveDocument={this.props.moveDocument} addDocTab={this.props.addDocTab} pinToPres={emptyFunction} + rootSelected={this.props.isSelected} removeDocument={this.props.removeDocument} onClick={undefined} ScreenToLocalTransform={this.getTransform(dref)} diff --git a/src/client/views/collections/CollectionSchemaView.tsx b/src/client/views/collections/CollectionSchemaView.tsx index 981438513..a1b541f74 100644 --- a/src/client/views/collections/CollectionSchemaView.tsx +++ b/src/client/views/collections/CollectionSchemaView.tsx @@ -124,6 +124,7 @@ export class CollectionSchemaView extends CollectionSubView(doc => doc) { LibraryPath={this.props.LibraryPath} childDocs={this.childDocs} renderDepth={this.props.renderDepth} + rootSelected={this.rootSelected} PanelWidth={this.previewWidth} PanelHeight={this.previewHeight} getTransform={this.getPreviewTransform} diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index 076dd3629..d21e17bbc 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -176,6 +176,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { LibraryPath={this.props.LibraryPath} renderDepth={this.props.renderDepth + 1} fitToBox={this.props.fitToBox} + rootSelected={this.rootSelected} dropAction={StrCast(this.props.Document.childDropAction) as dropActionType} onClick={layoutDoc.isTemplateDoc ? this.onClickHandler : this.onChildClickHandler} PanelWidth={width} diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index 70927cf22..d1d6ae3c1 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -34,6 +34,7 @@ export interface CollectionViewProps extends FieldViewProps { PanelHeight: () => number; VisibleHeight?: () => number; setPreviewCursor?: (func: (x: number, y: number, drag: boolean) => void) => void; + rootSelected: () => boolean; fieldKey: string; } @@ -95,6 +96,10 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T, moreProps?: this.props.Document.resolvedDataDoc ? this.props.Document : Doc.GetProto(this.props.Document)); // if the layout document has a resolvedDataDoc, then we don't want to get its parent which would be the unexpanded template } + rootSelected = () => { + return this.props.isSelected() || (this.props.Document.rootDocument || this.props.Document.forceActive ? this.props.rootSelected() : false); + } + // The data field for rendering this collection will be on the this.props.Document unless we're rendering a template in which case we try to use props.DataDoc. // When a document has a DataDoc but it's not a template, then it contains its own rendering data, but needs to pass the DataDoc through // to its children which may be templates. diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index 6ee48f11b..fc612c66d 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -373,6 +373,7 @@ class TreeView extends React.Component { DataDocument={this.templateDataDoc} LibraryPath={emptyPath} renderDepth={this.props.renderDepth + 1} + rootSelected={returnTrue} backgroundColor={this.props.backgroundColor} fitToBox={this.boundsOfCollectionDocument !== undefined} PanelWidth={this.docWidth} @@ -454,6 +455,7 @@ class TreeView extends React.Component { LibraryPath={this.props.libraryPath || []} addDocument={undefined} addDocTab={this.props.addDocTab} + rootSelected={returnTrue} pinToPres={emptyFunction} onClick={this.props.onChildClick || editTitle} dropAction={this.props.dropAction} diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index df1770ffe..3913ccd88 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -117,7 +117,7 @@ export class CollectionView extends Touchable { return viewField; } - active = (outsideReaction?: boolean) => this.props.isSelected(outsideReaction) || BoolCast(this.props.Document.forceActive) || this._isChildActive || this.props.renderDepth === 0; + active = (outsideReaction?: boolean) => this.props.isSelected(outsideReaction) || (this.props.rootSelected() && BoolCast(this.props.Document.forceActive)) || this._isChildActive || this.props.renderDepth === 0; whenActiveChanged = (isActive: boolean) => { this.props.whenActiveChanged(this._isChildActive = isActive); }; diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 2871fe192..a164e1794 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -832,6 +832,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { Document: childLayout, LibraryPath: this.libraryPath, layoutKey: undefined, + rootSelected: this.rootSelected, dropAction: StrCast(this.props.Document.childDropAction) as dropActionType, //onClick: undefined, // this.props.onClick, // bcz: check this out -- I don't think we want to inherit click handlers, or we at least need a way to ignore them onClick: this.onChildClickHandler, diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index 276a49570..503df10c2 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -5,7 +5,6 @@ import { InkField, InkData } from "../../../../new_fields/InkField"; import { List } from "../../../../new_fields/List"; import { SchemaHeaderField } from "../../../../new_fields/SchemaHeaderField"; import { Cast, NumCast, FieldValue, StrCast } from "../../../../new_fields/Types"; -import { CurrentUserUtils } from "../../../../server/authentication/models/current_user_utils"; import { Utils } from "../../../../Utils"; import { Docs, DocUtils } from "../../../documents/Documents"; import { SelectionManager } from "../../../util/SelectionManager"; diff --git a/src/client/views/nodes/AudioBox.tsx b/src/client/views/nodes/AudioBox.tsx index 03b2a2297..bd54d64ff 100644 --- a/src/client/views/nodes/AudioBox.tsx +++ b/src/client/views/nodes/AudioBox.tsx @@ -7,7 +7,7 @@ import { AudioField, nullAudio } from "../../../new_fields/URLField"; import { DocExtendableComponent } from "../DocComponent"; import { makeInterface, createSchema } from "../../../new_fields/Schema"; import { documentSchema } from "../../../new_fields/documentSchemas"; -import { Utils, returnTrue, emptyFunction, returnOne, returnTransparent } from "../../../Utils"; +import { Utils, returnTrue, emptyFunction, returnOne, returnTransparent, returnFalse } from "../../../Utils"; import { runInAction, observable, reaction, IReactionDisposer, computed, action } from "mobx"; import { DateField } from "../../../new_fields/DateField"; import { SelectionManager } from "../../util/SelectionManager"; @@ -258,9 +258,15 @@ export class AudioBox extends DocExtendableComponent
-
Doc.linkFollowHighlight(la1)} diff --git a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx index eaab4086c..356192797 100644 --- a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx +++ b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx @@ -89,14 +89,15 @@ export class CollectionFreeFormDocumentView extends DocComponent - {!this.props.fitToBox ? : + : boolean; pinToPres: (document: Doc) => void; dontRegisterView?: boolean; + rootSelected: () => boolean; } @observer diff --git a/src/client/views/nodes/DocumentBox.tsx b/src/client/views/nodes/DocumentBox.tsx index debe104d7..47118e758 100644 --- a/src/client/views/nodes/DocumentBox.tsx +++ b/src/client/views/nodes/DocumentBox.tsx @@ -122,6 +122,7 @@ export class DocumentBox extends DocAnnotatableComponent Opt; + makeLink?: () => Opt, // function to call when a link is made }> { @computed get layout(): string { TraceMobx(); diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 1e02ab44e..42f5fb946 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -60,6 +60,7 @@ export interface DocumentViewProps { LayoutDoc?: () => Opt; LibraryPath: Doc[]; fitToBox?: boolean; + rootSelected: () => boolean; // whether the root of a template has been selected onClick?: ScriptField; onPointerDown?: ScriptField; onPointerUp?: ScriptField; @@ -277,7 +278,7 @@ export class DocumentView extends DocComponent(Docu this.dontDecorateSelection = this.props.Document.dontDecorateSelection && (!e.ctrlKey || e.button < 2); if (!e.nativeEvent.cancelBubble && !this.Document.ignoreClick && (Math.abs(e.clientX - this._downX) < Utils.DRAG_THRESHOLD && Math.abs(e.clientY - this._downY) < Utils.DRAG_THRESHOLD)) { - e.stopPropagation(); + let stopPropagate = true; let preventDefault = true; this.props.bringToFront(this.props.Document); if (this._doubleTap && this.props.renderDepth && !this.onClickHandler?.script) { // disable double-click to show full screen for things that have an on click behavior since clicking them twice can be misinterpreted as a double click @@ -301,9 +302,14 @@ export class DocumentView extends DocComponent(Docu SelectionManager.SelectDoc(this, e.ctrlKey); // don't think this should happen if a button action is actually triggered. UndoManager.RunInBatch(() => this.buttonClick(e.altKey, e.ctrlKey), "on link button follow"); } else { - SelectionManager.SelectDoc(this, e.ctrlKey); + if (this.props.Document.isTemplateForField && !(e.ctrlKey || e.button > 0)) { + stopPropagate = false; + } else { + SelectionManager.SelectDoc(this, e.ctrlKey); + } preventDefault = false; } + stopPropagate && e.stopPropagation(); preventDefault && e.preventDefault(); } } @@ -928,6 +934,9 @@ export class DocumentView extends DocComponent(Docu const fallback = Cast(this.props.Document.layoutKey, "string"); return typeof fallback === "string" ? fallback : "layout"; } + rootSelected = () => { + return this.isSelected(false) || (this.props.Document.forceActive && this.props.rootSelected?.() ? true : false); + } childScaling = () => (this.layoutDoc._fitWidth ? this.props.PanelWidth() / this.nativeWidth : this.props.ContentScaling()); @computed get contents() { TraceMobx(); @@ -937,6 +946,7 @@ export class DocumentView extends DocComponent(Docu DataDoc={this.props.DataDoc} LayoutDoc={this.props.LayoutDoc} makeLink={this.makeLink} + rootSelected={this.rootSelected} fitToBox={this.props.fitToBox} LibraryPath={this.props.LibraryPath} addDocument={this.props.addDocument} @@ -985,9 +995,13 @@ export class DocumentView extends DocComponent(Docu {StrCast(this.props.Document.title)} {this.Document.links && DocListCast(this.Document.links).filter(d => !d.hidden).filter(this.isNonTemporalLink).map((d, i) =>
- doc.hidden = true)} /> + doc.hidden = true)} />
)}
; } diff --git a/src/client/views/nodes/FieldView.tsx b/src/client/views/nodes/FieldView.tsx index 0305f43d5..13a1becf7 100644 --- a/src/client/views/nodes/FieldView.tsx +++ b/src/client/views/nodes/FieldView.tsx @@ -29,6 +29,7 @@ export interface FieldViewProps { dropAction: dropActionType; isSelected: (outsideReaction?: boolean) => boolean; select: (isCtrlPressed: boolean) => void; + rootSelected: () => boolean; renderDepth: number; addDocument?: (document: Doc) => boolean; addDocTab: (document: Doc, where: string) => boolean; diff --git a/src/client/views/nodes/FormattedTextBoxComment.tsx b/src/client/views/nodes/FormattedTextBoxComment.tsx index 61df188f8..d1a563494 100644 --- a/src/client/views/nodes/FormattedTextBoxComment.tsx +++ b/src/client/views/nodes/FormattedTextBoxComment.tsx @@ -181,6 +181,7 @@ export class FormattedTextBoxComment { LibraryPath={emptyPath} fitToBox={true} moveDocument={returnFalse} + rootSelected={returnFalse} getTransform={Transform.Identity} active={returnFalse} addDocument={returnFalse} diff --git a/src/client/views/pdf/PDFViewer.tsx b/src/client/views/pdf/PDFViewer.tsx index 71495d95f..c032f019d 100644 --- a/src/client/views/pdf/PDFViewer.tsx +++ b/src/client/views/pdf/PDFViewer.tsx @@ -31,8 +31,6 @@ import { InkingControl } from "../InkingControl"; import { InkTool } from "../../../new_fields/InkField"; import { TraceMobx } from "../../../new_fields/util"; import { PdfField } from "../../../new_fields/URLField"; -import { PDFBox } from "../nodes/PDFBox"; -import { FormattedTextBox } from "../nodes/FormattedTextBox"; import { DocumentView } from "../nodes/DocumentView"; const PDFJSViewer = require("pdfjs-dist/web/pdf_viewer"); const pdfjsLib = require("pdfjs-dist"); @@ -61,6 +59,7 @@ interface IViewerProps { PanelHeight: () => number; ContentScaling: () => number; select: (isCtrlPressed: boolean) => void; + rootSelected: () => boolean; startupLive: boolean; renderDepth: number; focus: (doc: Doc) => void; diff --git a/src/client/views/presentationview/PresElementBox.tsx b/src/client/views/presentationview/PresElementBox.tsx index 758795ed5..7ad3474e8 100644 --- a/src/client/views/presentationview/PresElementBox.tsx +++ b/src/client/views/presentationview/PresElementBox.tsx @@ -9,7 +9,7 @@ import { documentSchema } from '../../../new_fields/documentSchemas'; import { Id } from "../../../new_fields/FieldSymbols"; import { createSchema, makeInterface } from '../../../new_fields/Schema'; import { Cast, NumCast } from "../../../new_fields/Types"; -import { emptyFunction, emptyPath, returnFalse } from "../../../Utils"; +import { emptyFunction, emptyPath, returnFalse, returnTrue } from "../../../Utils"; import { Transform } from "../../util/Transform"; import { CollectionViewType } from '../collections/CollectionView'; import { DocExtendableComponent } from '../DocComponent'; @@ -175,6 +175,7 @@ export class PresElementBox extends DocExtendableComponent { Date: Fri, 3 Apr 2020 23:45:34 -0400 Subject: fixed a bunch of warnings --- src/client/documents/Documents.ts | 7 ++-- src/client/util/SelectionManager.ts | 6 +--- src/client/views/DocumentDecorations.tsx | 1 - src/client/views/MainView.tsx | 40 +++++++++------------ src/client/views/SearchDocBox.tsx | 15 ++++---- src/client/views/TemplateMenu.tsx | 1 + .../views/collections/CollectionLinearView.scss | 2 ++ .../views/collections/CollectionLinearView.tsx | 27 +++++++------- .../views/collections/CollectionSchemaCells.tsx | 1 + src/client/views/nodes/DocumentBox.tsx | 2 +- src/client/views/nodes/DocumentView.tsx | 4 +-- src/client/views/nodes/FormattedTextBox.tsx | 2 +- src/client/views/nodes/KeyValuePair.tsx | 1 + src/client/views/pdf/PDFMenu.tsx | 2 +- src/client/views/search/SearchBox.tsx | 38 ++++++++------------ src/new_fields/documentSchemas.ts | 1 - .../authentication/models/current_user_utils.ts | 42 +++++++++++++--------- 17 files changed, 90 insertions(+), 102 deletions(-) (limited to 'src/client/views/MainView.tsx') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 1a2969cf5..514200d95 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -118,7 +118,6 @@ export interface DocumentOptions { lockedTransform?: boolean; // lock the panx,pany and scale parameters of the document so that it be panned/zoomed opacity?: number; defaultBackgroundColor?: string; - dontDecorateSelection?: boolean; // whether document decorations should be displayed when the document is selected isBackground?: boolean; isButton?: boolean; columnWidth?: number; @@ -164,9 +163,9 @@ export interface DocumentOptions { flexDirection?: "unset" | "row" | "column" | "row-reverse" | "column-reverse"; selectedIndex?: number; syntaxColor?: string; // can be applied to text for syntax highlighting all matches in the text - searchText?: string, //for searchbox - searchQuery?: string, // for queryBox - filterQuery?: string, + searchText?: string; //for searchbox + searchQuery?: string; // for queryBox + filterQuery?: string; linearViewIsExpanded?: boolean; // is linear view expanded } diff --git a/src/client/util/SelectionManager.ts b/src/client/util/SelectionManager.ts index 7221fbbf9..2a6e3bf8a 100644 --- a/src/client/util/SelectionManager.ts +++ b/src/client/util/SelectionManager.ts @@ -33,7 +33,6 @@ export namespace SelectionManager { @action DeselectDoc(docView: DocumentView): void { if (manager.SelectedDocuments.get(docView)) { - docView.dontDecorateSelection = false; manager.SelectedDocuments.delete(docView); docView.props.whenActiveChanged(false); Doc.UserDoc().SelectedDocs = new List(SelectionManager.SelectedDocuments().map(dv => dv.props.Document)); @@ -41,10 +40,7 @@ export namespace SelectionManager { } @action DeselectAll(): void { - Array.from(manager.SelectedDocuments.keys()).map(dv => { - dv.dontDecorateSelection = false; - dv.props.whenActiveChanged(false); - }); + Array.from(manager.SelectedDocuments.keys()).map(dv => dv.props.whenActiveChanged(false)); manager.SelectedDocuments.clear(); Doc.UserDoc().SelectedDocs = new List([]); } diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index c35263237..e313b117f 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -69,7 +69,6 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> get Bounds(): { x: number, y: number, b: number, r: number } { return SelectionManager.SelectedDocuments().reduce((bounds, documentView) => { if (documentView.props.renderDepth === 0 || - documentView.dontDecorateSelection || Doc.AreProtosEqual(documentView.props.Document, CurrentUserUtils.UserDocument)) { return bounds; } diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index fae520e40..558bc1a4a 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -1,54 +1,46 @@ import { library } from '@fortawesome/fontawesome-svg-core'; -import { - faFileAlt, faStickyNote, faArrowDown, faBullseye, faFilter, faArrowUp, faBolt, faCaretUp, faCat, faCheck, faChevronRight, faClone, faCloudUploadAlt, faCommentAlt, faCut, faEllipsisV, faExclamation, faFilePdf, faFilm, faFont, faGlobeAsia, faLongArrowAltRight, - faMusic, faObjectGroup, faPause, faMousePointer, faPenNib, faFileAudio, faPen, faEraser, faPlay, faPortrait, faRedoAlt, faThumbtack, faTree, faTv, faUndoAlt, faHighlighter, faMicrophone, faCompressArrowsAlt, faPhone, faStamp, faClipboard, faVideo, -} from '@fortawesome/free-solid-svg-icons'; +import { faArrowDown, faArrowUp, faBolt, faBullseye, faCaretUp, faCat, faCheck, faChevronRight, faClipboard, faClone, faCloudUploadAlt, faCommentAlt, faCompressArrowsAlt, faCut, faEllipsisV, faEraser, faExclamation, faFileAlt, faFileAudio, faFilePdf, faFilm, faFilter, faFont, faGlobeAsia, faHighlighter, faLongArrowAltRight, faMicrophone, faMousePointer, faMusic, faObjectGroup, faPause, faPen, faPenNib, faPhone, faPlay, faPortrait, faRedoAlt, faStamp, faStickyNote, faThumbtack, faTree, faTv, faUndoAlt, faVideo } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { action, computed, configure, observable, reaction, runInAction } from 'mobx'; import { observer } from 'mobx-react'; import "normalize.css"; import * as React from 'react'; import Measure from 'react-measure'; -import { Doc, DocListCast, Field, FieldResult, Opt } from '../../new_fields/Doc'; +import { Doc, DocListCast, Field, Opt } from '../../new_fields/Doc'; import { Id } from '../../new_fields/FieldSymbols'; import { List } from '../../new_fields/List'; import { listSpec } from '../../new_fields/Schema'; -import { Cast, FieldValue, StrCast, BoolCast } from '../../new_fields/Types'; +import { BoolCast, Cast, FieldValue, StrCast } from '../../new_fields/Types'; +import { TraceMobx } from '../../new_fields/util'; import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils'; -import { emptyFunction, returnEmptyString, returnFalse, returnOne, returnTrue, Utils, emptyPath } from '../../Utils'; +import { emptyFunction, emptyPath, returnFalse, returnOne, returnTrue, Utils } from '../../Utils'; import GoogleAuthenticationManager from '../apis/GoogleAuthenticationManager'; import { DocServer } from '../DocServer'; import { Docs, DocumentOptions } from '../documents/Documents'; +import { DocumentType } from '../documents/DocumentTypes'; import { HistoryUtil } from '../util/History'; +import RichTextMenu from '../util/RichTextMenu'; +import { Scripting } from '../util/Scripting'; +import SettingsManager from '../util/SettingsManager'; import SharingManager from '../util/SharingManager'; import { Transform } from '../util/Transform'; -import { CollectionLinearView } from './collections/CollectionLinearView'; -import { CollectionViewType, CollectionView } from './collections/CollectionView'; import { CollectionDockingView } from './collections/CollectionDockingView'; +import MarqueeOptionsMenu from './collections/collectionFreeForm/MarqueeOptionsMenu'; +import { CollectionLinearView } from './collections/CollectionLinearView'; +import { CollectionView, CollectionViewType } from './collections/CollectionView'; import { ContextMenu } from './ContextMenu'; import { DictationOverlay } from './DictationOverlay'; import { DocumentDecorations } from './DocumentDecorations'; +import GestureOverlay from './GestureOverlay'; import KeyManager from './GlobalKeyHandler'; import "./MainView.scss"; import { MainViewNotifs } from './MainViewNotifs'; +import { AudioBox } from './nodes/AudioBox'; import { DocumentView } from './nodes/DocumentView'; +import { RadialMenu } from './nodes/RadialMenu'; +import { OverlayView } from './OverlayView'; import PDFMenu from './pdf/PDFMenu'; import { PreviewCursor } from './PreviewCursor'; -import { FilterBox } from './search/FilterBox'; -import { SchemaHeaderField, RandomPastel } from '../../new_fields/SchemaHeaderField'; -//import { DocumentManager } from '../util/DocumentManager'; -import { RecommendationsBox } from './RecommendationsBox'; -import { PresBox } from './nodes/PresBox'; -import { OverlayView } from './OverlayView'; -import MarqueeOptionsMenu from './collections/collectionFreeForm/MarqueeOptionsMenu'; -import GestureOverlay from './GestureOverlay'; -import { Scripting } from '../util/Scripting'; -import { AudioBox } from './nodes/AudioBox'; -import SettingsManager from '../util/SettingsManager'; -import { TraceMobx } from '../../new_fields/util'; -import { RadialMenu } from './nodes/RadialMenu'; -import RichTextMenu from '../util/RichTextMenu'; -import { DocumentType } from '../documents/DocumentTypes'; @observer export class MainView extends React.Component { diff --git a/src/client/views/SearchDocBox.tsx b/src/client/views/SearchDocBox.tsx index cd9666af8..4790a2ad7 100644 --- a/src/client/views/SearchDocBox.tsx +++ b/src/client/views/SearchDocBox.tsx @@ -81,8 +81,8 @@ export class SearchDocBox extends React.Component { updateKey = async (newKey: string) => { this.query = newKey; if (newKey.length > 1) { - let newdocs = await this.getAllResults(this.query); - let things = newdocs.docs + const newdocs = await this.getAllResults(this.query); + const things = newdocs.docs; console.log(things); console.log(this.content); runInAction(() => { @@ -152,10 +152,9 @@ export class SearchDocBox extends React.Component { enter = async (e: React.KeyboardEvent) => { console.log(e.key); if (e.key === "Enter") { - let newdocs = await this.getAllResults(this.query) - let things = newdocs.docs - console.log(things); - this.content = Docs.Create.TreeDocument(things, { _width: 200, _height: 400, _chromeStatus: "disabled", title: `Search Docs: "Results"` }); + const newdocs = await this.getAllResults(this.query); + console.log(newdocs.docs); + this.content = Docs.Create.TreeDocument(newdocs.docs, { _width: 200, _height: 400, _chromeStatus: "disabled", title: `Search Docs: "Results"` }); } } @@ -290,7 +289,7 @@ export class SearchDocBox extends React.Component { } } //return Docs.Create.TreeDocument(docs, { _width: 200, _height: 400, backgroundColor: "grey", title: `Search Docs: "${this._searchString}"` }); - return Docs.Create.QueryDocument(docs, { _width: 200, _height: 400, searchText: this._searchString, title: `Query Docs: "${this._searchString}"` }); + return Docs.Create.QueryDocument({ _width: 200, _height: 400, searchText: this._searchString, title: `Query Docs: "${this._searchString}"` }); } @action.bound @@ -416,7 +415,7 @@ export class SearchDocBox extends React.Component { top: 0, }} title={"Add Metadata"} - onClick={action(() => { this.editingMetadata = !this.editingMetadata })} + onClick={action(() => this.editingMetadata = !this.editingMetadata)} />
{ CollectionView={undefined} ContainingCollectionDoc={undefined} ContainingCollectionView={undefined} + rootSelected={returnFalse} onCheckedClick={this.scriptField!} onChildClick={this.scriptField!} LibraryPath={emptyPath} diff --git a/src/client/views/collections/CollectionLinearView.scss b/src/client/views/collections/CollectionLinearView.scss index eae9e0220..123a27deb 100644 --- a/src/client/views/collections/CollectionLinearView.scss +++ b/src/client/views/collections/CollectionLinearView.scss @@ -8,6 +8,8 @@ display:flex; height: 100%; >label { + margin-top: "auto"; + margin-bottom: "auto"; background: $dark-color; color: $light-color; display: inline-block; diff --git a/src/client/views/collections/CollectionLinearView.tsx b/src/client/views/collections/CollectionLinearView.tsx index a6ada75b2..728b3066d 100644 --- a/src/client/views/collections/CollectionLinearView.tsx +++ b/src/client/views/collections/CollectionLinearView.tsx @@ -3,7 +3,7 @@ import { observer } from 'mobx-react'; import * as React from 'react'; import { Doc, HeightSym, WidthSym } from '../../../new_fields/Doc'; import { makeInterface } from '../../../new_fields/Schema'; -import { BoolCast, NumCast, StrCast, Cast } from '../../../new_fields/Types'; +import { BoolCast, NumCast, StrCast, Cast, ScriptCast } from '../../../new_fields/Types'; import { emptyFunction, returnEmptyString, returnOne, returnTrue, Utils, returnFalse } from '../../../Utils'; import { DragManager } from '../../util/DragManager'; import { Transform } from '../../util/Transform'; @@ -13,7 +13,6 @@ import { CollectionSubView } from './CollectionSubView'; import { DocumentView } from '../nodes/DocumentView'; import { documentSchema } from '../../../new_fields/documentSchemas'; import { Id } from '../../../new_fields/FieldSymbols'; -import { ScriptField } from '../../../new_fields/ScriptField'; type LinearDocument = makeInterface<[typeof documentSchema,]>; @@ -28,12 +27,10 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { private _selectedDisposer?: IReactionDisposer; componentWillUnmount() { - this._dropDisposer && this._dropDisposer(); - this._widthDisposer && this._widthDisposer(); - this._selectedDisposer && this._selectedDisposer(); - this.childLayoutPairs.map((pair, ind) => { - Cast(pair.layout.proto?.onPointerUp, ScriptField)?.script.run({ this: pair.layout.proto }, console.log); - }); + this._dropDisposer?.(); + this._widthDisposer?.(); + this._selectedDisposer?.(); + this.childLayoutPairs.map((pair, ind) => ScriptCast(pair.layout.proto?.onPointerUp)?.script.run({ this: pair.layout.proto }, console.log)); } componentDidMount() { @@ -54,11 +51,11 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { selected = pair; } else { - Cast(pair.layout.proto?.onPointerUp, ScriptField)?.script.run({ this: pair.layout.proto }, console.log); + ScriptCast(pair.layout.proto?.onPointerUp)?.script.run({ this: pair.layout.proto }, console.log); } }); if (selected && selected.layout) { - Cast(selected.layout.proto?.onPointerDown, ScriptField)?.script.run({ this: selected.layout.proto }, console.log); + ScriptCast(selected.layout.proto?.onPointerDown)?.script.run({ this: selected.layout.proto }, console.log); } }), { fireImmediately: true } @@ -81,14 +78,16 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { render() { const guid = Utils.GenerateGuid(); const flexDir: any = StrCast(this.Document.flexDirection); + const backgroundColor = StrCast(this.props.Document.backgroundColor, "black"); + const color = StrCast(this.props.Document.color, "white"); return
- this.props.Document.linearViewIsExpanded = this.addMenuToggle.current!.checked)} /> -
diff --git a/src/client/views/RecommendationsBox.tsx b/src/client/views/RecommendationsBox.tsx index bf8de36b4..ddeda28ac 100644 --- a/src/client/views/RecommendationsBox.tsx +++ b/src/client/views/RecommendationsBox.tsx @@ -80,8 +80,6 @@ export class RecommendationsBox extends React.Component { parentActive={returnFalse} whenActiveChanged={returnFalse} bringToFront={emptyFunction} - zoomToScale={emptyFunction} - getScale={returnOne} ContainingCollectionView={undefined} ContainingCollectionDoc={undefined} ContentScaling={scale} diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 4209bd574..11eecf771 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -803,9 +803,7 @@ export class DockedFrameRenderer extends React.Component { addDocTab={this.addDocTab} pinToPres={DockedFrameRenderer.PinDoc} ContainingCollectionView={undefined} - ContainingCollectionDoc={undefined} - zoomToScale={emptyFunction} - getScale={returnOne} />; + ContainingCollectionDoc={undefined} />; } render() { diff --git a/src/client/views/collections/CollectionLinearView.tsx b/src/client/views/collections/CollectionLinearView.tsx index 728b3066d..3bd50ad52 100644 --- a/src/client/views/collections/CollectionLinearView.tsx +++ b/src/client/views/collections/CollectionLinearView.tsx @@ -123,10 +123,7 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { whenActiveChanged={emptyFunction} bringToFront={emptyFunction} ContainingCollectionView={undefined} - ContainingCollectionDoc={undefined} - zoomToScale={emptyFunction} - getScale={returnOne}> - + ContainingCollectionDoc={undefined}/>
; })}
diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index fc612c66d..77dd9a162 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -473,8 +473,6 @@ class TreeView extends React.Component { dontRegisterView={BoolCast(this.props.treeViewId.dontRegisterChildren)} ContainingCollectionView={undefined} ContainingCollectionDoc={undefined} - zoomToScale={emptyFunction} - getScale={returnOne} />}
{this.props.treeViewHideHeaderFields() ? (null) : headerElements} diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index a164e1794..376d217bb 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -815,12 +815,6 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { this.Document.scale = scale * Math.min(this.props.PanelWidth() / NumCast(doc._width), this.props.PanelHeight() / NumCast(doc._height)); } - zoomToScale = (scale: number) => { - this.Document.scale = scale; - } - - getScale = () => this.Document.scale || 1; - @computed get libraryPath() { return this.props.LibraryPath ? [...this.props.LibraryPath, this.props.Document] : []; } @computed get onChildClickHandler() { return ScriptCast(this.Document.onChildClick); } backgroundHalo = () => BoolCast(this.Document.useClusters); @@ -848,8 +842,6 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { backgroundHalo: this.backgroundHalo, parentActive: this.props.active, bringToFront: this.bringToFront, - zoomToScale: this.zoomToScale, - getScale: this.getScale }; } diff --git a/src/client/views/nodes/AudioBox.tsx b/src/client/views/nodes/AudioBox.tsx index bd54d64ff..627a71d67 100644 --- a/src/client/views/nodes/AudioBox.tsx +++ b/src/client/views/nodes/AudioBox.tsx @@ -265,8 +265,6 @@ export class AudioBox extends DocExtendableComponent
Doc.linkFollowHighlight(la1)} diff --git a/src/client/views/nodes/ContentFittingDocumentView.tsx b/src/client/views/nodes/ContentFittingDocumentView.tsx index fdf2a9551..9ab6826a3 100644 --- a/src/client/views/nodes/ContentFittingDocumentView.tsx +++ b/src/client/views/nodes/ContentFittingDocumentView.tsx @@ -111,8 +111,6 @@ export class ContentFittingDocumentView extends React.Component
)}
); diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index d12530142..11bf5a6a7 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -80,10 +80,8 @@ export interface DocumentViewProps { bringToFront: (doc: Doc, sendToBack?: boolean) => void; addDocTab: (doc: Doc, where: string, libraryPath?: Doc[]) => boolean; pinToPres: (document: Doc) => void; - zoomToScale: (scale: number) => void; backgroundHalo?: () => boolean; backgroundColor?: (doc: Doc) => string | undefined; - getScale: () => number; ChromeHeight?: () => number; dontRegisterView?: boolean; layoutKey?: string; @@ -959,9 +957,7 @@ export class DocumentView extends DocComponent(Docu bringToFront={this.props.bringToFront} addDocTab={this.props.addDocTab} pinToPres={this.props.pinToPres} - zoomToScale={this.props.zoomToScale} backgroundColor={this.props.backgroundColor} - getScale={this.props.getScale} ContentScaling={this.childScaling} ChromeHeight={this.chromeHeight} isSelected={this.isSelected} diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index a39c337ca..73d09b4e1 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -49,14 +49,15 @@ export class PresBox extends React.Component { this.updateCurrentPresentation(); if (this.childDocs[this.currentIndex + 1] !== undefined) { let nextSelected = this.currentIndex + 1; + this.gotoDocument(nextSelected, this.currentIndex); - for (; nextSelected < this.childDocs.length - 1; nextSelected++) { - if (!this.childDocs[nextSelected + 1].groupButton) { + for (nextSelected = nextSelected + 1; nextSelected < this.childDocs.length; nextSelected++) { + if (!this.childDocs[nextSelected].groupButton) { break; + } else { + this.gotoDocument(nextSelected, this.currentIndex); } } - - this.gotoDocument(nextSelected, this.currentIndex); } } back = () => { @@ -72,13 +73,6 @@ export class PresBox extends React.Component { } prevSelected = Math.max(0, prevSelected - 1); - if (this.currentIndex > 0 && didZoom) { - const prevScale = NumCast(this.childDocs[prevSelected].viewScale); - const curScale = DocumentManager.Instance.getScaleOfDocView(docAtCurrent); - if (prevScale && prevScale !== curScale) { - DocumentManager.Instance.zoomIntoScale(docAtCurrent, prevScale); - } - } this.gotoDocument(prevSelected, this.currentIndex); } } @@ -171,31 +165,15 @@ export class PresBox extends React.Component { if (curDoc.navButton && target) { DocumentManager.Instance.jumpToDocument(target, false, undefined, srcContext); } else if (curDoc.zoomButton && target) { - const curScale = DocumentManager.Instance.getScaleOfDocView(fromDoc); //awaiting jump so that new scale can be found, since jumping is async await DocumentManager.Instance.jumpToDocument(target, true, undefined, srcContext); - curDoc.viewScale = DocumentManager.Instance.getScaleOfDocView(target); - - //saving the scale user was on before zooming in - if (curScale !== 1) { - fromDoc.viewScale = curScale; - } - } return; } - const curScale = DocumentManager.Instance.getScaleOfDocView(fromDoc); //awaiting jump so that new scale can be found, since jumping is async const presTargetDoc = await docToJump.presentationTargetDoc as Doc; await DocumentManager.Instance.jumpToDocument(presTargetDoc, willZoom, undefined, srcContext); - const newScale = DocumentManager.Instance.getScaleOfDocView(await curDoc.presentationTargetDoc as Doc); - curDoc.viewScale = newScale; - //saving the scale that user was on - if (curScale !== 1) { - fromDoc.viewScale = curScale; - } - } @@ -246,10 +224,9 @@ export class PresBox extends React.Component { //stops the presentaton. resetPresentation = () => { this.updateCurrentPresentation(); - this.childDocs.forEach(doc => doc.opacity = doc.viewScale = 1); + this.childDocs.forEach(doc => (doc.presentationTargetDoc as Doc).opacity = 1); this.props.Document._itemIndex = 0; this.props.Document.presStatus = false; - this.childDocs.length && DocumentManager.Instance.zoomIntoScale(this.childDocs[0], 1); } //The function that starts the presentation, also checking if actions should be applied @@ -258,13 +235,13 @@ export class PresBox extends React.Component { this.updateCurrentPresentation(); this.childDocs.map(doc => { if (doc.hideTillShownButton && this.childDocs.indexOf(doc) > startIndex) { - doc.opacity = 0; + (doc.presentationTargetDoc as Doc).opacity = 0; } if (doc.hideAfterButton && this.childDocs.indexOf(doc) < startIndex) { - doc.opacity = 0; + (doc.presentationTargetDoc as Doc).opacity = 0; } if (doc.fadeButton && this.childDocs.indexOf(doc) < startIndex) { - doc.opacity = 0.5; + (doc.presentationTargetDoc as Doc).opacity = 0.5; } }); } @@ -284,16 +261,11 @@ export class PresBox extends React.Component { } })); - /** - * Initially every document starts with a viewScale 1, which means - * that they will be displayed in a canvas with scale 1. - */ - initializeScaleViews = (docList: Doc[], viewtype: number) => { + initializeViewAliases = (docList: Doc[], viewtype: number) => { const hgt = (viewtype === CollectionViewType.Tree) ? 50 : 46; docList.forEach(doc => { doc.presBox = this.props.Document; // give contained documents a reference to the presentation doc.collapsedHeight = hgt; // set the collpased height for documents based on the type of view (Tree or Stack) they will be displaye din - !NumCast(doc.viewScale) && (doc.viewScale = 1); }); } @@ -319,7 +291,7 @@ export class PresBox extends React.Component { childLayoutTemplate = () => this.props.Document._viewType === CollectionViewType.Stacking ? Cast(Doc.UserDoc().presentationTemplate, Doc, null) : undefined; render() { const mode = NumCast(this.props.Document._viewType, CollectionViewType.Invalid); - this.initializeScaleViews(this.childDocs, mode); + this.initializeViewAliases(this.childDocs, mode); return
+ {templateMenu} ; } diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 11eecf771..28aaf0c57 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -15,7 +15,7 @@ import { FieldId } from "../../../new_fields/RefField"; import { Cast, NumCast, StrCast } from "../../../new_fields/Types"; import { TraceMobx } from '../../../new_fields/util'; import { CurrentUserUtils } from '../../../server/authentication/models/current_user_utils'; -import { emptyFunction, returnOne, returnTrue, Utils } from "../../../Utils"; +import { emptyFunction, returnOne, returnTrue, Utils, returnZero } from "../../../Utils"; import { DocServer } from "../../DocServer"; import { Docs } from '../../documents/Documents'; import { DocumentType } from '../../documents/DocumentTypes'; @@ -794,6 +794,8 @@ export class DockedFrameRenderer extends React.Component { ContentScaling={this.contentScaling} PanelWidth={this.panelWidth} PanelHeight={this.panelHeight} + NativeHeight={returnZero} + NativeWidth={returnZero} ScreenToLocalTransform={this.ScreenToLocalTransform} renderDepth={0} parentActive={returnTrue} diff --git a/src/client/views/collections/CollectionLinearView.tsx b/src/client/views/collections/CollectionLinearView.tsx index 3bd50ad52..cb0206260 100644 --- a/src/client/views/collections/CollectionLinearView.tsx +++ b/src/client/views/collections/CollectionLinearView.tsx @@ -4,7 +4,7 @@ import * as React from 'react'; import { Doc, HeightSym, WidthSym } from '../../../new_fields/Doc'; import { makeInterface } from '../../../new_fields/Schema'; import { BoolCast, NumCast, StrCast, Cast, ScriptCast } from '../../../new_fields/Types'; -import { emptyFunction, returnEmptyString, returnOne, returnTrue, Utils, returnFalse } from '../../../Utils'; +import { emptyFunction, returnEmptyString, returnOne, returnTrue, Utils, returnFalse, returnZero } from '../../../Utils'; import { DragManager } from '../../util/DragManager'; import { Transform } from '../../util/Transform'; import "./CollectionLinearView.scss"; @@ -114,6 +114,8 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { onClick={undefined} ScreenToLocalTransform={this.getTransform(dref)} ContentScaling={returnOne} + NativeHeight={returnZero} + NativeWidth={returnZero} PanelWidth={nested ? pair.layout[WidthSym] : () => this.dimension()}// ugh - need to get rid of this inline function to avoid recomputing PanelHeight={nested ? pair.layout[HeightSym] : () => this.dimension()} renderDepth={this.props.renderDepth + 1} @@ -123,7 +125,7 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { whenActiveChanged={emptyFunction} bringToFront={emptyFunction} ContainingCollectionView={undefined} - ContainingCollectionDoc={undefined}/> + ContainingCollectionDoc={undefined} />
; })}
diff --git a/src/client/views/collections/CollectionSchemaCells.tsx b/src/client/views/collections/CollectionSchemaCells.tsx index 7b16ff546..ae71c54f7 100644 --- a/src/client/views/collections/CollectionSchemaCells.tsx +++ b/src/client/views/collections/CollectionSchemaCells.tsx @@ -172,6 +172,8 @@ export class CollectionSchemaCell extends React.Component { whenActiveChanged: emptyFunction, PanelHeight: returnZero, PanelWidth: returnZero, + NativeHeight: returnZero, + NativeWidth: returnZero, addDocTab: this.props.addDocTab, pinToPres: this.props.pinToPres, ContentScaling: returnOne diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index d21e17bbc..8ceeb66f1 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -11,7 +11,7 @@ import { listSpec } from "../../../new_fields/Schema"; import { SchemaHeaderField } from "../../../new_fields/SchemaHeaderField"; import { BoolCast, Cast, NumCast, ScriptCast, StrCast } from "../../../new_fields/Types"; import { TraceMobx } from "../../../new_fields/util"; -import { Utils, setupMoveUpEvents, emptyFunction } from "../../../Utils"; +import { Utils, setupMoveUpEvents, emptyFunction, returnZero, returnOne } from "../../../Utils"; import { DragManager, dropActionType } from "../../util/DragManager"; import { Transform } from "../../util/Transform"; import { undoBatch } from "../../util/UndoManager"; @@ -24,7 +24,7 @@ import "./CollectionStackingView.scss"; import { CollectionStackingViewFieldColumn } from "./CollectionStackingViewFieldColumn"; import { CollectionSubView } from "./CollectionSubView"; import { CollectionViewType } from "./CollectionView"; -import { Docs } from "../../documents/Documents"; +import { DocumentView } from "../nodes/DocumentView"; @observer export class CollectionStackingView extends CollectionSubView(doc => doc) { @@ -53,6 +53,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { @computed get NodeWidth() { return this.props.PanelWidth() - this.gridGap; } children(docs: Doc[], columns?: number) { + TraceMobx(); this._docXfs.length = 0; return docs.map((d, i) => { const height = () => this.getDocHeight(d); @@ -115,7 +116,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { componentDidMount() { super.componentDidMount(); this._heightDisposer = reaction(() => { - if (this.props.Document._autoHeight) { + if (this.props.Document._autoHeight && !this.props.NativeHeight()) { const sectionsList = Array.from(this.Sections.size ? this.Sections.values() : [this.filteredChildren]); if (this.isStackingView) { const res = this.props.ContentScaling() * sectionsList.reduce((maxHght, s) => { @@ -168,12 +169,13 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { getDisplayDoc(doc: Doc, dataDoc: Doc | undefined, dxf: () => Transform, width: () => number) { const layoutDoc = Doc.Layout(doc, this.props.childLayoutTemplate?.()); const height = () => this.getDocHeight(doc); - return doc) { onClick={layoutDoc.isTemplateDoc ? this.onClickHandler : this.onChildClickHandler} PanelWidth={width} PanelHeight={height} - getTransform={dxf} + ScreenToLocalTransform={dxf} focus={this.props.focus} - CollectionDoc={this.props.CollectionView && this.props.CollectionView.props.Document} - CollectionView={this.props.CollectionView} + ContainingCollectionDoc={this.props.CollectionView && this.props.CollectionView.props.Document} + ContainingCollectionView={this.props.CollectionView} addDocument={this.props.addDocument} moveDocument={this.props.moveDocument} removeDocument={this.props.removeDocument} - active={this.props.active} + parentActive={this.props.active} + bringToFront={emptyFunction} + NativeHeight={returnZero} + NativeWidth={returnZero} + ContentScaling={returnOne} whenActiveChanged={this.props.whenActiveChanged} addDocTab={this.props.addDocTab} pinToPres={this.props.pinToPres}> - ; + ; } getDocWidth(d?: Doc) { @@ -387,7 +393,11 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { return sections.map(section => this.isStackingView ? this.sectionStacking(section[0], section[1]) : this.sectionMasonry(section[0], section[1])); } - @computed get scaling() { return !this.props.Document._nativeWidth ? 1 : this.props.PanelHeight() / NumCast(this.props.Document._nativeHeight); } + + @computed get nativeWidth() { return NumCast(this.layoutDoc._nativeWidth) || this.props.NativeWidth() || 0; } + @computed get nativeHeight() { return NumCast(this.layoutDoc._nativeHeight) || this.props.NativeHeight() || 0; } + + @computed get scaling() { return !this.nativeWidth ? 1 : this.props.PanelHeight() / this.nativeHeight; } render() { TraceMobx(); diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index d1d6ae3c1..32449de5e 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -36,12 +36,15 @@ export interface CollectionViewProps extends FieldViewProps { setPreviewCursor?: (func: (x: number, y: number, drag: boolean) => void) => void; rootSelected: () => boolean; fieldKey: string; + NativeWidth: () => number; + NativeHeight: () => number; } export interface SubCollectionViewProps extends CollectionViewProps { CollectionView: Opt; children?: never | (() => JSX.Element[]) | React.ReactNode; - overrideDocuments?: Doc[]; // used to override the documents shown by the sub collection to an explict list (see LinkBox) + freezeDimensions?: boolean; // used by TimeView to coerce documents to treat their width height as their native width/height + overrideDocuments?: Doc[]; // used to override the documents shown by the sub collection to an explicit list (see LinkBox) ignoreFields?: string[]; // used in TreeView to ignore specified fields (see LinkBox) isAnnotationOverlay?: boolean; annotationsKey: string; @@ -213,9 +216,6 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T, moreProps?: this.props.Document.dropConverter.script.run({ dragData: docDragData }); /// bcz: check this if (docDragData) { let added = false; - if (this.props.Document._freezeOnDrop) { - de.complete.docDragData?.droppedDocuments.forEach(drop => Doc.freezeNativeDimensions(drop, drop[WidthSym](), drop[HeightSym]())); - } if (docDragData.dropAction || docDragData.userDropAction) { added = docDragData.droppedDocuments.reduce((added: boolean, d) => this.props.addDocument(d) || added, false); } else if (docDragData.moveDocument) { diff --git a/src/client/views/collections/CollectionTimeView.tsx b/src/client/views/collections/CollectionTimeView.tsx index 4f77e8b0e..d9a10cdc8 100644 --- a/src/client/views/collections/CollectionTimeView.tsx +++ b/src/client/views/collections/CollectionTimeView.tsx @@ -5,7 +5,7 @@ import { List } from "../../../new_fields/List"; import { ObjectField } from "../../../new_fields/ObjectField"; import { RichTextField } from "../../../new_fields/RichTextField"; import { ComputedField, ScriptField } from "../../../new_fields/ScriptField"; -import { NumCast, StrCast } from "../../../new_fields/Types"; +import { NumCast, StrCast, BoolCast } from "../../../new_fields/Types"; import { emptyFunction, returnFalse, setupMoveUpEvents } from "../../../Utils"; import { Scripting } from "../../util/Scripting"; import { ContextMenu } from "../ContextMenu"; @@ -29,7 +29,6 @@ export class CollectionTimeView extends CollectionSubView(doc => doc) { this.props.Document.onChildClick = undefined; } componentDidMount() { - this.props.Document._freezeOnDrop = true; const childDetailed = this.props.Document.childDetailed; // bcz: needs to be here to make sure the childDetailed layout template has been loaded when the first item is clicked; const childText = "const alias = getAlias(this); Doc.ApplyTemplateTo(containingCollection.childDetailed, alias, 'layout_detailView'); alias.layoutKey='layout_detailedView'; alias.dropAction='alias'; alias.removeDropProperties=new List(['dropAction']); useRightSplit(alias, shiftKey); "; this.props.Document.onChildClick = ScriptField.MakeScript(childText, { this: Doc.name, heading: "string", containingCollection: Doc.name, shiftKey: "boolean" }); @@ -73,7 +72,7 @@ export class CollectionTimeView extends CollectionSubView(doc => doc) { @computed get contents() { return
- +
; } diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index 77dd9a162..10da50e35 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -465,6 +465,8 @@ class TreeView extends React.Component { ContentScaling={returnOne} PanelWidth={returnZero} PanelHeight={returnZero} + NativeHeight={returnZero} + NativeWidth={returnZero} renderDepth={1} focus={emptyFunction} parentActive={returnTrue} diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index a727da267..5d08a2bd8 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -13,7 +13,7 @@ import { List } from '../../../new_fields/List'; import { BoolCast, Cast, NumCast, StrCast, ScriptCast } from '../../../new_fields/Types'; import { ImageField } from '../../../new_fields/URLField'; import { TraceMobx } from '../../../new_fields/util'; -import { Utils, setupMoveUpEvents, returnFalse } from '../../../Utils'; +import { Utils, setupMoveUpEvents, returnFalse, returnZero } from '../../../Utils'; import { DocumentType } from '../../documents/DocumentTypes'; import { DocumentManager } from '../../util/DocumentManager'; import { ImageUtils } from '../../util/Import & Export/ImageUtils'; @@ -424,6 +424,8 @@ export class CollectionView extends Touchable { e.bounds && !e.bounds.z).map(e => e.bounds!), NumCast(this.layoutDoc.xPadding, 10), NumCast(this.layoutDoc.yPadding, 10)); } - @computed get nativeWidth() { return this.Document._fitToContent ? 0 : NumCast(this.Document._nativeWidth); } - @computed get nativeHeight() { return this.fitToContent ? 0 : NumCast(this.Document._nativeHeight); } + @computed get nativeWidth() { return this.Document._fitToContent ? 0 : NumCast(this.Document._nativeWidth, this.props.NativeWidth()); } + @computed get nativeHeight() { return this.fitToContent ? 0 : NumCast(this.Document._nativeHeight, this.props.NativeHeight()); } private get isAnnotationOverlay() { return this.props.isAnnotationOverlay; } private get borderWidth() { return this.isAnnotationOverlay ? 0 : COLLECTION_BORDER_WIDTH; } private easing = () => this.props.Document.panTransformType === "Ease"; @@ -825,6 +825,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { DataDoc: childData, Document: childLayout, LibraryPath: this.libraryPath, + FreezeDimensions: this.props.freezeDimensions, layoutKey: undefined, rootSelected: this.rootSelected, dropAction: StrCast(this.props.Document.childDropAction) as dropActionType, diff --git a/src/client/views/nodes/AudioBox.tsx b/src/client/views/nodes/AudioBox.tsx index be0e1aec4..ff9630273 100644 --- a/src/client/views/nodes/AudioBox.tsx +++ b/src/client/views/nodes/AudioBox.tsx @@ -7,7 +7,7 @@ import { AudioField, nullAudio } from "../../../new_fields/URLField"; import { DocExtendableComponent } from "../DocComponent"; import { makeInterface, createSchema } from "../../../new_fields/Schema"; import { documentSchema } from "../../../new_fields/documentSchemas"; -import { Utils, returnTrue, emptyFunction, returnOne, returnTransparent, returnFalse } from "../../../Utils"; +import { Utils, returnTrue, emptyFunction, returnOne, returnTransparent, returnFalse, returnZero } from "../../../Utils"; import { runInAction, observable, reaction, IReactionDisposer, computed, action } from "mobx"; import { DateField } from "../../../new_fields/DateField"; import { SelectionManager } from "../../util/SelectionManager"; @@ -261,6 +261,8 @@ export class AudioBox extends DocExtendableComponent this.props.focus(doc, false); + NativeWidth = () => this.nativeWidth; + NativeHeight = () => this.nativeHeight; render() { TraceMobx(); return
- {!this.props.fitToBox ? - - : + : }
; } diff --git a/src/client/views/nodes/ContentFittingDocumentView.tsx b/src/client/views/nodes/ContentFittingDocumentView.tsx index 9ab6826a3..09675bf73 100644 --- a/src/client/views/nodes/ContentFittingDocumentView.tsx +++ b/src/client/views/nodes/ContentFittingDocumentView.tsx @@ -18,6 +18,9 @@ interface ContentFittingDocumentViewProps { Document?: Doc; DataDocument?: Doc; LayoutDoc?: () => Opt; + NativeWidth?: () => number; + NativeHeight?: () => number; + FreezeDimensions?: boolean; LibraryPath: Doc[]; childDocs?: Doc[]; renderDepth: number; @@ -47,12 +50,12 @@ interface ContentFittingDocumentViewProps { export class ContentFittingDocumentView extends React.Component{ public get displayName() { return "DocumentView(" + this.props.Document?.title + ")"; } // this makes mobx trace() statements more descriptive private get layoutDoc() { return this.props.Document && (this.props.LayoutDoc?.() || Doc.Layout(this.props.Document)); } - private get nativeWidth() { return NumCast(this.layoutDoc?._nativeWidth, this.props.PanelWidth()); } - private get nativeHeight() { return NumCast(this.layoutDoc?._nativeHeight, this.props.PanelHeight()); } + private nativeWidth = () => NumCast(this.layoutDoc?._nativeWidth, this.props.NativeWidth?.() || this.props.PanelWidth()); + private nativeHeight = () => NumCast(this.layoutDoc?._nativeHeight, this.props.NativeHeight?.() || this.props.PanelHeight()); @computed get scaling() { - const wscale = this.props.PanelWidth() / (this.nativeWidth || this.props.PanelWidth() || 1); - if (wscale * this.nativeHeight > this.props.PanelHeight()) { - return (this.props.PanelHeight() / (this.nativeHeight || this.props.PanelHeight() || 1)) || 1; + const wscale = this.props.PanelWidth() / (this.nativeWidth() || this.props.PanelWidth() || 1); + if (wscale * this.nativeHeight() > this.props.PanelHeight()) { + return (this.props.PanelHeight() / (this.nativeHeight() || this.props.PanelHeight() || 1)) || 1; } return wscale || 1; } @@ -61,12 +64,12 @@ export class ContentFittingDocumentView extends React.Component this.panelWidth; private PanelHeight = () => this.panelHeight; - @computed get panelWidth() { return this.nativeWidth && (!this.props.Document || !this.props.Document._fitWidth) ? this.nativeWidth * this.contentScaling() : this.props.PanelWidth(); } - @computed get panelHeight() { return this.nativeHeight && (!this.props.Document || !this.props.Document._fitWidth) ? this.nativeHeight * this.contentScaling() : this.props.PanelHeight(); } + @computed get panelWidth() { return this.nativeWidth && (!this.props.Document || !this.props.Document._fitWidth) ? this.nativeWidth() * this.contentScaling() : this.props.PanelWidth(); } + @computed get panelHeight() { return this.nativeHeight && (!this.props.Document || !this.props.Document._fitWidth) ? this.nativeHeight() * this.contentScaling() : this.props.PanelHeight(); } private getTransform = () => this.props.getTransform().translate(-this.centeringOffset, -this.centeringYOffset).scale(1 / this.contentScaling()); - private get centeringOffset() { return this.nativeWidth && (!this.props.Document || !this.props.Document._fitWidth) ? (this.props.PanelWidth() - this.nativeWidth * this.contentScaling()) / 2 : 0; } - private get centeringYOffset() { return Math.abs(this.centeringOffset) < 0.001 ? (this.props.PanelHeight() - this.nativeHeight * this.contentScaling()) / 2 : 0; } + private get centeringOffset() { return this.nativeWidth && (!this.props.Document || !this.props.Document._fitWidth) ? (this.props.PanelWidth() - this.nativeWidth() * this.contentScaling()) / 2 : 0; } + private get centeringYOffset() { return Math.abs(this.centeringOffset) < 0.001 ? (this.props.PanelHeight() - this.nativeHeight() * this.contentScaling()) / 2 : 0; } @computed get borderRounding() { return StrCast(this.props.Document?.borderRounding); } @@ -81,7 +84,7 @@ export class ContentFittingDocumentView extends React.Component 0.001 ? `${100 * this.nativeHeight / this.nativeWidth * this.props.PanelWidth() / this.props.PanelHeight()}%` : this.props.PanelHeight(), + height: Math.abs(this.centeringYOffset) > 0.001 ? `${100 * this.nativeHeight() / this.nativeWidth() * this.props.PanelWidth() / this.props.PanelHeight()}%` : this.props.PanelHeight(), width: Math.abs(this.centeringOffset) > 0.001 ? `${100 * (this.props.PanelWidth() - this.centeringOffset * 2) / this.props.PanelWidth()}%` : this.props.PanelWidth() }}> boolean; export interface DocumentViewProps { ContainingCollectionView: Opt; ContainingCollectionDoc: Opt; + FreezeDimensions?: boolean; + NativeWidth: () => number; + NativeHeight: () => number; Document: Doc; DataDoc?: Doc; LayoutDoc?: () => Opt; @@ -109,11 +112,14 @@ export class DocumentView extends DocComponent(Docu public get ContentDiv() { return this._mainCont.current; } @computed get active() { return SelectionManager.IsSelected(this, true) || this.props.parentActive(true); } @computed get topMost() { return this.props.renderDepth === 0; } - @computed get nativeWidth() { return this.layoutDoc._nativeWidth || 0; } - @computed get nativeHeight() { return this.layoutDoc._nativeHeight || 0; } + @computed get freezeDimensions() { return this.props.FreezeDimensions || this.layoutDoc._freezeChildDimensions; } + @computed get nativeWidth() { return NumCast(this.layoutDoc._nativeWidth, this.props.NativeWidth() || (this.freezeDimensions ? this.layoutDoc[WidthSym]() : 0)); } + @computed get nativeHeight() { return NumCast(this.layoutDoc._nativeHeight, this.props.NativeHeight() || (this.freezeDimensions ? this.layoutDoc[HeightSym]() : 0)); } @computed get onClickHandler() { return this.props.onClick || this.layoutDoc.onClick || this.Document.onClick; } @computed get onPointerDownHandler() { return this.props.onPointerDown ? this.props.onPointerDown : this.Document.onPointerDown; } @computed get onPointerUpHandler() { return this.props.onPointerUp ? this.props.onPointerUp : this.Document.onPointerUp; } + NativeWidth = () => this.nativeWidth; + NativeHeight = () => this.nativeHeight; private _firstX: number = -1; private _firstY: number = -1; @@ -965,6 +971,8 @@ export class DocumentView extends DocComponent(Docu TraceMobx(); return ( void; PanelWidth: () => number; PanelHeight: () => number; + NativeHeight: () => number; + NativeWidth: () => number; setVideoBox?: (player: VideoBox) => void; ContentScaling: () => number; ChromeHeight?: () => number; diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 94195fbd6..37770a2e1 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -22,7 +22,7 @@ import { RichTextUtils } from '../../../new_fields/RichTextUtils'; import { createSchema, makeInterface } from "../../../new_fields/Schema"; import { Cast, NumCast, StrCast, BoolCast, DateCast } from "../../../new_fields/Types"; import { TraceMobx } from '../../../new_fields/util'; -import { addStyleSheet, addStyleSheetRule, clearStyleSheetRules, emptyFunction, numberRange, returnOne, Utils, returnTrue } from '../../../Utils'; +import { addStyleSheet, addStyleSheetRule, clearStyleSheetRules, emptyFunction, numberRange, returnOne, Utils, returnTrue, returnZero } from '../../../Utils'; import { GoogleApiClientUtils, Pulls, Pushes } from '../../apis/google_docs/GoogleApiClientUtils'; import { DocServer } from "../../DocServer"; import { Docs, DocUtils } from '../../documents/Documents'; @@ -1216,6 +1216,8 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & { rootSelected: returnFalse, isSelected: returnFalse, select: emptyFunction, - dropAction:"alias", - bringToFront:emptyFunction, + dropAction: "alias", + bringToFront: emptyFunction, renderDepth: 1, active: returnFalse, whenActiveChanged: emptyFunction, ScreenToLocalTransform: Transform.Identity, focus: emptyFunction, + NativeHeight: returnZero, + NativeWidth: returnZero, PanelWidth: this.props.PanelWidth, PanelHeight: this.props.PanelHeight, addDocTab: returnFalse, diff --git a/src/client/views/nodes/LinkBox.tsx b/src/client/views/nodes/LinkBox.tsx index 0e327e130..542c86049 100644 --- a/src/client/views/nodes/LinkBox.tsx +++ b/src/client/views/nodes/LinkBox.tsx @@ -23,6 +23,8 @@ export class LinkBox extends DocExtendableComponent PanelHeight={this.props.PanelHeight} PanelWidth={this.props.PanelWidth} annotationsKey={this.annotationKey} + NativeHeight={returnZero} + NativeWidth={returnZero} focus={this.props.focus} isSelected={this.props.isSelected} isAnnotationOverlay={true} diff --git a/src/client/views/pdf/PDFViewer.tsx b/src/client/views/pdf/PDFViewer.tsx index 25ceb6218..36e687f71 100644 --- a/src/client/views/pdf/PDFViewer.tsx +++ b/src/client/views/pdf/PDFViewer.tsx @@ -9,7 +9,7 @@ import { List } from "../../../new_fields/List"; import { makeInterface, createSchema } from "../../../new_fields/Schema"; import { ScriptField, ComputedField } from "../../../new_fields/ScriptField"; import { Cast, NumCast, StrCast } from "../../../new_fields/Types"; -import { smoothScroll, Utils, emptyFunction, returnOne, intersectRect, addStyleSheet, addStyleSheetRule, clearStyleSheetRules } from "../../../Utils"; +import { smoothScroll, Utils, emptyFunction, returnOne, intersectRect, addStyleSheet, addStyleSheetRule, clearStyleSheetRules, returnZero } from "../../../Utils"; import { Docs, DocUtils } from "../../documents/Documents"; import { DragManager } from "../../util/DragManager"; import { CompiledScript, CompileScript } from "../../util/Scripting"; @@ -648,6 +648,8 @@ export class PDFViewer extends DocAnnotatableComponent window.screen.width} PanelHeight={() => window.screen.height} renderDepth={0} @@ -173,6 +175,8 @@ export default class MobileInterface extends React.Component { e.stopPropagation(); } + panelHeight = () => window.innerHeight; + panelWidth = () => window.innerWidth; renderInkingContent = () => { console.log("rendering inking content"); // TODO: support panning and zooming @@ -201,8 +205,10 @@ export default class MobileInterface extends React.Component { bringToFront={emptyFunction} addDocTab={returnFalse} pinToPres={emptyFunction} - PanelHeight={() => window.innerHeight} - PanelWidth={() => window.innerWidth} + PanelWidth={this.panelWidth} + PanelHeight={this.panelHeight} + NativeHeight={returnZero} + NativeWidth={returnZero} focus={emptyFunction} isSelected={returnFalse} select={emptyFunction} @@ -289,6 +295,8 @@ export default class MobileInterface extends React.Component { onClick={undefined} ScreenToLocalTransform={Transform.Identity} ContentScaling={returnOne} + NativeHeight={returnZero} + NativeWidth={returnZero} PanelWidth={() => window.screen.width} PanelHeight={() => window.screen.height} renderDepth={0} diff --git a/src/new_fields/documentSchemas.ts b/src/new_fields/documentSchemas.ts index 1a5a471a0..ff02596f7 100644 --- a/src/new_fields/documentSchemas.ts +++ b/src/new_fields/documentSchemas.ts @@ -28,7 +28,7 @@ export const documentSchema = createSchema({ _pivotField: "string", // specifies which field should be used as the timeline/pivot axis _replacedChrome: "string", // what the default chrome is replaced with. Currently only supports the value of 'replaced' for PresBox's. _chromeStatus: "string", // determines the state of the collection chrome. values allowed are 'replaced', 'enabled', 'disabled', 'collapsed' - _freezeOnDrop: "boolean", // whether a document without native dimensions should have its width/height frozen as native dimensions on drop. Used by Timeline view to make sure documents are scaled to fit the display thumbnail + _freezeChildDimensions: "boolean", // freezes child document dimensions (e.g., used by time/pivot view to make sure all children will be scaled to fit their display rectangle) color: "string", // foreground color of document backgroundColor: "string", // background color of document opacity: "number", // opacity of document diff --git a/src/new_fields/util.ts b/src/new_fields/util.ts index 8c719ccd8..480a55da0 100644 --- a/src/new_fields/util.ts +++ b/src/new_fields/util.ts @@ -12,7 +12,7 @@ function _readOnlySetter(): never { throw new Error("Documents can't be modified in read-only mode"); } -const tracing = false; +const tracing = true; export function TraceMobx() { tracing && trace(); } -- cgit v1.2.3-70-g09d2 From e262d9ac73af5b2cef384468c47d69917e205d44 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 7 Apr 2020 23:01:46 -0400 Subject: lots of code cleanup - removed all northstar db stuff. added scriptingBox. renamed things. made collectiontypes strings not numbers. --- package-lock.json | 8 +- .../apis/google_docs/GoogleApiClientUtils.ts | 2 +- src/client/apis/youtube/YoutubeBox.tsx | 6 +- src/client/documents/DocumentTypes.ts | 61 +- src/client/documents/Documents.ts | 108 +- src/client/northstar/core/BaseObject.ts | 12 - .../northstar/core/attribute/AttributeModel.ts | 111 - .../core/attribute/AttributeTransformationModel.ts | 52 - .../core/attribute/CalculatedAttributeModel.ts | 42 - .../northstar/core/brusher/IBaseBrushable.ts | 13 - src/client/northstar/core/brusher/IBaseBrusher.ts | 11 - src/client/northstar/core/filter/FilterModel.ts | 83 - src/client/northstar/core/filter/FilterOperand.ts | 5 - src/client/northstar/core/filter/FilterType.ts | 6 - .../northstar/core/filter/IBaseFilterConsumer.ts | 12 - .../northstar/core/filter/IBaseFilterProvider.ts | 8 - .../northstar/core/filter/ValueComparision.ts | 78 - src/client/northstar/dash-fields/HistogramField.ts | 66 - .../dash-nodes/HistogramBinPrimitiveCollection.ts | 240 - src/client/northstar/dash-nodes/HistogramBox.scss | 40 - src/client/northstar/dash-nodes/HistogramBox.tsx | 175 - .../dash-nodes/HistogramBoxPrimitives.scss | 42 - .../dash-nodes/HistogramBoxPrimitives.tsx | 122 - .../dash-nodes/HistogramLabelPrimitives.scss | 13 - .../dash-nodes/HistogramLabelPrimitives.tsx | 80 - src/client/northstar/manager/Gateway.ts | 299 - src/client/northstar/model/ModelExtensions.ts | 48 - src/client/northstar/model/ModelHelpers.ts | 220 - .../model/binRanges/AlphabeticVisualBinRange.ts | 52 - .../model/binRanges/DateTimeVisualBinRange.ts | 105 - .../model/binRanges/NominalVisualBinRange.ts | 52 - .../model/binRanges/QuantitativeVisualBinRange.ts | 90 - .../northstar/model/binRanges/VisualBinRange.ts | 32 - .../model/binRanges/VisualBinRangeHelper.ts | 70 - .../northstar/model/idea/MetricTypeMapping.ts | 30 - src/client/northstar/model/idea/idea.ts | 8557 -------------------- src/client/northstar/operations/BaseOperation.ts | 162 - .../northstar/operations/HistogramOperation.ts | 158 - src/client/northstar/utils/ArrayUtil.ts | 90 - src/client/northstar/utils/Extensions.ts | 29 - src/client/northstar/utils/GeometryUtil.ts | 133 - src/client/northstar/utils/IDisposable.ts | 3 - src/client/northstar/utils/IEquatable.ts | 3 - src/client/northstar/utils/KeyCodes.ts | 137 - src/client/northstar/utils/LABColor.ts | 90 - src/client/northstar/utils/MathUtil.ts | 249 - src/client/northstar/utils/PartialClass.ts | 7 - src/client/northstar/utils/SizeConverter.ts | 101 - src/client/northstar/utils/StyleContants.ts | 95 - src/client/northstar/utils/Utils.ts | 75 - src/client/util/DictationManager.ts | 6 +- src/client/util/DropConverter.ts | 2 +- src/client/util/KeyCodes.ts | 136 + src/client/util/type_decls.d | 1 - src/client/views/DocComponent.tsx | 2 +- src/client/views/DocumentDecorations.tsx | 2 +- src/client/views/MainView.tsx | 6 +- src/client/views/ScriptBox.tsx | 2 +- src/client/views/SearchDocBox.tsx | 2 +- .../views/collections/CollectionSchemaCells.tsx | 5 +- .../views/collections/CollectionSchemaView.tsx | 22 - .../views/collections/CollectionStackingView.tsx | 2 +- src/client/views/collections/CollectionSubView.tsx | 2 +- src/client/views/collections/CollectionView.tsx | 52 +- .../views/collections/CollectionViewChromes.tsx | 7 +- .../views/collections/ParentDocumentSelector.tsx | 2 +- .../CollectionFreeFormLinkView.tsx | 10 +- .../CollectionFreeFormLinksView.tsx | 56 - src/client/views/nodes/AudioBox.scss | 4 +- src/client/views/nodes/ButtonBox.scss | 38 - src/client/views/nodes/ButtonBox.tsx | 97 - src/client/views/nodes/DocuLinkBox.scss | 29 - src/client/views/nodes/DocuLinkBox.tsx | 146 - src/client/views/nodes/DocumentBox.tsx | 8 +- src/client/views/nodes/DocumentContentsView.tsx | 14 +- src/client/views/nodes/DocumentView.scss | 4 +- src/client/views/nodes/DocumentView.tsx | 40 +- src/client/views/nodes/FormattedTextBox.tsx | 4 +- src/client/views/nodes/LabelBox.scss | 38 + src/client/views/nodes/LabelBox.tsx | 97 + src/client/views/nodes/LinkAnchorBox.scss | 29 + src/client/views/nodes/LinkAnchorBox.tsx | 146 + src/client/views/nodes/PDFBox.tsx | 3 +- src/client/views/nodes/PresBox.tsx | 10 +- src/client/views/nodes/ScriptingBox.scss | 0 src/client/views/nodes/ScriptingBox.tsx | 71 + src/client/views/nodes/VideoBox.tsx | 2 +- src/client/views/pdf/PDFViewer.tsx | 2 +- src/client/views/search/FilterBox.tsx | 2 +- src/client/views/search/IconBar.tsx | 2 +- src/client/views/search/IconButton.tsx | 8 +- src/client/views/search/SearchBox.tsx | 2 +- src/client/views/search/SearchItem.tsx | 9 +- src/new_fields/Doc.ts | 6 +- src/new_fields/RichTextField.ts | 3 - src/new_fields/ScriptField.ts | 5 +- src/new_fields/documentSchemas.ts | 2 +- src/server/Message.ts | 2 +- src/server/RouteManager.ts | 1 - src/server/Websocket/Websocket.ts | 3 +- .../authentication/models/current_user_utils.ts | 73 - src/server/updateProtos.ts | 3 +- 102 files changed, 695 insertions(+), 12808 deletions(-) delete mode 100644 src/client/northstar/core/BaseObject.ts delete mode 100644 src/client/northstar/core/attribute/AttributeModel.ts delete mode 100644 src/client/northstar/core/attribute/AttributeTransformationModel.ts delete mode 100644 src/client/northstar/core/attribute/CalculatedAttributeModel.ts delete mode 100644 src/client/northstar/core/brusher/IBaseBrushable.ts delete mode 100644 src/client/northstar/core/brusher/IBaseBrusher.ts delete mode 100644 src/client/northstar/core/filter/FilterModel.ts delete mode 100644 src/client/northstar/core/filter/FilterOperand.ts delete mode 100644 src/client/northstar/core/filter/FilterType.ts delete mode 100644 src/client/northstar/core/filter/IBaseFilterConsumer.ts delete mode 100644 src/client/northstar/core/filter/IBaseFilterProvider.ts delete mode 100644 src/client/northstar/core/filter/ValueComparision.ts delete mode 100644 src/client/northstar/dash-fields/HistogramField.ts delete mode 100644 src/client/northstar/dash-nodes/HistogramBinPrimitiveCollection.ts delete mode 100644 src/client/northstar/dash-nodes/HistogramBox.scss delete mode 100644 src/client/northstar/dash-nodes/HistogramBox.tsx delete mode 100644 src/client/northstar/dash-nodes/HistogramBoxPrimitives.scss delete mode 100644 src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx delete mode 100644 src/client/northstar/dash-nodes/HistogramLabelPrimitives.scss delete mode 100644 src/client/northstar/dash-nodes/HistogramLabelPrimitives.tsx delete mode 100644 src/client/northstar/manager/Gateway.ts delete mode 100644 src/client/northstar/model/ModelExtensions.ts delete mode 100644 src/client/northstar/model/ModelHelpers.ts delete mode 100644 src/client/northstar/model/binRanges/AlphabeticVisualBinRange.ts delete mode 100644 src/client/northstar/model/binRanges/DateTimeVisualBinRange.ts delete mode 100644 src/client/northstar/model/binRanges/NominalVisualBinRange.ts delete mode 100644 src/client/northstar/model/binRanges/QuantitativeVisualBinRange.ts delete mode 100644 src/client/northstar/model/binRanges/VisualBinRange.ts delete mode 100644 src/client/northstar/model/binRanges/VisualBinRangeHelper.ts delete mode 100644 src/client/northstar/model/idea/MetricTypeMapping.ts delete mode 100644 src/client/northstar/model/idea/idea.ts delete mode 100644 src/client/northstar/operations/BaseOperation.ts delete mode 100644 src/client/northstar/operations/HistogramOperation.ts delete mode 100644 src/client/northstar/utils/ArrayUtil.ts delete mode 100644 src/client/northstar/utils/Extensions.ts delete mode 100644 src/client/northstar/utils/GeometryUtil.ts delete mode 100644 src/client/northstar/utils/IDisposable.ts delete mode 100644 src/client/northstar/utils/IEquatable.ts delete mode 100644 src/client/northstar/utils/KeyCodes.ts delete mode 100644 src/client/northstar/utils/LABColor.ts delete mode 100644 src/client/northstar/utils/MathUtil.ts delete mode 100644 src/client/northstar/utils/PartialClass.ts delete mode 100644 src/client/northstar/utils/SizeConverter.ts delete mode 100644 src/client/northstar/utils/StyleContants.ts delete mode 100644 src/client/northstar/utils/Utils.ts create mode 100644 src/client/util/KeyCodes.ts delete mode 100644 src/client/views/nodes/ButtonBox.scss delete mode 100644 src/client/views/nodes/ButtonBox.tsx delete mode 100644 src/client/views/nodes/DocuLinkBox.scss delete mode 100644 src/client/views/nodes/DocuLinkBox.tsx create mode 100644 src/client/views/nodes/LabelBox.scss create mode 100644 src/client/views/nodes/LabelBox.tsx create mode 100644 src/client/views/nodes/LinkAnchorBox.scss create mode 100644 src/client/views/nodes/LinkAnchorBox.tsx create mode 100644 src/client/views/nodes/ScriptingBox.scss create mode 100644 src/client/views/nodes/ScriptingBox.tsx (limited to 'src/client/views/MainView.tsx') diff --git a/package-lock.json b/package-lock.json index 2cd3c0b82..1949a8a5c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -750,7 +750,7 @@ }, "@types/passport": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@types/passport/-/passport-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/@types/passport/-/passport-1.0.0.tgz", "integrity": "sha512-Pf39AYKf8q+YoONym3150cEwfUD66dtwHJWvbeOzKxnA0GZZ/vAXhNWv9vMhKyRQBQZiQyWQnhYBEBlKW6G8wg==", "requires": { "@types/express": "*" @@ -14376,7 +14376,7 @@ }, "readable-stream": { "version": "2.3.6", - "resolved": "http://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.6.tgz", "integrity": "sha512-tQtKA9WIAhBF3+VLAseyMqZeBjW0AHJoxOtYqSUZNJxauErmLbVm2FW1y+J/YA9dUrAC39ITejlZWhVIwawkKw==", "requires": { "core-util-is": "~1.0.0", @@ -15990,7 +15990,7 @@ }, "strip-ansi": { "version": "3.0.1", - "resolved": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-3.0.1.tgz", "integrity": "sha1-ajhfuIU9lS1f8F0Oiq+UJ43GPc8=", "requires": { "ansi-regex": "^2.0.0" @@ -18303,7 +18303,7 @@ }, "wrap-ansi": { "version": "2.1.0", - "resolved": "http://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz", "integrity": "sha1-2Pw9KE3QV5T+hJc8rs3Rz4JP3YU=", "requires": { "string-width": "^1.0.1", diff --git a/src/client/apis/google_docs/GoogleApiClientUtils.ts b/src/client/apis/google_docs/GoogleApiClientUtils.ts index 0d44ee8e0..fa67ddbef 100644 --- a/src/client/apis/google_docs/GoogleApiClientUtils.ts +++ b/src/client/apis/google_docs/GoogleApiClientUtils.ts @@ -97,7 +97,7 @@ export namespace GoogleApiClientUtils { const paragraphs = extractParagraphs(document); let text = paragraphs.map(paragraph => paragraph.contents.filter(content => !("inlineObjectId" in content)).map(run => run as docs_v1.Schema$TextRun).join("")).join(""); text = text.substring(0, text.length - 1); - removeNewlines && text.ReplaceAll("\n", ""); + removeNewlines && text.replace(/\n/g, ""); return { text, paragraphs }; }; diff --git a/src/client/apis/youtube/YoutubeBox.tsx b/src/client/apis/youtube/YoutubeBox.tsx index c940bba43..4b4145fcc 100644 --- a/src/client/apis/youtube/YoutubeBox.tsx +++ b/src/client/apis/youtube/YoutubeBox.tsx @@ -171,9 +171,9 @@ export class YoutubeBox extends React.Component { * in the title of the videos. */ filterYoutubeTitleResult = (resultTitle: string) => { - let processedTitle: string = resultTitle.ReplaceAll("&", "&"); - processedTitle = processedTitle.ReplaceAll("'", "'"); - processedTitle = processedTitle.ReplaceAll(""", "\""); + let processedTitle: string = resultTitle.replace(/&/g, "&");//.ReplaceAll("&", "&"); + processedTitle = processedTitle.replace(/"'/g, "'"); + processedTitle = processedTitle.replace(/"/g, "\""); return processedTitle; } diff --git a/src/client/documents/DocumentTypes.ts b/src/client/documents/DocumentTypes.ts index b6a6cc75a..ab32d7301 100644 --- a/src/client/documents/DocumentTypes.ts +++ b/src/client/documents/DocumentTypes.ts @@ -1,31 +1,36 @@ export enum DocumentType { NONE = "none", - TEXT = "text", - HIST = "histogram", - IMG = "image", - WEB = "web", - COL = "collection", - KVP = "kvp", - VID = "video", - AUDIO = "audio", - PDF = "pdf", - IMPORT = "import", - LINK = "link", - LINKDB = "linkdb", - BUTTON = "button", - SLIDER = "slider", - YOUTUBE = "youtube", - WEBCAM = "webcam", - FONTICON = "fonticonbox", - PRES = "presentation", - RECOMMENDATION = "recommendation", - LINKFOLLOW = "linkfollow", - PRESELEMENT = "preselement", - QUERY = "query", - COLOR = "color", - DOCULINK = "doculink", - PDFANNO = "pdfanno", - INK = "ink", - DOCUMENT = "document", - SCREENSHOT = "screenshot", + + // core data types + RTF = "rtf", // rich text + IMG = "image", // image box + WEB = "web", // web page or html clipping + COL = "collection", // collection + KVP = "kvp", // key value pane + VID = "video", // video + AUDIO = "audio", // audio + PDF = "pdf", // pdf + INK = "ink", // ink stroke + SCREENSHOT = "screenshot", // view of a desktop application + FONTICON = "fonticonbox", // font icon + QUERY = "query", // search query + LABEL = "label", // simple text label + WEBCAM = "webcam", // webcam + PDFANNO = "pdfanno", // pdf text selection (could be just a collection?) + DATE = "date", // calendar view of a date + SCRIPTING = "script", // script editor + + // special purpose wrappers that either take no data or are compositions of lower level types + LINK = "link", // link (view of a document that acts as a link) + LINKANCHOR = "linkanchor", // blue dot link anchor (view of a link document's anchor) + IMPORT = "import", // directory import box (file system directory) + SLIDER = "slider", // number slider (view of a number) + PRES = "presentation", // presentation (view of a collection) --- shouldn't this be a view type? technically requires a special view in which documents must have their aliasOf fields filled in + PRESELEMENT = "preselement",// presentation item (view of a document in a collection) + COLOR = "color", // color picker (view of a color picker for a color string) + YOUTUBE = "youtube", // youtube directory (view of you tube search results) + DOCHOLDER = "docholder", // nested document (view of a document) + + LINKDB = "linkdb", // database of links ??? why do we have this + RECOMMENDATION = "recommendation", // view of a recommendation } \ No newline at end of file diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index cca0e7bc6..b71205001 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -1,6 +1,3 @@ -import { HistogramField } from "../northstar/dash-fields/HistogramField"; -import { HistogramBox } from "../northstar/dash-nodes/HistogramBox"; -import { HistogramOperation } from "../northstar/operations/HistogramOperation"; import { CollectionView } from "../views/collections/CollectionView"; import { CollectionViewType } from "../views/collections/CollectionView"; import { AudioBox } from "../views/nodes/AudioBox"; @@ -8,21 +5,16 @@ import { FormattedTextBox } from "../views/nodes/FormattedTextBox"; import { ImageBox } from "../views/nodes/ImageBox"; import { KeyValueBox } from "../views/nodes/KeyValueBox"; import { PDFBox } from "../views/nodes/PDFBox"; +import { ScriptingBox } from "../views/nodes/ScriptingBox"; import { VideoBox } from "../views/nodes/VideoBox"; import { WebBox } from "../views/nodes/WebBox"; -import { Gateway } from "../northstar/manager/Gateway"; import { CurrentUserUtils } from "../../server/authentication/models/current_user_utils"; -import { action } from "mobx"; -import { ColumnAttributeModel } from "../northstar/core/attribute/AttributeModel"; -import { AttributeTransformationModel } from "../northstar/core/attribute/AttributeTransformationModel"; -import { AggregateFunction } from "../northstar/model/idea/idea"; import { OmitKeys, JSONUtils, Utils } from "../../Utils"; import { Field, Doc, Opt, DocListCastAsync, FieldResult, DocListCast } from "../../new_fields/Doc"; import { ImageField, VideoField, AudioField, PdfField, WebField, YoutubeField } from "../../new_fields/URLField"; import { HtmlField } from "../../new_fields/HtmlField"; import { List } from "../../new_fields/List"; import { Cast, NumCast, StrCast } from "../../new_fields/Types"; -import { listSpec } from "../../new_fields/Schema"; import { DocServer } from "../DocServer"; import { dropActionType } from "../util/DragManager"; import { DateField } from "../../new_fields/DateField"; @@ -32,7 +24,7 @@ import { LinkManager } from "../util/LinkManager"; import { DocumentManager } from "../util/DocumentManager"; import DirectoryImportBox from "../util/Import & Export/DirectoryImportBox"; import { Scripting } from "../util/Scripting"; -import { ButtonBox } from "../views/nodes/ButtonBox"; +import { LabelBox } from "../views/nodes/LabelBox"; import { SliderBox } from "../views/nodes/SliderBox"; import { FontIconBox } from "../views/nodes/FontIconBox"; import { SchemaHeaderField } from "../../new_fields/SchemaHeaderField"; @@ -41,16 +33,12 @@ import { ComputedField, ScriptField } from "../../new_fields/ScriptField"; import { ProxyField } from "../../new_fields/Proxy"; import { DocumentType } from "./DocumentTypes"; import { RecommendationsBox } from "../views/RecommendationsBox"; -import { SearchBox } from "../views/search/SearchBox"; - -//import { PresBox } from "../views/nodes/PresBox"; -//import { PresField } from "../../new_fields/PresField"; import { PresElementBox } from "../views/presentationview/PresElementBox"; import { DashWebRTCVideo } from "../views/webcam/DashWebRTCVideo"; import { QueryBox } from "../views/nodes/QueryBox"; import { ColorBox } from "../views/nodes/ColorBox"; -import { DocuLinkBox } from "../views/nodes/DocuLinkBox"; -import { DocumentBox } from "../views/nodes/DocumentBox"; +import { LinkAnchorBox } from "../views/nodes/LinkAnchorBox"; +import { DocHolderBox } from "../views/nodes/DocumentBox"; import { InkingStroke } from "../views/InkingStroke"; import { InkField } from "../../new_fields/InkField"; import { InkingControl } from "../views/InkingControl"; @@ -80,7 +68,7 @@ export interface DocumentOptions { _showCaption?: string; // which field to display in the caption area. leave empty to have no caption _scrollTop?: number; // scroll location for pdfs _chromeStatus?: string; - _viewType?: number; + _viewType?: string; // sub type of a collection _gridGap?: number; // gap between items in masonry view _xMargin?: number; // gap between left edge of document and start of masonry/stacking layouts _yMargin?: number; // gap between top edge of dcoument and start of masonry/stacking layouts @@ -156,6 +144,7 @@ export interface DocumentOptions { treeViewChecked?: ScriptField; // script to call when a tree view checkbox is checked isFacetFilter?: boolean; // whether document functions as a facet filter in a tree view limitHeight?: number; // maximum height for newly created (eg, from pasting) text documents + editScriptOnClick?: string; // script field key to edit when document is clicked (e.g., "onClick", "onChecked") // [key: string]: Opt; pointerHack?: boolean; // for buttons, allows onClick handler to fire onPointerDown textTransform?: string; // is linear view expanded @@ -192,14 +181,10 @@ export namespace Docs { const data = "data"; const TemplateMap: TemplateMap = new Map([ - [DocumentType.TEXT, { + [DocumentType.RTF, { layout: { view: FormattedTextBox, dataField: "text" }, options: { _height: 150, _xMargin: 10, _yMargin: 10 } }], - [DocumentType.HIST, { - layout: { view: HistogramBox, dataField: data }, - options: { _height: 300, backgroundColor: "black" } - }], [DocumentType.QUERY, { layout: { view: QueryBox, dataField: data }, options: { _width: 400 } @@ -224,8 +209,8 @@ export namespace Docs { layout: { view: KeyValueBox, dataField: data }, options: { _height: 150 } }], - [DocumentType.DOCUMENT, { - layout: { view: DocumentBox, dataField: data }, + [DocumentType.DOCHOLDER, { + layout: { view: DocHolderBox, dataField: data }, options: { _height: 250 } }], [DocumentType.VID, { @@ -253,11 +238,14 @@ export namespace Docs { layout: { view: EmptyBox, dataField: data }, options: { childDropAction: "alias", title: "LINK DB" } }], + [DocumentType.SCRIPTING, { + layout: { view: ScriptingBox, dataField: data } + }], [DocumentType.YOUTUBE, { layout: { view: YoutubeBox, dataField: data } }], - [DocumentType.BUTTON, { - layout: { view: ButtonBox, dataField: data }, + [DocumentType.LABEL, { + layout: { view: LabelBox, dataField: data }, }], [DocumentType.SLIDER, { layout: { view: SliderBox, dataField: data }, @@ -521,6 +509,10 @@ export namespace Docs { return InstanceFromProto(Prototypes.get(DocumentType.PRES), initial, options); } + export function ScriptingDocument(url: string, options: DocumentOptions = {}) { + return InstanceFromProto(Prototypes.get(DocumentType.SCRIPTING), new YoutubeField(new URL(url)), options); + } + export function VideoDocument(url: string, options: DocumentOptions = {}) { return InstanceFromProto(Prototypes.get(DocumentType.VID), new VideoField(new URL(url)), options); } @@ -543,10 +535,6 @@ export namespace Docs { return instance; } - export function HistogramDocument(histoOp: HistogramOperation, options: DocumentOptions = {}) { - return InstanceFromProto(Prototypes.get(DocumentType.HIST), new HistogramField(histoOp), options); - } - export function QueryDocument(options: DocumentOptions = {}) { return InstanceFromProto(Prototypes.get(DocumentType.QUERY), "", options); } @@ -556,7 +544,7 @@ export namespace Docs { } export function TextDocument(text: string, options: DocumentOptions = {}) { - return InstanceFromProto(Prototypes.get(DocumentType.TEXT), text, options, undefined, "text"); + return InstanceFromProto(Prototypes.get(DocumentType.RTF), text, options, undefined, "text"); } export function LinkDocument(source: { doc: Doc, ctx?: Doc }, target: { doc: Doc, ctx?: Doc }, options: DocumentOptions = {}, id?: string) { @@ -566,8 +554,8 @@ export namespace Docs { linkDocProto.anchor2 = target.doc; if (linkDocProto.layout_key1 === undefined) { - Cast(linkDocProto.proto, Doc, null).layout_key1 = DocuLinkBox.LayoutString("anchor1"); - Cast(linkDocProto.proto, Doc, null).layout_key2 = DocuLinkBox.LayoutString("anchor2"); + Cast(linkDocProto.proto, Doc, null).layout_key1 = LinkAnchorBox.LayoutString("anchor1"); + Cast(linkDocProto.proto, Doc, null).layout_key2 = LinkAnchorBox.LayoutString("anchor2"); Cast(linkDocProto.proto, Doc, null).linkBoxExcludedKeys = new List(["treeViewExpandedView", "treeViewHideTitle", "removeDropProperties", "linkBoxExcludedKeys", "treeViewOpen", "aliasNumber", "isPrototype", "lastOpened", "creationDate", "author"]); Cast(linkDocProto.proto, Doc, null).layoutKey = undefined; } @@ -605,37 +593,6 @@ export namespace Docs { return InstanceFromProto(Prototypes.get(DocumentType.PDF), new PdfField(new URL(url)), options); } - export async function DBDocument(url: string, options: DocumentOptions = {}, columnOptions: DocumentOptions = {}) { - const schemaName = options.title ? options.title : "-no schema-"; - const ctlog = await Gateway.Instance.GetSchema(url, schemaName); - if (ctlog && ctlog.schemas) { - const schema = ctlog.schemas[0]; - const schemaDoc = Docs.Create.TreeDocument([], { ...options, _nativeWidth: undefined, _nativeHeight: undefined, _width: 150, _height: 100, title: schema.displayName! }); - const schemaDocuments = Cast(schemaDoc.data, listSpec(Doc), []); - if (!schemaDocuments) { - return; - } - CurrentUserUtils.AddNorthstarSchema(schema, schemaDoc); - const docs = schemaDocuments; - CurrentUserUtils.GetAllNorthstarColumnAttributes(schema).map(attr => { - DocServer.GetRefField(attr.displayName! + ".alias").then(action((field: Opt) => { - if (field instanceof Doc) { - docs.push(field); - } else { - const atmod = new ColumnAttributeModel(attr); - const histoOp = new HistogramOperation(schema.displayName!, - new AttributeTransformationModel(atmod, AggregateFunction.None), - new AttributeTransformationModel(atmod, AggregateFunction.Count), - new AttributeTransformationModel(atmod, AggregateFunction.Count)); - docs.push(Docs.Create.HistogramDocument(histoOp, { ...columnOptions, _width: 200, _height: 200, title: attr.displayName! })); - } - })); - }); - return schemaDoc; - } - return Docs.Create.TreeDocument([], { _width: 50, _height: 100, title: schemaName }); - } - export function WebDocument(url: string, options: DocumentOptions = {}) { return InstanceFromProto(Prototypes.get(DocumentType.WEB), new WebField(new URL(url)), options); } @@ -649,7 +606,7 @@ export namespace Docs { } export function DocumentDocument(document?: Doc, options: DocumentOptions = {}) { - return InstanceFromProto(Prototypes.get(DocumentType.DOCUMENT), document, { title: document ? document.title + "" : "container", ...options }); + return InstanceFromProto(Prototypes.get(DocumentType.DOCHOLDER), document, { title: document ? document.title + "" : "container", ...options }); } export function FreeformDocument(documents: Array, options: DocumentOptions, id?: string) { @@ -688,8 +645,12 @@ export namespace Docs { return InstanceFromProto(Prototypes.get(DocumentType.COL), new List(documents), { _chromeStatus: "collapsed", schemaColumns: new List([new SchemaHeaderField("title", "#f1efeb")]), ...options, _viewType: CollectionViewType.Masonry }); } + export function LabelDocument(options?: DocumentOptions) { + return InstanceFromProto(Prototypes.get(DocumentType.LABEL), undefined, { ...(options || {}) }); + } + export function ButtonDocument(options?: DocumentOptions) { - return InstanceFromProto(Prototypes.get(DocumentType.BUTTON), undefined, { ...(options || {}) }); + return InstanceFromProto(Prototypes.get(DocumentType.LABEL), undefined, { ...(options || {}), editScriptOnClick: "onClick" }); } export function SliderDocument(options?: DocumentOptions) { @@ -842,9 +803,6 @@ export namespace Docs { } else if (field instanceof AudioField) { created = Docs.Create.AudioDocument((field).url.href, resolved); layout = AudioBox.LayoutString; - } else if (field instanceof HistogramField) { - created = Docs.Create.HistogramDocument((field).HistoOp, resolved); - layout = HistogramBox.LayoutString; } else if (field instanceof InkField) { const { selectedColor, selectedWidth, selectedTool } = InkingControl.Instance; created = Docs.Create.InkDocument(selectedColor, selectedTool, Number(selectedWidth), (field).inkData, resolved); @@ -856,9 +814,11 @@ export namespace Docs { created = Docs.Create.TextDocument("", { ...{ _width: 200, _height: 25, _autoHeight: true }, ...resolved }); layout = FormattedTextBox.LayoutString; } - created.layout = layout?.(fieldKey); - created.title = fieldKey; - proto && (created.proto = Doc.GetProto(proto)); + if (created) { + created.layout = layout?.(fieldKey); + created.title = fieldKey; + proto && created.proto && (created.proto = Doc.GetProto(proto)); + } return created; } @@ -881,10 +841,6 @@ export namespace Docs { if (!options._width) options._width = 400; if (!options._height) options._height = options._width * 1200 / 927; } - if (type.indexOf("excel") !== -1) { - ctor = Docs.Create.DBDocument; - options.dropAction = "copy"; - } if (type.indexOf("html") !== -1) { if (path.includes(window.location.hostname)) { const s = path.split('/'); diff --git a/src/client/northstar/core/BaseObject.ts b/src/client/northstar/core/BaseObject.ts deleted file mode 100644 index ed3818071..000000000 --- a/src/client/northstar/core/BaseObject.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { IEquatable } from '../utils/IEquatable'; -import { IDisposable } from '../utils/IDisposable'; - -export class BaseObject implements IEquatable, IDisposable { - - public Equals(other: Object): boolean { - return this === other; - } - - public Dispose(): void { - } -} \ No newline at end of file diff --git a/src/client/northstar/core/attribute/AttributeModel.ts b/src/client/northstar/core/attribute/AttributeModel.ts deleted file mode 100644 index c89b1617c..000000000 --- a/src/client/northstar/core/attribute/AttributeModel.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { Attribute, DataType, VisualizationHint } from '../../model/idea/idea'; -import { BaseObject } from '../BaseObject'; -import { observable } from "mobx"; - -export abstract class AttributeModel extends BaseObject { - public abstract get DisplayName(): string; - public abstract get CodeName(): string; - public abstract get DataType(): DataType; - public abstract get VisualizationHints(): VisualizationHint[]; -} - -export class ColumnAttributeModel extends AttributeModel { - public Attribute: Attribute; - - constructor(attribute: Attribute) { - super(); - this.Attribute = attribute; - } - - public get DataType(): DataType { - return this.Attribute.dataType ? this.Attribute.dataType : DataType.Undefined; - } - - public get DisplayName(): string { - return this.Attribute.displayName ? this.Attribute.displayName.ReplaceAll("_", " ") : ""; - } - - public get CodeName(): string { - return this.Attribute.rawName ? this.Attribute.rawName : ""; - } - - public get VisualizationHints(): VisualizationHint[] { - return this.Attribute.visualizationHints ? this.Attribute.visualizationHints : []; - } - - public Equals(other: ColumnAttributeModel): boolean { - return this.Attribute.rawName === other.Attribute.rawName; - } -} - -export class CodeAttributeModel extends AttributeModel { - private _visualizationHints: VisualizationHint[]; - - public CodeName: string; - - @observable - public Code: string; - - constructor(code: string, codeName: string, displayName: string, visualizationHints: VisualizationHint[]) { - super(); - this.Code = code; - this.CodeName = codeName; - this.DisplayName = displayName; - this._visualizationHints = visualizationHints; - } - - public get DataType(): DataType { - return DataType.Undefined; - } - - @observable - public DisplayName: string; - - public get VisualizationHints(): VisualizationHint[] { - return this._visualizationHints; - } - - public Equals(other: CodeAttributeModel): boolean { - return this.CodeName === other.CodeName; - } - -} - -export class BackendAttributeModel extends AttributeModel { - private _dataType: DataType; - private _displayName: string; - private _codeName: string; - private _visualizationHints: VisualizationHint[]; - - public Id: string; - - constructor(id: string, dataType: DataType, displayName: string, codeName: string, visualizationHints: VisualizationHint[]) { - super(); - this.Id = id; - this._dataType = dataType; - this._displayName = displayName; - this._codeName = codeName; - this._visualizationHints = visualizationHints; - } - - public get DataType(): DataType { - return this._dataType; - } - - public get DisplayName(): string { - return this._displayName.ReplaceAll("_", " "); - } - - public get CodeName(): string { - return this._codeName; - } - - public get VisualizationHints(): VisualizationHint[] { - return this._visualizationHints; - } - - public Equals(other: BackendAttributeModel): boolean { - 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 deleted file mode 100644 index 66485183b..000000000 --- a/src/client/northstar/core/attribute/AttributeTransformationModel.ts +++ /dev/null @@ -1,52 +0,0 @@ - -import { computed, observable } from "mobx"; -import { AggregateFunction } from "../../model/idea/idea"; -import { AttributeModel } from "./AttributeModel"; -import { IEquatable } from "../../utils/IEquatable"; - -export class AttributeTransformationModel implements IEquatable { - - @observable public AggregateFunction: AggregateFunction; - @observable public AttributeModel: AttributeModel; - - constructor(attributeModel: AttributeModel, aggregateFunction: AggregateFunction = AggregateFunction.None) { - this.AttributeModel = attributeModel; - this.AggregateFunction = aggregateFunction; - } - - @computed - public get PresentedName(): string { - var displayName = this.AttributeModel.DisplayName; - if (this.AggregateFunction === AggregateFunction.Count) { - return "count"; - } - if (this.AggregateFunction === AggregateFunction.Avg) { - displayName = "avg(" + displayName + ")"; - } - else if (this.AggregateFunction === AggregateFunction.Max) { - displayName = "max(" + displayName + ")"; - } - else if (this.AggregateFunction === AggregateFunction.Min) { - displayName = "min(" + displayName + ")"; - } - else if (this.AggregateFunction === AggregateFunction.Sum) { - displayName = "sum(" + displayName + ")"; - } - else if (this.AggregateFunction === AggregateFunction.SumE) { - displayName = "sumE(" + displayName + ")"; - } - - return displayName; - } - - public clone(): AttributeTransformationModel { - var clone = new AttributeTransformationModel(this.AttributeModel); - clone.AggregateFunction = this.AggregateFunction; - return clone; - } - - public Equals(other: AttributeTransformationModel): boolean { - 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 deleted file mode 100644 index a197c1305..000000000 --- a/src/client/northstar/core/attribute/CalculatedAttributeModel.ts +++ /dev/null @@ -1,42 +0,0 @@ -import { BackendAttributeModel, AttributeModel, CodeAttributeModel } from "./AttributeModel"; -import { DataType, VisualizationHint } from '../../model/idea/idea'; - -export class CalculatedAttributeManager { - public static AllCalculatedAttributes: Array = new Array(); - - public static Clear() { - this.AllCalculatedAttributes = new Array(); - } - - 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) { - return true; - } - return false; - }); - if (filtered.length > 0) { - return filtered[0] as BackendAttributeModel; - } - var newAttr = new BackendAttributeModel(id, dataType, displayName, codeName, visualizationHints); - this.AllCalculatedAttributes.push(newAttr); - return newAttr; - } - - public static CreateCodeAttributeModel(code: string, codeName: string, visualizationHints: VisualizationHint[]): CodeAttributeModel { - var filtered = this.AllCalculatedAttributes.filter(am => { - if (am instanceof CodeAttributeModel && - am.CodeName === codeName) { - return true; - } - return false; - }); - if (filtered.length > 0) { - return filtered[0] as CodeAttributeModel; - } - var newAttr = new CodeAttributeModel(code, codeName, codeName.ReplaceAll("_", " "), visualizationHints); - this.AllCalculatedAttributes.push(newAttr); - return newAttr; - } -} \ No newline at end of file diff --git a/src/client/northstar/core/brusher/IBaseBrushable.ts b/src/client/northstar/core/brusher/IBaseBrushable.ts deleted file mode 100644 index 87f4ba413..000000000 --- a/src/client/northstar/core/brusher/IBaseBrushable.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { PIXIPoint } from '../../utils/MathUtil'; -import { IEquatable } from '../../utils/IEquatable'; -import { Doc } from '../../../../new_fields/Doc'; - -export interface IBaseBrushable extends IEquatable { - BrusherModels: Array; - BrushColors: Array; - Position: PIXIPoint; - Size: PIXIPoint; -} -export function instanceOfIBaseBrushable(object: any): object is IBaseBrushable { - return 'BrusherModels' in object; -} \ No newline at end of file diff --git a/src/client/northstar/core/brusher/IBaseBrusher.ts b/src/client/northstar/core/brusher/IBaseBrusher.ts deleted file mode 100644 index d2de6ed62..000000000 --- a/src/client/northstar/core/brusher/IBaseBrusher.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { PIXIPoint } from '../../utils/MathUtil'; -import { IEquatable } from '../../utils/IEquatable'; - - -export interface IBaseBrusher extends IEquatable { - Position: PIXIPoint; - Size: PIXIPoint; -} -export function instanceOfIBaseBrusher(object: any): object is IBaseBrusher { - return 'BrushableModels' in object; -} \ No newline at end of file diff --git a/src/client/northstar/core/filter/FilterModel.ts b/src/client/northstar/core/filter/FilterModel.ts deleted file mode 100644 index 6ab96b33d..000000000 --- a/src/client/northstar/core/filter/FilterModel.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { ValueComparison } from "./ValueComparision"; -import { Utils } from "../../utils/Utils"; -import { IBaseFilterProvider } from "./IBaseFilterProvider"; -import { FilterOperand } from "./FilterOperand"; -import { HistogramField } from "../../dash-fields/HistogramField"; -import { Cast, FieldValue } from "../../../../new_fields/Types"; -import { Doc } from "../../../../new_fields/Doc"; - -export class FilterModel { - public ValueComparisons: ValueComparison[]; - constructor() { - this.ValueComparisons = new Array(); - } - - public Equals(other: FilterModel): boolean { - if (!Utils.EqualityHelper(this, other)) return false; - if (!this.isSame(this.ValueComparisons, (other).ValueComparisons)) return false; - return true; - } - - private isSame(a: ValueComparison[], b: ValueComparison[]): boolean { - if (a.length !== b.length) { - return false; - } - for (let i = 0; i < a.length; i++) { - let valueComp = a[i]; - if (!valueComp.Equals(b[i])) { - return false; - } - } - return true; - } - - public ToPythonString(): string { - return "(" + this.ValueComparisons.map(vc => vc.ToPythonString()).join("&&") + ")"; - } - - public static And(filters: string[]): string { - let ret = filters.filter(f => f !== "").join(" && "); - return ret; - } - public static GetFilterModelsRecursive(baseOperation: IBaseFilterProvider, visitedFilterProviders: Set, filterModels: FilterModel[], isFirst: boolean): string { - let ret = ""; - visitedFilterProviders.add(baseOperation); - 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(" || ") + ")"; - } - if (Utils.isBaseFilterConsumer(baseOperation) && baseOperation.Links) { - let children = new Array(); - let linkedGraphNodes = baseOperation.Links; - linkedGraphNodes.map(linkVm => { - let filterDoc = FieldValue(Cast(linkVm.linkedFrom, Doc)); - if (filterDoc) { - let filterHistogram = Cast(filterDoc.data, HistogramField); - if (filterHistogram) { - if (!visitedFilterProviders.has(filterHistogram.HistoOp)) { - let child = FilterModel.GetFilterModelsRecursive(filterHistogram.HistoOp, visitedFilterProviders, filterModels, false); - if (child !== "") { - // if (linkVm.IsInverted) { - // child = "! " + child; - // } - children.push(child); - } - } - } - } - }); - - let childrenJoined = children.join(baseOperation.FilterOperand === FilterOperand.AND ? " && " : " || "); - if (children.length > 0) { - if (ret !== "") { - ret = "(" + ret + " && (" + childrenJoined + "))"; - } - else { - ret = "(" + childrenJoined + ")"; - } - } - } - return ret; - } -} \ No newline at end of file diff --git a/src/client/northstar/core/filter/FilterOperand.ts b/src/client/northstar/core/filter/FilterOperand.ts deleted file mode 100644 index 2e8e8d6a0..000000000 --- a/src/client/northstar/core/filter/FilterOperand.ts +++ /dev/null @@ -1,5 +0,0 @@ -export enum FilterOperand -{ - AND, - OR -} \ No newline at end of file diff --git a/src/client/northstar/core/filter/FilterType.ts b/src/client/northstar/core/filter/FilterType.ts deleted file mode 100644 index 9adbc087f..000000000 --- a/src/client/northstar/core/filter/FilterType.ts +++ /dev/null @@ -1,6 +0,0 @@ -export enum FilterType -{ - Filter, - Brush, - Slice -} \ No newline at end of file diff --git a/src/client/northstar/core/filter/IBaseFilterConsumer.ts b/src/client/northstar/core/filter/IBaseFilterConsumer.ts deleted file mode 100644 index e7549d113..000000000 --- a/src/client/northstar/core/filter/IBaseFilterConsumer.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { FilterOperand } from '../filter/FilterOperand'; -import { IEquatable } from '../../utils/IEquatable'; -import { Doc } from '../../../../new_fields/Doc'; - -export interface IBaseFilterConsumer extends IEquatable { - FilterOperand: FilterOperand; - Links: Doc[]; -} - -export function instanceOfIBaseFilterConsumer(object: any): object is IBaseFilterConsumer { - return 'FilterOperand' in object; -} \ No newline at end of file diff --git a/src/client/northstar/core/filter/IBaseFilterProvider.ts b/src/client/northstar/core/filter/IBaseFilterProvider.ts deleted file mode 100644 index fc3301b11..000000000 --- a/src/client/northstar/core/filter/IBaseFilterProvider.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { FilterModel } from '../filter/FilterModel'; - -export interface IBaseFilterProvider { - FilterModels: Array; -} -export function instanceOfIBaseFilterProvider(object: any): object is IBaseFilterProvider { - return 'FilterModels' in object; -} \ No newline at end of file diff --git a/src/client/northstar/core/filter/ValueComparision.ts b/src/client/northstar/core/filter/ValueComparision.ts deleted file mode 100644 index 65687a82b..000000000 --- a/src/client/northstar/core/filter/ValueComparision.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { Predicate } from '../../model/idea/idea'; -import { Utils } from '../../utils/Utils'; -import { AttributeModel } from '../attribute/AttributeModel'; - -export class ValueComparison { - - public attributeModel: AttributeModel; - public Value: any; - public Predicate: Predicate; - - public constructor(attributeModel: AttributeModel, predicate: Predicate, value: any) { - this.attributeModel = attributeModel; - this.Value = value; - this.Predicate = predicate; - } - - public Equals(other: Object): boolean { - if (!Utils.EqualityHelper(this, other)) { - return false; - } - if (this.Predicate !== (other as ValueComparison).Predicate) { - return false; - } - let isComplex = (typeof this.Value === "object"); - if (!isComplex && this.Value !== (other as ValueComparison).Value) { - return false; - } - if (isComplex && !this.Value.Equals((other as ValueComparison).Value)) { - return false; - } - return true; - } - - public ToPythonString(): string { - var op = ""; - switch (this.Predicate) { - case Predicate.EQUALS: - op = "=="; - break; - case Predicate.GREATER_THAN: - op = ">"; - break; - case Predicate.GREATER_THAN_EQUAL: - op = ">="; - break; - case Predicate.LESS_THAN: - op = "<"; - break; - case Predicate.LESS_THAN_EQUAL: - op = "<="; - break; - default: - op = "=="; - break; - } - - var val = this.Value.toString(); - if (typeof this.Value === 'string' || this.Value instanceof String) { - val = "\"" + val + "\""; - } - var ret = " "; - var rawName = this.attributeModel.CodeName; - switch (this.Predicate) { - case Predicate.STARTS_WITH: - ret += rawName + " != null && " + rawName + ".StartsWith(" + val + ") "; - return ret; - case Predicate.ENDS_WITH: - ret += rawName + " != null && " + rawName + ".EndsWith(" + val + ") "; - return ret; - case Predicate.CONTAINS: - ret += rawName + " != null && " + rawName + ".Contains(" + val + ") "; - return ret; - default: - ret += rawName + " " + op + " " + val + " "; - return ret; - } - } -} \ No newline at end of file diff --git a/src/client/northstar/dash-fields/HistogramField.ts b/src/client/northstar/dash-fields/HistogramField.ts deleted file mode 100644 index 076516977..000000000 --- a/src/client/northstar/dash-fields/HistogramField.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { observable } from "mobx"; -import { custom, serializable } from "serializr"; -import { ColumnAttributeModel } from "../../../client/northstar/core/attribute/AttributeModel"; -import { AttributeTransformationModel } from "../../../client/northstar/core/attribute/AttributeTransformationModel"; -import { HistogramOperation } from "../../../client/northstar/operations/HistogramOperation"; -import { ObjectField } from "../../../new_fields/ObjectField"; -import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; -import { OmitKeys } from "../../../Utils"; -import { Deserializable } from "../../util/SerializationHelper"; -import { Copy, ToScriptString, ToString } from "../../../new_fields/FieldSymbols"; - -function serialize(field: HistogramField) { - const obj = OmitKeys(field, ['Links', 'BrushLinks', 'Result', 'BrushColors', 'FilterModels', 'FilterOperand']).omit; - return obj; -} - -function deserialize(jp: any) { - let X: AttributeTransformationModel | undefined; - let Y: AttributeTransformationModel | undefined; - let V: AttributeTransformationModel | undefined; - - const schema = CurrentUserUtils.GetNorthstarSchema(jp.SchemaName); - if (schema) { - CurrentUserUtils.GetAllNorthstarColumnAttributes(schema).map(attr => { - 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) { - Y = new AttributeTransformationModel(new ColumnAttributeModel(attr), jp.Y.AggregateFunction); - } - if (attr.displayName === jp.V.AttributeModel.Attribute.DisplayName) { - V = new AttributeTransformationModel(new ColumnAttributeModel(attr), jp.V.AggregateFunction); - } - }); - if (X && Y && V) { - return new HistogramOperation(jp.SchemaName, X, Y, V, jp.Normalization); - } - } - return HistogramOperation.Empty; -} - -@Deserializable("histogramField") -export class HistogramField extends ObjectField { - @serializable(custom(serialize, deserialize)) @observable public readonly HistoOp: HistogramOperation; - constructor(data?: HistogramOperation) { - super(); - this.HistoOp = data ? data : HistogramOperation.Empty; - } - - toString(): string { - return JSON.stringify(OmitKeys(this.HistoOp, ['Links', 'BrushLinks', 'Result', 'BrushColors', 'FilterModels', 'FilterOperand']).omit); - } - - [Copy]() { - // const y = this.HistoOp; - // const z = this.HistoOp.Copy; - return new HistogramField(HistogramOperation.Duplicate(this.HistoOp)); - } - - [ToScriptString]() { - return this.toString(); - } - [ToString]() { - return this.toString(); - } -} \ No newline at end of file diff --git a/src/client/northstar/dash-nodes/HistogramBinPrimitiveCollection.ts b/src/client/northstar/dash-nodes/HistogramBinPrimitiveCollection.ts deleted file mode 100644 index 6b36ffc9e..000000000 --- a/src/client/northstar/dash-nodes/HistogramBinPrimitiveCollection.ts +++ /dev/null @@ -1,240 +0,0 @@ -import React = require("react"); -import { AttributeTransformationModel } from "../../northstar/core/attribute/AttributeTransformationModel"; -import { ChartType } from '../../northstar/model/binRanges/VisualBinRange'; -import { AggregateFunction, Bin, Brush, DoubleValueAggregateResult, HistogramResult, MarginAggregateParameters, MarginAggregateResult } from "../../northstar/model/idea/idea"; -import { ModelHelpers } from "../../northstar/model/ModelHelpers"; -import { LABColor } from '../../northstar/utils/LABColor'; -import { PIXIRectangle } from "../../northstar/utils/MathUtil"; -import { StyleConstants } from "../../northstar/utils/StyleContants"; -import { HistogramBox } from "./HistogramBox"; -import "./HistogramBoxPrimitives.scss"; - -export class HistogramBinPrimitive { - constructor(init?: Partial) { - Object.assign(this, init); - } - public DataValue: number = 0; - public Rect: PIXIRectangle = PIXIRectangle.EMPTY; - public MarginRect: PIXIRectangle = PIXIRectangle.EMPTY; - public MarginPercentage: number = 0; - public Color: number = StyleConstants.WARNING_COLOR; - public Opacity: number = 1; - public BrushIndex: number = 0; - public BarAxis: number = -1; -} - -export class HistogramBinPrimitiveCollection { - private static TOLERANCE: number = 0.0001; - - private _histoBox: HistogramBox; - private get histoOp() { return this._histoBox.HistoOp; } - private get histoResult() { return this.histoOp.Result as HistogramResult; } - private get sizeConverter() { return this._histoBox.SizeConverter; } - public BinPrimitives: Array = new Array(); - public HitGeom: PIXIRectangle = PIXIRectangle.EMPTY; - - constructor(bin: Bin, histoBox: HistogramBox) { - this._histoBox = histoBox; - let brushing = this.setupBrushing(bin, this.histoOp.Normalization); // X= 0, Y = 1, V = 2 - - brushing.orderedBrushes.reduce((brushFactorSum, brush) => { - switch (histoBox.ChartType) { - case ChartType.VerticalBar: return this.createVerticalBarChartBinPrimitives(bin, brush, brushing.maxAxis, this.histoOp.Normalization); - case ChartType.HorizontalBar: return this.createHorizontalBarChartBinPrimitives(bin, brush, brushing.maxAxis, this.histoOp.Normalization); - case ChartType.SinglePoint: return this.createSinglePointChartBinPrimitives(bin, brush); - case ChartType.HeatMap: return this.createHeatmapBinPrimitives(bin, brush, brushFactorSum); - } - }, 0); - - // 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); - filteredBinPrims.reduce((sum, fbp) => { - 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) { - 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) { - 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) { - 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); - return sum + fbp.Rect.height; - } - } - return 0; - }, 0); - this.BinPrimitives = this.BinPrimitives.reverse(); - 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)); - return { - orderedBrushes, - maxAxis: orderedBrushes.reduce((prev, Brush) => { - let aggResult = this.getBinValue(normalization, bin, Brush.brushIndex!); - return aggResult !== undefined && aggResult > prev ? aggResult : prev; - }, Number.MIN_VALUE) - }; - } - - private createHeatmapBinPrimitives(bin: Bin, brush: Brush, brushFactorSum: number): number { - - let unNormalizedValue = this.getBinValue(2, bin, brush.brushIndex!); - if (unNormalizedValue === undefined) { - return brushFactorSum; - } - - var normalizedValue = (unNormalizedValue - this._histoBox.ValueRange[0]) / (Math.abs((this._histoBox.ValueRange[1] - this._histoBox.ValueRange[0])) < HistogramBinPrimitiveCollection.TOLERANCE ? - unNormalizedValue : this._histoBox.ValueRange[1] - this._histoBox.ValueRange[0]); - - let allUnNormalizedValue = this.getBinValue(2, bin, ModelHelpers.AllBrushIndex(this.histoResult)); - - // bcz: are these calls needed? - let [xFrom, xTo] = this.sizeConverter.DataToScreenXAxisRange(this._histoBox.VisualBinRanges, 0, bin); - let [yFrom, yTo] = this.sizeConverter.DataToScreenYAxisRange(this._histoBox.VisualBinRanges, 1, bin); - - var returnBrushFactorSum = brushFactorSum; - if (allUnNormalizedValue !== undefined) { - var brushFactor = (unNormalizedValue / allUnNormalizedValue); - returnBrushFactorSum += brushFactor; - returnBrushFactorSum = Math.min(returnBrushFactorSum, 1.0); - - var tempRect = new PIXIRectangle(xFrom, yTo, xTo - xFrom, yFrom - yTo); - var ratio = (tempRect.width / tempRect.height); - var newHeight = Math.sqrt((1.0 / ratio) * ((tempRect.width * tempRect.height) * returnBrushFactorSum)); - var newWidth = newHeight * ratio; - - xFrom = (tempRect.x + (tempRect.width - newWidth) / 2.0); - yTo = (tempRect.y + (tempRect.height - newHeight) / 2.0); - xTo = (xFrom + newWidth); - yFrom = (yTo + newHeight); - } - var alpha = 0.0; - var color = this.baseColorFromBrush(brush); - var lerpColor = LABColor.Lerp( - LABColor.FromColor(StyleConstants.MIN_VALUE_COLOR), - LABColor.FromColor(color), - (alpha + Math.pow(normalizedValue, 1.0 / 3.0) * (1.0 - alpha))); - var dataColor = LABColor.ToColor(lerpColor); - - this.createBinPrimitive(-1, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, dataColor, 1, unNormalizedValue); - return returnBrushFactorSum; - } - - private createSinglePointChartBinPrimitives(bin: Bin, brush: Brush): number { - let unNormalizedValue = this.getBinValue(2, bin, brush.brushIndex!); - 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) { - this.createBinPrimitive(-1, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, this.baseColorFromBrush(brush), 1, unNormalizedValue); - } - } - return 0; - } - - private createVerticalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number): number { - let dataValue = this.getBinValue(1, bin, brush.brushIndex!); - 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); - - var yMarginAbsolute = this.getMargin(bin, brush, this.histoOp.Y); - var marginRect = new PIXIRectangle(xFrom + (xTo - xFrom) / 2.0 - 1, - this.sizeConverter.DataToScreenY(yValue + yMarginAbsolute), 2, - 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); - } - return 0; - } - - private createHorizontalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number): number { - let dataValue = this.getBinValue(0, bin, brush.brushIndex!); - 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); - - var xMarginAbsolute = this.sizeConverter.IsSmall ? 0 : this.getMargin(bin, brush, this.histoOp.X); - var marginRect = new PIXIRectangle(this.sizeConverter.DataToScreenX(xValue - xMarginAbsolute), - yTo + (yFrom - yTo) / 2.0 - 1, - this.sizeConverter.DataToScreenX(xValue + xMarginAbsolute) - this.sizeConverter.DataToScreenX(xValue - xMarginAbsolute), - 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); - } - 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); - let dataValue = ModelHelpers.GetAggregateResult(bin, aggregateKey) as DoubleValueAggregateResult; - return dataValue !== null && dataValue.hasResult ? dataValue.result : undefined; - } - - private getMargin(bin: Bin, brush: Brush, axis: AttributeTransformationModel) { - var marginParams = new MarginAggregateParameters(); - marginParams.aggregateFunction = axis.AggregateFunction; - var marginAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Schema!.distinctAttributeParameters, axis, this.histoResult, brush.brushIndex!, marginParams); - let aggResult = ModelHelpers.GetAggregateResult(bin, marginAggregateKey); - return aggResult instanceof MarginAggregateResult && aggResult.absolutMargin ? aggResult.absolutMargin : 0; - } - - private createBinPrimitive(barAxis: number, brush: Brush, marginRect: PIXIRectangle, - marginPercentage: number, xFrom: number, xTo: number, yFrom: number, yTo: number, color: number, opacity: number, dataValue: number) { - var binPrimitive = new HistogramBinPrimitive( - { - Rect: new PIXIRectangle(xFrom, yTo, xTo - xFrom, yFrom - yTo), - MarginRect: marginRect, - MarginPercentage: marginPercentage, - BrushIndex: brush.brushIndex, - Color: color, - Opacity: opacity, - DataValue: dataValue, - BarAxis: barAxis - }); - this.BinPrimitives.push(binPrimitive); - } - - private baseColorFromBrush(brush: Brush): number { - let bc = StyleConstants.BRUSH_COLORS; - if (brush.brushIndex === ModelHelpers.RestBrushIndex(this.histoResult)) { - return StyleConstants.HIGHLIGHT_COLOR; - } - else if (brush.brushIndex === ModelHelpers.OverlapBrushIndex(this.histoResult)) { - return StyleConstants.OVERLAP_COLOR; - } - else if (brush.brushIndex === ModelHelpers.AllBrushIndex(this.histoResult)) { - return 0x00ff00; - } - else if (bc.length > 0) { - return bc[brush.brushIndex! % bc.length]; - } - // else if (this.histoOp.BrushColors.length > 0) { - // return this.histoOp.BrushColors[brush.brushIndex! % this.histoOp.BrushColors.length]; - // } - return StyleConstants.HIGHLIGHT_COLOR; - } -} diff --git a/src/client/northstar/dash-nodes/HistogramBox.scss b/src/client/northstar/dash-nodes/HistogramBox.scss deleted file mode 100644 index 06d781263..000000000 --- a/src/client/northstar/dash-nodes/HistogramBox.scss +++ /dev/null @@ -1,40 +0,0 @@ -.histogrambox-container { - padding: 0vw; - position: absolute; - top: -50%; - left:-50%; - text-align: center; - width: 100%; - height: 100%; - background: black; - } - .histogrambox-xaxislabel { - position:absolute; - left:0; - width:100%; - text-align: center; - bottom:0; - background: lightgray; - font-size: 14; - font-weight: bold; - } - .histogrambox-yaxislabel { - position:absolute; - height:100%; - width: 25px; - left:0; - bottom:0; - background: lightgray; - } - .histogrambox-yaxislabel-text { - position:absolute; - left:0; - width: 1000px; - transform-origin: 10px 10px; - transform: rotate(-90deg); - text-align: left; - font-size: 14; - font-weight: bold; - bottom: calc(50% - 25px); - } - \ No newline at end of file diff --git a/src/client/northstar/dash-nodes/HistogramBox.tsx b/src/client/northstar/dash-nodes/HistogramBox.tsx deleted file mode 100644 index 8fee53fb9..000000000 --- a/src/client/northstar/dash-nodes/HistogramBox.tsx +++ /dev/null @@ -1,175 +0,0 @@ -import React = require("react"); -import { action, computed, observable, reaction, runInAction, trace } from "mobx"; -import { observer } from "mobx-react"; -import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; -import { ChartType, VisualBinRange } from '../../northstar/model/binRanges/VisualBinRange'; -import { VisualBinRangeHelper } from "../../northstar/model/binRanges/VisualBinRangeHelper"; -import { AggregateBinRange, AggregateFunction, BinRange, Catalog, DoubleValueAggregateResult, HistogramResult } from "../../northstar/model/idea/idea"; -import { ModelHelpers } from "../../northstar/model/ModelHelpers"; -import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; -import { SizeConverter } from "../../northstar/utils/SizeConverter"; -import { DragManager } from "../../util/DragManager"; -import { FieldView, FieldViewProps } from "../../views/nodes/FieldView"; -import { AttributeTransformationModel } from "../core/attribute/AttributeTransformationModel"; -import { HistogramField } from "../dash-fields/HistogramField"; -import "../utils/Extensions"; -import "./HistogramBox.scss"; -import { HistogramBoxPrimitives } from './HistogramBoxPrimitives'; -import { HistogramLabelPrimitives } from "./HistogramLabelPrimitives"; -import { StyleConstants } from "../utils/StyleContants"; -import { Cast } from "../../../new_fields/Types"; -import { Doc, DocListCast, DocListCastAsync } from "../../../new_fields/Doc"; -import { Id } from "../../../new_fields/FieldSymbols"; - - -@observer -export class HistogramBox extends React.Component { - public static LayoutString(fieldStr: string) { return FieldView.LayoutString(HistogramBox, fieldStr); } - private _dropXRef = React.createRef(); - private _dropYRef = React.createRef(); - private _dropXDisposer?: DragManager.DragDropDisposer; - private _dropYDisposer?: DragManager.DragDropDisposer; - - @observable public HistoOp: HistogramOperation = HistogramOperation.Empty; - @observable public VisualBinRanges: VisualBinRange[] = []; - @observable public ValueRange: number[] = []; - @computed public get HistogramResult(): HistogramResult { return this.HistoOp.Result as HistogramResult; } - @observable public SizeConverter: SizeConverter = new SizeConverter(); - - @computed get createOperationParamsCache() { return this.HistoOp.CreateOperationParameters(); } - @computed get BinRanges() { return this.HistogramResult ? this.HistogramResult.binRanges : undefined; } - @computed get ChartType() { - return !this.BinRanges ? ChartType.SinglePoint : this.BinRanges[0] instanceof AggregateBinRange ? - (this.BinRanges[1] instanceof AggregateBinRange ? ChartType.SinglePoint : ChartType.HorizontalBar) : - this.BinRanges[1] instanceof AggregateBinRange ? ChartType.VerticalBar : ChartType.HeatMap; - } - - @action - dropX = (e: Event, de: DragManager.DropEvent) => { - if (de.complete.docDragData) { - let h = Cast(de.complete.docDragData.draggedDocuments[0].data, HistogramField); - if (h) { - this.HistoOp.X = h.HistoOp.X; - } - e.stopPropagation(); - e.preventDefault(); - } - } - @action - dropY = (e: Event, de: DragManager.DropEvent) => { - if (de.complete.docDragData) { - let h = Cast(de.complete.docDragData.draggedDocuments[0].data, HistogramField); - if (h) { - this.HistoOp.Y = h.HistoOp.X; - } - e.stopPropagation(); - e.preventDefault(); - } - } - - @action - xLabelPointerDown = (e: React.PointerEvent) => { - 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); - } - - componentDidMount() { - if (this._dropXRef.current) { - this._dropXDisposer = DragManager.MakeDropTarget(this._dropXRef.current, this.dropX.bind(this)); - } - if (this._dropYRef.current) { - this._dropYDisposer = DragManager.MakeDropTarget(this._dropYRef.current, this.dropY.bind(this)); - } - reaction(() => CurrentUserUtils.NorthstarDBCatalog, (catalog?: Catalog) => this.activateHistogramOperation(catalog), { fireImmediately: true }); - reaction(() => [this.VisualBinRanges && this.VisualBinRanges.slice()], () => this.SizeConverter.SetVisualBinRanges(this.VisualBinRanges)); - reaction(() => [this.props.PanelWidth(), this.props.PanelHeight()], (size: number[]) => this.SizeConverter.SetIsSmall(size[0] < 40 && size[1] < 40)); - reaction(() => this.HistogramResult ? this.HistogramResult.binRanges : undefined, - (binRanges: BinRange[] | undefined) => { - if (binRanges) { - this.VisualBinRanges.splice(0, this.VisualBinRanges.length, ...binRanges.map((br, ind) => - VisualBinRangeHelper.GetVisualBinRange(this.HistoOp.Schema!.distinctAttributeParameters, br, this.HistogramResult, ind ? this.HistoOp.Y : this.HistoOp.X, this.ChartType))); - - let valueAggregateKey = ModelHelpers.CreateAggregateKey(this.HistoOp.Schema!.distinctAttributeParameters, this.HistoOp.V, this.HistogramResult, ModelHelpers.AllBrushIndex(this.HistogramResult)); - this.ValueRange = Object.values(this.HistogramResult.bins!).reduce((prev, cur) => { - let value = ModelHelpers.GetAggregateResult(cur, valueAggregateKey) as DoubleValueAggregateResult; - return value && value.hasResult ? [Math.min(prev[0], value.result!), Math.max(prev[1], value.result!)] : prev; - }, [Number.MAX_VALUE, Number.MIN_VALUE]); - } - }); - } - - componentWillUnmount() { - if (this._dropXDisposer) { - this._dropXDisposer(); - } - if (this._dropYDisposer) { - this._dropYDisposer(); - } - } - - async activateHistogramOperation(catalog?: Catalog) { - if (catalog) { - let histoOp = await Cast(this.props.Document[this.props.fieldKey], HistogramField); - runInAction(() => { - this.HistoOp = histoOp ? histoOp.HistoOp : HistogramOperation.Empty; - if (this.HistoOp !== HistogramOperation.Empty) { - reaction(() => DocListCast(this.props.Document.linkedFromDocs), (docs) => this.HistoOp.Links.splice(0, this.HistoOp.Links.length, ...docs), { fireImmediately: true }); - reaction(() => DocListCast(this.props.Document.brushingDocs).length, - async () => { - let brushingDocs = await DocListCastAsync(this.props.Document.brushingDocs); - const proto = this.props.Document.proto; - if (proto && brushingDocs) { - let mapped = brushingDocs.map((brush, i) => { - brush.backgroundColor = StyleConstants.BRUSH_COLORS[i % StyleConstants.BRUSH_COLORS.length]; - let brushed = DocListCast(brush.brushingDocs); - if (!brushed.length) return null; - return { l: brush, b: brushed[0][Id] === proto[Id] ? brushed[1] : brushed[0] }; - }); - runInAction(() => this.HistoOp.BrushLinks.splice(0, this.HistoOp.BrushLinks.length, ...mapped.filter(m => m) as { l: Doc, b: Doc }[])); - } - }, { fireImmediately: true }); - reaction(() => this.createOperationParamsCache, () => this.HistoOp.Update(), { fireImmediately: true }); - } - }); - } - } - - @action - private onScrollWheel = (e: React.WheelEvent) => { - this.HistoOp.DrillDown(e.deltaY > 0); - e.stopPropagation(); - } - - render() { - let labelY = this.HistoOp && this.HistoOp.Y ? this.HistoOp.Y.PresentedName : "<...>"; - let labelX = this.HistoOp && this.HistoOp.X ? this.HistoOp.X.PresentedName : "<...>"; - let loff = this.SizeConverter.LeftOffset; - let toff = this.SizeConverter.TopOffset; - let roff = this.SizeConverter.RightOffset; - let boff = this.SizeConverter.BottomOffset; - return ( -
-
- - {labelY} - -
-
- - -
-
- {labelX} -
-
- ); - } -} - diff --git a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.scss b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.scss deleted file mode 100644 index 26203612a..000000000 --- a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.scss +++ /dev/null @@ -1,42 +0,0 @@ -.histogramboxprimitives-container { - width: 100%; - height: 100%; -} -.histogramboxprimitives-border { - border: 3px; - pointer-events: none; - position: absolute; - fill:"transparent"; - stroke: white; - stroke-width: 1px; -} -.histogramboxprimitives-bar { - position: absolute; - border: 1px; - border-style: solid; - border-color: #282828; - pointer-events: all; -} - -.histogramboxprimitives-placer { - position: absolute; - pointer-events: none; - width: 100%; - height: 100%; -} -.histogramboxprimitives-svgContainer { - position: absolute; - top:0; - left:0; - width:100%; - height: 100%; -} -.histogramboxprimitives-line { - position: absolute; - background: darkGray; - stroke: darkGray; - stroke-width: 1px; - width:100%; - height:100%; - opacity: 0.4; -} \ No newline at end of file diff --git a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx deleted file mode 100644 index 66d91cc1d..000000000 --- a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx +++ /dev/null @@ -1,122 +0,0 @@ -import React = require("react"); -import { computed, observable, reaction, runInAction, trace, action } from "mobx"; -import { observer } from "mobx-react"; -import { Utils as DashUtils, emptyFunction } from '../../../Utils'; -import { FilterModel } from "../../northstar/core/filter/FilterModel"; -import { ModelHelpers } from "../../northstar/model/ModelHelpers"; -import { ArrayUtil } from "../../northstar/utils/ArrayUtil"; -import { LABColor } from '../../northstar/utils/LABColor'; -import { PIXIRectangle } from "../../northstar/utils/MathUtil"; -import { StyleConstants } from "../../northstar/utils/StyleContants"; -import { HistogramBinPrimitiveCollection, HistogramBinPrimitive } from "./HistogramBinPrimitiveCollection"; -import { HistogramBox } from "./HistogramBox"; -import "./HistogramBoxPrimitives.scss"; - -export interface HistogramPrimitivesProps { - HistoBox: HistogramBox; -} -@observer -export class HistogramBoxPrimitives extends React.Component { - private get histoOp() { return this.props.HistoBox.HistoOp; } - private get renderDimension() { return this.props.HistoBox.SizeConverter.RenderDimension; } - @observable _selectedPrims: HistogramBinPrimitive[] = []; - @computed get xaxislines() { return this.renderGridLinesAndLabels(0); } - @computed get yaxislines() { return this.renderGridLinesAndLabels(1); } - @computed get selectedPrimitives() { return this._selectedPrims.map(bp => this.drawRect(bp.Rect, bp.BarAxis, undefined, "border")); } - @computed get barPrimitives() { - let histoResult = this.props.HistoBox.HistogramResult; - if (!histoResult || !histoResult.bins || !this.props.HistoBox.VisualBinRanges.length) { - return (null); - } - let allBrushIndex = ModelHelpers.AllBrushIndex(histoResult); - return Object.keys(histoResult.bins).reduce((prims: JSX.Element[], key: string) => { - let drawPrims = new HistogramBinPrimitiveCollection(histoResult.bins![key], this.props.HistoBox); - let toggle = this.getSelectionToggle(drawPrims.BinPrimitives, allBrushIndex, - ModelHelpers.GetBinFilterModel(histoResult.bins![key], allBrushIndex, histoResult, this.histoOp.X, this.histoOp.Y)); - drawPrims.BinPrimitives.filter(bp => bp.DataValue && bp.BrushIndex !== allBrushIndex).map(bp => - prims.push(...[{ r: bp.Rect, c: bp.Color }, { r: bp.MarginRect, c: StyleConstants.MARGIN_BARS_COLOR }].map(pair => this.drawRect(pair.r, bp.BarAxis, pair.c, "bar", toggle)))); - return prims; - }, [] as JSX.Element[]); - } - - componentDidMount() { - reaction(() => this.props.HistoBox.HistoOp.FilterString, () => this._selectedPrims.length = this.histoOp.FilterModels.length = 0); - } - - private getSelectionToggle(binPrimitives: HistogramBinPrimitive[], allBrushIndex: number, filterModel: FilterModel) { - let rawAllBrushPrim = ArrayUtil.FirstOrDefault(binPrimitives, bp => bp.BrushIndex === allBrushIndex); - if (!rawAllBrushPrim) { - return emptyFunction; - } - let allBrushPrim = rawAllBrushPrim; - return () => runInAction(() => { - if (ArrayUtil.Contains(this.histoOp.FilterModels, filterModel)) { - this._selectedPrims.splice(this._selectedPrims.indexOf(allBrushPrim), 1); - this.histoOp.RemoveFilterModels([filterModel]); - } - else { - this._selectedPrims.push(allBrushPrim); - this.histoOp.AddFilterModels([filterModel]); - } - }); - } - - private renderGridLinesAndLabels(axis: number) { - if (!this.props.HistoBox.SizeConverter.Initialized) { - return (null); - } - let labels = this.props.HistoBox.VisualBinRanges[axis].GetLabels(); - return - {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)); - } - return prims; - }, [] as JSX.Element[])} - ; - } - - drawLine(xFrom: number, yFrom: number, width: number, height: number) { - if (height < 0) { - yFrom += height; - height = -height; - } - if (width < 0) { - xFrom += width; - width = -width; - } - let trans2Xpercent = `${(xFrom + width) / this.renderDimension * 100}%`; - let trans2Ypercent = `${(yFrom + height) / this.renderDimension * 100}%`; - let trans1Xpercent = `${xFrom / this.renderDimension * 100}%`; - let trans1Ypercent = `${yFrom / this.renderDimension * 100}%`; - return ; - } - drawRect(r: PIXIRectangle, barAxis: number, color: number | undefined, classExt: string, tapHandler: () => void = emptyFunction) { - if (r.height < 0) { - r.y += r.height; - r.height = -r.height; - } - if (r.width < 0) { - r.x += r.width; - r.width = -r.width; - } - let transXpercent = `${r.x / this.renderDimension * 100}%`; - let transYpercent = `${r.y / this.renderDimension * 100}%`; - let widthXpercent = `${r.width / this.renderDimension * 100}%`; - let heightYpercent = `${r.height / this.renderDimension * 100}%`; - return ( { if (e.button === 0) tapHandler(); }} - x={transXpercent} width={`${widthXpercent}`} y={transYpercent} height={`${heightYpercent}`} fill={color ? `${LABColor.RGBtoHexString(color)}` : "transparent"} />); - } - render() { - return
- {this.xaxislines} - {this.yaxislines} - - {this.barPrimitives} - {this.selectedPrimitives} - -
; - } -} diff --git a/src/client/northstar/dash-nodes/HistogramLabelPrimitives.scss b/src/client/northstar/dash-nodes/HistogramLabelPrimitives.scss deleted file mode 100644 index 304d33771..000000000 --- a/src/client/northstar/dash-nodes/HistogramLabelPrimitives.scss +++ /dev/null @@ -1,13 +0,0 @@ - - .histogramLabelPrimitives-gridlabel { - position:absolute; - transform-origin: left top; - font-size: 11; - color:white; - } - .histogramLabelPrimitives-placer { - position:absolute; - width:100%; - height:100%; - pointer-events: none; - } \ No newline at end of file diff --git a/src/client/northstar/dash-nodes/HistogramLabelPrimitives.tsx b/src/client/northstar/dash-nodes/HistogramLabelPrimitives.tsx deleted file mode 100644 index 62aebd3c6..000000000 --- a/src/client/northstar/dash-nodes/HistogramLabelPrimitives.tsx +++ /dev/null @@ -1,80 +0,0 @@ -import React = require("react"); -import { action, computed, reaction } from "mobx"; -import { observer } from "mobx-react"; -import { Utils as DashUtils } from '../../../Utils'; -import { NominalVisualBinRange } from "../model/binRanges/NominalVisualBinRange"; -import "../utils/Extensions"; -import { StyleConstants } from "../utils/StyleContants"; -import { HistogramBox } from "./HistogramBox"; -import "./HistogramLabelPrimitives.scss"; -import { HistogramPrimitivesProps } from "./HistogramBoxPrimitives"; - -@observer -export class HistogramLabelPrimitives extends React.Component { - componentDidMount() { - reaction(() => [this.props.HistoBox.props.PanelWidth(), this.props.HistoBox.SizeConverter.LeftOffset, this.props.HistoBox.VisualBinRanges.length], - (fields) => HistogramLabelPrimitives.computeLabelAngle(fields[0], fields[1], this.props.HistoBox), { fireImmediately: true }); - } - - @action - static computeLabelAngle(panelWidth: number, leftOffset: number, histoBox: HistogramBox) { - const textWidth = 30; - if (panelWidth > 0 && histoBox.VisualBinRanges.length && histoBox.VisualBinRanges[0] instanceof NominalVisualBinRange) { - let space = (panelWidth - leftOffset * 2) / histoBox.VisualBinRanges[0].GetBins().length; - histoBox.SizeConverter.SetLabelAngle(Math.min(Math.PI / 2, Math.max(Math.PI / 6, textWidth / space * Math.PI / 2))); - } else if (histoBox.SizeConverter.LabelAngle) { - histoBox.SizeConverter.SetLabelAngle(0); - } - } - @computed get xaxislines() { return this.renderGridLinesAndLabels(0); } - @computed get yaxislines() { return this.renderGridLinesAndLabels(1); } - - private renderGridLinesAndLabels(axis: number) { - let sc = this.props.HistoBox.SizeConverter; - let vb = this.props.HistoBox.VisualBinRanges; - if (!vb.length || !sc.Initialized) { - return (null); - } - let dim = (axis === 0 ? this.props.HistoBox.props.PanelWidth() : this.props.HistoBox.props.PanelHeight()) / ((axis === 0 && vb[axis] instanceof NominalVisualBinRange) ? - (12 + 5) : // (FontStyles.AxisLabel.fontSize + 5))); - sc.MaxLabelSizes[axis].coords[axis] + 5); - - let labels = vb[axis].GetLabels(); - return labels.reduce((prims, binLabel, i) => { - let r = sc.DataToScreenRange(binLabel.minValue!, binLabel.maxValue!, axis); - if (i % Math.ceil(labels.length / dim) === 0 && binLabel.label) { - const label = binLabel.label.Truncate(StyleConstants.MAX_CHAR_FOR_HISTOGRAM_LABELS, "..."); - const textHeight = 14; const textWidth = 30; - 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) { - let space = (r.xTo - r.xFrom) / sc.RenderDimension * this.props.HistoBox.props.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.props.PanelHeight() - sc.BottomOffset - textHeight}px` : `${yStart / sc.RenderDimension * 100}%`; - - prims.push( -
-
- {label} -
-
- ); - } - return prims; - }, [] as JSX.Element[]); - } - - render() { - let xaxislines = this.xaxislines; - let yaxislines = this.yaxislines; - return
- {xaxislines} - {yaxislines} -
; - } - -} \ No newline at end of file diff --git a/src/client/northstar/manager/Gateway.ts b/src/client/northstar/manager/Gateway.ts deleted file mode 100644 index c541cce6a..000000000 --- a/src/client/northstar/manager/Gateway.ts +++ /dev/null @@ -1,299 +0,0 @@ -import { Catalog, OperationReference, Result, CompileResults } from "../model/idea/idea"; -import { computed, observable, action } from "mobx"; - -export class Gateway { - - private static _instance: Gateway; - - private constructor() { - } - - public static get Instance() { - return this._instance || (this._instance = new this()); - } - - public async GetCatalog(): Promise { - try { - const json = await this.MakeGetRequest("catalog"); - const cat = Catalog.fromJS(json); - return cat; - } - catch (error) { - throw new Error("can not reach northstar's backend"); - } - } - - public async PostSchema(csvdata: string, schemaname: string): Promise { - try { - const json = await this.MakePostJsonRequest("postSchema", { csv: csvdata, schema: schemaname }); - // const cat = Catalog.fromJS(json); - // return cat; - return json; - } - catch (error) { - throw new Error("can not reach northstar's backend"); - } - } - - public async GetSchema(pathname: string, schemaname: string): Promise { - try { - const json = await this.MakeGetRequest("schema", undefined, { path: pathname, schema: schemaname }); - const cat = Catalog.fromJS(json); - return cat; - } - catch (error) { - throw new Error("can not reach northstar's backend"); - } - } - - public async ClearCatalog(): Promise { - try { - await this.MakePostJsonRequest("Datamart/ClearAllAugmentations", {}); - } - catch (error) { - throw new Error("can not reach northstar's backend"); - } - } - - public async TerminateServer(): Promise { - try { - const url = Gateway.ConstructUrl("terminateServer"); - const response = await fetch(url, - { - redirect: "follow", - method: "POST", - credentials: "include" - }); - } - catch (error) { - throw new Error("can not reach northstar's backend"); - } - } - - public async Compile(data: any): Promise { - const json = await this.MakePostJsonRequest("compile", data); - if (json !== null) { - const cr = CompileResults.fromJS(json); - return cr; - } - } - - public async SubmitResult(data: any): Promise { - try { - console.log(data); - const url = Gateway.ConstructUrl("submitProblem"); - const response = await fetch(url, - { - redirect: "follow", - method: "POST", - credentials: "include", - body: JSON.stringify(data) - }); - } - catch (error) { - throw new Error("can not reach northstar's backend"); - } - } - - public async SpecifyProblem(data: any): Promise { - try { - console.log(data); - const url = Gateway.ConstructUrl("specifyProblem"); - const response = await fetch(url, - { - redirect: "follow", - method: "POST", - credentials: "include", - body: JSON.stringify(data) - }); - } - catch (error) { - throw new Error("can not reach northstar's backend"); - } - } - - public async ExportToScript(solutionId: string): Promise { - try { - const url = Gateway.ConstructUrl("exportsolution/script/" + solutionId); - const response = await fetch(url, - { - redirect: "follow", - method: "GET", - credentials: "include" - }); - return await response.text(); - } - catch (error) { - throw new Error("can not reach northstar's backend"); - } - } - - - public async StartOperation(data: any): Promise { - const json = await this.MakePostJsonRequest("operation", data); - if (json !== null) { - const or = OperationReference.fromJS(json); - return or; - } - } - - public async GetResult(data: any): Promise { - const json = await this.MakePostJsonRequest("result", data); - if (json !== null) { - const res = Result.fromJS(json); - return res; - } - } - - public async PauseOperation(data: any): Promise { - const url = Gateway.ConstructUrl("pause"); - await fetch(url, - { - redirect: "follow", - method: "POST", - credentials: "include", - body: JSON.stringify(data) - }); - } - - public async MakeGetRequest(endpoint: string, signal?: AbortSignal, params?: any): Promise { - let url = !params ? Gateway.ConstructUrl(endpoint) : - (() => { - let newUrl = new URL(Gateway.ConstructUrl(endpoint)); - Object.getOwnPropertyNames(params).map(prop => - newUrl.searchParams.append(prop, params[prop])); - return Gateway.ConstructUrl(endpoint) + newUrl.search; - })(); - - const response = await fetch(url, - { - redirect: "follow", - method: "GET", - credentials: "include", - signal - }); - const json = await response.json(); - return json; - } - - public async MakePostJsonRequest(endpoint: string, data: any, signal?: AbortSignal): Promise { - const url = Gateway.ConstructUrl(endpoint); - const response = await fetch(url, - { - redirect: "follow", - method: "POST", - credentials: "include", - body: JSON.stringify(data), - signal - }); - const json = await response.json(); - return json; - } - - - public static ConstructUrl(appendix: string): string { - let base = NorthstarSettings.Instance.ServerUrl; - if (base.slice(-1) === "/") { - base = base.slice(0, -1); - } - let url = base + "/" + NorthstarSettings.Instance.ServerApiPath + "/" + appendix; - return url; - } -} - -declare var ENV: any; - -export class NorthstarSettings { - private _environment: any; - - @observable - public ServerUrl: string = document.URL; - - @observable - public ServerApiPath?: string; - - @observable - public SampleSize?: number; - - @observable - public XBins?: number; - - @observable - public YBins?: number; - - @observable - public SplashTimeInMS?: number; - - @observable - public ShowFpsCounter?: boolean; - - @observable - public IsMenuFixed?: boolean; - - @observable - public ShowShutdownButton?: boolean; - - @observable - public IsDarpa?: boolean; - - @observable - public IsIGT?: boolean; - - @observable - public DegreeOfParallelism?: number; - - @observable - public ShowWarnings?: boolean; - - @computed - public get IsDev(): boolean { - return ENV.IsDev; - } - - @computed - public get TestDataFolderPath(): string { - return this.Origin + "testdata/"; - } - - @computed - public get Origin(): string { - return window.location.origin + "/"; - } - - private static _instance: NorthstarSettings; - - @action - public UpdateEnvironment(environment: any): void { - /*let serverParam = new URL(document.URL).searchParams.get("serverUrl"); - if (serverParam) { - if (serverParam === "debug") { - this.ServerUrl = `http://${window.location.hostname}:1234`; - } - else { - this.ServerUrl = serverParam; - } - } - 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; - } - - public static get Instance(): NorthstarSettings { - if (!this._instance) { - this._instance = new NorthstarSettings(); - } - return this._instance; - } -} diff --git a/src/client/northstar/model/ModelExtensions.ts b/src/client/northstar/model/ModelExtensions.ts deleted file mode 100644 index 29f80d2d1..000000000 --- a/src/client/northstar/model/ModelExtensions.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { AttributeParameters, Brush, MarginAggregateParameters, SingleDimensionAggregateParameters, Solution } from '../model/idea/idea'; -import { Utils } from '../utils/Utils'; - -import { FilterModel } from '../core/filter/FilterModel'; - -(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; - return true; -}; - -{ - (AttributeParameters as any).prototype.Equals = function (other: AttributeParameters) { - return (this).constructor.name === (other).constructor.name && - this.rawName === other.rawName; - }; -} - -{ - (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; - }; -} - -{ - (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 MarginAggregateParameters).aggregateFunction !== (other as MarginAggregateParameters).aggregateFunction) return false; - return true; - }; -} - -{ - (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; - return true; - }; -} \ No newline at end of file diff --git a/src/client/northstar/model/ModelHelpers.ts b/src/client/northstar/model/ModelHelpers.ts deleted file mode 100644 index 88e6e72b8..000000000 --- a/src/client/northstar/model/ModelHelpers.ts +++ /dev/null @@ -1,220 +0,0 @@ - -import { action } from "mobx"; -import { AggregateFunction, AggregateKey, AggregateParameters, AttributeColumnParameters, AttributeParameters, AverageAggregateParameters, Bin, BinningParameters, Brush, BrushEnum, CountAggregateParameters, DataType, EquiWidthBinningParameters, HistogramResult, MarginAggregateParameters, SingleBinBinningParameters, SingleDimensionAggregateParameters, SumAggregateParameters, AggregateBinRange, NominalBinRange, AlphabeticBinRange, Predicate, Schema, Attribute, AttributeGroup, Exception, AttributeBackendParameters, AttributeCodeParameters } from '../model/idea/idea'; -import { ValueComparison } from "../core/filter/ValueComparision"; -import { ArrayUtil } from "../utils/ArrayUtil"; -import { AttributeModel, ColumnAttributeModel, BackendAttributeModel, CodeAttributeModel } from "../core/attribute/AttributeModel"; -import { FilterModel } from "../core/filter/FilterModel"; -import { AlphabeticVisualBinRange } from "./binRanges/AlphabeticVisualBinRange"; -import { NominalVisualBinRange } from "./binRanges/NominalVisualBinRange"; -import { VisualBinRangeHelper } from "./binRanges/VisualBinRangeHelper"; -import { AttributeTransformationModel } from "../core/attribute/AttributeTransformationModel"; -import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; - -export class ModelHelpers { - - public static CreateAggregateKey(distinctAttributeParameters: AttributeParameters | undefined, atm: AttributeTransformationModel, histogramResult: HistogramResult, - brushIndex: number, aggParameters?: SingleDimensionAggregateParameters): AggregateKey { - { - if (aggParameters === undefined) { - aggParameters = ModelHelpers.GetAggregateParameter(distinctAttributeParameters, atm); - } - else { - aggParameters.attributeParameters = ModelHelpers.GetAttributeParameters(atm.AttributeModel); - } - return new AggregateKey( - { - aggregateParameterIndex: ModelHelpers.GetAggregateParametersIndex(histogramResult, aggParameters), - brushIndex: brushIndex - }); - } - } - - public static GetAggregateParametersIndex(histogramResult: HistogramResult, aggParameters?: AggregateParameters): number { - return Array.from(histogramResult.aggregateParameters!).findIndex((value, i, set) => { - if (set[i] instanceof CountAggregateParameters && value instanceof CountAggregateParameters) return true; - if (set[i] instanceof MarginAggregateParameters && value instanceof MarginAggregateParameters) return true; - if (set[i] instanceof SumAggregateParameters && value instanceof SumAggregateParameters) return true; - return false; - }); - } - - public static GetAggregateParameter(distinctAttributeParameters: AttributeParameters | undefined, atm: AttributeTransformationModel): AggregateParameters | undefined { - var aggParam: AggregateParameters | undefined; - if (atm.AggregateFunction === AggregateFunction.Avg) { - var avg = new AverageAggregateParameters(); - avg.attributeParameters = ModelHelpers.GetAttributeParameters(atm.AttributeModel); - avg.distinctAttributeParameters = distinctAttributeParameters; - aggParam = avg; - } - else if (atm.AggregateFunction === AggregateFunction.Count) { - var cnt = new CountAggregateParameters(); - cnt.attributeParameters = ModelHelpers.GetAttributeParameters(atm.AttributeModel); - cnt.distinctAttributeParameters = distinctAttributeParameters; - aggParam = cnt; - } - else if (atm.AggregateFunction === AggregateFunction.Sum) { - var sum = new SumAggregateParameters(); - sum.attributeParameters = ModelHelpers.GetAttributeParameters(atm.AttributeModel); - sum.distinctAttributeParameters = distinctAttributeParameters; - aggParam = sum; - } - return aggParam; - } - - public static GetAggregateParametersWithMargins(distinctAttributeParameters: AttributeParameters | undefined, atms: Array): Array { - var aggregateParameters = new Array(); - atms.forEach(agg => { - var aggParams = ModelHelpers.GetAggregateParameter(distinctAttributeParameters, agg); - if (aggParams) { - aggregateParameters.push(aggParams); - - var margin = new MarginAggregateParameters(); - margin.aggregateFunction = agg.AggregateFunction; - margin.attributeParameters = ModelHelpers.GetAttributeParameters(agg.AttributeModel); - margin.distinctAttributeParameters = distinctAttributeParameters; - aggregateParameters.push(margin); - } - }); - - return aggregateParameters; - } - - public static GetBinningParameters(attr: AttributeTransformationModel, nrOfBins: number, minvalue?: number, maxvalue?: number): BinningParameters { - if (attr.AggregateFunction === AggregateFunction.None) { - return new EquiWidthBinningParameters( - { - attributeParameters: ModelHelpers.GetAttributeParameters(attr.AttributeModel), - requestedNrOfBins: nrOfBins, - minValue: minvalue, - maxValue: maxvalue - }); - } - else { - return new SingleBinBinningParameters( - { - attributeParameters: ModelHelpers.GetAttributeParameters(attr.AttributeModel) - }); - } - } - - public static GetAttributeParametersFromAttributeModel(am: AttributeModel): AttributeParameters { - if (am instanceof ColumnAttributeModel) { - return new AttributeColumnParameters( - { - rawName: am.CodeName, - visualizationHints: am.VisualizationHints - }); - } - else if (am instanceof BackendAttributeModel) { - return new AttributeBackendParameters( - { - rawName: am.CodeName, - visualizationHints: am.VisualizationHints, - id: (am).Id - }); - } - else if (am instanceof CodeAttributeModel) { - return new AttributeCodeParameters( - { - rawName: am.CodeName, - visualizationHints: am.VisualizationHints, - code: (am).Code - }); - } - else { - throw new Exception(); - } - } - - public static GetAttributeParameters(am: AttributeModel): AttributeParameters { - return this.GetAttributeParametersFromAttributeModel(am); - } - - public static OverlapBrushIndex(histogramResult: HistogramResult): number { - var brush = ArrayUtil.First(histogramResult.brushes!, (b: any) => b.brushEnum === BrushEnum.Overlap); - return ModelHelpers.GetBrushIndex(histogramResult, brush); - } - - public static AllBrushIndex(histogramResult: HistogramResult): number { - var brush = ArrayUtil.First(histogramResult.brushes!, (b: any) => b.brushEnum === BrushEnum.All); - return ModelHelpers.GetBrushIndex(histogramResult, brush); - } - - public static RestBrushIndex(histogramResult: HistogramResult): number { - var brush = ArrayUtil.First(histogramResult.brushes!, (b: Brush) => b.brushEnum === BrushEnum.Rest); - return ModelHelpers.GetBrushIndex(histogramResult, brush); - } - - public static GetBrushIndex(histogramResult: HistogramResult, brush: Brush): number { - return ArrayUtil.IndexOfWithEqual(histogramResult.brushes!, brush); - } - - public static GetAggregateResult(bin: Bin, aggregateKey: AggregateKey) { - if (aggregateKey.aggregateParameterIndex === -1 || aggregateKey.brushIndex === -1) { - return null; - } - return bin.aggregateResults![aggregateKey.aggregateParameterIndex! * bin.ySize! + aggregateKey.brushIndex!]; - } - - @action - public static PossibleAggegationFunctions(atm: AttributeTransformationModel): Array { - var ret = new Array(); - ret.push(AggregateFunction.None); - ret.push(AggregateFunction.Count); - if (atm.AttributeModel.DataType === DataType.Float || - atm.AttributeModel.DataType === DataType.Double || - atm.AttributeModel.DataType === DataType.Int) { - ret.push(AggregateFunction.Avg); - ret.push(AggregateFunction.Sum); - } - return ret; - } - - public static GetBinFilterModel( - bin: Bin, brushIndex: number, histogramResult: HistogramResult, - xAom: AttributeTransformationModel, yAom: AttributeTransformationModel): FilterModel { - var dimensions: Array = [xAom, yAom]; - var filterModel = new FilterModel(); - - for (var i = 0; i < histogramResult.binRanges!.length; i++) { - if (!(histogramResult.binRanges![i] instanceof AggregateBinRange)) { - var binRange = VisualBinRangeHelper.GetNonAggregateVisualBinRange(histogramResult.binRanges![i]); - var dataFrom = binRange.GetValueFromIndex(bin.binIndex!.indices![i]); - var dataTo = binRange.AddStep(dataFrom); - - if (binRange instanceof NominalVisualBinRange) { - var tt = binRange.GetLabel(dataFrom); - filterModel.ValueComparisons.push(new ValueComparison(dimensions[i].AttributeModel, Predicate.EQUALS, tt)); - } - else if (binRange instanceof AlphabeticVisualBinRange) { - filterModel.ValueComparisons.push(new ValueComparison(dimensions[i].AttributeModel, Predicate.STARTS_WITH, - binRange.GetLabel(dataFrom))); - } - else { - filterModel.ValueComparisons.push(new ValueComparison(dimensions[i].AttributeModel, Predicate.GREATER_THAN_EQUAL, dataFrom)); - filterModel.ValueComparisons.push(new ValueComparison(dimensions[i].AttributeModel, Predicate.LESS_THAN, dataTo)); - } - } - } - - return filterModel; - } - - public GetAllAttributes(schema: Schema) { - if (!schema || !schema.rootAttributeGroup) { - return []; - } - const recurs = (attrs: Attribute[], g: AttributeGroup) => { - if (g.attributes) { - attrs.push.apply(attrs, g.attributes); - if (g.attributeGroups) { - g.attributeGroups.forEach(ng => recurs(attrs, ng)); - } - } - }; - const allAttributes: Attribute[] = new Array(); - recurs(allAttributes, schema.rootAttributeGroup); - return allAttributes; - } -} \ No newline at end of file diff --git a/src/client/northstar/model/binRanges/AlphabeticVisualBinRange.ts b/src/client/northstar/model/binRanges/AlphabeticVisualBinRange.ts deleted file mode 100644 index 120b034f2..000000000 --- a/src/client/northstar/model/binRanges/AlphabeticVisualBinRange.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { AlphabeticBinRange, BinLabel } from '../../model/idea/idea'; -import { VisualBinRange } from './VisualBinRange'; - -export class AlphabeticVisualBinRange extends VisualBinRange { - public DataBinRange: AlphabeticBinRange; - - constructor(dataBinRange: AlphabeticBinRange) { - super(); - this.DataBinRange = dataBinRange; - } - - public AddStep(value: number): number { - return value + 1; - } - - public GetValueFromIndex(index: number): number { - return index; - } - - public GetBins(): number[] { - var bins = new Array(); - var idx = 0; - for (var key in this.DataBinRange.labelsValue) { - if (this.DataBinRange.labelsValue.hasOwnProperty(key)) { - bins.push(idx); - idx++; - } - } - return bins; - } - - public GetLabel(value: number): string { - return this.DataBinRange.prefix + this.DataBinRange.valuesLabel![value]; - } - - public GetLabels(): Array { - var labels = new Array(); - var count = 0; - for (var key in this.DataBinRange.valuesLabel) { - if (this.DataBinRange.valuesLabel.hasOwnProperty(key)) { - var value = this.DataBinRange.valuesLabel[key]; - labels.push(new BinLabel({ - value: parseFloat(key), - minValue: count++, - maxValue: count, - label: this.DataBinRange.prefix + value - })); - } - } - return labels; - } -} \ No newline at end of file diff --git a/src/client/northstar/model/binRanges/DateTimeVisualBinRange.ts b/src/client/northstar/model/binRanges/DateTimeVisualBinRange.ts deleted file mode 100644 index 776e643cd..000000000 --- a/src/client/northstar/model/binRanges/DateTimeVisualBinRange.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { DateTimeBinRange, DateTimeStep, DateTimeStepGranularity } from '../idea/idea'; -import { VisualBinRange } from './VisualBinRange'; - -export class DateTimeVisualBinRange extends VisualBinRange { - public DataBinRange: DateTimeBinRange; - - constructor(dataBinRange: DateTimeBinRange) { - super(); - this.DataBinRange = dataBinRange; - } - - public AddStep(value: number): number { - return DateTimeVisualBinRange.AddToDateTimeTicks(value, this.DataBinRange.step!); - } - - public GetValueFromIndex(index: number): number { - var v = this.DataBinRange.minValue!; - for (var i = 0; i < index; i++) { - v = this.AddStep(v); - } - return v; - } - - public GetBins(): number[] { - var bins = new Array(); - for (var v: number = this.DataBinRange.minValue!; - v < this.DataBinRange.maxValue!; - v = DateTimeVisualBinRange.AddToDateTimeTicks(v, this.DataBinRange.step!)) { - bins.push(v); - } - return bins; - } - - private pad(n: number, size: number) { - var sign = n < 0 ? '-' : ''; - return sign + new Array(size).concat([Math.abs(n)]).join('0').slice(-size); - } - - - public GetLabel(value: number): string { - var dt = DateTimeVisualBinRange.TicksToDate(value); - 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) { - return (this.pad(dt.getHours(), 2) + ":" + this.pad(dt.getMinutes(), 2)); - //return dt.ToString("HH:mm"); - } - 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) { - //return dt.ToString("MM/yyyy"); - return ((dt.getMonth() + 1) + "/" + dt.getFullYear()); - } - else if (this.DataBinRange.step!.dateTimeStepGranularity === DateTimeStepGranularity.Year) { - return "" + dt.getFullYear(); - } - return "n/a"; - } - - public static TicksToDate(ticks: number): Date { - var dd = new Date((ticks - 621355968000000000) / 10000); - dd.setMinutes(dd.getMinutes() + dd.getTimezoneOffset()); - return dd; - } - - - public static DateToTicks(date: Date): number { - var copiedDate = new Date(date.getTime()); - copiedDate.setMinutes(copiedDate.getMinutes() - copiedDate.getTimezoneOffset()); - var t = copiedDate.getTime() * 10000 + 621355968000000000; - /*var dd = new Date((ticks - 621355968000000000) / 10000); - dd.setMinutes(dd.getMinutes() + dd.getTimezoneOffset()); - return dd;*/ - return t; - } - - 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) { - returnDate = new Date(copiedDate.setSeconds(copiedDate.getSeconds() + dateTimeStep.dateTimeStepValue!)); - } - else if (dateTimeStep.dateTimeStepGranularity === DateTimeStepGranularity.Minute) { - returnDate = new Date(copiedDate.setMinutes(copiedDate.getMinutes() + dateTimeStep.dateTimeStepValue!)); - } - else if (dateTimeStep.dateTimeStepGranularity === DateTimeStepGranularity.Hour) { - returnDate = new Date(copiedDate.setHours(copiedDate.getHours() + dateTimeStep.dateTimeStepValue!)); - } - else if (dateTimeStep.dateTimeStepGranularity === DateTimeStepGranularity.Day) { - returnDate = new Date(copiedDate.setDate(copiedDate.getDate() + dateTimeStep.dateTimeStepValue!)); - } - else if (dateTimeStep.dateTimeStepGranularity === DateTimeStepGranularity.Month) { - returnDate = new Date(copiedDate.setMonth(copiedDate.getMonth() + dateTimeStep.dateTimeStepValue!)); - } - else if (dateTimeStep.dateTimeStepGranularity === DateTimeStepGranularity.Year) { - returnDate = new Date(copiedDate.setFullYear(copiedDate.getFullYear() + dateTimeStep.dateTimeStepValue!)); - } - return DateTimeVisualBinRange.DateToTicks(returnDate); - } -} \ No newline at end of file diff --git a/src/client/northstar/model/binRanges/NominalVisualBinRange.ts b/src/client/northstar/model/binRanges/NominalVisualBinRange.ts deleted file mode 100644 index 42509d797..000000000 --- a/src/client/northstar/model/binRanges/NominalVisualBinRange.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { NominalBinRange, BinLabel } from '../../model/idea/idea'; -import { VisualBinRange } from './VisualBinRange'; - -export class NominalVisualBinRange extends VisualBinRange { - public DataBinRange: NominalBinRange; - - constructor(dataBinRange: NominalBinRange) { - super(); - this.DataBinRange = dataBinRange; - } - - public AddStep(value: number): number { - return value + 1; - } - - public GetValueFromIndex(index: number): number { - return index; - } - - public GetBins(): number[] { - var bins = new Array(); - var idx = 0; - for (var key in this.DataBinRange.labelsValue) { - if (this.DataBinRange.labelsValue.hasOwnProperty(key)) { - bins.push(idx); - idx++; - } - } - return bins; - } - - public GetLabel(value: number): string { - return this.DataBinRange.valuesLabel![value]; - } - - public GetLabels(): Array { - var labels = new Array(); - var count = 0; - for (var key in this.DataBinRange.valuesLabel) { - if (this.DataBinRange.valuesLabel.hasOwnProperty(key)) { - var value = this.DataBinRange.valuesLabel[key]; - labels.push(new BinLabel({ - value: parseFloat(key), - minValue: count++, - maxValue: count, - label: value - })); - } - } - return labels; - } -} \ No newline at end of file diff --git a/src/client/northstar/model/binRanges/QuantitativeVisualBinRange.ts b/src/client/northstar/model/binRanges/QuantitativeVisualBinRange.ts deleted file mode 100644 index 7bc097e1d..000000000 --- a/src/client/northstar/model/binRanges/QuantitativeVisualBinRange.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { QuantitativeBinRange } from '../idea/idea'; -import { VisualBinRange } from './VisualBinRange'; -import { format } from "d3-format"; - -export class QuantitativeVisualBinRange extends VisualBinRange { - - public DataBinRange: QuantitativeBinRange; - - constructor(dataBinRange: QuantitativeBinRange) { - super(); - this.DataBinRange = dataBinRange; - } - - public AddStep(value: number): number { - return value + this.DataBinRange.step!; - } - - public GetValueFromIndex(index: number): number { - return this.DataBinRange.minValue! + (index * this.DataBinRange.step!); - } - - public GetLabel(value: number): string { - return QuantitativeVisualBinRange.NumberFormatter(value); - } - - public static NumberFormatter(val: number): string { - if (val === 0) { - return "0"; - } - if (val < 1) { - /*if (val < Math.abs(0.001)) { - return val.toExponential(2); - }*/ - return format(".3")(val); - } - return format("~s")(val); - } - - public GetBins(): number[] { - const bins = new Array(); - - for (let v: number = this.DataBinRange.minValue!; v < this.DataBinRange.maxValue!; v += this.DataBinRange.step!) { - bins.push(v); - } - return bins; - } - - public static Initialize(dataMinValue: number, dataMaxValue: number, targetBinNumber: number, isIntegerRange: boolean): QuantitativeVisualBinRange { - const extent = QuantitativeVisualBinRange.getExtent(dataMinValue, dataMaxValue, targetBinNumber, isIntegerRange); - const dataBinRange = new QuantitativeBinRange(); - dataBinRange.minValue = extent[0]; - dataBinRange.maxValue = extent[1]; - dataBinRange.step = extent[2]; - - return new QuantitativeVisualBinRange(dataBinRange); - } - - private static getExtent(dataMin: number, dataMax: number, m: number, isIntegerRange: boolean): number[] { - if (dataMin === dataMax) { - // dataMin -= 0.1; - dataMax += 0.1; - } - const span = dataMax - dataMin; - - let step = Math.pow(10, Math.floor(Math.log10(span / m))); - const err = m / span * step; - - if (err <= .15) { - step *= 10; - } - else if (err <= .35) { - step *= 5; - } - else if (err <= .75) { - step *= 2; - } - - if (isIntegerRange) { - step = Math.ceil(step); - } - const ret: number[] = new Array(3); - const minDivStep = Math.floor(dataMin / step); - const maxDivStep = Math.floor(dataMax / step); - ret[0] = minDivStep * step; // Math.floor(Math.Round(dataMin, 8)/step)*step; - ret[1] = maxDivStep * step + step; // Math.floor(Math.Round(dataMax, 8)/step)*step + step; - ret[2] = step; - - return ret; - } -} \ No newline at end of file diff --git a/src/client/northstar/model/binRanges/VisualBinRange.ts b/src/client/northstar/model/binRanges/VisualBinRange.ts deleted file mode 100644 index 449a22e91..000000000 --- a/src/client/northstar/model/binRanges/VisualBinRange.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { BinLabel } from '../../model/idea/idea'; - -export abstract class VisualBinRange { - - public abstract AddStep(value: number): number; - - public abstract GetValueFromIndex(index: number): number; - - public abstract GetBins(): Array; - - public GetLabel(value: number): string { - return value.toString(); - } - - public GetLabels(): Array { - var labels = new Array(); - var bins = this.GetBins(); - bins.forEach(b => { - labels.push(new BinLabel({ - value: b, - minValue: b, - maxValue: this.AddStep(b), - label: this.GetLabel(b) - })); - }); - return labels; - } -} - -export enum ChartType { - HorizontalBar = 0, VerticalBar = 1, HeatMap = 2, SinglePoint = 3 -} \ No newline at end of file diff --git a/src/client/northstar/model/binRanges/VisualBinRangeHelper.ts b/src/client/northstar/model/binRanges/VisualBinRangeHelper.ts deleted file mode 100644 index a92412686..000000000 --- a/src/client/northstar/model/binRanges/VisualBinRangeHelper.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { BinRange, NominalBinRange, QuantitativeBinRange, Exception, AlphabeticBinRange, DateTimeBinRange, AggregateBinRange, DoubleValueAggregateResult, HistogramResult, AttributeParameters } from "../idea/idea"; -import { VisualBinRange, ChartType } from "./VisualBinRange"; -import { NominalVisualBinRange } from "./NominalVisualBinRange"; -import { QuantitativeVisualBinRange } from "./QuantitativeVisualBinRange"; -import { AlphabeticVisualBinRange } from "./AlphabeticVisualBinRange"; -import { DateTimeVisualBinRange } from "./DateTimeVisualBinRange"; -import { NorthstarSettings } from "../../manager/Gateway"; -import { ModelHelpers } from "../ModelHelpers"; -import { AttributeTransformationModel } from "../../core/attribute/AttributeTransformationModel"; - -export const SETTINGS_X_BINS = 15; -export const SETTINGS_Y_BINS = 15; -export const SETTINGS_SAMPLE_SIZE = 100000; - -export class VisualBinRangeHelper { - - public static GetNonAggregateVisualBinRange(dataBinRange: BinRange): VisualBinRange { - if (dataBinRange instanceof NominalBinRange) { - return new NominalVisualBinRange(dataBinRange); - } - else if (dataBinRange instanceof QuantitativeBinRange) { - return new QuantitativeVisualBinRange(dataBinRange); - } - else if (dataBinRange instanceof AlphabeticBinRange) { - return new AlphabeticVisualBinRange(dataBinRange); - } - else if (dataBinRange instanceof DateTimeBinRange) { - return new DateTimeVisualBinRange(dataBinRange); - } - throw new Exception(); - } - - public static GetVisualBinRange(distinctAttributeParameters: AttributeParameters | undefined, dataBinRange: BinRange, histoResult: HistogramResult, attr: AttributeTransformationModel, chartType: ChartType): VisualBinRange { - - if (!(dataBinRange instanceof AggregateBinRange)) { - return VisualBinRangeHelper.GetNonAggregateVisualBinRange(dataBinRange); - } - else { - var aggregateKey = ModelHelpers.CreateAggregateKey(distinctAttributeParameters, attr, histoResult, ModelHelpers.AllBrushIndex(histoResult)); - var minValue = Number.MAX_VALUE; - var maxValue = Number.MIN_VALUE; - for (const brush of histoResult.brushes!) { - aggregateKey.brushIndex = brush.brushIndex; - for (var key in histoResult.bins) { - if (histoResult.bins.hasOwnProperty(key)) { - var bin = histoResult.bins[key]; - var res = ModelHelpers.GetAggregateResult(bin, aggregateKey); - if (res && res.hasResult && res.result) { - minValue = Math.min(minValue, res.result); - maxValue = Math.max(maxValue, res.result); - } - } - } - } - - let visualBinRange = QuantitativeVisualBinRange.Initialize(minValue, maxValue, 10, false); - - if (chartType === ChartType.HorizontalBar || chartType === ChartType.VerticalBar) { - visualBinRange = QuantitativeVisualBinRange.Initialize(Math.min(0, minValue), - Math.max(0, (visualBinRange).DataBinRange.maxValue!), - SETTINGS_X_BINS, false); - } - else if (chartType === ChartType.SinglePoint) { - visualBinRange = QuantitativeVisualBinRange.Initialize(Math.min(0, minValue), Math.max(0, maxValue), - SETTINGS_X_BINS, false); - } - return visualBinRange; - } - } -} diff --git a/src/client/northstar/model/idea/MetricTypeMapping.ts b/src/client/northstar/model/idea/MetricTypeMapping.ts deleted file mode 100644 index e9759cf16..000000000 --- a/src/client/northstar/model/idea/MetricTypeMapping.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { MetricType } from "./Idea"; -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) { - return MetricInterpretation.HigherIsBetter; - } - return MetricInterpretation.LowerIsBetter; - } -} - -export enum MetricInterpretation { - HigherIsBetter, LowerIsBetter -} \ No newline at end of file diff --git a/src/client/northstar/model/idea/idea.ts b/src/client/northstar/model/idea/idea.ts deleted file mode 100644 index c73a822c7..000000000 --- a/src/client/northstar/model/idea/idea.ts +++ /dev/null @@ -1,8557 +0,0 @@ -/* tslint:disable */ -//---------------------- -// -// Generated using the NSwag toolchain v11.19.2.0 (NJsonSchema v9.10.73.0 (Newtonsoft.Json v9.0.0.0)) (http://NSwag.org) -// -//---------------------- -// ReSharper disable InconsistentNaming - - - -export enum AggregateFunction { - None = "None", - Sum = "Sum", - SumE = "SumE", - Count = "Count", - Min = "Min", - Max = "Max", - Avg = "Avg", -} - -export abstract class AggregateParameters implements IAggregateParameters { - - protected _discriminator: string; - - public Equals(other: Object): boolean { - return this == other; - } - constructor(data?: IAggregateParameters) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - this._discriminator = "AggregateParameters"; - } - - init(data?: any) { - if (data) { - } - } - - static fromJS(data: any): AggregateParameters { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "AverageAggregateParameters") { - let result = new AverageAggregateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "SingleDimensionAggregateParameters") { - throw new Error("The abstract class 'SingleDimensionAggregateParameters' cannot be instantiated."); - } - if (data["discriminator"] === "CountAggregateParameters") { - let result = new CountAggregateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "KDEAggregateParameters") { - let result = new KDEAggregateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "MarginAggregateParameters") { - let result = new MarginAggregateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "MaxAggregateParameters") { - let result = new MaxAggregateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "MinAggregateParameters") { - let result = new MinAggregateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "SumAggregateParameters") { - let result = new SumAggregateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "SumEstimationAggregateParameters") { - let result = new SumEstimationAggregateParameters(); - result.init(data); - return result; - } - throw new Error("The abstract class 'AggregateParameters' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["discriminator"] = this._discriminator; - return data; - } -} - -export interface IAggregateParameters { -} - -export abstract class SingleDimensionAggregateParameters extends AggregateParameters implements ISingleDimensionAggregateParameters { - attributeParameters?: AttributeParameters | undefined; - distinctAttributeParameters?: AttributeParameters | undefined; - - constructor(data?: ISingleDimensionAggregateParameters) { - super(data); - this._discriminator = "SingleDimensionAggregateParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.attributeParameters = data["AttributeParameters"] ? AttributeParameters.fromJS(data["AttributeParameters"]) : undefined; - this.distinctAttributeParameters = data["DistinctAttributeParameters"] ? AttributeParameters.fromJS(data["DistinctAttributeParameters"]) : undefined; - } - } - - static fromJS(data: any): SingleDimensionAggregateParameters { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "AverageAggregateParameters") { - let result = new AverageAggregateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "CountAggregateParameters") { - let result = new CountAggregateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "KDEAggregateParameters") { - let result = new KDEAggregateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "MarginAggregateParameters") { - let result = new MarginAggregateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "MaxAggregateParameters") { - let result = new MaxAggregateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "MinAggregateParameters") { - let result = new MinAggregateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "SumAggregateParameters") { - let result = new SumAggregateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "SumEstimationAggregateParameters") { - let result = new SumEstimationAggregateParameters(); - result.init(data); - return result; - } - throw new Error("The abstract class 'SingleDimensionAggregateParameters' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["AttributeParameters"] = this.attributeParameters ? this.attributeParameters.toJSON() : undefined; - data["DistinctAttributeParameters"] = this.distinctAttributeParameters ? this.distinctAttributeParameters.toJSON() : undefined; - super.toJSON(data); - return data; - } -} - -export interface ISingleDimensionAggregateParameters extends IAggregateParameters { - attributeParameters?: AttributeParameters | undefined; - distinctAttributeParameters?: AttributeParameters | undefined; -} - -export class AverageAggregateParameters extends SingleDimensionAggregateParameters implements IAverageAggregateParameters { - - constructor(data?: IAverageAggregateParameters) { - super(data); - this._discriminator = "AverageAggregateParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): AverageAggregateParameters { - data = typeof data === 'object' ? data : {}; - let result = new AverageAggregateParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface IAverageAggregateParameters extends ISingleDimensionAggregateParameters { -} - -export abstract class AttributeParameters implements IAttributeParameters { - visualizationHints?: VisualizationHint[] | undefined; - rawName?: string | undefined; - public Equals(other: Object): boolean { - return this == other; - } - - protected _discriminator: string; - - constructor(data?: IAttributeParameters) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - this._discriminator = "AttributeParameters"; - } - - init(data?: any) { - if (data) { - if (data["VisualizationHints"] && data["VisualizationHints"].constructor === Array) { - this.visualizationHints = []; - for (let item of data["VisualizationHints"]) - this.visualizationHints.push(item); - } - this.rawName = data["RawName"]; - } - } - - static fromJS(data: any): AttributeParameters { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "AttributeBackendParameters") { - let result = new AttributeBackendParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "AttributeCaclculatedParameters") { - throw new Error("The abstract class 'AttributeCaclculatedParameters' cannot be instantiated."); - } - if (data["discriminator"] === "AttributeCodeParameters") { - let result = new AttributeCodeParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "AttributeColumnParameters") { - let result = new AttributeColumnParameters(); - result.init(data); - return result; - } - throw new Error("The abstract class 'AttributeParameters' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["discriminator"] = this._discriminator; - if (this.visualizationHints && this.visualizationHints.constructor === Array) { - data["VisualizationHints"] = []; - for (let item of this.visualizationHints) - data["VisualizationHints"].push(item); - } - data["RawName"] = this.rawName; - return data; - } -} - -export interface IAttributeParameters { - visualizationHints?: VisualizationHint[] | undefined; - rawName?: string | undefined; -} - -export enum VisualizationHint { - TreatAsEnumeration = "TreatAsEnumeration", - DefaultFlipAxis = "DefaultFlipAxis", - Image = "Image", -} - -export abstract class AttributeCaclculatedParameters extends AttributeParameters implements IAttributeCaclculatedParameters { - - constructor(data?: IAttributeCaclculatedParameters) { - super(data); - this._discriminator = "AttributeCaclculatedParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): AttributeCaclculatedParameters { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "AttributeBackendParameters") { - let result = new AttributeBackendParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "AttributeCodeParameters") { - let result = new AttributeCodeParameters(); - result.init(data); - return result; - } - throw new Error("The abstract class 'AttributeCaclculatedParameters' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface IAttributeCaclculatedParameters extends IAttributeParameters { -} - -export class AttributeBackendParameters extends AttributeCaclculatedParameters implements IAttributeBackendParameters { - id?: string | undefined; - - constructor(data?: IAttributeBackendParameters) { - super(data); - this._discriminator = "AttributeBackendParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.id = data["Id"]; - } - } - - static fromJS(data: any): AttributeBackendParameters { - data = typeof data === 'object' ? data : {}; - let result = new AttributeBackendParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Id"] = this.id; - super.toJSON(data); - return data; - } -} - -export interface IAttributeBackendParameters extends IAttributeCaclculatedParameters { - id?: string | undefined; -} - -export class AttributeCodeParameters extends AttributeCaclculatedParameters implements IAttributeCodeParameters { - code?: string | undefined; - - constructor(data?: IAttributeCodeParameters) { - super(data); - this._discriminator = "AttributeCodeParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.code = data["Code"]; - } - } - - static fromJS(data: any): AttributeCodeParameters { - data = typeof data === 'object' ? data : {}; - let result = new AttributeCodeParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Code"] = this.code; - super.toJSON(data); - return data; - } -} - -export interface IAttributeCodeParameters extends IAttributeCaclculatedParameters { - code?: string | undefined; -} - -export class AttributeColumnParameters extends AttributeParameters implements IAttributeColumnParameters { - - constructor(data?: IAttributeColumnParameters) { - super(data); - this._discriminator = "AttributeColumnParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): AttributeColumnParameters { - data = typeof data === 'object' ? data : {}; - let result = new AttributeColumnParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface IAttributeColumnParameters extends IAttributeParameters { -} - -export class CountAggregateParameters extends SingleDimensionAggregateParameters implements ICountAggregateParameters { - - constructor(data?: ICountAggregateParameters) { - super(data); - this._discriminator = "CountAggregateParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): CountAggregateParameters { - data = typeof data === 'object' ? data : {}; - let result = new CountAggregateParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface ICountAggregateParameters extends ISingleDimensionAggregateParameters { -} - -export class KDEAggregateParameters extends SingleDimensionAggregateParameters implements IKDEAggregateParameters { - nrOfSamples?: number | undefined; - - constructor(data?: IKDEAggregateParameters) { - super(data); - this._discriminator = "KDEAggregateParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.nrOfSamples = data["NrOfSamples"]; - } - } - - static fromJS(data: any): KDEAggregateParameters { - data = typeof data === 'object' ? data : {}; - let result = new KDEAggregateParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["NrOfSamples"] = this.nrOfSamples; - super.toJSON(data); - return data; - } -} - -export interface IKDEAggregateParameters extends ISingleDimensionAggregateParameters { - nrOfSamples?: number | undefined; -} - -export class MarginAggregateParameters extends SingleDimensionAggregateParameters implements IMarginAggregateParameters { - aggregateFunction?: AggregateFunction | undefined; - - constructor(data?: IMarginAggregateParameters) { - super(data); - this._discriminator = "MarginAggregateParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.aggregateFunction = data["AggregateFunction"]; - } - } - - static fromJS(data: any): MarginAggregateParameters { - data = typeof data === 'object' ? data : {}; - let result = new MarginAggregateParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["AggregateFunction"] = this.aggregateFunction; - super.toJSON(data); - return data; - } -} - -export interface IMarginAggregateParameters extends ISingleDimensionAggregateParameters { - aggregateFunction?: AggregateFunction | undefined; -} - -export class MaxAggregateParameters extends SingleDimensionAggregateParameters implements IMaxAggregateParameters { - - constructor(data?: IMaxAggregateParameters) { - super(data); - this._discriminator = "MaxAggregateParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): MaxAggregateParameters { - data = typeof data === 'object' ? data : {}; - let result = new MaxAggregateParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface IMaxAggregateParameters extends ISingleDimensionAggregateParameters { -} - -export class MinAggregateParameters extends SingleDimensionAggregateParameters implements IMinAggregateParameters { - - constructor(data?: IMinAggregateParameters) { - super(data); - this._discriminator = "MinAggregateParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): MinAggregateParameters { - data = typeof data === 'object' ? data : {}; - let result = new MinAggregateParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface IMinAggregateParameters extends ISingleDimensionAggregateParameters { -} - -export class SumAggregateParameters extends SingleDimensionAggregateParameters implements ISumAggregateParameters { - - constructor(data?: ISumAggregateParameters) { - super(data); - this._discriminator = "SumAggregateParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): SumAggregateParameters { - data = typeof data === 'object' ? data : {}; - let result = new SumAggregateParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface ISumAggregateParameters extends ISingleDimensionAggregateParameters { -} - -export class SumEstimationAggregateParameters extends SingleDimensionAggregateParameters implements ISumEstimationAggregateParameters { - - constructor(data?: ISumEstimationAggregateParameters) { - super(data); - this._discriminator = "SumEstimationAggregateParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): SumEstimationAggregateParameters { - data = typeof data === 'object' ? data : {}; - let result = new SumEstimationAggregateParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface ISumEstimationAggregateParameters extends ISingleDimensionAggregateParameters { -} - -export enum OrderingFunction { - None = 0, - SortUp = 1, - SortDown = 2, -} - -export abstract class BinningParameters implements IBinningParameters { - attributeParameters?: AttributeParameters | undefined; - - protected _discriminator: string; - - constructor(data?: IBinningParameters) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - this._discriminator = "BinningParameters"; - } - - init(data?: any) { - if (data) { - this.attributeParameters = data["AttributeParameters"] ? AttributeParameters.fromJS(data["AttributeParameters"]) : undefined; - } - } - - static fromJS(data: any): BinningParameters { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "EquiWidthBinningParameters") { - let result = new EquiWidthBinningParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "SingleBinBinningParameters") { - let result = new SingleBinBinningParameters(); - result.init(data); - return result; - } - throw new Error("The abstract class 'BinningParameters' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["discriminator"] = this._discriminator; - data["AttributeParameters"] = this.attributeParameters ? this.attributeParameters.toJSON() : undefined; - return data; - } -} - -export interface IBinningParameters { - attributeParameters?: AttributeParameters | undefined; -} - -export class EquiWidthBinningParameters extends BinningParameters implements IEquiWidthBinningParameters { - minValue?: number | undefined; - maxValue?: number | undefined; - requestedNrOfBins?: number | undefined; - referenceValue?: number | undefined; - step?: number | undefined; - - constructor(data?: IEquiWidthBinningParameters) { - super(data); - this._discriminator = "EquiWidthBinningParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.minValue = data["MinValue"]; - this.maxValue = data["MaxValue"]; - this.requestedNrOfBins = data["RequestedNrOfBins"]; - this.referenceValue = data["ReferenceValue"]; - this.step = data["Step"]; - } - } - - static fromJS(data: any): EquiWidthBinningParameters { - data = typeof data === 'object' ? data : {}; - let result = new EquiWidthBinningParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["MinValue"] = this.minValue; - data["MaxValue"] = this.maxValue; - data["RequestedNrOfBins"] = this.requestedNrOfBins; - data["ReferenceValue"] = this.referenceValue; - data["Step"] = this.step; - super.toJSON(data); - return data; - } -} - -export interface IEquiWidthBinningParameters extends IBinningParameters { - minValue?: number | undefined; - maxValue?: number | undefined; - requestedNrOfBins?: number | undefined; - referenceValue?: number | undefined; - step?: number | undefined; -} - -export class SingleBinBinningParameters extends BinningParameters implements ISingleBinBinningParameters { - - constructor(data?: ISingleBinBinningParameters) { - super(data); - this._discriminator = "SingleBinBinningParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): SingleBinBinningParameters { - data = typeof data === 'object' ? data : {}; - let result = new SingleBinBinningParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface ISingleBinBinningParameters extends IBinningParameters { -} - -export class Attribute implements IAttribute { - displayName?: string | undefined; - rawName?: string | undefined; - description?: string | undefined; - dataType?: DataType | undefined; - visualizationHints?: VisualizationHint[] | undefined; - isTarget?: boolean | undefined; - - constructor(data?: IAttribute) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.displayName = data["DisplayName"]; - this.rawName = data["RawName"]; - this.description = data["Description"]; - this.dataType = data["DataType"]; - if (data["VisualizationHints"] && data["VisualizationHints"].constructor === Array) { - this.visualizationHints = []; - for (let item of data["VisualizationHints"]) - this.visualizationHints.push(item); - } - this.isTarget = data["IsTarget"]; - } - } - - static fromJS(data: any): Attribute { - data = typeof data === 'object' ? data : {}; - let result = new Attribute(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["DisplayName"] = this.displayName; - data["RawName"] = this.rawName; - data["Description"] = this.description; - data["DataType"] = this.dataType; - if (this.visualizationHints && this.visualizationHints.constructor === Array) { - data["VisualizationHints"] = []; - for (let item of this.visualizationHints) - data["VisualizationHints"].push(item); - } - data["IsTarget"] = this.isTarget; - return data; - } -} - -export interface IAttribute { - displayName?: string | undefined; - rawName?: string | undefined; - description?: string | undefined; - dataType?: DataType | undefined; - visualizationHints?: VisualizationHint[] | undefined; - isTarget?: boolean | undefined; -} - -export enum DataType { - Int = "Int", - String = "String", - Float = "Float", - Double = "Double", - DateTime = "DateTime", - Object = "Object", - Undefined = "Undefined", -} - -export class AttributeGroup implements IAttributeGroup { - name?: string | undefined; - attributeGroups?: AttributeGroup[] | undefined; - attributes?: Attribute[] | undefined; - - constructor(data?: IAttributeGroup) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.name = data["Name"]; - if (data["AttributeGroups"] && data["AttributeGroups"].constructor === Array) { - this.attributeGroups = []; - for (let item of data["AttributeGroups"]) - this.attributeGroups.push(AttributeGroup.fromJS(item)); - } - if (data["Attributes"] && data["Attributes"].constructor === Array) { - this.attributes = []; - for (let item of data["Attributes"]) - this.attributes.push(Attribute.fromJS(item)); - } - } - } - - static fromJS(data: any): AttributeGroup { - data = typeof data === 'object' ? data : {}; - let result = new AttributeGroup(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Name"] = this.name; - if (this.attributeGroups && this.attributeGroups.constructor === Array) { - data["AttributeGroups"] = []; - for (let item of this.attributeGroups) - data["AttributeGroups"].push(item.toJSON()); - } - if (this.attributes && this.attributes.constructor === Array) { - data["Attributes"] = []; - for (let item of this.attributes) - data["Attributes"].push(item.toJSON()); - } - return data; - } -} - -export interface IAttributeGroup { - name?: string | undefined; - attributeGroups?: AttributeGroup[] | undefined; - attributes?: Attribute[] | undefined; -} - -export class Catalog implements ICatalog { - supportedOperations?: string[] | undefined; - schemas?: Schema[] | undefined; - - constructor(data?: ICatalog) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - if (data["SupportedOperations"] && data["SupportedOperations"].constructor === Array) { - this.supportedOperations = []; - for (let item of data["SupportedOperations"]) - this.supportedOperations.push(item); - } - if (data["Schemas"] && data["Schemas"].constructor === Array) { - this.schemas = []; - for (let item of data["Schemas"]) - this.schemas.push(Schema.fromJS(item)); - } - } - } - - static fromJS(data: any): Catalog { - data = typeof data === 'object' ? data : {}; - let result = new Catalog(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.supportedOperations && this.supportedOperations.constructor === Array) { - data["SupportedOperations"] = []; - for (let item of this.supportedOperations) - data["SupportedOperations"].push(item); - } - if (this.schemas && this.schemas.constructor === Array) { - data["Schemas"] = []; - for (let item of this.schemas) - data["Schemas"].push(item.toJSON()); - } - return data; - } -} - -export interface ICatalog { - supportedOperations?: string[] | undefined; - schemas?: Schema[] | undefined; -} - -export class Schema implements ISchema { - rootAttributeGroup?: AttributeGroup | undefined; - displayName?: string | undefined; - augmentedFrom?: string | undefined; - rawName?: string | undefined; - problemDescription?: string | undefined; - darpaProblemDoc?: DarpaProblemDoc | undefined; - distinctAttributeParameters?: AttributeParameters | undefined; - darpaDatasetDoc?: DarpaDatasetDoc | undefined; - darpaDatasetLocation?: string | undefined; - isMultiResourceData?: boolean | undefined; - problemFinderRows?: ProblemFinderRows[] | undefined; - correlationRows?: ProblemFinderRows[] | undefined; - - constructor(data?: ISchema) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.rootAttributeGroup = data["RootAttributeGroup"] ? AttributeGroup.fromJS(data["RootAttributeGroup"]) : undefined; - this.displayName = data["DisplayName"]; - this.augmentedFrom = data["AugmentedFrom"]; - this.rawName = data["RawName"]; - this.problemDescription = data["ProblemDescription"]; - this.darpaProblemDoc = data["DarpaProblemDoc"] ? DarpaProblemDoc.fromJS(data["DarpaProblemDoc"]) : undefined; - this.distinctAttributeParameters = data["DistinctAttributeParameters"] ? AttributeParameters.fromJS(data["DistinctAttributeParameters"]) : undefined; - this.darpaDatasetDoc = data["DarpaDatasetDoc"] ? DarpaDatasetDoc.fromJS(data["DarpaDatasetDoc"]) : undefined; - this.darpaDatasetLocation = data["DarpaDatasetLocation"]; - this.isMultiResourceData = data["IsMultiResourceData"]; - if (data["ProblemFinderRows"] && data["ProblemFinderRows"].constructor === Array) { - this.problemFinderRows = []; - for (let item of data["ProblemFinderRows"]) - this.problemFinderRows.push(ProblemFinderRows.fromJS(item)); - } - if (data["CorrelationRows"] && data["CorrelationRows"].constructor === Array) { - this.correlationRows = []; - for (let item of data["CorrelationRows"]) - this.correlationRows.push(ProblemFinderRows.fromJS(item)); - } - } - } - - static fromJS(data: any): Schema { - data = typeof data === 'object' ? data : {}; - let result = new Schema(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["RootAttributeGroup"] = this.rootAttributeGroup ? this.rootAttributeGroup.toJSON() : undefined; - data["DisplayName"] = this.displayName; - data["AugmentedFrom"] = this.augmentedFrom; - data["RawName"] = this.rawName; - data["ProblemDescription"] = this.problemDescription; - data["DarpaProblemDoc"] = this.darpaProblemDoc ? this.darpaProblemDoc.toJSON() : undefined; - data["DistinctAttributeParameters"] = this.distinctAttributeParameters ? this.distinctAttributeParameters.toJSON() : undefined; - data["DarpaDatasetDoc"] = this.darpaDatasetDoc ? this.darpaDatasetDoc.toJSON() : undefined; - data["DarpaDatasetLocation"] = this.darpaDatasetLocation; - data["IsMultiResourceData"] = this.isMultiResourceData; - if (this.problemFinderRows && this.problemFinderRows.constructor === Array) { - data["ProblemFinderRows"] = []; - for (let item of this.problemFinderRows) - data["ProblemFinderRows"].push(item.toJSON()); - } - if (this.correlationRows && this.correlationRows.constructor === Array) { - data["CorrelationRows"] = []; - for (let item of this.correlationRows) - data["CorrelationRows"].push(item.toJSON()); - } - return data; - } -} - -export interface ISchema { - rootAttributeGroup?: AttributeGroup | undefined; - displayName?: string | undefined; - augmentedFrom?: string | undefined; - rawName?: string | undefined; - problemDescription?: string | undefined; - darpaProblemDoc?: DarpaProblemDoc | undefined; - distinctAttributeParameters?: AttributeParameters | undefined; - darpaDatasetDoc?: DarpaDatasetDoc | undefined; - darpaDatasetLocation?: string | undefined; - isMultiResourceData?: boolean | undefined; - problemFinderRows?: ProblemFinderRows[] | undefined; - correlationRows?: ProblemFinderRows[] | undefined; -} - -export class DarpaProblemDoc implements IDarpaProblemDoc { - about?: ProblemAbout | undefined; - inputs?: ProblemInputs | undefined; - - constructor(data?: IDarpaProblemDoc) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.about = data["about"] ? ProblemAbout.fromJS(data["about"]) : undefined; - this.inputs = data["inputs"] ? ProblemInputs.fromJS(data["inputs"]) : undefined; - } - } - - static fromJS(data: any): DarpaProblemDoc { - data = typeof data === 'object' ? data : {}; - let result = new DarpaProblemDoc(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["about"] = this.about ? this.about.toJSON() : undefined; - data["inputs"] = this.inputs ? this.inputs.toJSON() : undefined; - return data; - } -} - -export interface IDarpaProblemDoc { - about?: ProblemAbout | undefined; - inputs?: ProblemInputs | undefined; -} - -export class ProblemAbout implements IProblemAbout { - problemID?: string | undefined; - problemName?: string | undefined; - problemDescription?: string | undefined; - taskType?: string | undefined; - taskSubType?: string | undefined; - problemSchemaVersion?: string | undefined; - problemVersion?: string | undefined; - - constructor(data?: IProblemAbout) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.problemID = data["problemID"]; - this.problemName = data["problemName"]; - this.problemDescription = data["problemDescription"]; - this.taskType = data["taskType"]; - this.taskSubType = data["taskSubType"]; - this.problemSchemaVersion = data["problemSchemaVersion"]; - this.problemVersion = data["problemVersion"]; - } - } - - static fromJS(data: any): ProblemAbout { - data = typeof data === 'object' ? data : {}; - let result = new ProblemAbout(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["problemID"] = this.problemID; - data["problemName"] = this.problemName; - data["problemDescription"] = this.problemDescription; - data["taskType"] = this.taskType; - data["taskSubType"] = this.taskSubType; - data["problemSchemaVersion"] = this.problemSchemaVersion; - data["problemVersion"] = this.problemVersion; - return data; - } -} - -export interface IProblemAbout { - problemID?: string | undefined; - problemName?: string | undefined; - problemDescription?: string | undefined; - taskType?: string | undefined; - taskSubType?: string | undefined; - problemSchemaVersion?: string | undefined; - problemVersion?: string | undefined; -} - -export class ProblemInputs implements IProblemInputs { - data?: ProblemData[] | undefined; - performanceMetrics?: ProblemPerformanceMetric[] | undefined; - - constructor(data?: IProblemInputs) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - if (data["data"] && data["data"].constructor === Array) { - this.data = []; - for (let item of data["data"]) - this.data.push(ProblemData.fromJS(item)); - } - if (data["performanceMetrics"] && data["performanceMetrics"].constructor === Array) { - this.performanceMetrics = []; - for (let item of data["performanceMetrics"]) - this.performanceMetrics.push(ProblemPerformanceMetric.fromJS(item)); - } - } - } - - static fromJS(data: any): ProblemInputs { - data = typeof data === 'object' ? data : {}; - let result = new ProblemInputs(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.data && this.data.constructor === Array) { - data["data"] = []; - for (let item of this.data) - data["data"].push(item.toJSON()); - } - if (this.performanceMetrics && this.performanceMetrics.constructor === Array) { - data["performanceMetrics"] = []; - for (let item of this.performanceMetrics) - data["performanceMetrics"].push(item.toJSON()); - } - return data; - } -} - -export interface IProblemInputs { - data?: ProblemData[] | undefined; - performanceMetrics?: ProblemPerformanceMetric[] | undefined; -} - -export class ProblemData implements IProblemData { - datasetID?: string | undefined; - targets?: ProblemTarget[] | undefined; - - constructor(data?: IProblemData) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.datasetID = data["datasetID"]; - if (data["targets"] && data["targets"].constructor === Array) { - this.targets = []; - for (let item of data["targets"]) - this.targets.push(ProblemTarget.fromJS(item)); - } - } - } - - static fromJS(data: any): ProblemData { - data = typeof data === 'object' ? data : {}; - let result = new ProblemData(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["datasetID"] = this.datasetID; - if (this.targets && this.targets.constructor === Array) { - data["targets"] = []; - for (let item of this.targets) - data["targets"].push(item.toJSON()); - } - return data; - } -} - -export interface IProblemData { - datasetID?: string | undefined; - targets?: ProblemTarget[] | undefined; -} - -export class ProblemTarget implements IProblemTarget { - targetIndex?: number | undefined; - resID?: string | undefined; - colIndex?: number | undefined; - colName?: string | undefined; - - constructor(data?: IProblemTarget) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.targetIndex = data["targetIndex"]; - this.resID = data["resID"]; - this.colIndex = data["colIndex"]; - this.colName = data["colName"]; - } - } - - static fromJS(data: any): ProblemTarget { - data = typeof data === 'object' ? data : {}; - let result = new ProblemTarget(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["targetIndex"] = this.targetIndex; - data["resID"] = this.resID; - data["colIndex"] = this.colIndex; - data["colName"] = this.colName; - return data; - } -} - -export interface IProblemTarget { - targetIndex?: number | undefined; - resID?: string | undefined; - colIndex?: number | undefined; - colName?: string | undefined; -} - -export class ProblemPerformanceMetric implements IProblemPerformanceMetric { - metric?: string | undefined; - - constructor(data?: IProblemPerformanceMetric) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.metric = data["metric"]; - } - } - - static fromJS(data: any): ProblemPerformanceMetric { - data = typeof data === 'object' ? data : {}; - let result = new ProblemPerformanceMetric(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["metric"] = this.metric; - return data; - } -} - -export interface IProblemPerformanceMetric { - metric?: string | undefined; -} - -export class DarpaDatasetDoc implements IDarpaDatasetDoc { - about?: DatasetAbout | undefined; - dataResources?: Resource[] | undefined; - - constructor(data?: IDarpaDatasetDoc) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.about = data["about"] ? DatasetAbout.fromJS(data["about"]) : undefined; - if (data["dataResources"] && data["dataResources"].constructor === Array) { - this.dataResources = []; - for (let item of data["dataResources"]) - this.dataResources.push(Resource.fromJS(item)); - } - } - } - - static fromJS(data: any): DarpaDatasetDoc { - data = typeof data === 'object' ? data : {}; - let result = new DarpaDatasetDoc(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["about"] = this.about ? this.about.toJSON() : undefined; - if (this.dataResources && this.dataResources.constructor === Array) { - data["dataResources"] = []; - for (let item of this.dataResources) - data["dataResources"].push(item.toJSON()); - } - return data; - } -} - -export interface IDarpaDatasetDoc { - about?: DatasetAbout | undefined; - dataResources?: Resource[] | undefined; -} - -export class DatasetAbout implements IDatasetAbout { - datasetID?: string | undefined; - datasetName?: string | undefined; - description?: string | undefined; - citation?: string | undefined; - license?: string | undefined; - source?: string | undefined; - sourceURI?: string | undefined; - approximateSize?: string | undefined; - datasetSchemaVersion?: string | undefined; - redacted?: boolean | undefined; - datasetVersion?: string | undefined; - - constructor(data?: IDatasetAbout) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.datasetID = data["datasetID"]; - this.datasetName = data["datasetName"]; - this.description = data["description"]; - this.citation = data["citation"]; - this.license = data["license"]; - this.source = data["source"]; - this.sourceURI = data["sourceURI"]; - this.approximateSize = data["approximateSize"]; - this.datasetSchemaVersion = data["datasetSchemaVersion"]; - this.redacted = data["redacted"]; - this.datasetVersion = data["datasetVersion"]; - } - } - - static fromJS(data: any): DatasetAbout { - data = typeof data === 'object' ? data : {}; - let result = new DatasetAbout(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["datasetID"] = this.datasetID; - data["datasetName"] = this.datasetName; - data["description"] = this.description; - data["citation"] = this.citation; - data["license"] = this.license; - data["source"] = this.source; - data["sourceURI"] = this.sourceURI; - data["approximateSize"] = this.approximateSize; - data["datasetSchemaVersion"] = this.datasetSchemaVersion; - data["redacted"] = this.redacted; - data["datasetVersion"] = this.datasetVersion; - return data; - } -} - -export interface IDatasetAbout { - datasetID?: string | undefined; - datasetName?: string | undefined; - description?: string | undefined; - citation?: string | undefined; - license?: string | undefined; - source?: string | undefined; - sourceURI?: string | undefined; - approximateSize?: string | undefined; - datasetSchemaVersion?: string | undefined; - redacted?: boolean | undefined; - datasetVersion?: string | undefined; -} - -export class Resource implements IResource { - resID?: string | undefined; - resPath?: string | undefined; - resType?: string | undefined; - resFormat?: string[] | undefined; - columns?: Column[] | undefined; - isCollection?: boolean | undefined; - - constructor(data?: IResource) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.resID = data["resID"]; - this.resPath = data["resPath"]; - this.resType = data["resType"]; - if (data["resFormat"] && data["resFormat"].constructor === Array) { - this.resFormat = []; - for (let item of data["resFormat"]) - this.resFormat.push(item); - } - if (data["columns"] && data["columns"].constructor === Array) { - this.columns = []; - for (let item of data["columns"]) - this.columns.push(Column.fromJS(item)); - } - this.isCollection = data["isCollection"]; - } - } - - static fromJS(data: any): Resource { - data = typeof data === 'object' ? data : {}; - let result = new Resource(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["resID"] = this.resID; - data["resPath"] = this.resPath; - data["resType"] = this.resType; - if (this.resFormat && this.resFormat.constructor === Array) { - data["resFormat"] = []; - for (let item of this.resFormat) - data["resFormat"].push(item); - } - if (this.columns && this.columns.constructor === Array) { - data["columns"] = []; - for (let item of this.columns) - data["columns"].push(item.toJSON()); - } - data["isCollection"] = this.isCollection; - return data; - } -} - -export interface IResource { - resID?: string | undefined; - resPath?: string | undefined; - resType?: string | undefined; - resFormat?: string[] | undefined; - columns?: Column[] | undefined; - isCollection?: boolean | undefined; -} - -export class Column implements IColumn { - colIndex?: number | undefined; - colDescription?: string | undefined; - colName?: string | undefined; - colType?: string | undefined; - role?: string[] | undefined; - refersTo?: Reference | undefined; - - constructor(data?: IColumn) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.colIndex = data["colIndex"]; - this.colDescription = data["colDescription"]; - this.colName = data["colName"]; - this.colType = data["colType"]; - if (data["role"] && data["role"].constructor === Array) { - this.role = []; - for (let item of data["role"]) - this.role.push(item); - } - this.refersTo = data["refersTo"] ? Reference.fromJS(data["refersTo"]) : undefined; - } - } - - static fromJS(data: any): Column { - data = typeof data === 'object' ? data : {}; - let result = new Column(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["colIndex"] = this.colIndex; - data["colDescription"] = this.colDescription; - data["colName"] = this.colName; - data["colType"] = this.colType; - if (this.role && this.role.constructor === Array) { - data["role"] = []; - for (let item of this.role) - data["role"].push(item); - } - data["refersTo"] = this.refersTo ? this.refersTo.toJSON() : undefined; - return data; - } -} - -export interface IColumn { - colIndex?: number | undefined; - colDescription?: string | undefined; - colName?: string | undefined; - colType?: string | undefined; - role?: string[] | undefined; - refersTo?: Reference | undefined; -} - -export class Reference implements IReference { - resID?: string | undefined; - - constructor(data?: IReference) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.resID = data["resID"]; - } - } - - static fromJS(data: any): Reference { - data = typeof data === 'object' ? data : {}; - let result = new Reference(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["resID"] = this.resID; - return data; - } -} - -export interface IReference { - resID?: string | undefined; -} - -export class ProblemFinderRows implements IProblemFinderRows { - label?: string | undefined; - type?: string | undefined; - features?: Feature[] | undefined; - - constructor(data?: IProblemFinderRows) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.label = data["label"]; - this.type = data["type"]; - if (data["features"] && data["features"].constructor === Array) { - this.features = []; - for (let item of data["features"]) - this.features.push(Feature.fromJS(item)); - } - } - } - - static fromJS(data: any): ProblemFinderRows { - data = typeof data === 'object' ? data : {}; - let result = new ProblemFinderRows(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["label"] = this.label; - data["type"] = this.type; - if (this.features && this.features.constructor === Array) { - data["features"] = []; - for (let item of this.features) - data["features"].push(item.toJSON()); - } - return data; - } -} - -export interface IProblemFinderRows { - label?: string | undefined; - type?: string | undefined; - features?: Feature[] | undefined; -} - -export class Feature implements IFeature { - name?: string | undefined; - selected?: boolean | undefined; - value?: number | undefined; - - constructor(data?: IFeature) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.name = data["name"]; - this.selected = data["selected"]; - this.value = data["value"]; - } - } - - static fromJS(data: any): Feature { - data = typeof data === 'object' ? data : {}; - let result = new Feature(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["name"] = this.name; - data["selected"] = this.selected; - data["value"] = this.value; - return data; - } -} - -export interface IFeature { - name?: string | undefined; - selected?: boolean | undefined; - value?: number | undefined; -} - -export enum DataType2 { - Int = 0, - String = 1, - Float = 2, - Double = 3, - DateTime = 4, - Object = 5, - Undefined = 6, -} - -export abstract class DataTypeExtensions implements IDataTypeExtensions { - - constructor(data?: IDataTypeExtensions) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - } - } - - static fromJS(data: any): DataTypeExtensions { - data = typeof data === 'object' ? data : {}; - throw new Error("The abstract class 'DataTypeExtensions' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - return data; - } -} - -export interface IDataTypeExtensions { -} - -export class ResObject implements IResObject { - columnName?: string | undefined; - - constructor(data?: IResObject) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.columnName = data["columnName"]; - } - } - - static fromJS(data: any): ResObject { - data = typeof data === 'object' ? data : {}; - let result = new ResObject(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["columnName"] = this.columnName; - return data; - } -} - -export interface IResObject { - columnName?: string | undefined; -} - -export class Exception implements IException { - message?: string | undefined; - innerException?: Exception | undefined; - stackTrace?: string | undefined; - source?: string | undefined; - - constructor(data?: IException) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.message = data["Message"]; - this.innerException = data["InnerException"] ? Exception.fromJS(data["InnerException"]) : undefined; - this.stackTrace = data["StackTrace"]; - this.source = data["Source"]; - } - } - - static fromJS(data: any): Exception { - data = typeof data === 'object' ? data : {}; - let result = new Exception(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Message"] = this.message; - data["InnerException"] = this.innerException ? this.innerException.toJSON() : undefined; - data["StackTrace"] = this.stackTrace; - data["Source"] = this.source; - return data; - } -} - -export interface IException { - message?: string | undefined; - innerException?: Exception | undefined; - stackTrace?: string | undefined; - source?: string | undefined; -} - -export class IDEAException extends Exception implements IIDEAException { - - constructor(data?: IIDEAException) { - super(data); - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): IDEAException { - data = typeof data === 'object' ? data : {}; - let result = new IDEAException(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface IIDEAException extends IException { -} - -export class CodeParameters implements ICodeParameters { - attributeCodeParameters?: AttributeCodeParameters[] | undefined; - adapterName?: string | undefined; - - constructor(data?: ICodeParameters) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - if (data["AttributeCodeParameters"] && data["AttributeCodeParameters"].constructor === Array) { - this.attributeCodeParameters = []; - for (let item of data["AttributeCodeParameters"]) - this.attributeCodeParameters.push(AttributeCodeParameters.fromJS(item)); - } - this.adapterName = data["AdapterName"]; - } - } - - static fromJS(data: any): CodeParameters { - data = typeof data === 'object' ? data : {}; - let result = new CodeParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.attributeCodeParameters && this.attributeCodeParameters.constructor === Array) { - data["AttributeCodeParameters"] = []; - for (let item of this.attributeCodeParameters) - data["AttributeCodeParameters"].push(item.toJSON()); - } - data["AdapterName"] = this.adapterName; - return data; - } -} - -export interface ICodeParameters { - attributeCodeParameters?: AttributeCodeParameters[] | undefined; - adapterName?: string | undefined; -} - -export class CompileResult implements ICompileResult { - compileSuccess?: boolean | undefined; - compileMessage?: string | undefined; - dataType?: DataType | undefined; - replaceAttributeParameters?: AttributeParameters[] | undefined; - - constructor(data?: ICompileResult) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.compileSuccess = data["CompileSuccess"]; - this.compileMessage = data["CompileMessage"]; - this.dataType = data["DataType"]; - if (data["ReplaceAttributeParameters"] && data["ReplaceAttributeParameters"].constructor === Array) { - this.replaceAttributeParameters = []; - for (let item of data["ReplaceAttributeParameters"]) - this.replaceAttributeParameters.push(AttributeParameters.fromJS(item)); - } - } - } - - static fromJS(data: any): CompileResult { - data = typeof data === 'object' ? data : {}; - let result = new CompileResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["CompileSuccess"] = this.compileSuccess; - data["CompileMessage"] = this.compileMessage; - data["DataType"] = this.dataType; - if (this.replaceAttributeParameters && this.replaceAttributeParameters.constructor === Array) { - data["ReplaceAttributeParameters"] = []; - for (let item of this.replaceAttributeParameters) - data["ReplaceAttributeParameters"].push(item.toJSON()); - } - return data; - } -} - -export interface ICompileResult { - compileSuccess?: boolean | undefined; - compileMessage?: string | undefined; - dataType?: DataType | undefined; - replaceAttributeParameters?: AttributeParameters[] | undefined; -} - -export class CompileResults implements ICompileResults { - rawNameToCompileResult?: { [key: string]: CompileResult; } | undefined; - - constructor(data?: ICompileResults) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - if (data["RawNameToCompileResult"]) { - this.rawNameToCompileResult = {}; - for (let key in data["RawNameToCompileResult"]) { - if (data["RawNameToCompileResult"].hasOwnProperty(key)) - this.rawNameToCompileResult[key] = data["RawNameToCompileResult"][key] ? CompileResult.fromJS(data["RawNameToCompileResult"][key]) : new CompileResult(); - } - } - } - } - - static fromJS(data: any): CompileResults { - data = typeof data === 'object' ? data : {}; - let result = new CompileResults(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.rawNameToCompileResult) { - data["RawNameToCompileResult"] = {}; - for (let key in this.rawNameToCompileResult) { - if (this.rawNameToCompileResult.hasOwnProperty(key)) - data["RawNameToCompileResult"][key] = this.rawNameToCompileResult[key]; - } - } - return data; - } -} - -export interface ICompileResults { - rawNameToCompileResult?: { [key: string]: CompileResult; } | undefined; -} - -export abstract class UniqueJson implements IUniqueJson { - - constructor(data?: IUniqueJson) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - } - } - - static fromJS(data: any): UniqueJson { - data = typeof data === 'object' ? data : {}; - throw new Error("The abstract class 'UniqueJson' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - return data; - } -} - -export interface IUniqueJson { -} - -export abstract class OperationParameters extends UniqueJson implements IOperationParameters { - isCachable?: boolean | undefined; - - protected _discriminator: string; - - constructor(data?: IOperationParameters) { - super(data); - this._discriminator = "OperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.isCachable = data["IsCachable"]; - } - } - - static fromJS(data: any): OperationParameters { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "DataOperationParameters") { - throw new Error("The abstract class 'DataOperationParameters' cannot be instantiated."); - } - if (data["discriminator"] === "ExampleOperationParameters") { - let result = new ExampleOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "HistogramOperationParameters") { - let result = new HistogramOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "DistOperationParameters") { - throw new Error("The abstract class 'DistOperationParameters' cannot be instantiated."); - } - if (data["discriminator"] === "OptimizerOperationParameters") { - let result = new OptimizerOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "RawDataOperationParameters") { - let result = new RawDataOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "RecommenderOperationParameters") { - let result = new RecommenderOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "CDFOperationParameters") { - let result = new CDFOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "TestDistOperationParameters") { - throw new Error("The abstract class 'TestDistOperationParameters' cannot be instantiated."); - } - if (data["discriminator"] === "ChiSquaredTestOperationParameters") { - let result = new ChiSquaredTestOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "HypothesisTestParameters") { - throw new Error("The abstract class 'HypothesisTestParameters' cannot be instantiated."); - } - if (data["discriminator"] === "CorrelationTestOperationParameters") { - let result = new CorrelationTestOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "EmpiricalDistOperationParameters") { - let result = new EmpiricalDistOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "KSTestOperationParameters") { - let result = new KSTestOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "NewModelOperationParameters") { - let result = new NewModelOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "ModelOperationParameters") { - throw new Error("The abstract class 'ModelOperationParameters' cannot be instantiated."); - } - if (data["discriminator"] === "RootMeanSquareTestOperationParameters") { - let result = new RootMeanSquareTestOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "TTestOperationParameters") { - let result = new TTestOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "FeatureImportanceOperationParameters") { - let result = new FeatureImportanceOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "SampleOperationParameters") { - let result = new SampleOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "AddComparisonParameters") { - let result = new AddComparisonParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "GetModelStateParameters") { - let result = new GetModelStateParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "FrequentItemsetOperationParameters") { - let result = new FrequentItemsetOperationParameters(); - result.init(data); - return result; - } - throw new Error("The abstract class 'OperationParameters' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["discriminator"] = this._discriminator; - data["IsCachable"] = this.isCachable; - super.toJSON(data); - return data; - } -} - -export interface IOperationParameters extends IUniqueJson { - isCachable?: boolean | undefined; -} - -export abstract class DataOperationParameters extends OperationParameters implements IDataOperationParameters { - sampleStreamBlockSize?: number | undefined; - adapterName?: string | undefined; - isCachable?: boolean | undefined; - - constructor(data?: IDataOperationParameters) { - super(data); - this._discriminator = "DataOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.sampleStreamBlockSize = data["SampleStreamBlockSize"]; - this.adapterName = data["AdapterName"]; - this.isCachable = data["IsCachable"]; - } - } - - static fromJS(data: any): DataOperationParameters { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "ExampleOperationParameters") { - let result = new ExampleOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "HistogramOperationParameters") { - let result = new HistogramOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "DistOperationParameters") { - throw new Error("The abstract class 'DistOperationParameters' cannot be instantiated."); - } - if (data["discriminator"] === "OptimizerOperationParameters") { - let result = new OptimizerOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "RawDataOperationParameters") { - let result = new RawDataOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "RecommenderOperationParameters") { - let result = new RecommenderOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "CDFOperationParameters") { - let result = new CDFOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "TestDistOperationParameters") { - throw new Error("The abstract class 'TestDistOperationParameters' cannot be instantiated."); - } - if (data["discriminator"] === "EmpiricalDistOperationParameters") { - let result = new EmpiricalDistOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "FeatureImportanceOperationParameters") { - let result = new FeatureImportanceOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "SampleOperationParameters") { - let result = new SampleOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "FrequentItemsetOperationParameters") { - let result = new FrequentItemsetOperationParameters(); - result.init(data); - return result; - } - throw new Error("The abstract class 'DataOperationParameters' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["SampleStreamBlockSize"] = this.sampleStreamBlockSize; - data["AdapterName"] = this.adapterName; - data["IsCachable"] = this.isCachable; - super.toJSON(data); - return data; - } -} - -export interface IDataOperationParameters extends IOperationParameters { - sampleStreamBlockSize?: number | undefined; - adapterName?: string | undefined; - isCachable?: boolean | undefined; -} - -export class ExampleOperationParameters extends DataOperationParameters implements IExampleOperationParameters { - filter?: string | undefined; - attributeParameters?: AttributeParameters[] | undefined; - attributeCodeParameters?: AttributeCaclculatedParameters[] | undefined; - dummyValue?: number | undefined; - exampleType?: string | undefined; - - constructor(data?: IExampleOperationParameters) { - super(data); - this._discriminator = "ExampleOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.filter = data["Filter"]; - if (data["AttributeParameters"] && data["AttributeParameters"].constructor === Array) { - this.attributeParameters = []; - for (let item of data["AttributeParameters"]) - this.attributeParameters.push(AttributeParameters.fromJS(item)); - } - if (data["AttributeCodeParameters"] && data["AttributeCodeParameters"].constructor === Array) { - this.attributeCodeParameters = []; - for (let item of data["AttributeCodeParameters"]) - this.attributeCodeParameters.push(AttributeCaclculatedParameters.fromJS(item)); - } - this.dummyValue = data["DummyValue"]; - this.exampleType = data["ExampleType"]; - } - } - - static fromJS(data: any): ExampleOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new ExampleOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Filter"] = this.filter; - if (this.attributeParameters && this.attributeParameters.constructor === Array) { - data["AttributeParameters"] = []; - for (let item of this.attributeParameters) - data["AttributeParameters"].push(item.toJSON()); - } - if (this.attributeCodeParameters && this.attributeCodeParameters.constructor === Array) { - data["AttributeCodeParameters"] = []; - for (let item of this.attributeCodeParameters) - data["AttributeCodeParameters"].push(item.toJSON()); - } - data["DummyValue"] = this.dummyValue; - data["ExampleType"] = this.exampleType; - super.toJSON(data); - return data; - } -} - -export interface IExampleOperationParameters extends IDataOperationParameters { - filter?: string | undefined; - attributeParameters?: AttributeParameters[] | undefined; - attributeCodeParameters?: AttributeCaclculatedParameters[] | undefined; - dummyValue?: number | undefined; - exampleType?: string | undefined; -} - -export abstract class DistOperationParameters extends DataOperationParameters implements IDistOperationParameters { - filter?: string | undefined; - attributeCalculatedParameters?: AttributeCaclculatedParameters[] | undefined; - - constructor(data?: IDistOperationParameters) { - super(data); - this._discriminator = "DistOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.filter = data["Filter"]; - if (data["AttributeCalculatedParameters"] && data["AttributeCalculatedParameters"].constructor === Array) { - this.attributeCalculatedParameters = []; - for (let item of data["AttributeCalculatedParameters"]) - this.attributeCalculatedParameters.push(AttributeCaclculatedParameters.fromJS(item)); - } - } - } - - static fromJS(data: any): DistOperationParameters { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "HistogramOperationParameters") { - let result = new HistogramOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "OptimizerOperationParameters") { - let result = new OptimizerOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "RawDataOperationParameters") { - let result = new RawDataOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "CDFOperationParameters") { - let result = new CDFOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "TestDistOperationParameters") { - throw new Error("The abstract class 'TestDistOperationParameters' cannot be instantiated."); - } - if (data["discriminator"] === "EmpiricalDistOperationParameters") { - let result = new EmpiricalDistOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "FeatureImportanceOperationParameters") { - let result = new FeatureImportanceOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "SampleOperationParameters") { - let result = new SampleOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "FrequentItemsetOperationParameters") { - let result = new FrequentItemsetOperationParameters(); - result.init(data); - return result; - } - throw new Error("The abstract class 'DistOperationParameters' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Filter"] = this.filter; - if (this.attributeCalculatedParameters && this.attributeCalculatedParameters.constructor === Array) { - data["AttributeCalculatedParameters"] = []; - for (let item of this.attributeCalculatedParameters) - data["AttributeCalculatedParameters"].push(item.toJSON()); - } - super.toJSON(data); - return data; - } -} - -export interface IDistOperationParameters extends IDataOperationParameters { - filter?: string | undefined; - attributeCalculatedParameters?: AttributeCaclculatedParameters[] | undefined; -} - -export class HistogramOperationParameters extends DistOperationParameters implements IHistogramOperationParameters { - sortPerBinAggregateParameter?: AggregateParameters | undefined; - binningParameters?: BinningParameters[] | undefined; - perBinAggregateParameters?: AggregateParameters[] | undefined; - globalAggregateParameters?: AggregateParameters[] | undefined; - brushes?: string[] | undefined; - enableBrushComputation?: boolean | undefined; - degreeOfParallism?: number | undefined; - - constructor(data?: IHistogramOperationParameters) { - super(data); - this._discriminator = "HistogramOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.sortPerBinAggregateParameter = data["SortPerBinAggregateParameter"] ? AggregateParameters.fromJS(data["SortPerBinAggregateParameter"]) : undefined; - if (data["BinningParameters"] && data["BinningParameters"].constructor === Array) { - this.binningParameters = []; - for (let item of data["BinningParameters"]) - this.binningParameters.push(BinningParameters.fromJS(item)); - } - if (data["PerBinAggregateParameters"] && data["PerBinAggregateParameters"].constructor === Array) { - this.perBinAggregateParameters = []; - for (let item of data["PerBinAggregateParameters"]) - this.perBinAggregateParameters.push(AggregateParameters.fromJS(item)); - } - if (data["GlobalAggregateParameters"] && data["GlobalAggregateParameters"].constructor === Array) { - this.globalAggregateParameters = []; - for (let item of data["GlobalAggregateParameters"]) - this.globalAggregateParameters.push(AggregateParameters.fromJS(item)); - } - if (data["Brushes"] && data["Brushes"].constructor === Array) { - this.brushes = []; - for (let item of data["Brushes"]) - this.brushes.push(item); - } - this.enableBrushComputation = data["EnableBrushComputation"]; - this.degreeOfParallism = data["DegreeOfParallism"]; - } - } - - static fromJS(data: any): HistogramOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new HistogramOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["SortPerBinAggregateParameter"] = this.sortPerBinAggregateParameter ? this.sortPerBinAggregateParameter.toJSON() : undefined; - if (this.binningParameters && this.binningParameters.constructor === Array) { - data["BinningParameters"] = []; - for (let item of this.binningParameters) - data["BinningParameters"].push(item.toJSON()); - } - if (this.perBinAggregateParameters && this.perBinAggregateParameters.constructor === Array) { - data["PerBinAggregateParameters"] = []; - for (let item of this.perBinAggregateParameters) - data["PerBinAggregateParameters"].push(item.toJSON()); - } - if (this.globalAggregateParameters && this.globalAggregateParameters.constructor === Array) { - data["GlobalAggregateParameters"] = []; - for (let item of this.globalAggregateParameters) - data["GlobalAggregateParameters"].push(item.toJSON()); - } - if (this.brushes && this.brushes.constructor === Array) { - data["Brushes"] = []; - for (let item of this.brushes) - data["Brushes"].push(item); - } - data["EnableBrushComputation"] = this.enableBrushComputation; - data["DegreeOfParallism"] = this.degreeOfParallism; - super.toJSON(data); - return data; - } -} - -export interface IHistogramOperationParameters extends IDistOperationParameters { - sortPerBinAggregateParameter?: AggregateParameters | undefined; - binningParameters?: BinningParameters[] | undefined; - perBinAggregateParameters?: AggregateParameters[] | undefined; - globalAggregateParameters?: AggregateParameters[] | undefined; - brushes?: string[] | undefined; - enableBrushComputation?: boolean | undefined; - degreeOfParallism?: number | undefined; -} - -export class OptimizerOperationParameters extends DistOperationParameters implements IOptimizerOperationParameters { - taskType?: TaskType | undefined; - taskSubType?: TaskSubType | undefined; - metricType?: MetricType | undefined; - labelAttribute?: AttributeParameters | undefined; - featureAttributes?: AttributeParameters[] | undefined; - requiredPrimitives?: string[] | undefined; - pythonFilter?: string | undefined; - trainFilter?: string | undefined; - pythonTrainFilter?: string | undefined; - testFilter?: string | undefined; - pythonTestFilter?: string | undefined; - - constructor(data?: IOptimizerOperationParameters) { - super(data); - this._discriminator = "OptimizerOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.taskType = data["TaskType"]; - this.taskSubType = data["TaskSubType"]; - this.metricType = data["MetricType"]; - this.labelAttribute = data["LabelAttribute"] ? AttributeParameters.fromJS(data["LabelAttribute"]) : undefined; - if (data["FeatureAttributes"] && data["FeatureAttributes"].constructor === Array) { - this.featureAttributes = []; - for (let item of data["FeatureAttributes"]) - this.featureAttributes.push(AttributeParameters.fromJS(item)); - } - if (data["RequiredPrimitives"] && data["RequiredPrimitives"].constructor === Array) { - this.requiredPrimitives = []; - for (let item of data["RequiredPrimitives"]) - this.requiredPrimitives.push(item); - } - this.pythonFilter = data["PythonFilter"]; - this.trainFilter = data["TrainFilter"]; - this.pythonTrainFilter = data["PythonTrainFilter"]; - this.testFilter = data["TestFilter"]; - this.pythonTestFilter = data["PythonTestFilter"]; - } - } - - static fromJS(data: any): OptimizerOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new OptimizerOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["TaskType"] = this.taskType; - data["TaskSubType"] = this.taskSubType; - data["MetricType"] = this.metricType; - data["LabelAttribute"] = this.labelAttribute ? this.labelAttribute.toJSON() : undefined; - if (this.featureAttributes && this.featureAttributes.constructor === Array) { - data["FeatureAttributes"] = []; - for (let item of this.featureAttributes) - data["FeatureAttributes"].push(item.toJSON()); - } - if (this.requiredPrimitives && this.requiredPrimitives.constructor === Array) { - data["RequiredPrimitives"] = []; - for (let item of this.requiredPrimitives) - data["RequiredPrimitives"].push(item); - } - data["PythonFilter"] = this.pythonFilter; - data["TrainFilter"] = this.trainFilter; - data["PythonTrainFilter"] = this.pythonTrainFilter; - data["TestFilter"] = this.testFilter; - data["PythonTestFilter"] = this.pythonTestFilter; - super.toJSON(data); - return data; - } -} - -export interface IOptimizerOperationParameters extends IDistOperationParameters { - taskType?: TaskType | undefined; - taskSubType?: TaskSubType | undefined; - metricType?: MetricType | undefined; - labelAttribute?: AttributeParameters | undefined; - featureAttributes?: AttributeParameters[] | undefined; - requiredPrimitives?: string[] | undefined; - pythonFilter?: string | undefined; - trainFilter?: string | undefined; - pythonTrainFilter?: string | undefined; - testFilter?: string | undefined; - pythonTestFilter?: string | undefined; -} - -export enum TaskType { - Undefined = 0, - Classification = 1, - Regression = 2, - Clustering = 3, - LinkPrediction = 4, - VertexNomination = 5, - CommunityDetection = 6, - GraphClustering = 7, - GraphMatching = 8, - TimeSeriesForecasting = 9, - CollaborativeFiltering = 10, -} - -export enum TaskSubType { - Undefined = 0, - None = 1, - Binary = 2, - Multiclass = 3, - Multilabel = 4, - Univariate = 5, - Multivariate = 6, - Overlapping = 7, - Nonoverlapping = 8, -} - -export enum MetricType { - MetricUndefined = 0, - Accuracy = 1, - Precision = 2, - Recall = 3, - F1 = 4, - F1Micro = 5, - F1Macro = 6, - RocAuc = 7, - RocAucMicro = 8, - RocAucMacro = 9, - MeanSquaredError = 10, - RootMeanSquaredError = 11, - RootMeanSquaredErrorAvg = 12, - MeanAbsoluteError = 13, - RSquared = 14, - NormalizedMutualInformation = 15, - JaccardSimilarityScore = 16, - PrecisionAtTopK = 17, - ObjectDetectionAveragePrecision = 18, - Loss = 100, -} - -export class RawDataOperationParameters extends DistOperationParameters implements IRawDataOperationParameters { - sortUpRawName?: string | undefined; - sortDownRawName?: string | undefined; - numRecords?: number | undefined; - binningParameters?: BinningParameters[] | undefined; - brushes?: string[] | undefined; - enableBrushComputation?: boolean | undefined; - - constructor(data?: IRawDataOperationParameters) { - super(data); - this._discriminator = "RawDataOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.sortUpRawName = data["SortUpRawName"]; - this.sortDownRawName = data["SortDownRawName"]; - this.numRecords = data["NumRecords"]; - if (data["BinningParameters"] && data["BinningParameters"].constructor === Array) { - this.binningParameters = []; - for (let item of data["BinningParameters"]) - this.binningParameters.push(BinningParameters.fromJS(item)); - } - if (data["Brushes"] && data["Brushes"].constructor === Array) { - this.brushes = []; - for (let item of data["Brushes"]) - this.brushes.push(item); - } - this.enableBrushComputation = data["EnableBrushComputation"]; - } - } - - static fromJS(data: any): RawDataOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new RawDataOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["SortUpRawName"] = this.sortUpRawName; - data["SortDownRawName"] = this.sortDownRawName; - data["NumRecords"] = this.numRecords; - if (this.binningParameters && this.binningParameters.constructor === Array) { - data["BinningParameters"] = []; - for (let item of this.binningParameters) - data["BinningParameters"].push(item.toJSON()); - } - if (this.brushes && this.brushes.constructor === Array) { - data["Brushes"] = []; - for (let item of this.brushes) - data["Brushes"].push(item); - } - data["EnableBrushComputation"] = this.enableBrushComputation; - super.toJSON(data); - return data; - } -} - -export interface IRawDataOperationParameters extends IDistOperationParameters { - sortUpRawName?: string | undefined; - sortDownRawName?: string | undefined; - numRecords?: number | undefined; - binningParameters?: BinningParameters[] | undefined; - brushes?: string[] | undefined; - enableBrushComputation?: boolean | undefined; -} - -export class RecommenderOperationParameters extends DataOperationParameters implements IRecommenderOperationParameters { - target?: HistogramOperationParameters | undefined; - budget?: number | undefined; - modelId?: ModelId | undefined; - includeAttributeParameters?: AttributeParameters[] | undefined; - excludeAttributeParameters?: AttributeParameters[] | undefined; - riskControlType?: RiskControlType | undefined; - - constructor(data?: IRecommenderOperationParameters) { - super(data); - this._discriminator = "RecommenderOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.target = data["Target"] ? HistogramOperationParameters.fromJS(data["Target"]) : undefined; - this.budget = data["Budget"]; - this.modelId = data["ModelId"] ? ModelId.fromJS(data["ModelId"]) : undefined; - if (data["IncludeAttributeParameters"] && data["IncludeAttributeParameters"].constructor === Array) { - this.includeAttributeParameters = []; - for (let item of data["IncludeAttributeParameters"]) - this.includeAttributeParameters.push(AttributeParameters.fromJS(item)); - } - if (data["ExcludeAttributeParameters"] && data["ExcludeAttributeParameters"].constructor === Array) { - this.excludeAttributeParameters = []; - for (let item of data["ExcludeAttributeParameters"]) - this.excludeAttributeParameters.push(AttributeParameters.fromJS(item)); - } - this.riskControlType = data["RiskControlType"]; - } - } - - static fromJS(data: any): RecommenderOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new RecommenderOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Target"] = this.target ? this.target.toJSON() : undefined; - data["Budget"] = this.budget; - data["ModelId"] = this.modelId ? this.modelId.toJSON() : undefined; - if (this.includeAttributeParameters && this.includeAttributeParameters.constructor === Array) { - data["IncludeAttributeParameters"] = []; - for (let item of this.includeAttributeParameters) - data["IncludeAttributeParameters"].push(item.toJSON()); - } - if (this.excludeAttributeParameters && this.excludeAttributeParameters.constructor === Array) { - data["ExcludeAttributeParameters"] = []; - for (let item of this.excludeAttributeParameters) - data["ExcludeAttributeParameters"].push(item.toJSON()); - } - data["RiskControlType"] = this.riskControlType; - super.toJSON(data); - return data; - } -} - -export interface IRecommenderOperationParameters extends IDataOperationParameters { - target?: HistogramOperationParameters | undefined; - budget?: number | undefined; - modelId?: ModelId | undefined; - includeAttributeParameters?: AttributeParameters[] | undefined; - excludeAttributeParameters?: AttributeParameters[] | undefined; - riskControlType?: RiskControlType | undefined; -} - -export class ModelId implements IModelId { - value?: string | undefined; - - constructor(data?: IModelId) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.value = data["Value"]; - } - } - - static fromJS(data: any): ModelId { - data = typeof data === 'object' ? data : {}; - let result = new ModelId(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Value"] = this.value; - return data; - } -} - -export interface IModelId { - value?: string | undefined; -} - -export enum RiskControlType { - PCER = 0, - Bonferroni = 1, - AdaBonferroni = 2, - HolmBonferroni = 3, - BHFDR = 4, - SeqFDR = 5, - AlphaFDR = 6, - BestFootForward = 7, - BetaFarsighted = 8, - BetaFarsightedWithSupport = 9, - GammaFixed = 10, - DeltaHopeful = 11, - EpsilonHybrid = 12, - EpsilonHybridWithoutSupport = 13, - PsiSupport = 14, - ZetaDynamic = 15, - Unknown = 16, -} - -export abstract class TestDistOperationParameters extends DistOperationParameters implements ITestDistOperationParameters { - attributeParameters?: AttributeParameters[] | undefined; - - constructor(data?: ITestDistOperationParameters) { - super(data); - this._discriminator = "TestDistOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["AttributeParameters"] && data["AttributeParameters"].constructor === Array) { - this.attributeParameters = []; - for (let item of data["AttributeParameters"]) - this.attributeParameters.push(AttributeParameters.fromJS(item)); - } - } - } - - static fromJS(data: any): TestDistOperationParameters { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "CDFOperationParameters") { - let result = new CDFOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "EmpiricalDistOperationParameters") { - let result = new EmpiricalDistOperationParameters(); - result.init(data); - return result; - } - throw new Error("The abstract class 'TestDistOperationParameters' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.attributeParameters && this.attributeParameters.constructor === Array) { - data["AttributeParameters"] = []; - for (let item of this.attributeParameters) - data["AttributeParameters"].push(item.toJSON()); - } - super.toJSON(data); - return data; - } -} - -export interface ITestDistOperationParameters extends IDistOperationParameters { - attributeParameters?: AttributeParameters[] | undefined; -} - -export class CDFOperationParameters extends TestDistOperationParameters implements ICDFOperationParameters { - - constructor(data?: ICDFOperationParameters) { - super(data); - this._discriminator = "CDFOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): CDFOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new CDFOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface ICDFOperationParameters extends ITestDistOperationParameters { -} - -export abstract class HypothesisTestParameters extends OperationParameters implements IHypothesisTestParameters { - childOperationParameters?: OperationParameters[] | undefined; - isCachable?: boolean | undefined; - - constructor(data?: IHypothesisTestParameters) { - super(data); - this._discriminator = "HypothesisTestParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["ChildOperationParameters"] && data["ChildOperationParameters"].constructor === Array) { - this.childOperationParameters = []; - for (let item of data["ChildOperationParameters"]) - this.childOperationParameters.push(OperationParameters.fromJS(item)); - } - this.isCachable = data["IsCachable"]; - } - } - - static fromJS(data: any): HypothesisTestParameters { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "ChiSquaredTestOperationParameters") { - let result = new ChiSquaredTestOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "CorrelationTestOperationParameters") { - let result = new CorrelationTestOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "KSTestOperationParameters") { - let result = new KSTestOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "RootMeanSquareTestOperationParameters") { - let result = new RootMeanSquareTestOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "TTestOperationParameters") { - let result = new TTestOperationParameters(); - result.init(data); - return result; - } - throw new Error("The abstract class 'HypothesisTestParameters' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.childOperationParameters && this.childOperationParameters.constructor === Array) { - data["ChildOperationParameters"] = []; - for (let item of this.childOperationParameters) - data["ChildOperationParameters"].push(item.toJSON()); - } - data["IsCachable"] = this.isCachable; - super.toJSON(data); - return data; - } -} - -export interface IHypothesisTestParameters extends IOperationParameters { - childOperationParameters?: OperationParameters[] | undefined; - isCachable?: boolean | undefined; -} - -export class ChiSquaredTestOperationParameters extends HypothesisTestParameters implements IChiSquaredTestOperationParameters { - - constructor(data?: IChiSquaredTestOperationParameters) { - super(data); - this._discriminator = "ChiSquaredTestOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): ChiSquaredTestOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new ChiSquaredTestOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface IChiSquaredTestOperationParameters extends IHypothesisTestParameters { -} - -export class CorrelationTestOperationParameters extends HypothesisTestParameters implements ICorrelationTestOperationParameters { - - constructor(data?: ICorrelationTestOperationParameters) { - super(data); - this._discriminator = "CorrelationTestOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): CorrelationTestOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new CorrelationTestOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface ICorrelationTestOperationParameters extends IHypothesisTestParameters { -} - -export class SubmitProblemParameters implements ISubmitProblemParameters { - id?: string | undefined; - - constructor(data?: ISubmitProblemParameters) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.id = data["Id"]; - } - } - - static fromJS(data: any): SubmitProblemParameters { - data = typeof data === 'object' ? data : {}; - let result = new SubmitProblemParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Id"] = this.id; - return data; - } -} - -export interface ISubmitProblemParameters { - id?: string | undefined; -} - -export class SpecifyProblemParameters implements ISpecifyProblemParameters { - id?: string | undefined; - userComment?: string | undefined; - optimizerOperationParameters?: OptimizerOperationParameters | undefined; - - constructor(data?: ISpecifyProblemParameters) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.id = data["Id"]; - this.userComment = data["UserComment"]; - this.optimizerOperationParameters = data["OptimizerOperationParameters"] ? OptimizerOperationParameters.fromJS(data["OptimizerOperationParameters"]) : undefined; - } - } - - static fromJS(data: any): SpecifyProblemParameters { - data = typeof data === 'object' ? data : {}; - let result = new SpecifyProblemParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Id"] = this.id; - data["UserComment"] = this.userComment; - data["OptimizerOperationParameters"] = this.optimizerOperationParameters ? this.optimizerOperationParameters.toJSON() : undefined; - return data; - } -} - -export interface ISpecifyProblemParameters { - id?: string | undefined; - userComment?: string | undefined; - optimizerOperationParameters?: OptimizerOperationParameters | undefined; -} - -export class EmpiricalDistOperationParameters extends TestDistOperationParameters implements IEmpiricalDistOperationParameters { - keepSamples?: boolean | undefined; - - constructor(data?: IEmpiricalDistOperationParameters) { - super(data); - this._discriminator = "EmpiricalDistOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.keepSamples = data["KeepSamples"]; - } - } - - static fromJS(data: any): EmpiricalDistOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new EmpiricalDistOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["KeepSamples"] = this.keepSamples; - super.toJSON(data); - return data; - } -} - -export interface IEmpiricalDistOperationParameters extends ITestDistOperationParameters { - keepSamples?: boolean | undefined; -} - -export class KSTestOperationParameters extends HypothesisTestParameters implements IKSTestOperationParameters { - - constructor(data?: IKSTestOperationParameters) { - super(data); - this._discriminator = "KSTestOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): KSTestOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new KSTestOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface IKSTestOperationParameters extends IHypothesisTestParameters { -} - -export abstract class ModelOperationParameters extends OperationParameters implements IModelOperationParameters { - - constructor(data?: IModelOperationParameters) { - super(data); - this._discriminator = "ModelOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): ModelOperationParameters { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "NewModelOperationParameters") { - let result = new NewModelOperationParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "AddComparisonParameters") { - let result = new AddComparisonParameters(); - result.init(data); - return result; - } - if (data["discriminator"] === "GetModelStateParameters") { - let result = new GetModelStateParameters(); - result.init(data); - return result; - } - throw new Error("The abstract class 'ModelOperationParameters' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface IModelOperationParameters extends IOperationParameters { -} - -export class NewModelOperationParameters extends ModelOperationParameters implements INewModelOperationParameters { - riskControlTypes?: RiskControlType[] | undefined; - alpha?: number | undefined; - alphaInvestParameter?: AlphaInvestParameter | undefined; - - constructor(data?: INewModelOperationParameters) { - super(data); - this._discriminator = "NewModelOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["RiskControlTypes"] && data["RiskControlTypes"].constructor === Array) { - this.riskControlTypes = []; - for (let item of data["RiskControlTypes"]) - this.riskControlTypes.push(item); - } - this.alpha = data["Alpha"]; - this.alphaInvestParameter = data["AlphaInvestParameter"] ? AlphaInvestParameter.fromJS(data["AlphaInvestParameter"]) : undefined; - } - } - - static fromJS(data: any): NewModelOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new NewModelOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.riskControlTypes && this.riskControlTypes.constructor === Array) { - data["RiskControlTypes"] = []; - for (let item of this.riskControlTypes) - data["RiskControlTypes"].push(item); - } - data["Alpha"] = this.alpha; - data["AlphaInvestParameter"] = this.alphaInvestParameter ? this.alphaInvestParameter.toJSON() : undefined; - super.toJSON(data); - return data; - } -} - -export interface INewModelOperationParameters extends IModelOperationParameters { - riskControlTypes?: RiskControlType[] | undefined; - alpha?: number | undefined; - alphaInvestParameter?: AlphaInvestParameter | undefined; -} - -export class AlphaInvestParameter extends UniqueJson implements IAlphaInvestParameter { - beta?: number | undefined; - gamma?: number | undefined; - delta?: number | undefined; - epsilon?: number | undefined; - windowSize?: number | undefined; - psi?: number | undefined; - - constructor(data?: IAlphaInvestParameter) { - super(data); - } - - init(data?: any) { - super.init(data); - if (data) { - this.beta = data["Beta"]; - this.gamma = data["Gamma"]; - this.delta = data["Delta"]; - this.epsilon = data["Epsilon"]; - this.windowSize = data["WindowSize"]; - this.psi = data["Psi"]; - } - } - - static fromJS(data: any): AlphaInvestParameter { - data = typeof data === 'object' ? data : {}; - let result = new AlphaInvestParameter(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Beta"] = this.beta; - data["Gamma"] = this.gamma; - data["Delta"] = this.delta; - data["Epsilon"] = this.epsilon; - data["WindowSize"] = this.windowSize; - data["Psi"] = this.psi; - super.toJSON(data); - return data; - } -} - -export interface IAlphaInvestParameter extends IUniqueJson { - beta?: number | undefined; - gamma?: number | undefined; - delta?: number | undefined; - epsilon?: number | undefined; - windowSize?: number | undefined; - psi?: number | undefined; -} - -export class RootMeanSquareTestOperationParameters extends HypothesisTestParameters implements IRootMeanSquareTestOperationParameters { - seeded?: boolean | undefined; - pValueConvergenceThreshold?: number | undefined; - maxSimulationBatchCount?: number | undefined; - perBatchSimulationCount?: number | undefined; - - constructor(data?: IRootMeanSquareTestOperationParameters) { - super(data); - this._discriminator = "RootMeanSquareTestOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.seeded = data["Seeded"]; - this.pValueConvergenceThreshold = data["PValueConvergenceThreshold"]; - this.maxSimulationBatchCount = data["MaxSimulationBatchCount"]; - this.perBatchSimulationCount = data["PerBatchSimulationCount"]; - } - } - - static fromJS(data: any): RootMeanSquareTestOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new RootMeanSquareTestOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Seeded"] = this.seeded; - data["PValueConvergenceThreshold"] = this.pValueConvergenceThreshold; - data["MaxSimulationBatchCount"] = this.maxSimulationBatchCount; - data["PerBatchSimulationCount"] = this.perBatchSimulationCount; - super.toJSON(data); - return data; - } -} - -export interface IRootMeanSquareTestOperationParameters extends IHypothesisTestParameters { - seeded?: boolean | undefined; - pValueConvergenceThreshold?: number | undefined; - maxSimulationBatchCount?: number | undefined; - perBatchSimulationCount?: number | undefined; -} - -export class TTestOperationParameters extends HypothesisTestParameters implements ITTestOperationParameters { - - constructor(data?: ITTestOperationParameters) { - super(data); - this._discriminator = "TTestOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): TTestOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new TTestOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface ITTestOperationParameters extends IHypothesisTestParameters { -} - -export enum EffectSize { - Small = 1, - Meduim = 2, - Large = 4, -} - -export abstract class Result extends UniqueJson implements IResult { - progress?: number | undefined; - - protected _discriminator: string; - - constructor(data?: IResult) { - super(data); - this._discriminator = "Result"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.progress = data["Progress"]; - } - } - - static fromJS(data: any): Result { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "ErrorResult") { - let result = new ErrorResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "HistogramResult") { - let result = new HistogramResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "DistResult") { - throw new Error("The abstract class 'DistResult' cannot be instantiated."); - } - if (data["discriminator"] === "ModelWealthResult") { - let result = new ModelWealthResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "HypothesisTestResult") { - throw new Error("The abstract class 'HypothesisTestResult' cannot be instantiated."); - } - if (data["discriminator"] === "ModelOperationResult") { - throw new Error("The abstract class 'ModelOperationResult' cannot be instantiated."); - } - if (data["discriminator"] === "RecommenderResult") { - let result = new RecommenderResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "Decision") { - let result = new Decision(); - result.init(data); - return result; - } - if (data["discriminator"] === "OptimizerResult") { - let result = new OptimizerResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "ExampleResult") { - let result = new ExampleResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "NewModelOperationResult") { - let result = new NewModelOperationResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "AddComparisonResult") { - let result = new AddComparisonResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "GetModelStateResult") { - let result = new GetModelStateResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "FeatureImportanceResult") { - let result = new FeatureImportanceResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "RawDataResult") { - let result = new RawDataResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "SampleResult") { - let result = new SampleResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "CDFResult") { - let result = new CDFResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "ChiSquaredTestResult") { - let result = new ChiSquaredTestResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "CorrelationTestResult") { - let result = new CorrelationTestResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "EmpiricalDistResult") { - let result = new EmpiricalDistResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "KSTestResult") { - let result = new KSTestResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "RootMeanSquareTestResult") { - let result = new RootMeanSquareTestResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "TTestResult") { - let result = new TTestResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "FrequentItemsetResult") { - let result = new FrequentItemsetResult(); - result.init(data); - return result; - } - throw new Error("The abstract class 'Result' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["discriminator"] = this._discriminator; - data["Progress"] = this.progress; - super.toJSON(data); - return data; - } -} - -export interface IResult extends IUniqueJson { - progress?: number | undefined; -} - -export class ErrorResult extends Result implements IErrorResult { - message?: string | undefined; - - constructor(data?: IErrorResult) { - super(data); - this._discriminator = "ErrorResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.message = data["Message"]; - } - } - - static fromJS(data: any): ErrorResult { - data = typeof data === 'object' ? data : {}; - let result = new ErrorResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Message"] = this.message; - super.toJSON(data); - return data; - } -} - -export interface IErrorResult extends IResult { - message?: string | undefined; -} - -export abstract class DistResult extends Result implements IDistResult { - sampleSize?: number | undefined; - populationSize?: number | undefined; - - constructor(data?: IDistResult) { - super(data); - this._discriminator = "DistResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.sampleSize = data["SampleSize"]; - this.populationSize = data["PopulationSize"]; - } - } - - static fromJS(data: any): DistResult { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "HistogramResult") { - let result = new HistogramResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "RawDataResult") { - let result = new RawDataResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "SampleResult") { - let result = new SampleResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "CDFResult") { - let result = new CDFResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "EmpiricalDistResult") { - let result = new EmpiricalDistResult(); - result.init(data); - return result; - } - throw new Error("The abstract class 'DistResult' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["SampleSize"] = this.sampleSize; - data["PopulationSize"] = this.populationSize; - super.toJSON(data); - return data; - } -} - -export interface IDistResult extends IResult { - sampleSize?: number | undefined; - populationSize?: number | undefined; -} - -export class HistogramResult extends DistResult implements IHistogramResult { - aggregateResults?: AggregateResult[][] | undefined; - isEmpty?: boolean | undefined; - brushes?: Brush[] | undefined; - binRanges?: BinRange[] | undefined; - aggregateParameters?: AggregateParameters[] | undefined; - nullValueCount?: number | undefined; - bins?: { [key: string]: Bin; } | undefined; - - constructor(data?: IHistogramResult) { - super(data); - this._discriminator = "HistogramResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["AggregateResults"] && data["AggregateResults"].constructor === Array) { - this.aggregateResults = []; - for (let item of data["AggregateResults"]) - this.aggregateResults.push(item); - } - this.isEmpty = data["IsEmpty"]; - if (data["Brushes"] && data["Brushes"].constructor === Array) { - this.brushes = []; - for (let item of data["Brushes"]) - this.brushes.push(Brush.fromJS(item)); - } - if (data["BinRanges"] && data["BinRanges"].constructor === Array) { - this.binRanges = []; - for (let item of data["BinRanges"]) - this.binRanges.push(BinRange.fromJS(item)); - } - if (data["AggregateParameters"] && data["AggregateParameters"].constructor === Array) { - this.aggregateParameters = []; - for (let item of data["AggregateParameters"]) - this.aggregateParameters.push(AggregateParameters.fromJS(item)); - } - this.nullValueCount = data["NullValueCount"]; - if (data["Bins"]) { - this.bins = {}; - for (let key in data["Bins"]) { - if (data["Bins"].hasOwnProperty(key)) - this.bins[key] = data["Bins"][key] ? Bin.fromJS(data["Bins"][key]) : new Bin(); - } - } - } - } - - static fromJS(data: any): HistogramResult { - data = typeof data === 'object' ? data : {}; - let result = new HistogramResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.aggregateResults && this.aggregateResults.constructor === Array) { - data["AggregateResults"] = []; - for (let item of this.aggregateResults) - data["AggregateResults"].push(item); - } - data["IsEmpty"] = this.isEmpty; - if (this.brushes && this.brushes.constructor === Array) { - data["Brushes"] = []; - for (let item of this.brushes) - data["Brushes"].push(item.toJSON()); - } - if (this.binRanges && this.binRanges.constructor === Array) { - data["BinRanges"] = []; - for (let item of this.binRanges) - data["BinRanges"].push(item.toJSON()); - } - if (this.aggregateParameters && this.aggregateParameters.constructor === Array) { - data["AggregateParameters"] = []; - for (let item of this.aggregateParameters) - data["AggregateParameters"].push(item.toJSON()); - } - data["NullValueCount"] = this.nullValueCount; - if (this.bins) { - data["Bins"] = {}; - for (let key in this.bins) { - if (this.bins.hasOwnProperty(key)) - data["Bins"][key] = this.bins[key]; - } - } - super.toJSON(data); - return data; - } -} - -export interface IHistogramResult extends IDistResult { - aggregateResults?: AggregateResult[][] | undefined; - isEmpty?: boolean | undefined; - brushes?: Brush[] | undefined; - binRanges?: BinRange[] | undefined; - aggregateParameters?: AggregateParameters[] | undefined; - nullValueCount?: number | undefined; - bins?: { [key: string]: Bin; } | undefined; -} - -export abstract class AggregateResult implements IAggregateResult { - hasResult?: boolean | undefined; - n?: number | undefined; - - protected _discriminator: string; - - constructor(data?: IAggregateResult) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - this._discriminator = "AggregateResult"; - } - - init(data?: any) { - if (data) { - this.hasResult = data["HasResult"]; - this.n = data["N"]; - } - } - - static fromJS(data: any): AggregateResult | undefined { - if (data === null || data === undefined) { - return undefined; - } - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "MarginAggregateResult") { - let result = new MarginAggregateResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "DoubleValueAggregateResult") { - let result = new DoubleValueAggregateResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "PointsAggregateResult") { - let result = new PointsAggregateResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "SumEstimationAggregateResult") { - let result = new SumEstimationAggregateResult(); - result.init(data); - return result; - } - throw new Error("The abstract class 'AggregateResult' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["discriminator"] = this._discriminator; - data["HasResult"] = this.hasResult; - data["N"] = this.n; - return data; - } -} - -export interface IAggregateResult { - hasResult?: boolean | undefined; - n?: number | undefined; -} - -export class MarginAggregateResult extends AggregateResult implements IMarginAggregateResult { - margin?: number | undefined; - absolutMargin?: number | undefined; - sumOfSquare?: number | undefined; - sampleStandardDeviation?: number | undefined; - mean?: number | undefined; - ex?: number | undefined; - ex2?: number | undefined; - variance?: number | undefined; - - constructor(data?: IMarginAggregateResult) { - super(data); - this._discriminator = "MarginAggregateResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.margin = data["Margin"]; - this.absolutMargin = data["AbsolutMargin"]; - this.sumOfSquare = data["SumOfSquare"]; - this.sampleStandardDeviation = data["SampleStandardDeviation"]; - this.mean = data["Mean"]; - this.ex = data["Ex"]; - this.ex2 = data["Ex2"]; - this.variance = data["Variance"]; - } - } - - static fromJS(data: any): MarginAggregateResult { - data = typeof data === 'object' ? data : {}; - let result = new MarginAggregateResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Margin"] = this.margin; - data["AbsolutMargin"] = this.absolutMargin; - data["SumOfSquare"] = this.sumOfSquare; - data["SampleStandardDeviation"] = this.sampleStandardDeviation; - data["Mean"] = this.mean; - data["Ex"] = this.ex; - data["Ex2"] = this.ex2; - data["Variance"] = this.variance; - super.toJSON(data); - return data; - } -} - -export interface IMarginAggregateResult extends IAggregateResult { - margin?: number | undefined; - absolutMargin?: number | undefined; - sumOfSquare?: number | undefined; - sampleStandardDeviation?: number | undefined; - mean?: number | undefined; - ex?: number | undefined; - ex2?: number | undefined; - variance?: number | undefined; -} - -export class DoubleValueAggregateResult extends AggregateResult implements IDoubleValueAggregateResult { - result?: number | undefined; - temporaryResult?: number | undefined; - - constructor(data?: IDoubleValueAggregateResult) { - super(data); - this._discriminator = "DoubleValueAggregateResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.result = data["Result"]; - this.temporaryResult = data["TemporaryResult"]; - } - } - - static fromJS(data: any): DoubleValueAggregateResult { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "SumEstimationAggregateResult") { - let result = new SumEstimationAggregateResult(); - result.init(data); - return result; - } - let result = new DoubleValueAggregateResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Result"] = this.result; - data["TemporaryResult"] = this.temporaryResult; - super.toJSON(data); - return data; - } -} - -export interface IDoubleValueAggregateResult extends IAggregateResult { - result?: number | undefined; - temporaryResult?: number | undefined; -} - -export class PointsAggregateResult extends AggregateResult implements IPointsAggregateResult { - points?: Point[] | undefined; - - constructor(data?: IPointsAggregateResult) { - super(data); - this._discriminator = "PointsAggregateResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["Points"] && data["Points"].constructor === Array) { - this.points = []; - for (let item of data["Points"]) - this.points.push(Point.fromJS(item)); - } - } - } - - static fromJS(data: any): PointsAggregateResult { - data = typeof data === 'object' ? data : {}; - let result = new PointsAggregateResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.points && this.points.constructor === Array) { - data["Points"] = []; - for (let item of this.points) - data["Points"].push(item.toJSON()); - } - super.toJSON(data); - return data; - } -} - -export interface IPointsAggregateResult extends IAggregateResult { - points?: Point[] | undefined; -} - -export class Point implements IPoint { - x?: number | undefined; - y?: number | undefined; - - constructor(data?: IPoint) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.x = data["X"]; - this.y = data["Y"]; - } - } - - static fromJS(data: any): Point { - data = typeof data === 'object' ? data : {}; - let result = new Point(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["X"] = this.x; - data["Y"] = this.y; - return data; - } -} - -export interface IPoint { - x?: number | undefined; - y?: number | undefined; -} - -export class SumEstimationAggregateResult extends DoubleValueAggregateResult implements ISumEstimationAggregateResult { - sum?: number | undefined; - sumEstimation?: number | undefined; - - constructor(data?: ISumEstimationAggregateResult) { - super(data); - this._discriminator = "SumEstimationAggregateResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.sum = data["Sum"]; - this.sumEstimation = data["SumEstimation"]; - } - } - - static fromJS(data: any): SumEstimationAggregateResult { - data = typeof data === 'object' ? data : {}; - let result = new SumEstimationAggregateResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Sum"] = this.sum; - data["SumEstimation"] = this.sumEstimation; - super.toJSON(data); - return data; - } -} - -export interface ISumEstimationAggregateResult extends IDoubleValueAggregateResult { - sum?: number | undefined; - sumEstimation?: number | undefined; -} - -export class Brush implements IBrush { - brushIndex?: number | undefined; - brushEnum?: BrushEnum | undefined; - - constructor(data?: IBrush) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.brushIndex = data["BrushIndex"]; - this.brushEnum = data["BrushEnum"]; - } - } - - static fromJS(data: any): Brush { - data = typeof data === 'object' ? data : {}; - let result = new Brush(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["BrushIndex"] = this.brushIndex; - data["BrushEnum"] = this.brushEnum; - return data; - } -} - -export interface IBrush { - brushIndex?: number | undefined; - brushEnum?: BrushEnum | undefined; -} - -export enum BrushEnum { - Overlap = 0, - Rest = 1, - All = 2, - UserSpecified = 3, -} - -export abstract class BinRange implements IBinRange { - minValue?: number | undefined; - maxValue?: number | undefined; - targetBinNumber?: number | undefined; - - protected _discriminator: string; - - constructor(data?: IBinRange) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - this._discriminator = "BinRange"; - } - - init(data?: any) { - if (data) { - this.minValue = data["MinValue"]; - this.maxValue = data["MaxValue"]; - this.targetBinNumber = data["TargetBinNumber"]; - } - } - - static fromJS(data: any): BinRange { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "NominalBinRange") { - let result = new NominalBinRange(); - result.init(data); - return result; - } - if (data["discriminator"] === "QuantitativeBinRange") { - let result = new QuantitativeBinRange(); - result.init(data); - return result; - } - if (data["discriminator"] === "AggregateBinRange") { - let result = new AggregateBinRange(); - result.init(data); - return result; - } - if (data["discriminator"] === "AlphabeticBinRange") { - let result = new AlphabeticBinRange(); - result.init(data); - return result; - } - if (data["discriminator"] === "DateTimeBinRange") { - let result = new DateTimeBinRange(); - result.init(data); - return result; - } - throw new Error("The abstract class 'BinRange' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["discriminator"] = this._discriminator; - data["MinValue"] = this.minValue; - data["MaxValue"] = this.maxValue; - data["TargetBinNumber"] = this.targetBinNumber; - return data; - } -} - -export interface IBinRange { - minValue?: number | undefined; - maxValue?: number | undefined; - targetBinNumber?: number | undefined; -} - -export class NominalBinRange extends BinRange implements INominalBinRange { - labelsValue?: { [key: string]: number; } | undefined; - valuesLabel?: { [key: string]: string; } | undefined; - - constructor(data?: INominalBinRange) { - super(data); - this._discriminator = "NominalBinRange"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["LabelsValue"]) { - this.labelsValue = {}; - for (let key in data["LabelsValue"]) { - if (data["LabelsValue"].hasOwnProperty(key)) - this.labelsValue[key] = data["LabelsValue"][key]; - } - } - if (data["ValuesLabel"]) { - this.valuesLabel = {}; - for (let key in data["ValuesLabel"]) { - if (data["ValuesLabel"].hasOwnProperty(key)) - this.valuesLabel[key] = data["ValuesLabel"][key]; - } - } - } - } - - static fromJS(data: any): NominalBinRange { - data = typeof data === 'object' ? data : {}; - let result = new NominalBinRange(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.labelsValue) { - data["LabelsValue"] = {}; - for (let key in this.labelsValue) { - if (this.labelsValue.hasOwnProperty(key)) - data["LabelsValue"][key] = this.labelsValue[key]; - } - } - if (this.valuesLabel) { - data["ValuesLabel"] = {}; - for (let key in this.valuesLabel) { - if (this.valuesLabel.hasOwnProperty(key)) - data["ValuesLabel"][key] = this.valuesLabel[key]; - } - } - super.toJSON(data); - return data; - } -} - -export interface INominalBinRange extends IBinRange { - labelsValue?: { [key: string]: number; } | undefined; - valuesLabel?: { [key: string]: string; } | undefined; -} - -export class QuantitativeBinRange extends BinRange implements IQuantitativeBinRange { - isIntegerRange?: boolean | undefined; - step?: number | undefined; - - constructor(data?: IQuantitativeBinRange) { - super(data); - this._discriminator = "QuantitativeBinRange"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.isIntegerRange = data["IsIntegerRange"]; - this.step = data["Step"]; - } - } - - static fromJS(data: any): QuantitativeBinRange { - data = typeof data === 'object' ? data : {}; - let result = new QuantitativeBinRange(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["IsIntegerRange"] = this.isIntegerRange; - data["Step"] = this.step; - super.toJSON(data); - return data; - } -} - -export interface IQuantitativeBinRange extends IBinRange { - isIntegerRange?: boolean | undefined; - step?: number | undefined; -} - -export class AggregateBinRange extends BinRange implements IAggregateBinRange { - - constructor(data?: IAggregateBinRange) { - super(data); - this._discriminator = "AggregateBinRange"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): AggregateBinRange { - data = typeof data === 'object' ? data : {}; - let result = new AggregateBinRange(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface IAggregateBinRange extends IBinRange { -} - -export class AlphabeticBinRange extends BinRange implements IAlphabeticBinRange { - prefix?: string | undefined; - labelsValue?: { [key: string]: number; } | undefined; - valuesLabel?: { [key: string]: string; } | undefined; - - constructor(data?: IAlphabeticBinRange) { - super(data); - this._discriminator = "AlphabeticBinRange"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.prefix = data["Prefix"]; - if (data["LabelsValue"]) { - this.labelsValue = {}; - for (let key in data["LabelsValue"]) { - if (data["LabelsValue"].hasOwnProperty(key)) - this.labelsValue[key] = data["LabelsValue"][key]; - } - } - if (data["ValuesLabel"]) { - this.valuesLabel = {}; - for (let key in data["ValuesLabel"]) { - if (data["ValuesLabel"].hasOwnProperty(key)) - this.valuesLabel[key] = data["ValuesLabel"][key]; - } - } - } - } - - static fromJS(data: any): AlphabeticBinRange { - data = typeof data === 'object' ? data : {}; - let result = new AlphabeticBinRange(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Prefix"] = this.prefix; - if (this.labelsValue) { - data["LabelsValue"] = {}; - for (let key in this.labelsValue) { - if (this.labelsValue.hasOwnProperty(key)) - data["LabelsValue"][key] = this.labelsValue[key]; - } - } - if (this.valuesLabel) { - data["ValuesLabel"] = {}; - for (let key in this.valuesLabel) { - if (this.valuesLabel.hasOwnProperty(key)) - data["ValuesLabel"][key] = this.valuesLabel[key]; - } - } - super.toJSON(data); - return data; - } -} - -export interface IAlphabeticBinRange extends IBinRange { - prefix?: string | undefined; - labelsValue?: { [key: string]: number; } | undefined; - valuesLabel?: { [key: string]: string; } | undefined; -} - -export class DateTimeBinRange extends BinRange implements IDateTimeBinRange { - step?: DateTimeStep | undefined; - - constructor(data?: IDateTimeBinRange) { - super(data); - this._discriminator = "DateTimeBinRange"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.step = data["Step"] ? DateTimeStep.fromJS(data["Step"]) : undefined; - } - } - - static fromJS(data: any): DateTimeBinRange { - data = typeof data === 'object' ? data : {}; - let result = new DateTimeBinRange(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Step"] = this.step ? this.step.toJSON() : undefined; - super.toJSON(data); - return data; - } -} - -export interface IDateTimeBinRange extends IBinRange { - step?: DateTimeStep | undefined; -} - -export class DateTimeStep implements IDateTimeStep { - dateTimeStepGranularity?: DateTimeStepGranularity | undefined; - dateTimeStepValue?: number | undefined; - dateTimeStepMaxValue?: number | undefined; - - constructor(data?: IDateTimeStep) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.dateTimeStepGranularity = data["DateTimeStepGranularity"]; - this.dateTimeStepValue = data["DateTimeStepValue"]; - this.dateTimeStepMaxValue = data["DateTimeStepMaxValue"]; - } - } - - static fromJS(data: any): DateTimeStep { - data = typeof data === 'object' ? data : {}; - let result = new DateTimeStep(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["DateTimeStepGranularity"] = this.dateTimeStepGranularity; - data["DateTimeStepValue"] = this.dateTimeStepValue; - data["DateTimeStepMaxValue"] = this.dateTimeStepMaxValue; - return data; - } -} - -export interface IDateTimeStep { - dateTimeStepGranularity?: DateTimeStepGranularity | undefined; - dateTimeStepValue?: number | undefined; - dateTimeStepMaxValue?: number | undefined; -} - -export enum DateTimeStepGranularity { - Second = 0, - Minute = 1, - Hour = 2, - Day = 3, - Month = 4, - Year = 5, -} - -export class Bin implements IBin { - aggregateResults?: AggregateResult[] | undefined; - count?: number | undefined; - binIndex?: BinIndex | undefined; - spans?: Span[] | undefined; - xSize?: number | undefined; - ySize?: number | undefined; - - constructor(data?: IBin) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - if (data["AggregateResults"] && data["AggregateResults"].constructor === Array) { - this.aggregateResults = []; - for (let item of data["AggregateResults"]) { - let fromJs = AggregateResult.fromJS(item); - if (fromJs) - this.aggregateResults.push(fromJs); - } - } - this.count = data["Count"]; - this.binIndex = data["BinIndex"] ? BinIndex.fromJS(data["BinIndex"]) : undefined; - if (data["Spans"] && data["Spans"].constructor === Array) { - this.spans = []; - for (let item of data["Spans"]) - this.spans.push(Span.fromJS(item)); - } - this.xSize = data["XSize"]; - this.ySize = data["YSize"]; - } - } - - static fromJS(data: any): Bin { - data = typeof data === 'object' ? data : {}; - let result = new Bin(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.aggregateResults && this.aggregateResults.constructor === Array) { - data["AggregateResults"] = []; - for (let item of this.aggregateResults) - data["AggregateResults"].push(item.toJSON()); - } - data["Count"] = this.count; - data["BinIndex"] = this.binIndex ? this.binIndex.toJSON() : undefined; - if (this.spans && this.spans.constructor === Array) { - data["Spans"] = []; - for (let item of this.spans) - data["Spans"].push(item.toJSON()); - } - data["XSize"] = this.xSize; - data["YSize"] = this.ySize; - return data; - } -} - -export interface IBin { - aggregateResults?: AggregateResult[] | undefined; - count?: number | undefined; - binIndex?: BinIndex | undefined; - spans?: Span[] | undefined; - xSize?: number | undefined; - ySize?: number | undefined; -} - -export class BinIndex implements IBinIndex { - indices?: number[] | undefined; - flatIndex?: number | undefined; - - constructor(data?: IBinIndex) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - if (data["Indices"] && data["Indices"].constructor === Array) { - this.indices = []; - for (let item of data["Indices"]) - this.indices.push(item); - } - this.flatIndex = data["FlatIndex"]; - } - } - - static fromJS(data: any): BinIndex { - data = typeof data === 'object' ? data : {}; - let result = new BinIndex(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.indices && this.indices.constructor === Array) { - data["Indices"] = []; - for (let item of this.indices) - data["Indices"].push(item); - } - data["FlatIndex"] = this.flatIndex; - return data; - } -} - -export interface IBinIndex { - indices?: number[] | undefined; - flatIndex?: number | undefined; -} - -export class Span implements ISpan { - min?: number | undefined; - max?: number | undefined; - index?: number | undefined; - - constructor(data?: ISpan) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.min = data["Min"]; - this.max = data["Max"]; - this.index = data["Index"]; - } - } - - static fromJS(data: any): Span { - data = typeof data === 'object' ? data : {}; - let result = new Span(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Min"] = this.min; - data["Max"] = this.max; - data["Index"] = this.index; - return data; - } -} - -export interface ISpan { - min?: number | undefined; - max?: number | undefined; - index?: number | undefined; -} - -export class ModelWealthResult extends Result implements IModelWealthResult { - wealth?: number | undefined; - startWealth?: number | undefined; - - constructor(data?: IModelWealthResult) { - super(data); - this._discriminator = "ModelWealthResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.wealth = data["Wealth"]; - this.startWealth = data["StartWealth"]; - } - } - - static fromJS(data: any): ModelWealthResult { - data = typeof data === 'object' ? data : {}; - let result = new ModelWealthResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Wealth"] = this.wealth; - data["StartWealth"] = this.startWealth; - super.toJSON(data); - return data; - } -} - -export interface IModelWealthResult extends IResult { - wealth?: number | undefined; - startWealth?: number | undefined; -} - -export abstract class HypothesisTestResult extends Result implements IHypothesisTestResult { - pValue?: number | undefined; - statistic?: number | undefined; - support?: number | undefined; - sampleSizes?: number[] | undefined; - errorMessage?: string | undefined; - - constructor(data?: IHypothesisTestResult) { - super(data); - this._discriminator = "HypothesisTestResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.pValue = data["PValue"]; - this.statistic = data["Statistic"]; - this.support = data["Support"]; - if (data["SampleSizes"] && data["SampleSizes"].constructor === Array) { - this.sampleSizes = []; - for (let item of data["SampleSizes"]) - this.sampleSizes.push(item); - } - this.errorMessage = data["ErrorMessage"]; - } - } - - static fromJS(data: any): HypothesisTestResult { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "ChiSquaredTestResult") { - let result = new ChiSquaredTestResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "CorrelationTestResult") { - let result = new CorrelationTestResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "KSTestResult") { - let result = new KSTestResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "RootMeanSquareTestResult") { - let result = new RootMeanSquareTestResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "TTestResult") { - let result = new TTestResult(); - result.init(data); - return result; - } - throw new Error("The abstract class 'HypothesisTestResult' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["PValue"] = this.pValue; - data["Statistic"] = this.statistic; - data["Support"] = this.support; - if (this.sampleSizes && this.sampleSizes.constructor === Array) { - data["SampleSizes"] = []; - for (let item of this.sampleSizes) - data["SampleSizes"].push(item); - } - data["ErrorMessage"] = this.errorMessage; - super.toJSON(data); - return data; - } -} - -export interface IHypothesisTestResult extends IResult { - pValue?: number | undefined; - statistic?: number | undefined; - support?: number | undefined; - sampleSizes?: number[] | undefined; - errorMessage?: string | undefined; -} - -export abstract class ModelOperationResult extends Result implements IModelOperationResult { - modelId?: ModelId | undefined; - - constructor(data?: IModelOperationResult) { - super(data); - this._discriminator = "ModelOperationResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.modelId = data["ModelId"] ? ModelId.fromJS(data["ModelId"]) : undefined; - } - } - - static fromJS(data: any): ModelOperationResult { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "NewModelOperationResult") { - let result = new NewModelOperationResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "AddComparisonResult") { - let result = new AddComparisonResult(); - result.init(data); - return result; - } - if (data["discriminator"] === "GetModelStateResult") { - let result = new GetModelStateResult(); - result.init(data); - return result; - } - throw new Error("The abstract class 'ModelOperationResult' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["ModelId"] = this.modelId ? this.modelId.toJSON() : undefined; - super.toJSON(data); - return data; - } -} - -export interface IModelOperationResult extends IResult { - modelId?: ModelId | undefined; -} - -export class RecommenderResult extends Result implements IRecommenderResult { - recommendedHistograms?: RecommendedHistogram[] | undefined; - totalCount?: number | undefined; - - constructor(data?: IRecommenderResult) { - super(data); - this._discriminator = "RecommenderResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["RecommendedHistograms"] && data["RecommendedHistograms"].constructor === Array) { - this.recommendedHistograms = []; - for (let item of data["RecommendedHistograms"]) - this.recommendedHistograms.push(RecommendedHistogram.fromJS(item)); - } - this.totalCount = data["TotalCount"]; - } - } - - static fromJS(data: any): RecommenderResult { - data = typeof data === 'object' ? data : {}; - let result = new RecommenderResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.recommendedHistograms && this.recommendedHistograms.constructor === Array) { - data["RecommendedHistograms"] = []; - for (let item of this.recommendedHistograms) - data["RecommendedHistograms"].push(item.toJSON()); - } - data["TotalCount"] = this.totalCount; - super.toJSON(data); - return data; - } -} - -export interface IRecommenderResult extends IResult { - recommendedHistograms?: RecommendedHistogram[] | undefined; - totalCount?: number | undefined; -} - -export class RecommendedHistogram implements IRecommendedHistogram { - histogramResult?: HistogramResult | undefined; - selectedBinIndices?: BinIndex[] | undefined; - selections?: Selection[] | undefined; - pValue?: number | undefined; - significance?: boolean | undefined; - decision?: Decision | undefined; - effectSize?: number | undefined; - hypothesisTestResult?: HypothesisTestResult | undefined; - id?: string | undefined; - xAttribute?: Attribute | undefined; - yAttribute?: Attribute | undefined; - - constructor(data?: IRecommendedHistogram) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.histogramResult = data["HistogramResult"] ? HistogramResult.fromJS(data["HistogramResult"]) : undefined; - if (data["SelectedBinIndices"] && data["SelectedBinIndices"].constructor === Array) { - this.selectedBinIndices = []; - for (let item of data["SelectedBinIndices"]) - this.selectedBinIndices.push(BinIndex.fromJS(item)); - } - if (data["Selections"] && data["Selections"].constructor === Array) { - this.selections = []; - for (let item of data["Selections"]) - this.selections.push(Selection.fromJS(item)); - } - this.pValue = data["PValue"]; - this.significance = data["Significance"]; - this.decision = data["Decision"] ? Decision.fromJS(data["Decision"]) : undefined; - this.effectSize = data["EffectSize"]; - this.hypothesisTestResult = data["HypothesisTestResult"] ? HypothesisTestResult.fromJS(data["HypothesisTestResult"]) : undefined; - this.id = data["Id"]; - this.xAttribute = data["XAttribute"] ? Attribute.fromJS(data["XAttribute"]) : undefined; - this.yAttribute = data["YAttribute"] ? Attribute.fromJS(data["YAttribute"]) : undefined; - } - } - - static fromJS(data: any): RecommendedHistogram { - data = typeof data === 'object' ? data : {}; - let result = new RecommendedHistogram(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["HistogramResult"] = this.histogramResult ? this.histogramResult.toJSON() : undefined; - if (this.selectedBinIndices && this.selectedBinIndices.constructor === Array) { - data["SelectedBinIndices"] = []; - for (let item of this.selectedBinIndices) - data["SelectedBinIndices"].push(item.toJSON()); - } - if (this.selections && this.selections.constructor === Array) { - data["Selections"] = []; - for (let item of this.selections) - data["Selections"].push(item.toJSON()); - } - data["PValue"] = this.pValue; - data["Significance"] = this.significance; - data["Decision"] = this.decision ? this.decision.toJSON() : undefined; - data["EffectSize"] = this.effectSize; - data["HypothesisTestResult"] = this.hypothesisTestResult ? this.hypothesisTestResult.toJSON() : undefined; - data["Id"] = this.id; - data["XAttribute"] = this.xAttribute ? this.xAttribute.toJSON() : undefined; - data["YAttribute"] = this.yAttribute ? this.yAttribute.toJSON() : undefined; - return data; - } -} - -export interface IRecommendedHistogram { - histogramResult?: HistogramResult | undefined; - selectedBinIndices?: BinIndex[] | undefined; - selections?: Selection[] | undefined; - pValue?: number | undefined; - significance?: boolean | undefined; - decision?: Decision | undefined; - effectSize?: number | undefined; - hypothesisTestResult?: HypothesisTestResult | undefined; - id?: string | undefined; - xAttribute?: Attribute | undefined; - yAttribute?: Attribute | undefined; -} - -export class Selection implements ISelection { - statements?: Statement[] | undefined; - filterHistogramOperationReference?: IOperationReference | undefined; - - constructor(data?: ISelection) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - if (data["Statements"] && data["Statements"].constructor === Array) { - this.statements = []; - for (let item of data["Statements"]) - this.statements.push(Statement.fromJS(item)); - } - this.filterHistogramOperationReference = data["FilterHistogramOperationReference"] ? IOperationReference.fromJS(data["FilterHistogramOperationReference"]) : undefined; - } - } - - static fromJS(data: any): Selection { - data = typeof data === 'object' ? data : {}; - let result = new Selection(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.statements && this.statements.constructor === Array) { - data["Statements"] = []; - for (let item of this.statements) - data["Statements"].push(item.toJSON()); - } - data["FilterHistogramOperationReference"] = this.filterHistogramOperationReference ? this.filterHistogramOperationReference.toJSON() : undefined; - return data; - } -} - -export interface ISelection { - statements?: Statement[] | undefined; - filterHistogramOperationReference?: IOperationReference | undefined; -} - -export class Statement implements IStatement { - attribute?: Attribute | undefined; - predicate?: Predicate | undefined; - value?: any | undefined; - - constructor(data?: IStatement) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.attribute = data["Attribute"] ? Attribute.fromJS(data["Attribute"]) : undefined; - this.predicate = data["Predicate"]; - this.value = data["Value"]; - } - } - - static fromJS(data: any): Statement { - data = typeof data === 'object' ? data : {}; - let result = new Statement(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Attribute"] = this.attribute ? this.attribute.toJSON() : undefined; - data["Predicate"] = this.predicate; - data["Value"] = this.value; - return data; - } -} - -export interface IStatement { - attribute?: Attribute | undefined; - predicate?: Predicate | undefined; - value?: any | undefined; -} - -export enum Predicate { - EQUALS = 0, - LIKE = 1, - GREATER_THAN = 2, - LESS_THAN = 3, - GREATER_THAN_EQUAL = 4, - LESS_THAN_EQUAL = 5, - STARTS_WITH = 6, - ENDS_WITH = 7, - CONTAINS = 8, -} - -export abstract class IOperationReference implements IIOperationReference { - id?: string | undefined; - - protected _discriminator: string; - - constructor(data?: IIOperationReference) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - this._discriminator = "IOperationReference"; - } - - init(data?: any) { - if (data) { - this.id = data["Id"]; - } - } - - static fromJS(data: any): IOperationReference { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "OperationReference") { - let result = new OperationReference(); - result.init(data); - return result; - } - throw new Error("The abstract class 'IOperationReference' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["discriminator"] = this._discriminator; - data["Id"] = this.id; - return data; - } -} - -export interface IIOperationReference { - id?: string | undefined; -} - -export class OperationReference extends IOperationReference implements IOperationReference { - id?: string | undefined; - - constructor(data?: IOperationReference) { - super(data); - this._discriminator = "OperationReference"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.id = data["Id"]; - } - } - - static fromJS(data: any): OperationReference { - data = typeof data === 'object' ? data : {}; - let result = new OperationReference(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Id"] = this.id; - super.toJSON(data); - return data; - } -} - -export interface IOperationReference extends IIOperationReference { - id?: string | undefined; -} - -export class Decision extends Result implements IDecision { - comparisonId?: ComparisonId | undefined; - riskControlType?: RiskControlType | undefined; - significance?: boolean | undefined; - pValue?: number | undefined; - lhs?: number | undefined; - significanceLevel?: number | undefined; - sampleSizeEstimate?: number | undefined; - - constructor(data?: IDecision) { - super(data); - this._discriminator = "Decision"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.comparisonId = data["ComparisonId"] ? ComparisonId.fromJS(data["ComparisonId"]) : undefined; - this.riskControlType = data["RiskControlType"]; - this.significance = data["Significance"]; - this.pValue = data["PValue"]; - this.lhs = data["Lhs"]; - this.significanceLevel = data["SignificanceLevel"]; - this.sampleSizeEstimate = data["SampleSizeEstimate"]; - } - } - - static fromJS(data: any): Decision { - data = typeof data === 'object' ? data : {}; - let result = new Decision(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["ComparisonId"] = this.comparisonId ? this.comparisonId.toJSON() : undefined; - data["RiskControlType"] = this.riskControlType; - data["Significance"] = this.significance; - data["PValue"] = this.pValue; - data["Lhs"] = this.lhs; - data["SignificanceLevel"] = this.significanceLevel; - data["SampleSizeEstimate"] = this.sampleSizeEstimate; - super.toJSON(data); - return data; - } -} - -export interface IDecision extends IResult { - comparisonId?: ComparisonId | undefined; - riskControlType?: RiskControlType | undefined; - significance?: boolean | undefined; - pValue?: number | undefined; - lhs?: number | undefined; - significanceLevel?: number | undefined; - sampleSizeEstimate?: number | undefined; -} - -export class ComparisonId implements IComparisonId { - value?: string | undefined; - - constructor(data?: IComparisonId) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.value = data["Value"]; - } - } - - static fromJS(data: any): ComparisonId { - data = typeof data === 'object' ? data : {}; - let result = new ComparisonId(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Value"] = this.value; - return data; - } -} - -export interface IComparisonId { - value?: string | undefined; -} - -export class OptimizerResult extends Result implements IOptimizerResult { - topKSolutions?: Solution[] | undefined; - - constructor(data?: IOptimizerResult) { - super(data); - this._discriminator = "OptimizerResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["TopKSolutions"] && data["TopKSolutions"].constructor === Array) { - this.topKSolutions = []; - for (let item of data["TopKSolutions"]) - this.topKSolutions.push(Solution.fromJS(item)); - } - } - } - - static fromJS(data: any): OptimizerResult { - data = typeof data === 'object' ? data : {}; - let result = new OptimizerResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.topKSolutions && this.topKSolutions.constructor === Array) { - data["TopKSolutions"] = []; - for (let item of this.topKSolutions) - data["TopKSolutions"].push(item.toJSON()); - } - super.toJSON(data); - return data; - } -} - -export interface IOptimizerResult extends IResult { - topKSolutions?: Solution[] | undefined; -} - -export class Solution implements ISolution { - solutionId?: string | undefined; - stepDescriptions?: StepDescription[] | undefined; - pipelineDescription?: PipelineDescription | undefined; - score?: Score | undefined; - naiveScore?: Score | undefined; - - constructor(data?: ISolution) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.solutionId = data["SolutionId"]; - if (data["StepDescriptions"] && data["StepDescriptions"].constructor === Array) { - this.stepDescriptions = []; - for (let item of data["StepDescriptions"]) - this.stepDescriptions.push(StepDescription.fromJS(item)); - } - this.pipelineDescription = data["PipelineDescription"] ? PipelineDescription.fromJS(data["PipelineDescription"]) : undefined; - this.score = data["Score"] ? Score.fromJS(data["Score"]) : undefined; - this.naiveScore = data["NaiveScore"] ? Score.fromJS(data["NaiveScore"]) : undefined; - } - } - - static fromJS(data: any): Solution { - data = typeof data === 'object' ? data : {}; - let result = new Solution(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["SolutionId"] = this.solutionId; - if (this.stepDescriptions && this.stepDescriptions.constructor === Array) { - data["StepDescriptions"] = []; - for (let item of this.stepDescriptions) - data["StepDescriptions"].push(item.toJSON()); - } - data["PipelineDescription"] = this.pipelineDescription ? this.pipelineDescription.toJSON() : undefined; - data["Score"] = this.score ? this.score.toJSON() : undefined; - data["NaiveScore"] = this.naiveScore ? this.naiveScore.toJSON() : undefined; - return data; - } -} - -export interface ISolution { - solutionId?: string | undefined; - stepDescriptions?: StepDescription[] | undefined; - pipelineDescription?: PipelineDescription | undefined; - score?: Score | undefined; - naiveScore?: Score | undefined; -} - -export class StepDescription implements IStepDescription { - - protected _discriminator: string; - - constructor(data?: IStepDescription) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - this._discriminator = "StepDescription"; - } - - init(data?: any) { - if (data) { - } - } - - static fromJS(data: any): StepDescription { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "SubpipelineStepDescription") { - let result = new SubpipelineStepDescription(); - result.init(data); - return result; - } - if (data["discriminator"] === "PrimitiveStepDescription") { - let result = new PrimitiveStepDescription(); - result.init(data); - return result; - } - let result = new StepDescription(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["discriminator"] = this._discriminator; - return data; - } -} - -export interface IStepDescription { -} - -export class SubpipelineStepDescription extends StepDescription implements ISubpipelineStepDescription { - steps?: StepDescription[] | undefined; - - constructor(data?: ISubpipelineStepDescription) { - super(data); - this._discriminator = "SubpipelineStepDescription"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["Steps"] && data["Steps"].constructor === Array) { - this.steps = []; - for (let item of data["Steps"]) - this.steps.push(StepDescription.fromJS(item)); - } - } - } - - static fromJS(data: any): SubpipelineStepDescription { - data = typeof data === 'object' ? data : {}; - let result = new SubpipelineStepDescription(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.steps && this.steps.constructor === Array) { - data["Steps"] = []; - for (let item of this.steps) - data["Steps"].push(item.toJSON()); - } - super.toJSON(data); - return data; - } -} - -export interface ISubpipelineStepDescription extends IStepDescription { - steps?: StepDescription[] | undefined; -} - -export class PipelineDescription implements IPipelineDescription { - id?: string | undefined; - name?: string | undefined; - description?: string | undefined; - inputs?: PipelineDescriptionInput[] | undefined; - outputs?: PipelineDescriptionOutput[] | undefined; - steps?: PipelineDescriptionStep[] | undefined; - - constructor(data?: IPipelineDescription) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.id = data["Id"]; - this.name = data["Name"]; - this.description = data["Description"]; - if (data["Inputs"] && data["Inputs"].constructor === Array) { - this.inputs = []; - for (let item of data["Inputs"]) - this.inputs.push(PipelineDescriptionInput.fromJS(item)); - } - if (data["Outputs"] && data["Outputs"].constructor === Array) { - this.outputs = []; - for (let item of data["Outputs"]) - this.outputs.push(PipelineDescriptionOutput.fromJS(item)); - } - if (data["Steps"] && data["Steps"].constructor === Array) { - this.steps = []; - for (let item of data["Steps"]) - this.steps.push(PipelineDescriptionStep.fromJS(item)); - } - } - } - - static fromJS(data: any): PipelineDescription { - data = typeof data === 'object' ? data : {}; - let result = new PipelineDescription(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Id"] = this.id; - data["Name"] = this.name; - data["Description"] = this.description; - if (this.inputs && this.inputs.constructor === Array) { - data["Inputs"] = []; - for (let item of this.inputs) - data["Inputs"].push(item.toJSON()); - } - if (this.outputs && this.outputs.constructor === Array) { - data["Outputs"] = []; - for (let item of this.outputs) - data["Outputs"].push(item.toJSON()); - } - if (this.steps && this.steps.constructor === Array) { - data["Steps"] = []; - for (let item of this.steps) - data["Steps"].push(item.toJSON()); - } - return data; - } -} - -export interface IPipelineDescription { - id?: string | undefined; - name?: string | undefined; - description?: string | undefined; - inputs?: PipelineDescriptionInput[] | undefined; - outputs?: PipelineDescriptionOutput[] | undefined; - steps?: PipelineDescriptionStep[] | undefined; -} - -export class PipelineDescriptionInput implements IPipelineDescriptionInput { - name?: string | undefined; - - constructor(data?: IPipelineDescriptionInput) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.name = data["Name"]; - } - } - - static fromJS(data: any): PipelineDescriptionInput { - data = typeof data === 'object' ? data : {}; - let result = new PipelineDescriptionInput(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Name"] = this.name; - return data; - } -} - -export interface IPipelineDescriptionInput { - name?: string | undefined; -} - -export class PipelineDescriptionOutput implements IPipelineDescriptionOutput { - name?: string | undefined; - data?: string | undefined; - - constructor(data?: IPipelineDescriptionOutput) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.name = data["Name"]; - this.data = data["Data"]; - } - } - - static fromJS(data: any): PipelineDescriptionOutput { - data = typeof data === 'object' ? data : {}; - let result = new PipelineDescriptionOutput(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Name"] = this.name; - data["Data"] = this.data; - return data; - } -} - -export interface IPipelineDescriptionOutput { - name?: string | undefined; - data?: string | undefined; -} - -export class PipelineDescriptionStep implements IPipelineDescriptionStep { - outputs?: StepOutput[] | undefined; - - protected _discriminator: string; - - constructor(data?: IPipelineDescriptionStep) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - this._discriminator = "PipelineDescriptionStep"; - } - - init(data?: any) { - if (data) { - if (data["Outputs"] && data["Outputs"].constructor === Array) { - this.outputs = []; - for (let item of data["Outputs"]) - this.outputs.push(StepOutput.fromJS(item)); - } - } - } - - static fromJS(data: any): PipelineDescriptionStep { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "PlaceholderPipelineDescriptionStep") { - let result = new PlaceholderPipelineDescriptionStep(); - result.init(data); - return result; - } - if (data["discriminator"] === "SubpipelinePipelineDescriptionStep") { - let result = new SubpipelinePipelineDescriptionStep(); - result.init(data); - return result; - } - if (data["discriminator"] === "PrimitivePipelineDescriptionStep") { - let result = new PrimitivePipelineDescriptionStep(); - result.init(data); - return result; - } - let result = new PipelineDescriptionStep(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["discriminator"] = this._discriminator; - if (this.outputs && this.outputs.constructor === Array) { - data["Outputs"] = []; - for (let item of this.outputs) - data["Outputs"].push(item.toJSON()); - } - return data; - } -} - -export interface IPipelineDescriptionStep { - outputs?: StepOutput[] | undefined; -} - -export class StepOutput implements IStepOutput { - id?: string | undefined; - - constructor(data?: IStepOutput) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.id = data["Id"]; - } - } - - static fromJS(data: any): StepOutput { - data = typeof data === 'object' ? data : {}; - let result = new StepOutput(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Id"] = this.id; - return data; - } -} - -export interface IStepOutput { - id?: string | undefined; -} - -export class PlaceholderPipelineDescriptionStep extends PipelineDescriptionStep implements IPlaceholderPipelineDescriptionStep { - inputs?: StepInput[] | undefined; - - constructor(data?: IPlaceholderPipelineDescriptionStep) { - super(data); - this._discriminator = "PlaceholderPipelineDescriptionStep"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["Inputs"] && data["Inputs"].constructor === Array) { - this.inputs = []; - for (let item of data["Inputs"]) - this.inputs.push(StepInput.fromJS(item)); - } - } - } - - static fromJS(data: any): PlaceholderPipelineDescriptionStep { - data = typeof data === 'object' ? data : {}; - let result = new PlaceholderPipelineDescriptionStep(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.inputs && this.inputs.constructor === Array) { - data["Inputs"] = []; - for (let item of this.inputs) - data["Inputs"].push(item.toJSON()); - } - super.toJSON(data); - return data; - } -} - -export interface IPlaceholderPipelineDescriptionStep extends IPipelineDescriptionStep { - inputs?: StepInput[] | undefined; -} - -export class StepInput implements IStepInput { - data?: string | undefined; - - constructor(data?: IStepInput) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.data = data["Data"]; - } - } - - static fromJS(data: any): StepInput { - data = typeof data === 'object' ? data : {}; - let result = new StepInput(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Data"] = this.data; - return data; - } -} - -export interface IStepInput { - data?: string | undefined; -} - -export class SubpipelinePipelineDescriptionStep extends PipelineDescriptionStep implements ISubpipelinePipelineDescriptionStep { - pipelineDescription?: PipelineDescription | undefined; - inputs?: StepInput[] | undefined; - - constructor(data?: ISubpipelinePipelineDescriptionStep) { - super(data); - this._discriminator = "SubpipelinePipelineDescriptionStep"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.pipelineDescription = data["PipelineDescription"] ? PipelineDescription.fromJS(data["PipelineDescription"]) : undefined; - if (data["Inputs"] && data["Inputs"].constructor === Array) { - this.inputs = []; - for (let item of data["Inputs"]) - this.inputs.push(StepInput.fromJS(item)); - } - } - } - - static fromJS(data: any): SubpipelinePipelineDescriptionStep { - data = typeof data === 'object' ? data : {}; - let result = new SubpipelinePipelineDescriptionStep(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["PipelineDescription"] = this.pipelineDescription ? this.pipelineDescription.toJSON() : undefined; - if (this.inputs && this.inputs.constructor === Array) { - data["Inputs"] = []; - for (let item of this.inputs) - data["Inputs"].push(item.toJSON()); - } - super.toJSON(data); - return data; - } -} - -export interface ISubpipelinePipelineDescriptionStep extends IPipelineDescriptionStep { - pipelineDescription?: PipelineDescription | undefined; - inputs?: StepInput[] | undefined; -} - -export class PrimitivePipelineDescriptionStep extends PipelineDescriptionStep implements IPrimitivePipelineDescriptionStep { - primitive?: Primitive | undefined; - arguments?: { [key: string]: PrimitiveStepArgument; } | undefined; - hyperparams?: { [key: string]: PrimitiveStepHyperparameter; } | undefined; - - constructor(data?: IPrimitivePipelineDescriptionStep) { - super(data); - this._discriminator = "PrimitivePipelineDescriptionStep"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.primitive = data["Primitive"] ? Primitive.fromJS(data["Primitive"]) : undefined; - if (data["Arguments"]) { - this.arguments = {}; - for (let key in data["Arguments"]) { - if (data["Arguments"].hasOwnProperty(key)) - this.arguments[key] = data["Arguments"][key] ? PrimitiveStepArgument.fromJS(data["Arguments"][key]) : new PrimitiveStepArgument(); - } - } - if (data["Hyperparams"]) { - this.hyperparams = {}; - for (let key in data["Hyperparams"]) { - if (data["Hyperparams"].hasOwnProperty(key)) - this.hyperparams[key] = data["Hyperparams"][key] ? PrimitiveStepHyperparameter.fromJS(data["Hyperparams"][key]) : new PrimitiveStepHyperparameter(); - } - } - } - } - - static fromJS(data: any): PrimitivePipelineDescriptionStep { - data = typeof data === 'object' ? data : {}; - let result = new PrimitivePipelineDescriptionStep(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Primitive"] = this.primitive ? this.primitive.toJSON() : undefined; - if (this.arguments) { - data["Arguments"] = {}; - for (let key in this.arguments) { - if (this.arguments.hasOwnProperty(key)) - data["Arguments"][key] = this.arguments[key]; - } - } - if (this.hyperparams) { - data["Hyperparams"] = {}; - for (let key in this.hyperparams) { - if (this.hyperparams.hasOwnProperty(key)) - data["Hyperparams"][key] = this.hyperparams[key]; - } - } - super.toJSON(data); - return data; - } -} - -export interface IPrimitivePipelineDescriptionStep extends IPipelineDescriptionStep { - primitive?: Primitive | undefined; - arguments?: { [key: string]: PrimitiveStepArgument; } | undefined; - hyperparams?: { [key: string]: PrimitiveStepHyperparameter; } | undefined; -} - -export class Primitive implements IPrimitive { - id?: string | undefined; - version?: string | undefined; - pythonPath?: string | undefined; - name?: string | undefined; - digest?: string | undefined; - - constructor(data?: IPrimitive) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.id = data["Id"]; - this.version = data["Version"]; - this.pythonPath = data["PythonPath"]; - this.name = data["Name"]; - this.digest = data["Digest"]; - } - } - - static fromJS(data: any): Primitive { - data = typeof data === 'object' ? data : {}; - let result = new Primitive(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Id"] = this.id; - data["Version"] = this.version; - data["PythonPath"] = this.pythonPath; - data["Name"] = this.name; - data["Digest"] = this.digest; - return data; - } -} - -export interface IPrimitive { - id?: string | undefined; - version?: string | undefined; - pythonPath?: string | undefined; - name?: string | undefined; - digest?: string | undefined; -} - -export class PrimitiveStepHyperparameter implements IPrimitiveStepHyperparameter { - - protected _discriminator: string; - - constructor(data?: IPrimitiveStepHyperparameter) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - this._discriminator = "PrimitiveStepHyperparameter"; - } - - init(data?: any) { - if (data) { - } - } - - static fromJS(data: any): PrimitiveStepHyperparameter { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "PrimitiveStepArgument") { - let result = new PrimitiveStepArgument(); - result.init(data); - return result; - } - if (data["discriminator"] === "DataArguments") { - let result = new DataArguments(); - result.init(data); - return result; - } - if (data["discriminator"] === "PrimitiveArgument") { - let result = new PrimitiveArgument(); - result.init(data); - return result; - } - if (data["discriminator"] === "PrimitiveArguments") { - let result = new PrimitiveArguments(); - result.init(data); - return result; - } - if (data["discriminator"] === "ValueArgument") { - let result = new ValueArgument(); - result.init(data); - return result; - } - if (data["discriminator"] === "ContainerArgument") { - let result = new ContainerArgument(); - result.init(data); - return result; - } - if (data["discriminator"] === "DataArgument") { - let result = new DataArgument(); - result.init(data); - return result; - } - let result = new PrimitiveStepHyperparameter(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["discriminator"] = this._discriminator; - return data; - } -} - -export interface IPrimitiveStepHyperparameter { -} - -export class PrimitiveStepArgument extends PrimitiveStepHyperparameter implements IPrimitiveStepArgument { - - protected _discriminator: string; - - constructor(data?: IPrimitiveStepArgument) { - super(data); - this._discriminator = "PrimitiveStepArgument"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): PrimitiveStepArgument { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "ContainerArgument") { - let result = new ContainerArgument(); - result.init(data); - return result; - } - if (data["discriminator"] === "DataArgument") { - let result = new DataArgument(); - result.init(data); - return result; - } - let result = new PrimitiveStepArgument(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["discriminator"] = this._discriminator; - super.toJSON(data); - return data; - } -} - -export interface IPrimitiveStepArgument extends IPrimitiveStepHyperparameter { -} - -export class DataArguments extends PrimitiveStepHyperparameter implements IDataArguments { - data?: string[] | undefined; - - constructor(data?: IDataArguments) { - super(data); - this._discriminator = "DataArguments"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["Data"] && data["Data"].constructor === Array) { - this.data = []; - for (let item of data["Data"]) - this.data.push(item); - } - } - } - - static fromJS(data: any): DataArguments { - data = typeof data === 'object' ? data : {}; - let result = new DataArguments(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.data && this.data.constructor === Array) { - data["Data"] = []; - for (let item of this.data) - data["Data"].push(item); - } - super.toJSON(data); - return data; - } -} - -export interface IDataArguments extends IPrimitiveStepHyperparameter { - data?: string[] | undefined; -} - -export class PrimitiveArgument extends PrimitiveStepHyperparameter implements IPrimitiveArgument { - data?: number | undefined; - - constructor(data?: IPrimitiveArgument) { - super(data); - this._discriminator = "PrimitiveArgument"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.data = data["Data"]; - } - } - - static fromJS(data: any): PrimitiveArgument { - data = typeof data === 'object' ? data : {}; - let result = new PrimitiveArgument(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Data"] = this.data; - super.toJSON(data); - return data; - } -} - -export interface IPrimitiveArgument extends IPrimitiveStepHyperparameter { - data?: number | undefined; -} - -export class PrimitiveArguments extends PrimitiveStepHyperparameter implements IPrimitiveArguments { - data?: number[] | undefined; - - constructor(data?: IPrimitiveArguments) { - super(data); - this._discriminator = "PrimitiveArguments"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["Data"] && data["Data"].constructor === Array) { - this.data = []; - for (let item of data["Data"]) - this.data.push(item); - } - } - } - - static fromJS(data: any): PrimitiveArguments { - data = typeof data === 'object' ? data : {}; - let result = new PrimitiveArguments(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.data && this.data.constructor === Array) { - data["Data"] = []; - for (let item of this.data) - data["Data"].push(item); - } - super.toJSON(data); - return data; - } -} - -export interface IPrimitiveArguments extends IPrimitiveStepHyperparameter { - data?: number[] | undefined; -} - -export class ValueArgument extends PrimitiveStepHyperparameter implements IValueArgument { - data?: Value | undefined; - - constructor(data?: IValueArgument) { - super(data); - this._discriminator = "ValueArgument"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.data = data["Data"] ? Value.fromJS(data["Data"]) : undefined; - } - } - - static fromJS(data: any): ValueArgument { - data = typeof data === 'object' ? data : {}; - let result = new ValueArgument(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Data"] = this.data ? this.data.toJSON() : undefined; - super.toJSON(data); - return data; - } -} - -export interface IValueArgument extends IPrimitiveStepHyperparameter { - data?: Value | undefined; -} - -export abstract class Value implements IValue { - - protected _discriminator: string; - - constructor(data?: IValue) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - this._discriminator = "Value"; - } - - init(data?: any) { - if (data) { - } - } - - static fromJS(data: any): Value { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "ErrorValue") { - let result = new ErrorValue(); - result.init(data); - return result; - } - if (data["discriminator"] === "DoubleValue") { - let result = new DoubleValue(); - result.init(data); - return result; - } - if (data["discriminator"] === "LongValue") { - let result = new LongValue(); - result.init(data); - return result; - } - if (data["discriminator"] === "BoolValue") { - let result = new BoolValue(); - result.init(data); - return result; - } - if (data["discriminator"] === "StringValue") { - let result = new StringValue(); - result.init(data); - return result; - } - if (data["discriminator"] === "DatasetUriValue") { - let result = new DatasetUriValue(); - result.init(data); - return result; - } - if (data["discriminator"] === "CsvUriValue") { - let result = new CsvUriValue(); - result.init(data); - return result; - } - if (data["discriminator"] === "PickleUriValue") { - let result = new PickleUriValue(); - result.init(data); - return result; - } - if (data["discriminator"] === "PickleBlobValue") { - let result = new PickleBlobValue(); - result.init(data); - return result; - } - if (data["discriminator"] === "PlasmaIdValue") { - let result = new PlasmaIdValue(); - result.init(data); - return result; - } - if (data["discriminator"] === "BytesValue") { - let result = new BytesValue(); - result.init(data); - return result; - } - if (data["discriminator"] === "ListValue") { - let result = new ListValue(); - result.init(data); - return result; - } - throw new Error("The abstract class 'Value' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["discriminator"] = this._discriminator; - return data; - } -} - -export interface IValue { -} - -export class ErrorValue extends Value implements IErrorValue { - message?: string | undefined; - - constructor(data?: IErrorValue) { - super(data); - this._discriminator = "ErrorValue"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.message = data["Message"]; - } - } - - static fromJS(data: any): ErrorValue { - data = typeof data === 'object' ? data : {}; - let result = new ErrorValue(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Message"] = this.message; - super.toJSON(data); - return data; - } -} - -export interface IErrorValue extends IValue { - message?: string | undefined; -} - -export class DoubleValue extends Value implements IDoubleValue { - value?: number | undefined; - - constructor(data?: IDoubleValue) { - super(data); - this._discriminator = "DoubleValue"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.value = data["Value"]; - } - } - - static fromJS(data: any): DoubleValue { - data = typeof data === 'object' ? data : {}; - let result = new DoubleValue(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Value"] = this.value; - super.toJSON(data); - return data; - } -} - -export interface IDoubleValue extends IValue { - value?: number | undefined; -} - -export class LongValue extends Value implements ILongValue { - value?: number | undefined; - - constructor(data?: ILongValue) { - super(data); - this._discriminator = "LongValue"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.value = data["Value"]; - } - } - - static fromJS(data: any): LongValue { - data = typeof data === 'object' ? data : {}; - let result = new LongValue(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Value"] = this.value; - super.toJSON(data); - return data; - } -} - -export interface ILongValue extends IValue { - value?: number | undefined; -} - -export class BoolValue extends Value implements IBoolValue { - value?: boolean | undefined; - - constructor(data?: IBoolValue) { - super(data); - this._discriminator = "BoolValue"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.value = data["Value"]; - } - } - - static fromJS(data: any): BoolValue { - data = typeof data === 'object' ? data : {}; - let result = new BoolValue(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Value"] = this.value; - super.toJSON(data); - return data; - } -} - -export interface IBoolValue extends IValue { - value?: boolean | undefined; -} - -export class StringValue extends Value implements IStringValue { - value?: string | undefined; - - constructor(data?: IStringValue) { - super(data); - this._discriminator = "StringValue"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.value = data["Value"]; - } - } - - static fromJS(data: any): StringValue { - data = typeof data === 'object' ? data : {}; - let result = new StringValue(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Value"] = this.value; - super.toJSON(data); - return data; - } -} - -export interface IStringValue extends IValue { - value?: string | undefined; -} - -export class DatasetUriValue extends Value implements IDatasetUriValue { - value?: string | undefined; - - constructor(data?: IDatasetUriValue) { - super(data); - this._discriminator = "DatasetUriValue"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.value = data["Value"]; - } - } - - static fromJS(data: any): DatasetUriValue { - data = typeof data === 'object' ? data : {}; - let result = new DatasetUriValue(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Value"] = this.value; - super.toJSON(data); - return data; - } -} - -export interface IDatasetUriValue extends IValue { - value?: string | undefined; -} - -export class CsvUriValue extends Value implements ICsvUriValue { - value?: string | undefined; - - constructor(data?: ICsvUriValue) { - super(data); - this._discriminator = "CsvUriValue"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.value = data["Value"]; - } - } - - static fromJS(data: any): CsvUriValue { - data = typeof data === 'object' ? data : {}; - let result = new CsvUriValue(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Value"] = this.value; - super.toJSON(data); - return data; - } -} - -export interface ICsvUriValue extends IValue { - value?: string | undefined; -} - -export class PickleUriValue extends Value implements IPickleUriValue { - value?: string | undefined; - - constructor(data?: IPickleUriValue) { - super(data); - this._discriminator = "PickleUriValue"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.value = data["Value"]; - } - } - - static fromJS(data: any): PickleUriValue { - data = typeof data === 'object' ? data : {}; - let result = new PickleUriValue(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Value"] = this.value; - super.toJSON(data); - return data; - } -} - -export interface IPickleUriValue extends IValue { - value?: string | undefined; -} - -export class PickleBlobValue extends Value implements IPickleBlobValue { - value?: string | undefined; - - constructor(data?: IPickleBlobValue) { - super(data); - this._discriminator = "PickleBlobValue"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.value = data["Value"]; - } - } - - static fromJS(data: any): PickleBlobValue { - data = typeof data === 'object' ? data : {}; - let result = new PickleBlobValue(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Value"] = this.value; - super.toJSON(data); - return data; - } -} - -export interface IPickleBlobValue extends IValue { - value?: string | undefined; -} - -export class PlasmaIdValue extends Value implements IPlasmaIdValue { - value?: string | undefined; - - constructor(data?: IPlasmaIdValue) { - super(data); - this._discriminator = "PlasmaIdValue"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.value = data["Value"]; - } - } - - static fromJS(data: any): PlasmaIdValue { - data = typeof data === 'object' ? data : {}; - let result = new PlasmaIdValue(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Value"] = this.value; - super.toJSON(data); - return data; - } -} - -export interface IPlasmaIdValue extends IValue { - value?: string | undefined; -} - -export class BytesValue extends Value implements IBytesValue { - value?: string | undefined; - - constructor(data?: IBytesValue) { - super(data); - this._discriminator = "BytesValue"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.value = data["Value"]; - } - } - - static fromJS(data: any): BytesValue { - data = typeof data === 'object' ? data : {}; - let result = new BytesValue(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Value"] = this.value; - super.toJSON(data); - return data; - } -} - -export interface IBytesValue extends IValue { - value?: string | undefined; -} - -export class ContainerArgument extends PrimitiveStepArgument implements IContainerArgument { - data?: string | undefined; - - constructor(data?: IContainerArgument) { - super(data); - this._discriminator = "ContainerArgument"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.data = data["Data"]; - } - } - - static fromJS(data: any): ContainerArgument { - data = typeof data === 'object' ? data : {}; - let result = new ContainerArgument(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Data"] = this.data; - super.toJSON(data); - return data; - } -} - -export interface IContainerArgument extends IPrimitiveStepArgument { - data?: string | undefined; -} - -export class Score implements IScore { - metricType?: MetricType | undefined; - value?: number | undefined; - - constructor(data?: IScore) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.metricType = data["MetricType"]; - this.value = data["Value"]; - } - } - - static fromJS(data: any): Score { - data = typeof data === 'object' ? data : {}; - let result = new Score(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["MetricType"] = this.metricType; - data["Value"] = this.value; - return data; - } -} - -export interface IScore { - metricType?: MetricType | undefined; - value?: number | undefined; -} - -export class ExampleResult extends Result implements IExampleResult { - resultValues?: { [key: string]: string; } | undefined; - message?: string | undefined; - - constructor(data?: IExampleResult) { - super(data); - this._discriminator = "ExampleResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["ResultValues"]) { - this.resultValues = {}; - for (let key in data["ResultValues"]) { - if (data["ResultValues"].hasOwnProperty(key)) - this.resultValues[key] = data["ResultValues"][key]; - } - } - this.message = data["Message"]; - } - } - - static fromJS(data: any): ExampleResult { - data = typeof data === 'object' ? data : {}; - let result = new ExampleResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.resultValues) { - data["ResultValues"] = {}; - for (let key in this.resultValues) { - if (this.resultValues.hasOwnProperty(key)) - data["ResultValues"][key] = this.resultValues[key]; - } - } - data["Message"] = this.message; - super.toJSON(data); - return data; - } -} - -export interface IExampleResult extends IResult { - resultValues?: { [key: string]: string; } | undefined; - message?: string | undefined; -} - -export class NewModelOperationResult extends ModelOperationResult implements INewModelOperationResult { - - constructor(data?: INewModelOperationResult) { - super(data); - this._discriminator = "NewModelOperationResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): NewModelOperationResult { - data = typeof data === 'object' ? data : {}; - let result = new NewModelOperationResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface INewModelOperationResult extends IModelOperationResult { -} - -export class AddComparisonResult extends ModelOperationResult implements IAddComparisonResult { - comparisonId?: ComparisonId | undefined; - - constructor(data?: IAddComparisonResult) { - super(data); - this._discriminator = "AddComparisonResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.comparisonId = data["ComparisonId"] ? ComparisonId.fromJS(data["ComparisonId"]) : undefined; - } - } - - static fromJS(data: any): AddComparisonResult { - data = typeof data === 'object' ? data : {}; - let result = new AddComparisonResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["ComparisonId"] = this.comparisonId ? this.comparisonId.toJSON() : undefined; - super.toJSON(data); - return data; - } -} - -export interface IAddComparisonResult extends IModelOperationResult { - comparisonId?: ComparisonId | undefined; -} - -export class GetModelStateResult extends ModelOperationResult implements IGetModelStateResult { - decisions?: Decision[] | undefined; - startingWealth?: number | undefined; - currentWealth?: number | undefined; - - constructor(data?: IGetModelStateResult) { - super(data); - this._discriminator = "GetModelStateResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["Decisions"] && data["Decisions"].constructor === Array) { - this.decisions = []; - for (let item of data["Decisions"]) - this.decisions.push(Decision.fromJS(item)); - } - this.startingWealth = data["StartingWealth"]; - this.currentWealth = data["CurrentWealth"]; - } - } - - static fromJS(data: any): GetModelStateResult { - data = typeof data === 'object' ? data : {}; - let result = new GetModelStateResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.decisions && this.decisions.constructor === Array) { - data["Decisions"] = []; - for (let item of this.decisions) - data["Decisions"].push(item.toJSON()); - } - data["StartingWealth"] = this.startingWealth; - data["CurrentWealth"] = this.currentWealth; - super.toJSON(data); - return data; - } -} - -export interface IGetModelStateResult extends IModelOperationResult { - decisions?: Decision[] | undefined; - startingWealth?: number | undefined; - currentWealth?: number | undefined; -} - -export class AggregateKey implements IAggregateKey { - aggregateParameterIndex?: number | undefined; - brushIndex?: number | undefined; - - constructor(data?: IAggregateKey) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.aggregateParameterIndex = data["AggregateParameterIndex"]; - this.brushIndex = data["BrushIndex"]; - } - } - - static fromJS(data: any): AggregateKey { - data = typeof data === 'object' ? data : {}; - let result = new AggregateKey(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["AggregateParameterIndex"] = this.aggregateParameterIndex; - data["BrushIndex"] = this.brushIndex; - return data; - } -} - -export interface IAggregateKey { - aggregateParameterIndex?: number | undefined; - brushIndex?: number | undefined; -} - -export abstract class IResult implements IIResult { - - constructor(data?: IIResult) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - } - } - - static fromJS(data: any): IResult { - data = typeof data === 'object' ? data : {}; - throw new Error("The abstract class 'IResult' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - return data; - } -} - -export interface IIResult { -} - -export class DataArgument extends PrimitiveStepArgument implements IDataArgument { - data?: string | undefined; - - constructor(data?: IDataArgument) { - super(data); - this._discriminator = "DataArgument"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.data = data["Data"]; - } - } - - static fromJS(data: any): DataArgument { - data = typeof data === 'object' ? data : {}; - let result = new DataArgument(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Data"] = this.data; - super.toJSON(data); - return data; - } -} - -export interface IDataArgument extends IPrimitiveStepArgument { - data?: string | undefined; -} - -export class ListValue extends Value implements IListValue { - items?: Value[] | undefined; - - constructor(data?: IListValue) { - super(data); - this._discriminator = "ListValue"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["Items"] && data["Items"].constructor === Array) { - this.items = []; - for (let item of data["Items"]) - this.items.push(Value.fromJS(item)); - } - } - } - - static fromJS(data: any): ListValue { - data = typeof data === 'object' ? data : {}; - let result = new ListValue(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.items && this.items.constructor === Array) { - data["Items"] = []; - for (let item of this.items) - data["Items"].push(item.toJSON()); - } - super.toJSON(data); - return data; - } -} - -export interface IListValue extends IValue { - items?: Value[] | undefined; -} - -export class Metrics implements IMetrics { - averageAccuracy?: number | undefined; - averageRSquared?: number | undefined; - f1Macro?: number | undefined; - - constructor(data?: IMetrics) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.averageAccuracy = data["AverageAccuracy"]; - this.averageRSquared = data["AverageRSquared"]; - this.f1Macro = data["F1Macro"]; - } - } - - static fromJS(data: any): Metrics { - data = typeof data === 'object' ? data : {}; - let result = new Metrics(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["AverageAccuracy"] = this.averageAccuracy; - data["AverageRSquared"] = this.averageRSquared; - data["F1Macro"] = this.f1Macro; - return data; - } -} - -export interface IMetrics { - averageAccuracy?: number | undefined; - averageRSquared?: number | undefined; - f1Macro?: number | undefined; -} - -export class FeatureImportanceOperationParameters extends DistOperationParameters implements IFeatureImportanceOperationParameters { - solutionId?: string | undefined; - - constructor(data?: IFeatureImportanceOperationParameters) { - super(data); - this._discriminator = "FeatureImportanceOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.solutionId = data["SolutionId"]; - } - } - - static fromJS(data: any): FeatureImportanceOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new FeatureImportanceOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["SolutionId"] = this.solutionId; - super.toJSON(data); - return data; - } -} - -export interface IFeatureImportanceOperationParameters extends IDistOperationParameters { - solutionId?: string | undefined; -} - -export class FeatureImportanceResult extends Result implements IFeatureImportanceResult { - featureImportances?: { [key: string]: TupleOfDoubleAndDouble; } | undefined; - - constructor(data?: IFeatureImportanceResult) { - super(data); - this._discriminator = "FeatureImportanceResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["FeatureImportances"]) { - this.featureImportances = {}; - for (let key in data["FeatureImportances"]) { - if (data["FeatureImportances"].hasOwnProperty(key)) - this.featureImportances[key] = data["FeatureImportances"][key] ? TupleOfDoubleAndDouble.fromJS(data["FeatureImportances"][key]) : new TupleOfDoubleAndDouble(); - } - } - } - } - - static fromJS(data: any): FeatureImportanceResult { - data = typeof data === 'object' ? data : {}; - let result = new FeatureImportanceResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.featureImportances) { - data["FeatureImportances"] = {}; - for (let key in this.featureImportances) { - if (this.featureImportances.hasOwnProperty(key)) - data["FeatureImportances"][key] = this.featureImportances[key]; - } - } - super.toJSON(data); - return data; - } -} - -export interface IFeatureImportanceResult extends IResult { - featureImportances?: { [key: string]: TupleOfDoubleAndDouble; } | undefined; -} - -export class TupleOfDoubleAndDouble implements ITupleOfDoubleAndDouble { - item1?: number | undefined; - item2?: number | undefined; - - constructor(data?: ITupleOfDoubleAndDouble) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.item1 = data["Item1"]; - this.item2 = data["Item2"]; - } - } - - static fromJS(data: any): TupleOfDoubleAndDouble { - data = typeof data === 'object' ? data : {}; - let result = new TupleOfDoubleAndDouble(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Item1"] = this.item1; - data["Item2"] = this.item2; - return data; - } -} - -export interface ITupleOfDoubleAndDouble { - item1?: number | undefined; - item2?: number | undefined; -} - -export class PrimitiveStepDescription extends StepDescription implements IPrimitiveStepDescription { - hyperparams?: { [key: string]: Value; } | undefined; - - constructor(data?: IPrimitiveStepDescription) { - super(data); - this._discriminator = "PrimitiveStepDescription"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["Hyperparams"]) { - this.hyperparams = {}; - for (let key in data["Hyperparams"]) { - if (data["Hyperparams"].hasOwnProperty(key)) - this.hyperparams[key] = data["Hyperparams"][key] ? Value.fromJS(data["Hyperparams"][key]) : undefined; - } - } - } - } - - static fromJS(data: any): PrimitiveStepDescription { - data = typeof data === 'object' ? data : {}; - let result = new PrimitiveStepDescription(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.hyperparams) { - data["Hyperparams"] = {}; - for (let key in this.hyperparams) { - if (this.hyperparams.hasOwnProperty(key)) - data["Hyperparams"][key] = this.hyperparams[key]; - } - } - super.toJSON(data); - return data; - } -} - -export interface IPrimitiveStepDescription extends IStepDescription { - hyperparams?: { [key: string]: Value; } | undefined; -} - -export enum ValueType { - VALUE_TYPE_UNDEFINED = 0, - RAW = 1, - DATASET_URI = 2, - CSV_URI = 3, - PICKLE_URI = 4, - PICKLE_BLOB = 5, - PLASMA_ID = 6, -} - -export class DatamartSearchParameters implements IDatamartSearchParameters { - adapterName?: string | undefined; - queryJson?: string | undefined; - - constructor(data?: IDatamartSearchParameters) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.adapterName = data["AdapterName"]; - this.queryJson = data["QueryJson"]; - } - } - - static fromJS(data: any): DatamartSearchParameters { - data = typeof data === 'object' ? data : {}; - let result = new DatamartSearchParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["AdapterName"] = this.adapterName; - data["QueryJson"] = this.queryJson; - return data; - } -} - -export interface IDatamartSearchParameters { - adapterName?: string | undefined; - queryJson?: string | undefined; -} - -export class DatamartAugmentParameters implements IDatamartAugmentParameters { - adapterName?: string | undefined; - augmentationJson?: string | undefined; - numberOfSamples?: number | undefined; - augmentedAdapterName?: string | undefined; - - constructor(data?: IDatamartAugmentParameters) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.adapterName = data["AdapterName"]; - this.augmentationJson = data["AugmentationJson"]; - this.numberOfSamples = data["NumberOfSamples"]; - this.augmentedAdapterName = data["AugmentedAdapterName"]; - } - } - - static fromJS(data: any): DatamartAugmentParameters { - data = typeof data === 'object' ? data : {}; - let result = new DatamartAugmentParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["AdapterName"] = this.adapterName; - data["AugmentationJson"] = this.augmentationJson; - data["NumberOfSamples"] = this.numberOfSamples; - data["AugmentedAdapterName"] = this.augmentedAdapterName; - return data; - } -} - -export interface IDatamartAugmentParameters { - adapterName?: string | undefined; - augmentationJson?: string | undefined; - numberOfSamples?: number | undefined; - augmentedAdapterName?: string | undefined; -} - -export class RawDataResult extends DistResult implements IRawDataResult { - samples?: { [key: string]: any[]; } | undefined; - weightedWords?: { [key: string]: Word[]; } | undefined; - - constructor(data?: IRawDataResult) { - super(data); - this._discriminator = "RawDataResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["Samples"]) { - this.samples = {}; - for (let key in data["Samples"]) { - if (data["Samples"].hasOwnProperty(key)) - this.samples[key] = data["Samples"][key] !== undefined ? data["Samples"][key] : []; - } - } - if (data["WeightedWords"]) { - this.weightedWords = {}; - for (let key in data["WeightedWords"]) { - if (data["WeightedWords"].hasOwnProperty(key)) - this.weightedWords[key] = data["WeightedWords"][key] ? data["WeightedWords"][key].map((i: any) => Word.fromJS(i)) : []; - } - } - } - } - - static fromJS(data: any): RawDataResult { - data = typeof data === 'object' ? data : {}; - let result = new RawDataResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.samples) { - data["Samples"] = {}; - for (let key in this.samples) { - if (this.samples.hasOwnProperty(key)) - data["Samples"][key] = this.samples[key]; - } - } - if (this.weightedWords) { - data["WeightedWords"] = {}; - for (let key in this.weightedWords) { - if (this.weightedWords.hasOwnProperty(key)) - data["WeightedWords"][key] = this.weightedWords[key]; - } - } - super.toJSON(data); - return data; - } -} - -export interface IRawDataResult extends IDistResult { - samples?: { [key: string]: any[]; } | undefined; - weightedWords?: { [key: string]: Word[]; } | undefined; -} - -export class Word implements IWord { - text?: string | undefined; - occurrences?: number | undefined; - stem?: string | undefined; - isWordGroup?: boolean | undefined; - - constructor(data?: IWord) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.text = data["Text"]; - this.occurrences = data["Occurrences"]; - this.stem = data["Stem"]; - this.isWordGroup = data["IsWordGroup"]; - } - } - - static fromJS(data: any): Word { - data = typeof data === 'object' ? data : {}; - let result = new Word(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Text"] = this.text; - data["Occurrences"] = this.occurrences; - data["Stem"] = this.stem; - data["IsWordGroup"] = this.isWordGroup; - return data; - } -} - -export interface IWord { - text?: string | undefined; - occurrences?: number | undefined; - stem?: string | undefined; - isWordGroup?: boolean | undefined; -} - -export class SampleOperationParameters extends DistOperationParameters implements ISampleOperationParameters { - numSamples?: number | undefined; - attributeParameters?: AttributeParameters[] | undefined; - brushes?: string[] | undefined; - - constructor(data?: ISampleOperationParameters) { - super(data); - this._discriminator = "SampleOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.numSamples = data["NumSamples"]; - if (data["AttributeParameters"] && data["AttributeParameters"].constructor === Array) { - this.attributeParameters = []; - for (let item of data["AttributeParameters"]) - this.attributeParameters.push(AttributeParameters.fromJS(item)); - } - if (data["Brushes"] && data["Brushes"].constructor === Array) { - this.brushes = []; - for (let item of data["Brushes"]) - this.brushes.push(item); - } - } - } - - static fromJS(data: any): SampleOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new SampleOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["NumSamples"] = this.numSamples; - if (this.attributeParameters && this.attributeParameters.constructor === Array) { - data["AttributeParameters"] = []; - for (let item of this.attributeParameters) - data["AttributeParameters"].push(item.toJSON()); - } - if (this.brushes && this.brushes.constructor === Array) { - data["Brushes"] = []; - for (let item of this.brushes) - data["Brushes"].push(item); - } - super.toJSON(data); - return data; - } -} - -export interface ISampleOperationParameters extends IDistOperationParameters { - numSamples?: number | undefined; - attributeParameters?: AttributeParameters[] | undefined; - brushes?: string[] | undefined; -} - -export class SampleResult extends DistResult implements ISampleResult { - samples?: { [key: string]: { [key: string]: number; }; } | undefined; - isTruncated?: boolean | undefined; - - constructor(data?: ISampleResult) { - super(data); - this._discriminator = "SampleResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["Samples"]) { - this.samples = {}; - for (let key in data["Samples"]) { - if (data["Samples"].hasOwnProperty(key)) - this.samples[key] = data["Samples"][key] !== undefined ? data["Samples"][key] : {}; - } - } - this.isTruncated = data["IsTruncated"]; - } - } - - static fromJS(data: any): SampleResult { - data = typeof data === 'object' ? data : {}; - let result = new SampleResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.samples) { - data["Samples"] = {}; - for (let key in this.samples) { - if (this.samples.hasOwnProperty(key)) - data["Samples"][key] = this.samples[key]; - } - } - data["IsTruncated"] = this.isTruncated; - super.toJSON(data); - return data; - } -} - -export interface ISampleResult extends IDistResult { - samples?: { [key: string]: { [key: string]: number; }; } | undefined; - isTruncated?: boolean | undefined; -} - -export class ResultParameters extends UniqueJson implements IResultParameters { - operationReference?: IOperationReference | undefined; - stopOperation?: boolean | undefined; - - protected _discriminator: string; - - constructor(data?: IResultParameters) { - super(data); - this._discriminator = "ResultParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.operationReference = data["OperationReference"] ? IOperationReference.fromJS(data["OperationReference"]) : undefined; - this.stopOperation = data["StopOperation"]; - } - } - - static fromJS(data: any): ResultParameters { - data = typeof data === 'object' ? data : {}; - if (data["discriminator"] === "RecommenderResultParameters") { - let result = new RecommenderResultParameters(); - result.init(data); - return result; - } - let result = new ResultParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["discriminator"] = this._discriminator; - data["OperationReference"] = this.operationReference ? this.operationReference.toJSON() : undefined; - data["StopOperation"] = this.stopOperation; - super.toJSON(data); - return data; - } -} - -export interface IResultParameters extends IUniqueJson { - operationReference?: IOperationReference | undefined; - stopOperation?: boolean | undefined; -} - -export class RecommenderResultParameters extends ResultParameters implements IRecommenderResultParameters { - from?: number | undefined; - to?: number | undefined; - pValueSorting?: Sorting | undefined; - effectSizeFilter?: EffectSize | undefined; - - constructor(data?: IRecommenderResultParameters) { - super(data); - this._discriminator = "RecommenderResultParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.from = data["From"]; - this.to = data["To"]; - this.pValueSorting = data["PValueSorting"]; - this.effectSizeFilter = data["EffectSizeFilter"]; - } - } - - static fromJS(data: any): RecommenderResultParameters { - data = typeof data === 'object' ? data : {}; - let result = new RecommenderResultParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["From"] = this.from; - data["To"] = this.to; - data["PValueSorting"] = this.pValueSorting; - data["EffectSizeFilter"] = this.effectSizeFilter; - super.toJSON(data); - return data; - } -} - -export interface IRecommenderResultParameters extends IResultParameters { - from?: number | undefined; - to?: number | undefined; - pValueSorting?: Sorting | undefined; - effectSizeFilter?: EffectSize | undefined; -} - -export enum Sorting { - Ascending = "Ascending", - Descending = "Descending", -} - -export class AddComparisonParameters extends ModelOperationParameters implements IAddComparisonParameters { - modelId?: ModelId | undefined; - comparisonOrder?: number | undefined; - childOperationParameters?: OperationParameters[] | undefined; - isCachable?: boolean | undefined; - - constructor(data?: IAddComparisonParameters) { - super(data); - this._discriminator = "AddComparisonParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.modelId = data["ModelId"] ? ModelId.fromJS(data["ModelId"]) : undefined; - this.comparisonOrder = data["ComparisonOrder"]; - if (data["ChildOperationParameters"] && data["ChildOperationParameters"].constructor === Array) { - this.childOperationParameters = []; - for (let item of data["ChildOperationParameters"]) - this.childOperationParameters.push(OperationParameters.fromJS(item)); - } - this.isCachable = data["IsCachable"]; - } - } - - static fromJS(data: any): AddComparisonParameters { - data = typeof data === 'object' ? data : {}; - let result = new AddComparisonParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["ModelId"] = this.modelId ? this.modelId.toJSON() : undefined; - data["ComparisonOrder"] = this.comparisonOrder; - if (this.childOperationParameters && this.childOperationParameters.constructor === Array) { - data["ChildOperationParameters"] = []; - for (let item of this.childOperationParameters) - data["ChildOperationParameters"].push(item.toJSON()); - } - data["IsCachable"] = this.isCachable; - super.toJSON(data); - return data; - } -} - -export interface IAddComparisonParameters extends IModelOperationParameters { - modelId?: ModelId | undefined; - comparisonOrder?: number | undefined; - childOperationParameters?: OperationParameters[] | undefined; - isCachable?: boolean | undefined; -} - -export class CDFResult extends DistResult implements ICDFResult { - cDF?: { [key: string]: number; } | undefined; - - constructor(data?: ICDFResult) { - super(data); - this._discriminator = "CDFResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["CDF"]) { - this.cDF = {}; - for (let key in data["CDF"]) { - if (data["CDF"].hasOwnProperty(key)) - this.cDF[key] = data["CDF"][key]; - } - } - } - } - - static fromJS(data: any): CDFResult { - data = typeof data === 'object' ? data : {}; - let result = new CDFResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.cDF) { - data["CDF"] = {}; - for (let key in this.cDF) { - if (this.cDF.hasOwnProperty(key)) - data["CDF"][key] = this.cDF[key]; - } - } - super.toJSON(data); - return data; - } -} - -export interface ICDFResult extends IDistResult { - cDF?: { [key: string]: number; } | undefined; -} - -export class ChiSquaredTestResult extends HypothesisTestResult implements IChiSquaredTestResult { - hs_aligned?: TupleOfDoubleAndDouble[] | undefined; - - constructor(data?: IChiSquaredTestResult) { - super(data); - this._discriminator = "ChiSquaredTestResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["hs_aligned"] && data["hs_aligned"].constructor === Array) { - this.hs_aligned = []; - for (let item of data["hs_aligned"]) - this.hs_aligned.push(TupleOfDoubleAndDouble.fromJS(item)); - } - } - } - - static fromJS(data: any): ChiSquaredTestResult { - data = typeof data === 'object' ? data : {}; - let result = new ChiSquaredTestResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.hs_aligned && this.hs_aligned.constructor === Array) { - data["hs_aligned"] = []; - for (let item of this.hs_aligned) - data["hs_aligned"].push(item.toJSON()); - } - super.toJSON(data); - return data; - } -} - -export interface IChiSquaredTestResult extends IHypothesisTestResult { - hs_aligned?: TupleOfDoubleAndDouble[] | undefined; -} - -export class CorrelationTestResult extends HypothesisTestResult implements ICorrelationTestResult { - degreeOfFreedom?: number | undefined; - sampleCorrelationCoefficient?: number | undefined; - distResult?: EmpiricalDistResult | undefined; - - constructor(data?: ICorrelationTestResult) { - super(data); - this._discriminator = "CorrelationTestResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.degreeOfFreedom = data["DegreeOfFreedom"]; - this.sampleCorrelationCoefficient = data["SampleCorrelationCoefficient"]; - this.distResult = data["DistResult"] ? EmpiricalDistResult.fromJS(data["DistResult"]) : undefined; - } - } - - static fromJS(data: any): CorrelationTestResult { - data = typeof data === 'object' ? data : {}; - let result = new CorrelationTestResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["DegreeOfFreedom"] = this.degreeOfFreedom; - data["SampleCorrelationCoefficient"] = this.sampleCorrelationCoefficient; - data["DistResult"] = this.distResult ? this.distResult.toJSON() : undefined; - super.toJSON(data); - return data; - } -} - -export interface ICorrelationTestResult extends IHypothesisTestResult { - degreeOfFreedom?: number | undefined; - sampleCorrelationCoefficient?: number | undefined; - distResult?: EmpiricalDistResult | undefined; -} - -export class EmpiricalDistResult extends DistResult implements IEmpiricalDistResult { - marginals?: AttributeParameters[] | undefined; - marginalDistParameters?: { [key: string]: DistParameter; } | undefined; - jointDistParameter?: JointDistParameter | undefined; - - constructor(data?: IEmpiricalDistResult) { - super(data); - this._discriminator = "EmpiricalDistResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["Marginals"] && data["Marginals"].constructor === Array) { - this.marginals = []; - for (let item of data["Marginals"]) - this.marginals.push(AttributeParameters.fromJS(item)); - } - if (data["MarginalDistParameters"]) { - this.marginalDistParameters = {}; - for (let key in data["MarginalDistParameters"]) { - if (data["MarginalDistParameters"].hasOwnProperty(key)) - this.marginalDistParameters[key] = data["MarginalDistParameters"][key] ? DistParameter.fromJS(data["MarginalDistParameters"][key]) : new DistParameter(); - } - } - this.jointDistParameter = data["JointDistParameter"] ? JointDistParameter.fromJS(data["JointDistParameter"]) : undefined; - } - } - - static fromJS(data: any): EmpiricalDistResult { - data = typeof data === 'object' ? data : {}; - let result = new EmpiricalDistResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.marginals && this.marginals.constructor === Array) { - data["Marginals"] = []; - for (let item of this.marginals) - data["Marginals"].push(item.toJSON()); - } - if (this.marginalDistParameters) { - data["MarginalDistParameters"] = {}; - for (let key in this.marginalDistParameters) { - if (this.marginalDistParameters.hasOwnProperty(key)) - data["MarginalDistParameters"][key] = this.marginalDistParameters[key]; - } - } - data["JointDistParameter"] = this.jointDistParameter ? this.jointDistParameter.toJSON() : undefined; - super.toJSON(data); - return data; - } -} - -export interface IEmpiricalDistResult extends IDistResult { - marginals?: AttributeParameters[] | undefined; - marginalDistParameters?: { [key: string]: DistParameter; } | undefined; - jointDistParameter?: JointDistParameter | undefined; -} - -export class DistParameter implements IDistParameter { - mean?: number | undefined; - moment2?: number | undefined; - variance?: number | undefined; - varianceEstimate?: number | undefined; - min?: number | undefined; - max?: number | undefined; - - constructor(data?: IDistParameter) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.mean = data["Mean"]; - this.moment2 = data["Moment2"]; - this.variance = data["Variance"]; - this.varianceEstimate = data["VarianceEstimate"]; - this.min = data["Min"]; - this.max = data["Max"]; - } - } - - static fromJS(data: any): DistParameter { - data = typeof data === 'object' ? data : {}; - let result = new DistParameter(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Mean"] = this.mean; - data["Moment2"] = this.moment2; - data["Variance"] = this.variance; - data["VarianceEstimate"] = this.varianceEstimate; - data["Min"] = this.min; - data["Max"] = this.max; - return data; - } -} - -export interface IDistParameter { - mean?: number | undefined; - moment2?: number | undefined; - variance?: number | undefined; - varianceEstimate?: number | undefined; - min?: number | undefined; - max?: number | undefined; -} - -export class JointDistParameter implements IJointDistParameter { - jointDist?: DistParameter | undefined; - covariance?: number | undefined; - - constructor(data?: IJointDistParameter) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.jointDist = data["JointDist"] ? DistParameter.fromJS(data["JointDist"]) : undefined; - this.covariance = data["Covariance"]; - } - } - - static fromJS(data: any): JointDistParameter { - data = typeof data === 'object' ? data : {}; - let result = new JointDistParameter(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["JointDist"] = this.jointDist ? this.jointDist.toJSON() : undefined; - data["Covariance"] = this.covariance; - return data; - } -} - -export interface IJointDistParameter { - jointDist?: DistParameter | undefined; - covariance?: number | undefined; -} - -export enum DistributionType { - Continuous = 0, - Discrete = 1, -} - -export abstract class DistributionTypeExtension implements IDistributionTypeExtension { - - constructor(data?: IDistributionTypeExtension) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - } - } - - static fromJS(data: any): DistributionTypeExtension { - data = typeof data === 'object' ? data : {}; - throw new Error("The abstract class 'DistributionTypeExtension' cannot be instantiated."); - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - return data; - } -} - -export interface IDistributionTypeExtension { -} - -export class GetModelStateParameters extends ModelOperationParameters implements IGetModelStateParameters { - modelId?: ModelId | undefined; - comparisonIds?: ComparisonId[] | undefined; - riskControlType?: RiskControlType | undefined; - - constructor(data?: IGetModelStateParameters) { - super(data); - this._discriminator = "GetModelStateParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.modelId = data["ModelId"] ? ModelId.fromJS(data["ModelId"]) : undefined; - if (data["ComparisonIds"] && data["ComparisonIds"].constructor === Array) { - this.comparisonIds = []; - for (let item of data["ComparisonIds"]) - this.comparisonIds.push(ComparisonId.fromJS(item)); - } - this.riskControlType = data["RiskControlType"]; - } - } - - static fromJS(data: any): GetModelStateParameters { - data = typeof data === 'object' ? data : {}; - let result = new GetModelStateParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["ModelId"] = this.modelId ? this.modelId.toJSON() : undefined; - if (this.comparisonIds && this.comparisonIds.constructor === Array) { - data["ComparisonIds"] = []; - for (let item of this.comparisonIds) - data["ComparisonIds"].push(item.toJSON()); - } - data["RiskControlType"] = this.riskControlType; - super.toJSON(data); - return data; - } -} - -export interface IGetModelStateParameters extends IModelOperationParameters { - modelId?: ModelId | undefined; - comparisonIds?: ComparisonId[] | undefined; - riskControlType?: RiskControlType | undefined; -} - -export class KSTestResult extends HypothesisTestResult implements IKSTestResult { - - constructor(data?: IKSTestResult) { - super(data); - this._discriminator = "KSTestResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - } - } - - static fromJS(data: any): KSTestResult { - data = typeof data === 'object' ? data : {}; - let result = new KSTestResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - super.toJSON(data); - return data; - } -} - -export interface IKSTestResult extends IHypothesisTestResult { -} - -export class ModelWealthParameters extends UniqueJson implements IModelWealthParameters { - modelId?: ModelId | undefined; - riskControlType?: RiskControlType | undefined; - - constructor(data?: IModelWealthParameters) { - super(data); - } - - init(data?: any) { - super.init(data); - if (data) { - this.modelId = data["ModelId"] ? ModelId.fromJS(data["ModelId"]) : undefined; - this.riskControlType = data["RiskControlType"]; - } - } - - static fromJS(data: any): ModelWealthParameters { - data = typeof data === 'object' ? data : {}; - let result = new ModelWealthParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["ModelId"] = this.modelId ? this.modelId.toJSON() : undefined; - data["RiskControlType"] = this.riskControlType; - super.toJSON(data); - return data; - } -} - -export interface IModelWealthParameters extends IUniqueJson { - modelId?: ModelId | undefined; - riskControlType?: RiskControlType | undefined; -} - -export class RootMeanSquareTestResult extends HypothesisTestResult implements IRootMeanSquareTestResult { - simulationCount?: number | undefined; - extremeSimulationCount?: number | undefined; - - constructor(data?: IRootMeanSquareTestResult) { - super(data); - this._discriminator = "RootMeanSquareTestResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.simulationCount = data["SimulationCount"]; - this.extremeSimulationCount = data["ExtremeSimulationCount"]; - } - } - - static fromJS(data: any): RootMeanSquareTestResult { - data = typeof data === 'object' ? data : {}; - let result = new RootMeanSquareTestResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["SimulationCount"] = this.simulationCount; - data["ExtremeSimulationCount"] = this.extremeSimulationCount; - super.toJSON(data); - return data; - } -} - -export interface IRootMeanSquareTestResult extends IHypothesisTestResult { - simulationCount?: number | undefined; - extremeSimulationCount?: number | undefined; -} - -export class TTestResult extends HypothesisTestResult implements ITTestResult { - degreeOfFreedom?: number | undefined; - distResults?: EmpiricalDistResult[] | undefined; - - constructor(data?: ITTestResult) { - super(data); - this._discriminator = "TTestResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.degreeOfFreedom = data["DegreeOfFreedom"]; - if (data["DistResults"] && data["DistResults"].constructor === Array) { - this.distResults = []; - for (let item of data["DistResults"]) - this.distResults.push(EmpiricalDistResult.fromJS(item)); - } - } - } - - static fromJS(data: any): TTestResult { - data = typeof data === 'object' ? data : {}; - let result = new TTestResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["DegreeOfFreedom"] = this.degreeOfFreedom; - if (this.distResults && this.distResults.constructor === Array) { - data["DistResults"] = []; - for (let item of this.distResults) - data["DistResults"].push(item.toJSON()); - } - super.toJSON(data); - return data; - } -} - -export interface ITTestResult extends IHypothesisTestResult { - degreeOfFreedom?: number | undefined; - distResults?: EmpiricalDistResult[] | undefined; -} - -export enum Sorting2 { - Ascending = 0, - Descending = 1, -} - -export class BinLabel implements IBinLabel { - value?: number | undefined; - minValue?: number | undefined; - maxValue?: number | undefined; - label?: string | undefined; - - constructor(data?: IBinLabel) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.value = data["Value"]; - this.minValue = data["MinValue"]; - this.maxValue = data["MaxValue"]; - this.label = data["Label"]; - } - } - - static fromJS(data: any): BinLabel { - data = typeof data === 'object' ? data : {}; - let result = new BinLabel(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Value"] = this.value; - data["MinValue"] = this.minValue; - data["MaxValue"] = this.maxValue; - data["Label"] = this.label; - return data; - } -} - -export interface IBinLabel { - value?: number | undefined; - minValue?: number | undefined; - maxValue?: number | undefined; - label?: string | undefined; -} - -export class PreProcessedString implements IPreProcessedString { - value?: string | undefined; - id?: number | undefined; - stringLookup?: { [key: string]: number; } | undefined; - indexLookup?: { [key: string]: string; } | undefined; - - constructor(data?: IPreProcessedString) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.value = data["Value"]; - this.id = data["Id"]; - if (data["StringLookup"]) { - this.stringLookup = {}; - for (let key in data["StringLookup"]) { - if (data["StringLookup"].hasOwnProperty(key)) - this.stringLookup[key] = data["StringLookup"][key]; - } - } - if (data["IndexLookup"]) { - this.indexLookup = {}; - for (let key in data["IndexLookup"]) { - if (data["IndexLookup"].hasOwnProperty(key)) - this.indexLookup[key] = data["IndexLookup"][key]; - } - } - } - } - - static fromJS(data: any): PreProcessedString { - data = typeof data === 'object' ? data : {}; - let result = new PreProcessedString(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Value"] = this.value; - data["Id"] = this.id; - if (this.stringLookup) { - data["StringLookup"] = {}; - for (let key in this.stringLookup) { - if (this.stringLookup.hasOwnProperty(key)) - data["StringLookup"][key] = this.stringLookup[key]; - } - } - if (this.indexLookup) { - data["IndexLookup"] = {}; - for (let key in this.indexLookup) { - if (this.indexLookup.hasOwnProperty(key)) - data["IndexLookup"][key] = this.indexLookup[key]; - } - } - return data; - } -} - -export interface IPreProcessedString { - value?: string | undefined; - id?: number | undefined; - stringLookup?: { [key: string]: number; } | undefined; - indexLookup?: { [key: string]: string; } | undefined; -} - -export class BitSet implements IBitSet { - length?: number | undefined; - size?: number | undefined; - - constructor(data?: IBitSet) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - this.length = data["Length"]; - this.size = data["Size"]; - } - } - - static fromJS(data: any): BitSet { - data = typeof data === 'object' ? data : {}; - let result = new BitSet(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Length"] = this.length; - data["Size"] = this.size; - return data; - } -} - -export interface IBitSet { - length?: number | undefined; - size?: number | undefined; -} - -export class DateTimeUtil implements IDateTimeUtil { - - constructor(data?: IDateTimeUtil) { - if (data) { - for (var property in data) { - if (data.hasOwnProperty(property)) - (this)[property] = (data)[property]; - } - } - } - - init(data?: any) { - if (data) { - } - } - - static fromJS(data: any): DateTimeUtil { - data = typeof data === 'object' ? data : {}; - let result = new DateTimeUtil(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - return data; - } -} - -export interface IDateTimeUtil { -} - -export class FrequentItemsetOperationParameters extends DistOperationParameters implements IFrequentItemsetOperationParameters { - filter?: string | undefined; - attributeParameters?: AttributeParameters[] | undefined; - attributeCodeParameters?: AttributeCaclculatedParameters[] | undefined; - - constructor(data?: IFrequentItemsetOperationParameters) { - super(data); - this._discriminator = "FrequentItemsetOperationParameters"; - } - - init(data?: any) { - super.init(data); - if (data) { - this.filter = data["Filter"]; - if (data["AttributeParameters"] && data["AttributeParameters"].constructor === Array) { - this.attributeParameters = []; - for (let item of data["AttributeParameters"]) - this.attributeParameters.push(AttributeParameters.fromJS(item)); - } - if (data["AttributeCodeParameters"] && data["AttributeCodeParameters"].constructor === Array) { - this.attributeCodeParameters = []; - for (let item of data["AttributeCodeParameters"]) - this.attributeCodeParameters.push(AttributeCaclculatedParameters.fromJS(item)); - } - } - } - - static fromJS(data: any): FrequentItemsetOperationParameters { - data = typeof data === 'object' ? data : {}; - let result = new FrequentItemsetOperationParameters(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - data["Filter"] = this.filter; - if (this.attributeParameters && this.attributeParameters.constructor === Array) { - data["AttributeParameters"] = []; - for (let item of this.attributeParameters) - data["AttributeParameters"].push(item.toJSON()); - } - if (this.attributeCodeParameters && this.attributeCodeParameters.constructor === Array) { - data["AttributeCodeParameters"] = []; - for (let item of this.attributeCodeParameters) - data["AttributeCodeParameters"].push(item.toJSON()); - } - super.toJSON(data); - return data; - } -} - -export interface IFrequentItemsetOperationParameters extends IDistOperationParameters { - filter?: string | undefined; - attributeParameters?: AttributeParameters[] | undefined; - attributeCodeParameters?: AttributeCaclculatedParameters[] | undefined; -} - -export class FrequentItemsetResult extends Result implements IFrequentItemsetResult { - frequentItems?: { [key: string]: number; } | undefined; - - constructor(data?: IFrequentItemsetResult) { - super(data); - this._discriminator = "FrequentItemsetResult"; - } - - init(data?: any) { - super.init(data); - if (data) { - if (data["FrequentItems"]) { - this.frequentItems = {}; - for (let key in data["FrequentItems"]) { - if (data["FrequentItems"].hasOwnProperty(key)) - this.frequentItems[key] = data["FrequentItems"][key]; - } - } - } - } - - static fromJS(data: any): FrequentItemsetResult { - data = typeof data === 'object' ? data : {}; - let result = new FrequentItemsetResult(); - result.init(data); - return result; - } - - toJSON(data?: any) { - data = typeof data === 'object' ? data : {}; - if (this.frequentItems) { - data["FrequentItems"] = {}; - for (let key in this.frequentItems) { - if (this.frequentItems.hasOwnProperty(key)) - data["FrequentItems"][key] = this.frequentItems[key]; - } - } - super.toJSON(data); - return data; - } -} - -export interface IFrequentItemsetResult extends IResult { - frequentItems?: { [key: string]: number; } | undefined; -} - diff --git a/src/client/northstar/operations/BaseOperation.ts b/src/client/northstar/operations/BaseOperation.ts deleted file mode 100644 index 013f2244e..000000000 --- a/src/client/northstar/operations/BaseOperation.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { FilterModel } from '../core/filter/FilterModel'; -import { ErrorResult, Exception, OperationParameters, OperationReference, Result, ResultParameters } from '../model/idea/idea'; -import { action, computed, observable } from "mobx"; -import { Gateway } from '../manager/Gateway'; - -export abstract class BaseOperation { - private _interactionTimeoutId: number = 0; - private static _currentOperations: Map = new Map(); - //public InteractionTimeout: EventDelegate = new EventDelegate(); - - @observable public Error: string = ""; - @observable public OverridingFilters: FilterModel[] = []; - //@observable - @observable public Result?: Result = undefined; - @observable public ComputationStarted: boolean = false; - public OperationReference?: OperationReference = undefined; - - private static _nextId = 0; - public RequestSalt: string = ""; - public Id: number; - - constructor() { - this.Id = BaseOperation._nextId++; - } - - @computed - public get FilterString(): string { - return ""; - } - - - @action - public SetResult(result: Result): void { - this.Result = result; - } - - public async Update(): Promise { - - try { - if (BaseOperation._currentOperations.has(this.Id)) { - BaseOperation._currentOperations.get(this.Id)!.Cancel(); - if (this.OperationReference) { - Gateway.Instance.PauseOperation(this.OperationReference.toJSON()); - } - } - - const operationParameters = this.CreateOperationParameters(); - if (this.Result) { - this.Result.progress = 0; - } // bcz: used to set Result to undefined, but that causes the display to blink - this.Error = ""; - const salt = Math.random().toString(); - this.RequestSalt = salt; - - if (!operationParameters) { - this.ComputationStarted = false; - return; - } - - this.ComputationStarted = true; - //let start = performance.now(); - const promise = Gateway.Instance.StartOperation(operationParameters.toJSON()); - promise.catch(err => { - action(() => { - this.Error = err; - console.error(err); - }); - }); - const operationReference = await promise; - - - if (operationReference) { - this.OperationReference = operationReference; - - const resultParameters = new ResultParameters(); - resultParameters.operationReference = operationReference; - - const pollPromise = new PollPromise(salt, operationReference); - BaseOperation._currentOperations.set(this.Id, pollPromise); - - pollPromise.Start(async () => { - const result = await Gateway.Instance.GetResult(resultParameters.toJSON()); - if (result instanceof ErrorResult) { - throw new Error((result).message); - } - 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."); - start = performance.now(); - }*/ - this.SetResult(result); - } - - if (!result || result.progress! < 1) { - return true; - } - } - return false; - }, 100).catch((err: Error) => action(() => { - this.Error = err.message; - console.error(err.message); - })() - ); - } - } - catch (err) { - console.error(err as Exception); - // ErrorDialog.Instance.HandleError(err, operationViewModel); - } - } - - public CreateOperationParameters(): OperationParameters | undefined { return undefined; } - - private interactionTimeout() { - // clearTimeout(this._interactionTimeoutId); - // this.InteractionTimeout.Fire(new InteractionTimeoutEventArgs(this.TypedViewModel, InteractionTimeoutType.Timeout)); - } -} - -export class PollPromise { - public RequestSalt: string; - public OperationReference: OperationReference; - - private _notCanceled: boolean = true; - private _poll: undefined | (() => Promise); - private _delay: number = 0; - - public constructor(requestKey: string, operationReference: OperationReference) { - this.RequestSalt = requestKey; - this.OperationReference = operationReference; - } - - public Cancel(): void { - this._notCanceled = false; - } - - public Start(poll: () => Promise, delay: number): Promise { - this._poll = poll; - this._delay = delay; - return this.pollRecursive(); - } - - private pollRecursive = (): Promise => { - return Promise.resolve().then(this._poll).then((flag) => { - this._notCanceled && flag && new Promise((res) => (setTimeout(res, this._delay))) - .then(this.pollRecursive); - }); - } -} - - -export class InteractionTimeoutEventArgs { - constructor(public Sender: object, public Type: InteractionTimeoutType) { - } -} - -export enum InteractionTimeoutType { - Reset = 0, - Timeout = 1 -} diff --git a/src/client/northstar/operations/HistogramOperation.ts b/src/client/northstar/operations/HistogramOperation.ts deleted file mode 100644 index 74e23ea48..000000000 --- a/src/client/northstar/operations/HistogramOperation.ts +++ /dev/null @@ -1,158 +0,0 @@ -import { action, computed, observable, trace } from "mobx"; -import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; -import { ColumnAttributeModel } from "../core/attribute/AttributeModel"; -import { AttributeTransformationModel } from "../core/attribute/AttributeTransformationModel"; -import { CalculatedAttributeManager } from "../core/attribute/CalculatedAttributeModel"; -import { FilterModel } from "../core/filter/FilterModel"; -import { FilterOperand } from "../core/filter/FilterOperand"; -import { IBaseFilterConsumer } from "../core/filter/IBaseFilterConsumer"; -import { IBaseFilterProvider } from "../core/filter/IBaseFilterProvider"; -import { HistogramField } from "../dash-fields/HistogramField"; -import { SETTINGS_SAMPLE_SIZE, SETTINGS_X_BINS, SETTINGS_Y_BINS } from "../model/binRanges/VisualBinRangeHelper"; -import { AggregateFunction, AggregateParameters, Attribute, AverageAggregateParameters, Bin, DataType, DoubleValueAggregateResult, HistogramOperationParameters, HistogramResult, QuantitativeBinRange } from "../model/idea/idea"; -import { ModelHelpers } from "../model/ModelHelpers"; -import { ArrayUtil } from "../utils/ArrayUtil"; -import { BaseOperation } from "./BaseOperation"; -import { Doc } from "../../../new_fields/Doc"; -import { Cast, NumCast } from "../../../new_fields/Types"; - -export class HistogramOperation extends BaseOperation implements IBaseFilterConsumer, IBaseFilterProvider { - public static Empty = new HistogramOperation("-empty schema-", new AttributeTransformationModel(new ColumnAttributeModel(new Attribute())), new AttributeTransformationModel(new ColumnAttributeModel(new Attribute())), new AttributeTransformationModel(new ColumnAttributeModel(new Attribute()))); - @observable public FilterOperand: FilterOperand = FilterOperand.AND; - @observable public Links: Doc[] = []; - @observable public BrushLinks: { l: Doc, b: Doc }[] = []; - @observable public BrushColors: number[] = []; - @observable public BarFilterModels: FilterModel[] = []; - - @observable public Normalization: number = -1; - @observable public X: AttributeTransformationModel; - @observable public Y: AttributeTransformationModel; - @observable public V: AttributeTransformationModel; - @observable public SchemaName: string; - @observable public QRange: QuantitativeBinRange | undefined; - public get Schema() { return CurrentUserUtils.GetNorthstarSchema(this.SchemaName); } - - constructor(schemaName: string, x: AttributeTransformationModel, y: AttributeTransformationModel, v: AttributeTransformationModel, normalized?: number) { - super(); - this.X = x; - this.Y = y; - this.V = v; - this.Normalization = normalized ? normalized : -1; - this.SchemaName = schemaName; - } - - public static Duplicate(op: HistogramOperation) { - - return new HistogramOperation(op.SchemaName, op.X, op.Y, op.V, op.Normalization); - } - public Copy(): HistogramOperation { - return new HistogramOperation(this.SchemaName, this.X, this.Y, this.V, this.Normalization); - } - - Equals(other: Object): boolean { - throw new Error("Method not implemented."); - } - - - public get FilterModels() { - return this.BarFilterModels; - } - @action - public AddFilterModels(filterModels: FilterModel[]): void { - filterModels.filter(f => f !== null).forEach(fm => this.BarFilterModels.push(fm)); - } - @action - public RemoveFilterModels(filterModels: FilterModel[]): void { - ArrayUtil.RemoveMany(this.BarFilterModels, filterModels); - } - - @computed - public get FilterString(): string { - if (this.OverridingFilters.length > 0) { - return "(" + this.OverridingFilters.filter(fm => fm !== null).map(fm => fm.ToPythonString()).join(" || ") + ")"; - } - let filterModels: FilterModel[] = []; - return FilterModel.GetFilterModelsRecursive(this, new Set(), filterModels, true); - } - - public get BrushString(): string[] { - let brushes: string[] = []; - this.BrushLinks.map(brushLink => { - let brushHistogram = Cast(brushLink.b.data, HistogramField); - if (brushHistogram) { - let filterModels: FilterModel[] = []; - brushes.push(FilterModel.GetFilterModelsRecursive(brushHistogram.HistoOp, new Set(), filterModels, false)); - } - }); - return brushes; - } - - _stackedFilters: (FilterModel[])[] = []; - @action - public DrillDown(up: boolean) { - if (!up) { - if (!this.BarFilterModels.length) { - return; - } - this._stackedFilters.push(this.BarFilterModels.map(f => f)); - this.OverridingFilters.length = 0; - this.OverridingFilters.push(...this._stackedFilters[this._stackedFilters.length - 1]); - this.BarFilterModels.map(fm => fm).map(fm => this.RemoveFilterModels([fm])); - //this.updateHistogram(); - } else { - this.OverridingFilters.length = 0; - if (this._stackedFilters.length) { - this.OverridingFilters.push(...this._stackedFilters.pop()!); - } - // else - // this.updateHistogram(); - } - } - - private getAggregateParameters(histoX: AttributeTransformationModel, histoY: AttributeTransformationModel, histoValue: AttributeTransformationModel) { - let allAttributes = new Array(histoX, histoY, histoValue); - allAttributes = ArrayUtil.Distinct(allAttributes.filter(a => a.AggregateFunction !== AggregateFunction.None)); - - let numericDataTypes = [DataType.Int, DataType.Double, DataType.Float]; - let perBinAggregateParameters: AggregateParameters[] = ModelHelpers.GetAggregateParametersWithMargins(this.Schema!.distinctAttributeParameters, allAttributes); - let globalAggregateParameters: AggregateParameters[] = []; - [histoX, histoY] - .filter(a => a.AggregateFunction === AggregateFunction.None && ArrayUtil.Contains(numericDataTypes, a.AttributeModel.DataType)) - .forEach(a => { - let avg = new AverageAggregateParameters(); - avg.attributeParameters = ModelHelpers.GetAttributeParameters(a.AttributeModel); - globalAggregateParameters.push(avg); - }); - return [perBinAggregateParameters, globalAggregateParameters]; - } - - public CreateOperationParameters(): HistogramOperationParameters | undefined { - if (this.X && this.Y && this.V) { - let [perBinAggregateParameters, globalAggregateParameters] = this.getAggregateParameters(this.X, this.Y, this.V); - return new HistogramOperationParameters({ - enableBrushComputation: true, - adapterName: this.SchemaName, - filter: this.FilterString, - brushes: this.BrushString, - binningParameters: [ModelHelpers.GetBinningParameters(this.X, SETTINGS_X_BINS, this.QRange ? this.QRange.minValue : undefined, this.QRange ? this.QRange.maxValue : undefined), - ModelHelpers.GetBinningParameters(this.Y, SETTINGS_Y_BINS)], - sampleStreamBlockSize: SETTINGS_SAMPLE_SIZE, - perBinAggregateParameters: perBinAggregateParameters, - globalAggregateParameters: globalAggregateParameters, - sortPerBinAggregateParameter: undefined, - attributeCalculatedParameters: CalculatedAttributeManager - .AllCalculatedAttributes.map(a => ModelHelpers.GetAttributeParametersFromAttributeModel(a)), - degreeOfParallism: 1, // Settings.Instance.DegreeOfParallelism, - isCachable: false - }); - } - } - - @action - public async Update(): Promise { - this.BrushColors = this.BrushLinks.map(e => NumCast(e.l.backgroundColor)); - return super.Update(); - } -} - - diff --git a/src/client/northstar/utils/ArrayUtil.ts b/src/client/northstar/utils/ArrayUtil.ts deleted file mode 100644 index 12b8d8e77..000000000 --- a/src/client/northstar/utils/ArrayUtil.ts +++ /dev/null @@ -1,90 +0,0 @@ -import { Exception } from "../model/idea/idea"; - -export class ArrayUtil { - - public static Contains(arr1: any[], arr2: any): boolean { - if (arr1.length === 0) { - return false; - } - let isComplex = typeof arr1[0] === "object"; - for (const ele of arr1) { - if (isComplex && "Equals" in ele) { - if (ele.Equals(arr2)) { - return true; - } - } - else { - if (ele === arr2) { - return true; - } - } - } - return false; - } - - - public static RemoveMany(arr: any[], elements: Object[]) { - elements.forEach(e => ArrayUtil.Remove(arr, e)); - } - - public static AddMany(arr: any[], others: Object[]) { - arr.push(...others); - } - - public static Clear(arr: any[]) { - arr.splice(0, arr.length); - } - - - public static Remove(arr: any[], other: Object) { - const index = ArrayUtil.IndexOfWithEqual(arr, other); - if (index === -1) { - return; - } - arr.splice(index, 1); - } - - - public static First(arr: T[], predicate: (x: any) => boolean): T { - let filtered = arr.filter(predicate); - if (filtered.length > 0) { - return filtered[0]; - } - throw new Exception(); - } - - public static FirstOrDefault(arr: T[], predicate: (x: any) => boolean): T | undefined { - let filtered = arr.filter(predicate); - if (filtered.length > 0) { - return filtered[0]; - } - return undefined; - } - - public static Distinct(arr: any[]): any[] { - let ret = []; - for (const ele of arr) { - if (!ArrayUtil.Contains(ret, ele)) { - ret.push(ele); - } - } - return ret; - } - - public static IndexOfWithEqual(arr: any[], other: any): number { - for (let i = 0; i < arr.length; i++) { - let isComplex = typeof arr[0] === "object"; - if (isComplex && "Equals" in arr[i]) { - if (arr[i].Equals(other)) { - return i; - } - } - else { - if (arr[i] === other) { - return i; - } - } - } - return -1; - } -} \ No newline at end of file diff --git a/src/client/northstar/utils/Extensions.ts b/src/client/northstar/utils/Extensions.ts deleted file mode 100644 index df14d4da0..000000000 --- a/src/client/northstar/utils/Extensions.ts +++ /dev/null @@ -1,29 +0,0 @@ -interface String { - ReplaceAll(toReplace: string, replacement: string): string; - Truncate(length: number, replacement: string): String; -} - -String.prototype.ReplaceAll = function (toReplace: string, replacement: string): string { - var target = this; - return target.split(toReplace).join(replacement); -}; - -String.prototype.Truncate = function (length: number, replacement: string): String { - var target = this; - if (target.length >= length) { - target = target.slice(0, Math.max(0, length - replacement.length)) + replacement; - } - return target; -}; - -interface Math { - log10(val: number): number; -} - -Math.log10 = function (val: number): number { - return Math.log(val) / Math.LN10; -}; - -declare interface ObjectConstructor { - assign(...objects: Object[]): Object; -} diff --git a/src/client/northstar/utils/GeometryUtil.ts b/src/client/northstar/utils/GeometryUtil.ts deleted file mode 100644 index d5220c479..000000000 --- a/src/client/northstar/utils/GeometryUtil.ts +++ /dev/null @@ -1,133 +0,0 @@ -import { MathUtil, PIXIRectangle, PIXIPoint } from "./MathUtil"; - - -export class GeometryUtil { - - public static ComputeBoundingBox(points: { x: number, y: number }[], scale = 1, padding: number = 0): PIXIRectangle { - let minX: number = Number.MAX_VALUE; - let minY: number = Number.MAX_VALUE; - let maxX: number = Number.MIN_VALUE; - let maxY: number = Number.MIN_VALUE; - for (const point of points) { - if (point.x < minX) { - minX = point.x; - } - if (point.y < minY) { - minY = point.y; - } - if (point.x > maxX) { - maxX = point.x; - } - if (point.y > maxY) { - maxY = point.y; - } - } - return new PIXIRectangle(minX * scale - padding, minY * scale - padding, (maxX - minX) * scale + padding * 2, (maxY - minY) * scale + padding * 2); - } - - public static RectangleOverlap(rect1: PIXIRectangle, rect2: PIXIRectangle) { - let x_overlap = Math.max(0, Math.min(rect1.right, rect2.right) - Math.max(rect1.left, rect2.left)); - let y_overlap = Math.max(0, Math.min(rect1.bottom, rect2.bottom) - Math.max(rect1.top, rect2.top)); - return x_overlap * y_overlap; - } - - public static RotatePoints(center: { x: number, y: number }, points: { x: number, y: number }[], angle: number): PIXIPoint[] { - const rotate = (cx: number, cy: number, x: number, y: number, angle: number) => { - const radians = angle, - cos = Math.cos(radians), - sin = Math.sin(radians), - nx = (cos * (x - cx)) + (sin * (y - cy)) + cx, - ny = (cos * (y - cy)) - (sin * (x - cx)) + cy; - return new PIXIPoint(nx, ny); - }; - return points.map(p => rotate(center.x, center.y, p.x, p.y, angle)); - } - - public static LineByLeastSquares(points: { x: number, y: number }[]): PIXIPoint[] { - let sum_x: number = 0; - let sum_y: number = 0; - let sum_xy: number = 0; - let sum_xx: number = 0; - let count: number = 0; - - let x: number = 0; - let y: number = 0; - - - if (points.length === 0) { - return []; - } - - for (const point of points) { - x = point.x; - y = point.y; - sum_x += x; - sum_y += y; - sum_xx += x * x; - sum_xy += x * y; - count++; - } - - let m = (count * sum_xy - sum_x * sum_y) / (count * sum_xx - sum_x * sum_x); - let b = (sum_y / count) - (m * sum_x) / count; - let result: PIXIPoint[] = new Array(); - - for (const point of points) { - x = point.x; - y = x * m + b; - result.push(new PIXIPoint(x, y)); - } - return result; - } - - // public static PointInsidePolygon(vs:Point[], x:number, y:number):boolean { - // // ray-casting algorithm based on - // // http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html - - // var inside = false; - // for (var i = 0, j = vs.length - 1; i < vs.length; j = i++) { - // 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); - // if (intersect) - // inside = !inside; - // } - - // return inside; - // }; - - public static IntersectLines(x1: number, y1: number, x2: number, y2: number, x3: number, y3: number, x4: number, y4: number): boolean { - let a1: number, a2: number, b1: number, b2: number, c1: number, c2: number; - let r1: number, r2: number, r3: number, r4: number; - let denom: number, offset: number, num: number; - - a1 = y2 - y1; - b1 = x1 - x2; - c1 = (x2 * y1) - (x1 * y2); - r3 = ((a1 * x3) + (b1 * y3) + c1); - r4 = ((a1 * x4) + (b1 * y4) + c1); - - if ((r3 !== 0) && (r4 !== 0) && (MathUtil.Sign(r3) === MathUtil.Sign(r4))) { - return false; - } - - a2 = y4 - y3; - b2 = x3 - x4; - c2 = (x4 * y3) - (x3 * y4); - - r1 = (a2 * x1) + (b2 * y1) + c2; - r2 = (a2 * x2) + (b2 * y2) + c2; - - if ((r1 !== 0) && (r2 !== 0) && (MathUtil.Sign(r1) === MathUtil.Sign(r2))) { - return false; - } - - denom = (a1 * b2) - (a2 * b1); - - if (denom === 0) { - return false; - } - return true; - } -} \ No newline at end of file diff --git a/src/client/northstar/utils/IDisposable.ts b/src/client/northstar/utils/IDisposable.ts deleted file mode 100644 index 5e9843326..000000000 --- a/src/client/northstar/utils/IDisposable.ts +++ /dev/null @@ -1,3 +0,0 @@ -export interface IDisposable { - Dispose(): void; -} \ No newline at end of file diff --git a/src/client/northstar/utils/IEquatable.ts b/src/client/northstar/utils/IEquatable.ts deleted file mode 100644 index 2f81c2478..000000000 --- a/src/client/northstar/utils/IEquatable.ts +++ /dev/null @@ -1,3 +0,0 @@ -export interface IEquatable { - Equals(other: Object): boolean; -} \ No newline at end of file diff --git a/src/client/northstar/utils/KeyCodes.ts b/src/client/northstar/utils/KeyCodes.ts deleted file mode 100644 index 044569ffe..000000000 --- a/src/client/northstar/utils/KeyCodes.ts +++ /dev/null @@ -1,137 +0,0 @@ -/** - * Class contains the keycodes for keys on your keyboard. - * - * Useful for auto completion: - * - * ``` - * switch (event.key) - * { - * case KeyCode.UP: - * { - * // Up key pressed - * break; - * } - * case KeyCode.DOWN: - * { - * // Down key pressed - * break; - * } - * case KeyCode.LEFT: - * { - * // Left key pressed - * break; - * } - * case KeyCode.RIGHT: - * { - * // Right key pressed - * break; - * } - * default: - * { - * // ignore - * break; - * } - * } - * ``` - */ -export class KeyCodes -{ - public static TAB:number = 9; - public static CAPS_LOCK:number = 20; - public static SHIFT:number = 16; - public static CONTROL:number = 17; - public static SPACE:number = 32; - public static DOWN:number = 40; - public static UP:number = 38; - public static LEFT:number = 37; - public static RIGHT:number = 39; - public static ESCAPE:number = 27; - public static F1:number = 112; - public static F2:number = 113; - public static F3:number = 114; - public static F4:number = 115; - public static F5:number = 116; - public static F6:number = 117; - public static F7:number = 118; - public static F8:number = 119; - public static F9:number = 120; - public static F10:number = 121; - public static F11:number = 122; - public static F12:number = 123; - public static INSERT:number = 45; - public static HOME:number = 36; - public static PAGE_UP:number = 33; - public static PAGE_DOWN:number = 34; - public static DELETE:number = 46; - public static END:number = 35; - public static ENTER:number = 13; - public static BACKSPACE:number = 8; - public static NUMPAD_0:number = 96; - public static NUMPAD_1:number = 97; - public static NUMPAD_2:number = 98; - public static NUMPAD_3:number = 99; - public static NUMPAD_4:number = 100; - public static NUMPAD_5:number = 101; - public static NUMPAD_6:number = 102; - public static NUMPAD_7:number = 103; - public static NUMPAD_8:number = 104; - public static NUMPAD_9:number = 105; - public static NUMPAD_DIVIDE:number = 111; - public static NUMPAD_ADD:number = 107; - public static NUMPAD_ENTER:number = 13; - public static NUMPAD_DECIMAL:number = 110; - public static NUMPAD_SUBTRACT:number = 109; - public static NUMPAD_MULTIPLY:number = 106; - public static SEMICOLON:number = 186; - public static EQUAL:number = 187; - public static COMMA:number = 188; - public static MINUS:number = 189; - public static PERIOD:number = 190; - public static SLASH:number = 191; - public static BACKQUOTE:number = 192; - public static LEFTBRACKET:number = 219; - public static BACKSLASH:number = 220; - public static RIGHTBRACKET:number = 221; - public static QUOTE:number = 222; - public static ALT:number = 18; - public static COMMAND:number = 15; - public static NUMPAD:number = 21; - public static A:number = 65; - public static B:number = 66; - public static C:number = 67; - public static D:number = 68; - public static E:number = 69; - public static F:number = 70; - public static G:number = 71; - public static H:number = 72; - public static I:number = 73; - public static J:number = 74; - public static K:number = 75; - public static L:number = 76; - public static M:number = 77; - public static N:number = 78; - public static O:number = 79; - public static P:number = 80; - public static Q:number = 81; - public static R:number = 82; - public static S:number = 83; - public static T:number = 84; - public static U:number = 85; - public static V:number = 86; - public static W:number = 87; - public static X:number = 88; - public static Y:number = 89; - public static Z:number = 90; - public static NUM_0:number = 48; - public static NUM_1:number = 49; - public static NUM_2:number = 50; - public static NUM_3:number = 51; - public static NUM_4:number = 52; - public static NUM_5:number = 53; - public static NUM_6:number = 54; - public static NUM_7:number = 55; - public static NUM_8:number = 56; - public static NUM_9:number = 57; - public static SUBSTRACT:number = 189; - public static ADD:number = 187; -} \ No newline at end of file diff --git a/src/client/northstar/utils/LABColor.ts b/src/client/northstar/utils/LABColor.ts deleted file mode 100644 index 72e46fb7f..000000000 --- a/src/client/northstar/utils/LABColor.ts +++ /dev/null @@ -1,90 +0,0 @@ - -export class LABColor { - public L: number; - public A: number; - public B: number; - - // constructor - takes three floats for lightness and color-opponent dimensions - constructor(l: number, a: number, b: number) { - this.L = l; - this.A = a; - this.B = b; - } - - // static function for linear interpolation between two LABColors - public static Lerp(a: LABColor, b: LABColor, t: number): LABColor { - return new LABColor(LABColor.LerpNumber(a.L, b.L, t), LABColor.LerpNumber(a.A, b.A, t), LABColor.LerpNumber(a.B, b.B, t)); - } - - public static LerpNumber(a: number, b: number, percent: number): number { - return a + percent * (b - a); - } - - static hexToRGB(hex: number, alpha: number): number[] { - var r = (hex & (0xff << 16)) >> 16; - var g = (hex & (0xff << 8)) >> 8; - var b = (hex & (0xff << 0)) >> 0; - return [r, g, b]; - } - static RGBtoHex(red: number, green: number, blue: number): number { - return blue | (green << 8) | (red << 16); - } - - public static RGBtoHexString(rgb: number): string { - let str = "#" + this.hex((rgb & (0xff << 16)) >> 16) + this.hex((rgb & (0xff << 8)) >> 8) + this.hex((rgb & (0xff << 0)) >> 0); - return str; - } - - static hex(x: number): string { - var hexDigits = new Array - ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"); - return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16]; - } - - public static FromColor(c: number): LABColor { - var rgb = LABColor.hexToRGB(c, 0); - var r = LABColor.d3_rgb_xyz(rgb[0] * 255); - var g = LABColor.d3_rgb_xyz(rgb[1] * 255); - var b = LABColor.d3_rgb_xyz(rgb[2] * 255); - - var x = LABColor.d3_xyz_lab((0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / LABColor.d3_lab_X); - var y = LABColor.d3_xyz_lab((0.2126729 * r + 0.7151522 * g + 0.0721750 * b) / LABColor.d3_lab_Y); - var z = LABColor.d3_xyz_lab((0.0193339 * r + 0.1191920 * g + 0.9503041 * b) / LABColor.d3_lab_Z); - var lab = new LABColor(116 * y - 16, 500 * (x - y), 200 * (y - z)); - return lab; - } - - private static d3_lab_X: number = 0.950470; - private static d3_lab_Y: number = 1; - private static d3_lab_Z: number = 1.088830; - - public static d3_lab_xyz(x: number): number { - return x > 0.206893034 ? x * x * x : (x - 4 / 29) / 7.787037; - } - - public static d3_xyz_rgb(r: number): number { - return Math.round(255 * (r <= 0.00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - 0.055)); - } - - public static d3_rgb_xyz(r: number): number { - return (r /= 255) <= 0.04045 ? r / 12.92 : Math.pow((r + 0.055) / 1.055, 2.4); - } - - public static d3_xyz_lab(x: number): number { - return x > 0.008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; - } - - public static ToColor(lab: LABColor): number { - var y = (lab.L + 16) / 116; - var x = y + lab.A / 500; - var z = y - lab.B / 200; - x = LABColor.d3_lab_xyz(x) * LABColor.d3_lab_X; - y = LABColor.d3_lab_xyz(y) * LABColor.d3_lab_Y; - z = LABColor.d3_lab_xyz(z) * LABColor.d3_lab_Z; - - return LABColor.RGBtoHex( - LABColor.d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z) / 255, - LABColor.d3_xyz_rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z) / 255, - LABColor.d3_xyz_rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z) / 255); - } -} \ No newline at end of file diff --git a/src/client/northstar/utils/MathUtil.ts b/src/client/northstar/utils/MathUtil.ts deleted file mode 100644 index 5def5e704..000000000 --- a/src/client/northstar/utils/MathUtil.ts +++ /dev/null @@ -1,249 +0,0 @@ - - -export class PIXIPoint { - public get x() { return this.coords[0]; } - public get y() { return this.coords[1]; } - public set x(value: number) { this.coords[0] = value; } - public set y(value: number) { this.coords[1] = value; } - public coords: number[] = [0, 0]; - constructor(x: number, y: number) { - this.coords[0] = x; - this.coords[1] = y; - } -} - -export class PIXIRectangle { - public x: number; - public y: number; - public width: number; - public height: number; - public get left() { return this.x; } - public get right() { return this.x + this.width; } - public get top() { return this.y; } - public get bottom() { return this.top + this.height; } - public static get EMPTY() { return new PIXIRectangle(0, 0, -1, -1); } - constructor(x: number, y: number, width: number, height: number) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - } -} - -export class MathUtil { - - public static EPSILON: number = 0.001; - - public static Sign(value: number): number { - return value >= 0 ? 1 : -1; - } - - public static AddPoint(p1: PIXIPoint, p2: PIXIPoint, inline: boolean = false): PIXIPoint { - if (inline) { - p1.x += p2.x; - p1.y += p2.y; - return p1; - } - else { - return new PIXIPoint(p1.x + p2.x, p1.y + p2.y); - } - } - - public static Perp(p1: PIXIPoint): PIXIPoint { - return new PIXIPoint(-p1.y, p1.x); - } - - public static DividePoint(p1: PIXIPoint, by: number, inline: boolean = false): PIXIPoint { - if (inline) { - p1.x /= by; - p1.y /= by; - return p1; - } - else { - return new PIXIPoint(p1.x / by, p1.y / by); - } - } - - public static MultiplyConstant(p1: PIXIPoint, by: number, inline: boolean = false) { - if (inline) { - p1.x *= by; - p1.y *= by; - return p1; - } - else { - return new PIXIPoint(p1.x * by, p1.y * by); - } - } - - public static SubtractPoint(p1: PIXIPoint, p2: PIXIPoint, inline: boolean = false): PIXIPoint { - if (inline) { - p1.x -= p2.x; - p1.y -= p2.y; - return p1; - } - else { - return new PIXIPoint(p1.x - p2.x, p1.y - p2.y); - } - } - - public static Area(rect: PIXIRectangle): number { - return rect.width * rect.height; - } - - public static DistToLineSegment(v: PIXIPoint, w: PIXIPoint, p: PIXIPoint) { - // Return minimum distance between line segment vw and point p - const 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 - // 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 - // We clamp t from [0,1] to handle points outside the segment vw. - const dot = MathUtil.Dot( - MathUtil.SubtractPoint(p, v), - MathUtil.SubtractPoint(w, v)) / l2; - const t = Math.max(0, Math.min(1, dot)); - // Projection falls on the segment - const projection = MathUtil.AddPoint(v, - MathUtil.MultiplyConstant( - MathUtil.SubtractPoint(w, v), t)); - return MathUtil.Dist(p, projection); - } - - public static LineSegmentIntersection(ps1: PIXIPoint, pe1: PIXIPoint, ps2: PIXIPoint, pe2: PIXIPoint): PIXIPoint | undefined { - const a1 = pe1.y - ps1.y; - const b1 = ps1.x - pe1.x; - - const a2 = pe2.y - ps2.y; - const b2 = ps2.x - pe2.x; - - const delta = a1 * b2 - a2 * b1; - if (delta === 0) { - return undefined; - } - const c2 = a2 * ps2.x + b2 * ps2.y; - const c1 = a1 * ps1.x + b1 * ps1.y; - const invdelta = 1 / delta; - return new PIXIPoint((b2 * c1 - b1 * c2) * invdelta, (a1 * c2 - a2 * c1) * invdelta); - } - - public static PointInPIXIRectangle(p: PIXIPoint, rect: PIXIRectangle): boolean { - if (p.x < rect.left - this.EPSILON) { - return false; - } - if (p.x > rect.right + this.EPSILON) { - return false; - } - if (p.y < rect.top - this.EPSILON) { - return false; - } - if (p.y > rect.bottom + this.EPSILON) { - return false; - } - - return true; - } - - public static LinePIXIRectangleIntersection(lineFrom: PIXIPoint, lineTo: PIXIPoint, rect: PIXIRectangle): Array { - const r1 = new PIXIPoint(rect.left, rect.top); - const r2 = new PIXIPoint(rect.right, rect.top); - const r3 = new PIXIPoint(rect.right, rect.bottom); - const r4 = new PIXIPoint(rect.left, rect.bottom); - const ret = new Array(); - const dist = this.Dist(lineFrom, lineTo); - let inter = this.LineSegmentIntersection(lineFrom, lineTo, r1, r2); - 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 && 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 && 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 && this.PointInPIXIRectangle(inter, rect) && - this.Dist(inter, lineFrom) < dist && this.Dist(inter, lineTo) < dist) { - ret.push(inter); - } - return ret; - } - - public static Intersection(rect1: PIXIRectangle, rect2: PIXIRectangle): PIXIRectangle { - const left = Math.max(rect1.x, rect2.x); - const right = Math.min(rect1.x + rect1.width, rect2.x + rect2.width); - const top = Math.max(rect1.y, rect2.y); - const bottom = Math.min(rect1.y + rect1.height, rect2.y + rect2.height); - return new PIXIRectangle(left, top, right - left, bottom - top); - } - - public static Dist(p1: PIXIPoint, p2: PIXIPoint): number { - return Math.sqrt(MathUtil.DistSquared(p1, p2)); - } - - public static Dot(p1: PIXIPoint, p2: PIXIPoint): number { - return p1.x * p2.x + p1.y * p2.y; - } - - public static Normalize(p1: PIXIPoint) { - const d = this.Length(p1); - return new PIXIPoint(p1.x / d, p1.y / d); - } - - public static Length(p1: PIXIPoint): number { - return Math.sqrt(p1.x * p1.x + p1.y * p1.y); - } - - public static DistSquared(p1: PIXIPoint, p2: PIXIPoint): number { - const a = p1.x - p2.x; - const b = p1.y - p2.y; - return (a * a + b * b); - } - - public static RectIntersectsRect(r1: PIXIRectangle, r2: PIXIRectangle): boolean { - return !(r2.x > r1.x + r1.width || - r2.x + r2.width < r1.x || - r2.y > r1.y + r1.height || - r2.y + r2.height < r1.y); - } - - public static ArgMin(temp: number[]): number { - let index = 0; - let value = temp[0]; - for (let i = 1; i < temp.length; i++) { - if (temp[i] < value) { - value = temp[i]; - index = i; - } - } - return index; - } - - public static ArgMax(temp: number[]): number { - let index = 0; - let value = temp[0]; - for (let i = 1; i < temp.length; i++) { - if (temp[i] > value) { - value = temp[i]; - index = i; - } - } - return index; - } - - public static Combinations(chars: T[]) { - const result = new Array(); - const f = (prefix: any, chars: any) => { - for (let i = 0; i < chars.length; i++) { - result.push(prefix.concat(chars[i])); - f(prefix.concat(chars[i]), chars.slice(i + 1)); - } - }; - f([], chars); - return result; - } -} \ No newline at end of file diff --git a/src/client/northstar/utils/PartialClass.ts b/src/client/northstar/utils/PartialClass.ts deleted file mode 100644 index 2f20de96f..000000000 --- a/src/client/northstar/utils/PartialClass.ts +++ /dev/null @@ -1,7 +0,0 @@ - -export class PartialClass { - - constructor(data?: Partial) { - Object.assign(this, data); - } -} \ No newline at end of file diff --git a/src/client/northstar/utils/SizeConverter.ts b/src/client/northstar/utils/SizeConverter.ts deleted file mode 100644 index a52890ed9..000000000 --- a/src/client/northstar/utils/SizeConverter.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { PIXIPoint } from "./MathUtil"; -import { VisualBinRange } from "../model/binRanges/VisualBinRange"; -import { Bin, DoubleValueAggregateResult, AggregateKey } from "../model/idea/idea"; -import { ModelHelpers } from "../model/ModelHelpers"; -import { observable, action, computed } from "mobx"; - -export class SizeConverter { - public DataMins: Array = new Array(2); - public DataMaxs: Array = new Array(2); - public DataRanges: Array = new Array(2); - public MaxLabelSizes: Array = new Array(2); - public RenderDimension: number = 300; - - @observable _leftOffset: number = 40; - @observable _rightOffset: number = 20; - @observable _topOffset: number = 20; - @observable _bottomOffset: number = 45; - @observable _labelAngle: number = 0; - @observable _isSmall: boolean = false; - @observable public Initialized = 0; - - @action public SetIsSmall(isSmall: boolean) { this._isSmall = isSmall; } - @action public SetLabelAngle(angle: number) { this._labelAngle = angle; } - @computed public get IsSmall() { return this._isSmall; } - @computed public get LabelAngle() { return this._labelAngle; } - @computed public get LeftOffset() { return this.IsSmall ? 5 : this._leftOffset; } - @computed public get RightOffset() { return this.IsSmall ? 5 : !this._labelAngle ? this._bottomOffset : Math.max(this._rightOffset, Math.cos(this._labelAngle) * (this.MaxLabelSizes[0].x + 18)); } - @computed public get TopOffset() { return this.IsSmall ? 5 : this._topOffset; } - @computed public get BottomOffset() { return this.IsSmall ? 25 : !this._labelAngle ? this._bottomOffset : Math.max(this._bottomOffset, Math.sin(this._labelAngle) * (this.MaxLabelSizes[0].x + 18)) + 18; } - - public SetVisualBinRanges(visualBinRanges: Array) { - this.Initialized++; - var xLabels = visualBinRanges[0].GetLabels(); - var yLabels = visualBinRanges[1].GetLabels(); - var xLabelStrings = xLabels.map(l => l.label!).sort(function (a, b) { return b.length - a.length; }); - var yLabelStrings = yLabels.map(l => l.label!).sort(function (a, b) { return b.length - a.length; }); - - var metricsX = { width: 75 }; // RenderUtils.MeasureText(FontStyles.Default.fontFamily.toString(), 12, // FontStyles.AxisLabel.fontSize as number, - //xLabelStrings[0]!.slice(0, 20)) // StyleConstants.MAX_CHAR_FOR_HISTOGRAM_LABELS)); - var metricsY = { width: 22 }; // RenderUtils.MeasureText(FontStyles.Default.fontFamily.toString(), 12, // FontStyles.AxisLabel.fontSize as number, - // yLabelStrings[0]!.slice(0, 20)); // StyleConstants.MAX_CHAR_FOR_HISTOGRAM_LABELS)); - this.MaxLabelSizes[0] = new PIXIPoint(metricsX.width, 12);// FontStyles.AxisLabel.fontSize as number); - this.MaxLabelSizes[1] = new PIXIPoint(metricsY.width, 12); // FontStyles.AxisLabel.fontSize as number); - - this._leftOffset = Math.max(10, metricsY.width + 10 + 20); - - this.DataMins[0] = xLabels.map(l => l.minValue!).reduce((m, c) => Math.min(m, c), Number.MAX_VALUE); - this.DataMins[1] = yLabels.map(l => l.minValue!).reduce((m, c) => Math.min(m, c), Number.MAX_VALUE); - this.DataMaxs[0] = xLabels.map(l => l.maxValue!).reduce((m, c) => Math.max(m, c), Number.MIN_VALUE); - this.DataMaxs[1] = yLabels.map(l => l.maxValue!).reduce((m, c) => Math.max(m, c), Number.MIN_VALUE); - - this.DataRanges[0] = this.DataMaxs[0] - this.DataMins[0]; - this.DataRanges[1] = this.DataMaxs[1] - this.DataMins[1]; - } - - 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 from = this.DataToScreenCoord(Math.min(0, value), axis); - var to = this.DataToScreenCoord(Math.max(0, value), axis); - return [from, value, to]; - } - - public DataToScreenPointRange(axis: number, bin: Bin, aggregateKey: AggregateKey) { - var value = ModelHelpers.GetAggregateResult(bin, aggregateKey) as DoubleValueAggregateResult; - if (value && value.hasResult) { - return [this.DataToScreenCoord(value.result!, axis) - 5, - this.DataToScreenCoord(value.result!, axis) + 5]; - } - return [undefined, undefined]; - } - - public DataToScreenXAxisRange(visualBinRanges: VisualBinRange[], index: number, bin: Bin) { - var value = visualBinRanges[0].GetValueFromIndex(bin.binIndex!.indices![index]); - return [this.DataToScreenX(value), this.DataToScreenX(visualBinRanges[index].AddStep(value))]; - } - public DataToScreenYAxisRange(visualBinRanges: VisualBinRange[], index: number, bin: Bin) { - var value = visualBinRanges[1].GetValueFromIndex(bin.binIndex!.indices![index]); - return [this.DataToScreenY(value), this.DataToScreenY(visualBinRanges[index].AddStep(value))]; - } - - public DataToScreenX(x: number): number { - return ((x - this.DataMins[0]) / this.DataRanges[0]) * this.RenderDimension; - } - public DataToScreenY(y: number, flip: boolean = true) { - var retY = ((y - this.DataMins[1]) / this.DataRanges[1]) * this.RenderDimension; - return flip ? (this.RenderDimension) - retY : retY; - } - public DataToScreenCoord(v: number, axis: number) { - if (axis === 0) { - return this.DataToScreenX(v); - } - return this.DataToScreenY(v); - } - public DataToScreenRange(minVal: number, maxVal: number, axis: number) { - let xFrom = this.DataToScreenX(axis === 0 ? minVal : this.DataMins[0]); - let xTo = this.DataToScreenX(axis === 0 ? maxVal : this.DataMaxs[0]); - let yFrom = this.DataToScreenY(axis === 1 ? minVal : this.DataMins[1]); - let yTo = this.DataToScreenY(axis === 1 ? maxVal : this.DataMaxs[1]); - return { xFrom, yFrom, xTo, yTo }; - } -} \ No newline at end of file diff --git a/src/client/northstar/utils/StyleContants.ts b/src/client/northstar/utils/StyleContants.ts deleted file mode 100644 index e9b6e0297..000000000 --- a/src/client/northstar/utils/StyleContants.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { PIXIPoint } from "./MathUtil"; - -export class StyleConstants { - - static DEFAULT_FONT: string = "Roboto Condensed"; - - static MENU_SUBMENU_WIDTH: number = 85; - static MENU_SUBMENU_HEIGHT: number = 400; - static MENU_BOX_SIZE: PIXIPoint = new PIXIPoint(80, 35); - static MENU_BOX_PADDING: number = 10; - - static OPERATOR_MENU_LARGE: number = 35; - static OPERATOR_MENU_SMALL: number = 25; - static BRUSH_PALETTE: number[] = [0x42b43c, 0xfa217f, 0x6a9c75, 0xfb5de7, 0x25b8ea, 0x9b5bc4, 0xda9f63, 0xe23209, 0xfb899b, 0x94a6fd]; - static GAP: number = 3; - - static BACKGROUND_COLOR: number = 0xF3F3F3; - static TOOL_TIP_BACKGROUND_COLOR: number = 0xffffff; - static LIGHT_TEXT_COLOR: number = 0xffffff; - static LIGHT_TEXT_COLOR_STR: string = StyleConstants.HexToHexString(StyleConstants.LIGHT_TEXT_COLOR); - static DARK_TEXT_COLOR: number = 0x282828; - static HIGHLIGHT_TEXT_COLOR: number = 0xffcc00; - static FPS_TEXT_COLOR: number = StyleConstants.DARK_TEXT_COLOR; - static CORRELATION_LABEL_TEXT_COLOR_STR: string = StyleConstants.HexToHexString(StyleConstants.DARK_TEXT_COLOR); - static LOADING_SCREEN_TEXT_COLOR_STR: string = StyleConstants.HexToHexString(StyleConstants.DARK_TEXT_COLOR); - static ERROR_COLOR: number = 0x540E25; - static WARNING_COLOR: number = 0xE58F24; - static LOWER_THAN_NAIVE_COLOR: number = 0xee0000; - static HIGHLIGHT_COLOR: number = 0x82A8D9; - static HIGHLIGHT_COLOR_STR: string = StyleConstants.HexToHexString(StyleConstants.HIGHLIGHT_COLOR); - static OPERATOR_BACKGROUND_COLOR: number = 0x282828; - static LOADING_ANIMATION_COLOR: number = StyleConstants.OPERATOR_BACKGROUND_COLOR; - static MENU_COLOR: number = 0x282828; - static MENU_FONT_COLOR: number = StyleConstants.LIGHT_TEXT_COLOR; - static MENU_SELECTED_COLOR: number = StyleConstants.HIGHLIGHT_COLOR; - static MENU_SELECTED_FONT_COLOR: number = StyleConstants.LIGHT_TEXT_COLOR; - static BRUSH_COLOR: number = 0xff0000; - static DROP_ACCEPT_COLOR: number = StyleConstants.HIGHLIGHT_COLOR; - static SELECTED_COLOR: number = 0xffffff; - static SELECTED_COLOR_STR: string = StyleConstants.HexToHexString(StyleConstants.SELECTED_COLOR); - static PROGRESS_BACKGROUND_COLOR: number = 0x595959; - static GRID_LINES_COLOR: number = 0x3D3D3D; - static GRID_LINES_COLOR_STR: string = StyleConstants.HexToHexString(StyleConstants.GRID_LINES_COLOR); - - static MAX_CHAR_FOR_HISTOGRAM_LABELS: number = 20; - - static OVERLAP_COLOR: number = 0x0000ff;//0x540E25; - static BRUSH_COLORS: Array = new Array( - 0xFFDA7E, 0xFE8F65, 0xDA5655, 0x8F2240 - ); - - static MIN_VALUE_COLOR: number = 0x373d43; //32343d, 373d43, 3b4648 - static MARGIN_BARS_COLOR: number = 0xffffff; - static MARGIN_BARS_COLOR_STR: string = StyleConstants.HexToHexString(StyleConstants.MARGIN_BARS_COLOR); - - static HISTOGRAM_WIDTH: number = 200; - static HISTOGRAM_HEIGHT: number = 150; - static PREDICTOR_WIDTH: number = 150; - static PREDICTOR_HEIGHT: number = 100; - static RAWDATA_WIDTH: number = 150; - static RAWDATA_HEIGHT: number = 100; - static FREQUENT_ITEM_WIDTH: number = 180; - static FREQUENT_ITEM_HEIGHT: number = 100; - static CORRELATION_WIDTH: number = 555; - static CORRELATION_HEIGHT: number = 390; - static PROBLEM_FINDER_WIDTH: number = 450; - static PROBLEM_FINDER_HEIGHT: number = 150; - static PIPELINE_OPERATOR_WIDTH: number = 300; - static PIPELINE_OPERATOR_HEIGHT: number = 120; - static SLICE_WIDTH: number = 150; - static SLICE_HEIGHT: number = 45; - static BORDER_MENU_ITEM_WIDTH: number = 50; - static BORDER_MENU_ITEM_HEIGHT: number = 30; - - - static SLICE_BG_COLOR: string = StyleConstants.HexToHexString(StyleConstants.OPERATOR_BACKGROUND_COLOR); - static SLICE_EMPTY_COLOR: number = StyleConstants.OPERATOR_BACKGROUND_COLOR; - static SLICE_OCCUPIED_COLOR: number = 0xffffff; - static SLICE_OCCUPIED_BG_COLOR: string = StyleConstants.HexToHexString(StyleConstants.OPERATOR_BACKGROUND_COLOR); - static SLICE_HOVER_BG_COLOR: string = StyleConstants.HexToHexString(StyleConstants.HIGHLIGHT_COLOR); - static SLICE_HOVER_COLOR: number = 0xffffff; - - static HexToHexString(hex: number): string { - if (hex === undefined) { - return "#000000"; - } - var s = hex.toString(16); - while (s.length < 6) { - s = "0" + s; - } - return "#" + s; - } - - -} diff --git a/src/client/northstar/utils/Utils.ts b/src/client/northstar/utils/Utils.ts deleted file mode 100644 index d071dec62..000000000 --- a/src/client/northstar/utils/Utils.ts +++ /dev/null @@ -1,75 +0,0 @@ -import { IBaseBrushable } from '../core/brusher/IBaseBrushable'; -import { IBaseFilterConsumer } from '../core/filter/IBaseFilterConsumer'; -import { IBaseFilterProvider } from '../core/filter/IBaseFilterProvider'; -import { AggregateFunction } from '../model/idea/idea'; - -export class Utils { - - public static EqualityHelper(a: Object, b: Object): boolean { - if (a === b) return true; - if (a === undefined && b !== undefined) return false; - if (a === null && b !== null) return false; - if (b === undefined && a !== undefined) return false; - if (b === null && a !== null) return false; - if ((a).constructor.name !== (b).constructor.name) return false; - return true; - } - - public static LowercaseFirstLetter(str: string) { - return str.charAt(0).toUpperCase() + str.slice(1); - } - - // - // this Type Guard tests if dropTarget is an IDropTarget. If it is, it coerces the compiler - // to treat the dropTarget parameter as an IDropTarget *ouside* this function scope (ie, in - // the scope of where this function is called from). - // - - public static isBaseBrushable(obj: Object): obj is IBaseBrushable { - let typed = >obj; - return typed !== null && typed.BrusherModels !== undefined; - } - - public static isBaseFilterProvider(obj: Object): obj is IBaseFilterProvider { - let typed = obj; - return typed !== null && typed.FilterModels !== undefined; - } - - public static isBaseFilterConsumer(obj: Object): obj is IBaseFilterConsumer { - let typed = obj; - return typed !== null && typed.FilterOperand !== undefined; - } - - public static EncodeQueryData(data: any): string { - const ret = []; - for (let d in data) { - ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d])); - } - return ret.join("&"); - } - - public static ToVegaAggregationString(agg: AggregateFunction): string { - if (agg === AggregateFunction.Avg) { - return "average"; - } - else if (agg === AggregateFunction.Count) { - return "count"; - } - else { - return ""; - } - } - - public static GetQueryVariable(variable: string) { - let query = window.location.search.substring(1); - let vars = query.split("&"); - for (const variable of vars) { - let pair = variable.split("="); - if (decodeURIComponent(pair[0]) === variable) { - return decodeURIComponent(pair[1]); - } - } - return undefined; - } -} - diff --git a/src/client/util/DictationManager.ts b/src/client/util/DictationManager.ts index 569c1ef6d..b3295ece0 100644 --- a/src/client/util/DictationManager.ts +++ b/src/client/util/DictationManager.ts @@ -10,7 +10,6 @@ import { CollectionViewType } from "../views/collections/CollectionView"; import { Cast, CastCtor } from "../../new_fields/Types"; import { listSpec } from "../../new_fields/Schema"; import { AudioField, ImageField } from "../../new_fields/URLField"; -import { HistogramField } from "../northstar/dash-fields/HistogramField"; import { Utils } from "../../Utils"; import { RichTextField } from "../../new_fields/RichTextField"; import { DictationOverlay } from "../views/DictationOverlay"; @@ -282,9 +281,8 @@ export namespace DictationManager { [DocumentType.COL, listSpec(Doc)], [DocumentType.AUDIO, AudioField], [DocumentType.IMG, ImageField], - [DocumentType.HIST, HistogramField], [DocumentType.IMPORT, listSpec(Doc)], - [DocumentType.TEXT, "string"] + [DocumentType.RTF, "string"] ]); const tryCast = (view: DocumentView, type: DocumentType) => { @@ -377,7 +375,7 @@ export namespace DictationManager { { expression: /view as (freeform|stacking|masonry|schema|tree)/g, action: (target: DocumentView, matches: RegExpExecArray) => { - const mode = CollectionViewType.valueOf(matches[1]); + const mode = matches[1]; mode && (target.props.Document._viewType = mode); }, restrictTo: [DocumentType.COL] diff --git a/src/client/util/DropConverter.ts b/src/client/util/DropConverter.ts index d96257ca1..7b38fdac2 100644 --- a/src/client/util/DropConverter.ts +++ b/src/client/util/DropConverter.ts @@ -52,7 +52,7 @@ export function convertDropDataToButtons(data: DragManager.DocumentDragData) { // bcz: isButtonBar is intended to allow a collection of linear buttons to be dropped and nested into another collection of buttons... it's not being used yet, and isn't very elegant if (!doc.onDragStart && !doc.isButtonBar) { const layoutDoc = doc.layout instanceof Doc && doc.layout.isTemplateForField ? doc.layout : doc; - if (layoutDoc.type === DocumentType.COL || layoutDoc.type === DocumentType.TEXT || layoutDoc.type === DocumentType.IMG) { + if (layoutDoc.type === DocumentType.COL || layoutDoc.type === DocumentType.RTF || layoutDoc.type === DocumentType.IMG) { !layoutDoc.isTemplateDoc && makeTemplate(layoutDoc); } else { (layoutDoc.layout instanceof Doc) && !data.userDropAction; diff --git a/src/client/util/KeyCodes.ts b/src/client/util/KeyCodes.ts new file mode 100644 index 000000000..cacb72a57 --- /dev/null +++ b/src/client/util/KeyCodes.ts @@ -0,0 +1,136 @@ +/** + * Class contains the keycodes for keys on your keyboard. + * + * Useful for auto completion: + * + * ``` + * switch (event.key) + * { + * case KeyCode.UP: + * { + * // Up key pressed + * break; + * } + * case KeyCode.DOWN: + * { + * // Down key pressed + * break; + * } + * case KeyCode.LEFT: + * { + * // Left key pressed + * break; + * } + * case KeyCode.RIGHT: + * { + * // Right key pressed + * break; + * } + * default: + * { + * // ignore + * break; + * } + * } + * ``` + */ +export class KeyCodes { + public static TAB: number = 9; + public static CAPS_LOCK: number = 20; + public static SHIFT: number = 16; + public static CONTROL: number = 17; + public static SPACE: number = 32; + public static DOWN: number = 40; + public static UP: number = 38; + public static LEFT: number = 37; + public static RIGHT: number = 39; + public static ESCAPE: number = 27; + public static F1: number = 112; + public static F2: number = 113; + public static F3: number = 114; + public static F4: number = 115; + public static F5: number = 116; + public static F6: number = 117; + public static F7: number = 118; + public static F8: number = 119; + public static F9: number = 120; + public static F10: number = 121; + public static F11: number = 122; + public static F12: number = 123; + public static INSERT: number = 45; + public static HOME: number = 36; + public static PAGE_UP: number = 33; + public static PAGE_DOWN: number = 34; + public static DELETE: number = 46; + public static END: number = 35; + public static ENTER: number = 13; + public static BACKSPACE: number = 8; + public static NUMPAD_0: number = 96; + public static NUMPAD_1: number = 97; + public static NUMPAD_2: number = 98; + public static NUMPAD_3: number = 99; + public static NUMPAD_4: number = 100; + public static NUMPAD_5: number = 101; + public static NUMPAD_6: number = 102; + public static NUMPAD_7: number = 103; + public static NUMPAD_8: number = 104; + public static NUMPAD_9: number = 105; + public static NUMPAD_DIVIDE: number = 111; + public static NUMPAD_ADD: number = 107; + public static NUMPAD_ENTER: number = 13; + public static NUMPAD_DECIMAL: number = 110; + public static NUMPAD_SUBTRACT: number = 109; + public static NUMPAD_MULTIPLY: number = 106; + public static SEMICOLON: number = 186; + public static EQUAL: number = 187; + public static COMMA: number = 188; + public static MINUS: number = 189; + public static PERIOD: number = 190; + public static SLASH: number = 191; + public static BACKQUOTE: number = 192; + public static LEFTBRACKET: number = 219; + public static BACKSLASH: number = 220; + public static RIGHTBRACKET: number = 221; + public static QUOTE: number = 222; + public static ALT: number = 18; + public static COMMAND: number = 15; + public static NUMPAD: number = 21; + public static A: number = 65; + public static B: number = 66; + public static C: number = 67; + public static D: number = 68; + public static E: number = 69; + public static F: number = 70; + public static G: number = 71; + public static H: number = 72; + public static I: number = 73; + public static J: number = 74; + public static K: number = 75; + public static L: number = 76; + public static M: number = 77; + public static N: number = 78; + public static O: number = 79; + public static P: number = 80; + public static Q: number = 81; + public static R: number = 82; + public static S: number = 83; + public static T: number = 84; + public static U: number = 85; + public static V: number = 86; + public static W: number = 87; + public static X: number = 88; + public static Y: number = 89; + public static Z: number = 90; + public static NUM_0: number = 48; + public static NUM_1: number = 49; + public static NUM_2: number = 50; + public static NUM_3: number = 51; + public static NUM_4: number = 52; + public static NUM_5: number = 53; + public static NUM_6: number = 54; + public static NUM_7: number = 55; + public static NUM_8: number = 56; + public static NUM_9: number = 57; + public static SUBSTRACT: number = 189; + public static ADD: number = 187; +} \ No newline at end of file diff --git a/src/client/util/type_decls.d b/src/client/util/type_decls.d index 97f6b79fb..08aec3724 100644 --- a/src/client/util/type_decls.d +++ b/src/client/util/type_decls.d @@ -195,7 +195,6 @@ interface DocumentOptions { } declare const Docs: { ImageDocument(url: string, options?: DocumentOptions): Doc; VideoDocument(url: string, options?: DocumentOptions): Doc; - // HistogramDocument(url:string, options?:DocumentOptions); TextDocument(options?: DocumentOptions): Doc; PdfDocument(url: string, options?: DocumentOptions): Doc; WebDocument(url: string, options?: DocumentOptions): Doc; diff --git a/src/client/views/DocComponent.tsx b/src/client/views/DocComponent.tsx index 21eec66be..0c8ce28c3 100644 --- a/src/client/views/DocComponent.tsx +++ b/src/client/views/DocComponent.tsx @@ -9,7 +9,7 @@ import { PositionDocument } from '../../new_fields/documentSchemas'; import { InteractionUtils } from '../util/InteractionUtils'; -/// DocComponent returns a generic React base class used by views that don't have any data extensions (e.g.,CollectionFreeFormDocumentView, DocumentView, ButtonBox) +/// DocComponent returns a generic React base class used by views that don't have any data extensions (e.g.,CollectionFreeFormDocumentView, DocumentView, LabelBox) interface DocComponentProps { Document: Doc; LayoutDoc?: () => Opt; diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index e313b117f..bd72385ef 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -76,7 +76,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> var [sptX, sptY] = transform.transformPoint(0, 0); let [bptX, bptY] = transform.transformPoint(documentView.props.PanelWidth(), documentView.props.PanelHeight()); if (documentView.props.Document.type === DocumentType.LINK) { - const docuBox = documentView.ContentDiv!.getElementsByClassName("docuLinkBox-cont"); + const docuBox = documentView.ContentDiv!.getElementsByClassName("linkAnchorBox-cont"); if (docuBox.length) { const rect = docuBox[0].getBoundingClientRect(); sptX = rect.left; diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index bef92f0fd..7c9f47fe4 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -275,7 +275,7 @@ export class MainView extends React.Component { defaultBackgroundColors = (doc: Doc) => { if (this.darkScheme) { switch (doc.type) { - case DocumentType.TEXT || DocumentType.BUTTON: return "#2d2d2d"; + case DocumentType.RTF || DocumentType.LABEL: return "#2d2d2d"; case DocumentType.LINK: case DocumentType.COL: { if (doc._viewType !== CollectionViewType.Freeform && doc._viewType !== CollectionViewType.Time) return "rgb(62,62,62)"; @@ -284,8 +284,8 @@ export class MainView extends React.Component { } } else { switch (doc.type) { - case DocumentType.TEXT: return "#f1efeb"; - case DocumentType.BUTTON: return "lightgray"; + case DocumentType.RTF: return "#f1efeb"; + case DocumentType.LABEL: return "lightgray"; case DocumentType.LINK: case DocumentType.COL: { if (doc._viewType !== CollectionViewType.Freeform && doc._viewType !== CollectionViewType.Time) return "lightgray"; diff --git a/src/client/views/ScriptBox.tsx b/src/client/views/ScriptBox.tsx index 1e81bb80b..0352ddaca 100644 --- a/src/client/views/ScriptBox.tsx +++ b/src/client/views/ScriptBox.tsx @@ -50,7 +50,7 @@ export class ScriptBox extends React.Component { } onBlur = () => { - this.overlayDisposer && this.overlayDisposer(); + this.overlayDisposer?.(); } render() { diff --git a/src/client/views/SearchDocBox.tsx b/src/client/views/SearchDocBox.tsx index 4790a2ad7..799fa9d85 100644 --- a/src/client/views/SearchDocBox.tsx +++ b/src/client/views/SearchDocBox.tsx @@ -394,7 +394,7 @@ export class SearchDocBox extends React.Component { render() { const isEditing = this.editingMetadata; - return ( + return !this.content ? (null) : (
{ } } - @action - makeDB = async () => { - let csv: string = this.columns.reduce((val, col) => val + col + ",", ""); - csv = csv.substr(0, csv.length - 1) + "\n"; - const self = this; - this.childDocs.map(doc => { - csv += self.columns.reduce((val, col) => val + (doc[col.heading] ? doc[col.heading]!.toString() : "0") + ",", ""); - csv = csv.substr(0, csv.length - 1) + "\n"; - }); - csv.substring(0, csv.length - 1); - const dbName = StrCast(this.props.Document.title); - const res = await Gateway.Instance.PostSchema(csv, dbName); - if (self.props.CollectionView && self.props.CollectionView.props.addDocument) { - const schemaDoc = await Docs.Create.DBDocument("https://www.cs.brown.edu/" + dbName, { title: dbName }, { dbDoc: self.props.Document }); - if (schemaDoc) { - //self.props.CollectionView.props.addDocument(schemaDoc, false); - self.props.Document.schemaDoc = schemaDoc; - } - } - } - getField = (row: number, col?: number) => { const docs = this.childDocs; diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index b066f2be3..da53888fc 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -343,7 +343,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { const doc = this.props.DataDoc && this.props.DataDoc.layout === this.layoutDoc ? this.props.DataDoc : this.layoutDoc; this.observer = new _global.ResizeObserver(action((entries: any) => { if (this.props.Document._autoHeight && ref && this.refList.length && !SelectionManager.GetIsDragging()) { - Doc.Layout(doc)._height = this.refList.reduce((p, r) => p + Number(getComputedStyle(r).height.replace("px", "")), 0) + Doc.Layout(doc)._height = this.refList.reduce((p, r) => p + Number(getComputedStyle(r).height.replace("px", "")), 0); } })); this.observer.observe(ref); diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index 746b2e174..41f4fb3f0 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -99,7 +99,7 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T, moreProps?: this.props.Document.resolvedDataDoc ? this.props.Document : Doc.GetProto(this.props.Document)); // if the layout document has a resolvedDataDoc, then we don't want to get its parent which would be the unexpanded template } - rootSelected = (outsideReaction: boolean) => { + rootSelected = (outsideReaction?: boolean) => { return this.props.isSelected(outsideReaction) || (this.props.Document.rootDocument || this.props.Document.forceActive ? this.props.rootSelected(outsideReaction) : false); } diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index c7ab66c9f..5819c829f 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -52,39 +52,19 @@ const path = require('path'); library.add(faTh, faTree, faSquare, faProjectDiagram, faSignature, faThList, faFingerprint, faColumns, faEllipsisV, faImage, faEye as any, faCopy); export enum CollectionViewType { - Invalid, - Freeform, - Schema, - Docking, - Tree, - Stacking, - Masonry, - Multicolumn, - Multirow, - Time, - Carousel, - Linear, - Staff -} - -export namespace CollectionViewType { - const stringMapping = new Map([ - ["invalid", CollectionViewType.Invalid], - ["freeform", CollectionViewType.Freeform], - ["schema", CollectionViewType.Schema], - ["docking", CollectionViewType.Docking], - ["tree", CollectionViewType.Tree], - ["stacking", CollectionViewType.Stacking], - ["masonry", CollectionViewType.Masonry], - ["multicolumn", CollectionViewType.Multicolumn], - ["multirow", CollectionViewType.Multirow], - ["time", CollectionViewType.Time], - ["carousel", CollectionViewType.Carousel], - ["linear", CollectionViewType.Linear], - ]); - - export const valueOf = (value: string) => stringMapping.get(value.toLowerCase()); - export const stringFor = (value: number) => Array.from(stringMapping.entries()).find(entry => entry[1] === value)?.[0]; + Invalid = "invalid", + Freeform = "freeform", + Schema = "schema", + Docking = "docking", + Tree = 'tree', + Stacking = "stacking", + Masonry = "masonry", + Multicolumn = "multicolumn", + Multirow = "multirow", + Time = "time", + Carousel = "carousel", + Linear = "linear", + Staff = "staff", } export interface CollectionRenderProps { @@ -110,7 +90,7 @@ export class CollectionView extends Touchable { protected multiTouchDisposer?: InteractionUtils.MultiTouchEventDisposer; get collectionViewType(): CollectionViewType | undefined { - const viewField = NumCast(this.props.Document._viewType); + const viewField = StrCast(this.props.Document._viewType); if (CollectionView._safeMode) { if (viewField === CollectionViewType.Freeform) { return CollectionViewType.Tree; @@ -119,7 +99,7 @@ export class CollectionView extends Touchable { return CollectionViewType.Freeform; } } - return viewField; + return viewField as any as CollectionViewType; } active = (outsideReaction?: boolean) => this.props.isSelected(outsideReaction) || (this.props.rootSelected(outsideReaction) && BoolCast(this.props.Document.forceActive)) || this._isChildActive || this.props.renderDepth === 0; @@ -394,7 +374,7 @@ export class CollectionView extends Touchable { const params = { layoutDoc: Doc.name, dataDoc: Doc.name, }; newFacet.data = ComputedField.MakeFunction(`readFacetData(layoutDoc, dataDoc, "${this.props.fieldKey}", "${facetHeader}")`, params, capturedVariables); } - Doc.AddDocToList(facetCollection, this.props.fieldKey + "-filter", newFacet); + newFacet && Doc.AddDocToList(facetCollection, this.props.fieldKey + "-filter", newFacet); } } diff --git a/src/client/views/collections/CollectionViewChromes.tsx b/src/client/views/collections/CollectionViewChromes.tsx index 9bade1c82..7741f7d42 100644 --- a/src/client/views/collections/CollectionViewChromes.tsx +++ b/src/client/views/collections/CollectionViewChromes.tsx @@ -18,7 +18,6 @@ import { CollectionView } from "./CollectionView"; import "./CollectionViewChromes.scss"; import * as Autosuggest from 'react-autosuggest'; import KeyRestrictionRow from "./KeyRestrictionRow"; -import { ObjectField } from "../../../new_fields/ObjectField"; const datepicker = require('js-datepicker'); interface CollectionViewChromeProps { @@ -349,11 +348,11 @@ export class CollectionViewBaseChrome extends React.Component { setupMoveUpEvents(this, e, (e, down, delta) => { - const vtype = NumCast(this.props.CollectionView.props.Document._viewType) as CollectionViewType; + const vtype = this.props.CollectionView.collectionViewType; const c = { - params: ["target"], title: CollectionViewType.stringFor(vtype), + params: ["target"], title: vtype, script: `this.target._viewType = ${NumCast(this.props.CollectionView.props.Document._viewType)}`, - immediate: (source: Doc[]) => this.target = Doc.getTemplateDoc(source?.[0]), + immediate: (source: Doc[]) => this.props.CollectionView.props.Document._viewType = Doc.getDocTemplate(source?.[0]), initialize: emptyFunction, }; DragManager.StartButtonDrag([this._viewRef.current!], c.script, StrCast(c.title), diff --git a/src/client/views/collections/ParentDocumentSelector.tsx b/src/client/views/collections/ParentDocumentSelector.tsx index afe269ec3..2f0132fec 100644 --- a/src/client/views/collections/ParentDocumentSelector.tsx +++ b/src/client/views/collections/ParentDocumentSelector.tsx @@ -54,7 +54,7 @@ export class SelectorContextMenu extends React.Component { getOnClick({ col, target }: { col: Doc, target: Doc }) { return () => { col = Doc.IsPrototype(col) ? Doc.MakeDelegate(col) : col; - if (NumCast(col._viewType, CollectionViewType.Invalid) === CollectionViewType.Freeform) { + if (col._viewType === CollectionViewType.Freeform) { const newPanX = NumCast(target.x) + NumCast(target._width) / 2; const newPanY = NumCast(target.y) + NumCast(target._height) / 2; col._panX = newPanX; diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx index a33146388..09fc5148e 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx @@ -26,8 +26,8 @@ export class CollectionFreeFormLinkView extends React.Component { setTimeout(action(() => this._opacity = 1), 0); // since the render code depends on querying the Dom through getBoudndingClientRect, we need to delay triggering render() setTimeout(action(() => this._opacity = 0.05), 750); // this will unhighlight the link line. - const acont = this.props.A.props.Document.type === DocumentType.LINK ? this.props.A.ContentDiv!.getElementsByClassName("docuLinkBox-cont") : []; - const bcont = this.props.B.props.Document.type === DocumentType.LINK ? this.props.B.ContentDiv!.getElementsByClassName("docuLinkBox-cont") : []; + const acont = this.props.A.props.Document.type === DocumentType.LINK ? this.props.A.ContentDiv!.getElementsByClassName("linkAnchorBox-cont") : []; + const bcont = this.props.B.props.Document.type === DocumentType.LINK ? this.props.B.ContentDiv!.getElementsByClassName("linkAnchorBox-cont") : []; const adiv = (acont.length ? acont[0] : this.props.A.ContentDiv!); const bdiv = (bcont.length ? bcont[0] : this.props.B.ContentDiv!); const a = adiv.getBoundingClientRect(); @@ -43,7 +43,7 @@ export class CollectionFreeFormLinkView extends React.Component; } - // _brushReactionDisposer?: IReactionDisposer; - // componentDidMount() { - // this._brushReactionDisposer = reaction( - // () => { - // let doclist = DocListCast(this.props.Document[this.props.fieldKey]); - // return { doclist: doclist ? doclist : [], xs: doclist.map(d => d.x) }; - // }, - // () => { - // let doclist = DocListCast(this.props.Document[this.props.fieldKey]); - // let views = doclist ? doclist.filter(doc => StrCast(doc.backgroundLayout).indexOf("istogram") !== -1) : []; - // views.forEach((dstDoc, i) => { - // views.forEach((srcDoc, j) => { - // let dstTarg = dstDoc; - // let srcTarg = srcDoc; - // let x1 = NumCast(srcDoc.x); - // let x2 = NumCast(dstDoc.x); - // let x1w = NumCast(srcDoc.width, -1); - // let x2w = NumCast(dstDoc.width, -1); - // if (x1w < 0 || x2w < 0 || i === j) { } - // else { - // let findBrush = (field: (Doc | Promise)[]) => field.findIndex(brush => { - // let bdocs = brush instanceof Doc ? Cast(brush.brushingDocs, listSpec(Doc), []) : undefined; - // return bdocs && bdocs.length && ((bdocs[0] === dstTarg && bdocs[1] === srcTarg)) ? true : false; - // }); - // let brushAction = (field: (Doc | Promise)[]) => { - // let found = findBrush(field); - // if (found !== -1) { - // field.splice(found, 1); - // } - // }; - // if (Math.abs(x1 + x1w - x2) < 20) { - // let linkDoc: Doc = new Doc(); - // linkDoc.title = "Histogram Brush"; - // linkDoc.linkDescription = "Brush between " + StrCast(srcTarg.title) + " and " + StrCast(dstTarg.Title); - // linkDoc.brushingDocs = new List([dstTarg, srcTarg]); - - // brushAction = (field: (Doc | Promise)[]) => { - // if (findBrush(field) === -1) { - // field.push(linkDoc); - // } - // }; - // } - // if (dstTarg.brushingDocs === undefined) dstTarg.brushingDocs = new List(); - // if (srcTarg.brushingDocs === undefined) srcTarg.brushingDocs = new List(); - // let dstBrushDocs = Cast(dstTarg.brushingDocs, listSpec(Doc), []); - // let srcBrushDocs = Cast(srcTarg.brushingDocs, listSpec(Doc), []); - // brushAction(dstBrushDocs); - // brushAction(srcBrushDocs); - // } - // }); - // }); - // }); - // } - // componentWillUnmount() { - // this._brushReactionDisposer?.(); - // } } \ No newline at end of file diff --git a/src/client/views/nodes/AudioBox.scss b/src/client/views/nodes/AudioBox.scss index fb16b8365..53b54d7e4 100644 --- a/src/client/views/nodes/AudioBox.scss +++ b/src/client/views/nodes/AudioBox.scss @@ -88,7 +88,7 @@ opacity:0.9; background-color: transparent; box-shadow: black 2px 2px 1px; - .docuLinkBox-cont { + .linkAnchorBox-cont { position: relative !important; height: 100% !important; width: 100% !important; @@ -103,7 +103,7 @@ box-shadow: black 1px 1px 1px; margin-left: -1; margin-top: -2; - .docuLinkBox-cont { + .linkAnchorBox-cont { position: relative !important; height: 100% !important; width: 100% !important; diff --git a/src/client/views/nodes/ButtonBox.scss b/src/client/views/nodes/ButtonBox.scss deleted file mode 100644 index 293af289d..000000000 --- a/src/client/views/nodes/ButtonBox.scss +++ /dev/null @@ -1,38 +0,0 @@ -.buttonBox-outerDiv { - width: 100%; - height: 100%; - pointer-events: all; - border-radius: inherit; - display: flex; - flex-direction: column; -} - -.buttonBox-mainButton { - width: 100%; - height: 100%; - border-radius: inherit; - letter-spacing: 2px; - text-transform: uppercase; - overflow: hidden; - display:flex; -} - -.buttonBox-mainButtonCenter { - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; - display: inline; - align-items: center; - margin: auto; -} - -.buttonBox-params { - display: flex; - flex-direction: row; -} - -.buttonBox-missingParam { - width: 100%; - background: lightgray; - border: dimGray solid 1px; -} \ No newline at end of file diff --git a/src/client/views/nodes/ButtonBox.tsx b/src/client/views/nodes/ButtonBox.tsx deleted file mode 100644 index 1b70ff824..000000000 --- a/src/client/views/nodes/ButtonBox.tsx +++ /dev/null @@ -1,97 +0,0 @@ -import { library } from '@fortawesome/fontawesome-svg-core'; -import { faEdit } from '@fortawesome/free-regular-svg-icons'; -import { action, computed } from 'mobx'; -import { observer } from 'mobx-react'; -import * as React from 'react'; -import { Doc, DocListCast } from '../../../new_fields/Doc'; -import { List } from '../../../new_fields/List'; -import { createSchema, makeInterface, listSpec } from '../../../new_fields/Schema'; -import { ScriptField } from '../../../new_fields/ScriptField'; -import { BoolCast, StrCast, Cast, FieldValue } from '../../../new_fields/Types'; -import { DragManager } from '../../util/DragManager'; -import { undoBatch } from '../../util/UndoManager'; -import { DocComponent } from '../DocComponent'; -import './ButtonBox.scss'; -import { FieldView, FieldViewProps } from './FieldView'; -import { ContextMenuProps } from '../ContextMenuItem'; -import { ContextMenu } from '../ContextMenu'; -import { documentSchema } from '../../../new_fields/documentSchemas'; - - -library.add(faEdit as any); - -const ButtonSchema = createSchema({ - onClick: ScriptField, - buttonParams: listSpec("string"), - text: "string" -}); - -type ButtonDocument = makeInterface<[typeof ButtonSchema, typeof documentSchema]>; -const ButtonDocument = makeInterface(ButtonSchema, documentSchema); - -@observer -export class ButtonBox extends DocComponent(ButtonDocument) { - public static LayoutString(fieldKey: string) { return FieldView.LayoutString(ButtonBox, fieldKey); } - private dropDisposer?: DragManager.DragDropDisposer; - - @computed get dataDoc() { - return this.props.DataDoc && - (this.Document.isTemplateForField || BoolCast(this.props.DataDoc.isTemplateForField) || - this.props.DataDoc.layout === this.props.Document) ? this.props.DataDoc : Doc.GetProto(this.props.Document); - } - - - protected createDropTarget = (ele: HTMLDivElement) => { - this.dropDisposer?.(); - if (ele) { - this.dropDisposer = DragManager.MakeDropTarget(ele, this.drop.bind(this)); - } - } - - specificContextMenu = (e: React.MouseEvent): void => { - const funcs: ContextMenuProps[] = []; - funcs.push({ - description: "Clear Script Params", event: () => { - const params = FieldValue(this.Document.buttonParams); - params?.map(p => this.props.Document[p] = undefined); - }, icon: "trash" - }); - - ContextMenu.Instance.addItem({ description: "OnClick...", subitems: funcs, icon: "asterisk" }); - } - - @undoBatch - @action - drop = (e: Event, de: DragManager.DropEvent) => { - const docDragData = de.complete.docDragData; - const params = this.Document.buttonParams; - const missingParams = params?.filter(p => this.props.Document[p] === undefined); - if (docDragData && missingParams?.includes((e.target as any).textContent)) { - this.props.Document[(e.target as any).textContent] = new List(docDragData.droppedDocuments.map((d, i) => - d.onDragStart ? docDragData.draggedDocuments[i] : d)); - e.stopPropagation(); - } - } - // (!missingParams || !missingParams.length ? "" : "(" + missingParams.map(m => m + ":").join(" ") + ")") - render() { - const params = this.Document.buttonParams; - const missingParams = params?.filter(p => this.props.Document[p] === undefined); - params?.map(p => DocListCast(this.props.Document[p])); // bcz: really hacky form of prefetching ... - return ( -
-
-
- {(this.Document.text || this.Document.title)} -
-
-
- {!missingParams || !missingParams.length ? (null) : missingParams.map(m =>
{m}
)} -
-
- ); - } -} \ No newline at end of file diff --git a/src/client/views/nodes/DocuLinkBox.scss b/src/client/views/nodes/DocuLinkBox.scss deleted file mode 100644 index f2c203548..000000000 --- a/src/client/views/nodes/DocuLinkBox.scss +++ /dev/null @@ -1,29 +0,0 @@ -.docuLinkBox-cont, .docuLinkBox-cont-small { - cursor: default; - position: absolute; - width: 15; - height: 15; - border-radius: 20px; - pointer-events: all; - user-select: none; - - .docuLinkBox-linkCloser { - position: absolute; - width: 18; - height: 18; - background: rgb(219, 21, 21); - top: -1px; - left: -1px; - border-radius: 5px; - display: flex; - justify-content: center; - align-items: center; - padding-left: 2px; - padding-top: 1px; - } -} - -.docuLinkBox-cont-small { - width:5px; - height:5px; -} \ No newline at end of file diff --git a/src/client/views/nodes/DocuLinkBox.tsx b/src/client/views/nodes/DocuLinkBox.tsx deleted file mode 100644 index 31ce58079..000000000 --- a/src/client/views/nodes/DocuLinkBox.tsx +++ /dev/null @@ -1,146 +0,0 @@ -import { action, observable } from "mobx"; -import { observer } from "mobx-react"; -import { Doc, DocListCast } from "../../../new_fields/Doc"; -import { documentSchema } from "../../../new_fields/documentSchemas"; -import { makeInterface } from "../../../new_fields/Schema"; -import { Cast, NumCast, StrCast } from "../../../new_fields/Types"; -import { Utils, setupMoveUpEvents } from '../../../Utils'; -import { DocumentManager } from "../../util/DocumentManager"; -import { DragManager } from "../../util/DragManager"; -import { DocComponent } from "../DocComponent"; -import "./DocuLinkBox.scss"; -import { FieldView, FieldViewProps } from "./FieldView"; -import React = require("react"); -import { ContextMenuProps } from "../ContextMenuItem"; -import { ContextMenu } from "../ContextMenu"; -import { LinkEditor } from "../linking/LinkEditor"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { SelectionManager } from "../../util/SelectionManager"; -import { TraceMobx } from "../../../new_fields/util"; -const higflyout = require("@hig/flyout"); -export const { anchorPoints } = higflyout; -export const Flyout = higflyout.default; - -type DocLinkSchema = makeInterface<[typeof documentSchema]>; -const DocLinkDocument = makeInterface(documentSchema); - -@observer -export class DocuLinkBox extends DocComponent(DocLinkDocument) { - public static LayoutString(fieldKey: string) { return FieldView.LayoutString(DocuLinkBox, fieldKey); } - _doubleTap = false; - _lastTap: number = 0; - _ref = React.createRef(); - _isOpen = false; - _timeout: NodeJS.Timeout | undefined; - @observable _x = 0; - @observable _y = 0; - @observable _selected = false; - @observable _editing = false; - @observable _forceOpen = false; - - onPointerDown = (e: React.PointerEvent) => { - setupMoveUpEvents(this, e, this.onPointerMove, () => { }, this.onClick); - } - onPointerMove = action((e: PointerEvent, down: number[], delta: number[]) => { - const cdiv = this._ref && this._ref.current && this._ref.current.parentElement; - if (!this._isOpen && cdiv) { - const bounds = cdiv.getBoundingClientRect(); - const pt = Utils.getNearestPointInPerimeter(bounds.left, bounds.top, bounds.width, bounds.height, e.clientX, e.clientY); - const separation = Math.sqrt((pt[0] - e.clientX) * (pt[0] - e.clientX) + (pt[1] - e.clientY) * (pt[1] - e.clientY)); - const dragdist = Math.sqrt((pt[0] - down[0]) * (pt[0] - down[0]) + (pt[1] - down[1]) * (pt[1] - down[1])); - if (separation > 100) { - const dragData = new DragManager.DocumentDragData([this.props.Document]); - dragData.dropAction = "alias"; - dragData.removeDropProperties = ["anchor1_x", "anchor1_y", "anchor2_x", "anchor2_y", "isButton"]; - DragManager.StartDocumentDrag([this._ref.current!], dragData, down[0], down[1]); - return true; - } else if (dragdist > separation) { - this.props.Document[this.props.fieldKey + "_x"] = (pt[0] - bounds.left) / bounds.width * 100; - this.props.Document[this.props.fieldKey + "_y"] = (pt[1] - bounds.top) / bounds.height * 100; - } - } - return false; - }); - @action - onClick = (e: PointerEvent) => { - this._doubleTap = (Date.now() - this._lastTap < 300 && e.button === 0); - this._lastTap = Date.now(); - if ((e.button === 2 || e.ctrlKey || !this.props.Document.isButton)) { - this.props.select(false); - } - if (!this._doubleTap) { - const anchorContainerDoc = this.props.ContainingCollectionDoc; // bcz: hack! need a better prop for passing the anchor's container - this._editing = true; - anchorContainerDoc && this.props.bringToFront(anchorContainerDoc, false); - if (anchorContainerDoc && !this.props.Document.onClick && !this._isOpen) { - this._timeout = setTimeout(action(() => { - DocumentManager.Instance.FollowLink(this.props.Document, anchorContainerDoc, document => this.props.addDocTab(document, StrCast(this.props.Document.linkOpenLocation, "inTab")), false); - this._editing = false; - }), 300 - (Date.now() - this._lastTap)); - } - } else { - this._timeout && clearTimeout(this._timeout); - this._timeout = undefined; - } - } - - openLinkDocOnRight = (e: React.MouseEvent) => { - this.props.addDocTab(this.props.Document, "onRight"); - } - openLinkTargetOnRight = (e: React.MouseEvent) => { - const alias = Doc.MakeAlias(Cast(this.props.Document[this.props.fieldKey], Doc, null)); - alias.isButton = undefined; - alias.isBackground = undefined; - alias.layoutKey = "layout"; - this.props.addDocTab(alias, "onRight"); - } - @action - openLinkEditor = action((e: React.MouseEvent) => { - SelectionManager.DeselectAll(); - this._editing = this._forceOpen = true; - }); - - specificContextMenu = (e: React.MouseEvent): void => { - const funcs: ContextMenuProps[] = []; - funcs.push({ description: "Open Link Target on Right", event: () => this.openLinkTargetOnRight(e), icon: "eye" }); - funcs.push({ description: "Open Link on Right", event: () => this.openLinkDocOnRight(e), icon: "eye" }); - funcs.push({ description: "Open Link Editor", event: () => this.openLinkEditor(e), icon: "eye" }); - - ContextMenu.Instance.addItem({ description: "Link Funcs...", subitems: funcs, icon: "asterisk" }); - } - - render() { - TraceMobx(); - const x = this.props.PanelWidth() > 1 ? NumCast(this.props.Document[this.props.fieldKey + "_x"], 100) : 0; - const y = this.props.PanelWidth() > 1 ? NumCast(this.props.Document[this.props.fieldKey + "_y"], 100) : 0; - const c = StrCast(this.props.Document.backgroundColor, "lightblue"); - const anchor = this.props.fieldKey === "anchor1" ? "anchor2" : "anchor1"; - const anchorScale = (x === 0 || x === 100 || y === 0 || y === 100) ? 1 : .15; - - const timecode = this.props.Document[anchor + "Timecode"]; - const targetTitle = StrCast((this.props.Document[anchor]! as Doc).title) + (timecode !== undefined ? ":" + timecode : ""); - const flyout = ( -
Doc.UnBrushDoc(this.props.Document)}> - { })} /> - {!this._forceOpen ? (null) :
this._isOpen = this._editing = this._forceOpen = false)}> - -
} -
- ); - const small = this.props.PanelWidth() <= 1; - return
- {!this._editing && !this._forceOpen ? (null) : - this._isOpen = true} onClose={action(() => this._isOpen = this._forceOpen = this._editing = false)}> - - - - } -
; - } -} diff --git a/src/client/views/nodes/DocumentBox.tsx b/src/client/views/nodes/DocumentBox.tsx index 0e2685d41..4f2b3b656 100644 --- a/src/client/views/nodes/DocumentBox.tsx +++ b/src/client/views/nodes/DocumentBox.tsx @@ -18,12 +18,12 @@ import { TraceMobx } from "../../../new_fields/util"; import { DocumentView } from "./DocumentView"; import { Docs } from "../../documents/Documents"; -type DocBoxSchema = makeInterface<[typeof documentSchema]>; -const DocBoxDocument = makeInterface(documentSchema); +type DocHolderBoxSchema = makeInterface<[typeof documentSchema]>; +const DocHolderBoxDocument = makeInterface(documentSchema); @observer -export class DocumentBox extends DocAnnotatableComponent(DocBoxDocument) { - public static LayoutString(fieldKey: string) { return FieldView.LayoutString(DocumentBox, fieldKey); } +export class DocHolderBox extends DocAnnotatableComponent(DocHolderBoxDocument) { + public static LayoutString(fieldKey: string) { return FieldView.LayoutString(DocHolderBox, fieldKey); } _prevSelectionDisposer: IReactionDisposer | undefined; _selections: Doc[] = []; _curSelection = -1; diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index dc71ba280..7522af3a3 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -3,7 +3,6 @@ import { observer } from "mobx-react"; import { Doc, Opt } from "../../../new_fields/Doc"; import { Cast, StrCast } from "../../../new_fields/Types"; import { OmitKeys, Without } from "../../../Utils"; -import { HistogramBox } from "../../northstar/dash-nodes/HistogramBox"; import DirectoryImportBox from "../../util/Import & Export/DirectoryImportBox"; import { CollectionDockingView } from "../collections/CollectionDockingView"; import { CollectionFreeFormView } from "../collections/collectionFreeForm/CollectionFreeFormView"; @@ -11,10 +10,11 @@ import { CollectionSchemaView } from "../collections/CollectionSchemaView"; import { CollectionView } from "../collections/CollectionView"; import { YoutubeBox } from "./../../apis/youtube/YoutubeBox"; import { AudioBox } from "./AudioBox"; -import { ButtonBox } from "./ButtonBox"; +import { LabelBox } from "./LabelBox"; import { SliderBox } from "./SliderBox"; import { LinkBox } from "./LinkBox"; -import { DocumentBox } from "./DocumentBox"; +import { ScriptingBox } from "./ScriptingBox"; +import { DocHolderBox } from "./DocumentBox"; import { DocumentViewProps } from "./DocumentView"; import "./DocumentView.scss"; import { FontIconBox } from "./FontIconBox"; @@ -27,7 +27,7 @@ import { PresBox } from "./PresBox"; import { QueryBox } from "./QueryBox"; import { ColorBox } from "./ColorBox"; import { DashWebRTCVideo } from "../webcam/DashWebRTCVideo"; -import { DocuLinkBox } from "./DocuLinkBox"; +import { LinkAnchorBox } from "./LinkAnchorBox"; import { PresElementBox } from "../presentationview/PresElementBox"; import { ScreenshotBox } from "./ScreenshotBox"; import { VideoBox } from "./VideoBox"; @@ -109,10 +109,10 @@ export class DocumentContentsView extends React.Component(Docu this: this.props.Document, self: Cast(this.props.Document.rootDocument, Doc, null) || this.props.Document, thisContainer: this.props.ContainingCollectionDoc, shiftKey: e.shiftKey - }, console.log);// && !this.props.Document.isButton && this.select(false); + }, console.log); if (this.props.Document !== Doc.UserDoc().undoBtn && this.props.Document !== Doc.UserDoc().redoBtn) { UndoManager.RunInBatch(func, "on click"); } else func(); - } else if (this.Document.type === DocumentType.BUTTON) { - UndoManager.RunInBatch(() => ScriptBox.EditButtonScript("On Button Clicked ...", this.props.Document, "onClick", e.clientX, e.clientY), "on button click"); - } else if (this.Document.isButton) { + } else if (this.Document.editScriptOnClick) { + UndoManager.RunInBatch(() => ScriptBox.EditButtonScript("On Button Clicked ...", this.props.Document, StrCast(this.Document.editScriptOnClick), e.clientX, e.clientY), "on button click"); + } else if (this.Document.isLinkButton) { DocListCast(this.props.Document.links).length && this.followLinkClick(e.altKey, e.ctrlKey, e.shiftKey); } else { if (this.props.Document.isTemplateForField && !(e.ctrlKey || e.button > 0)) { @@ -327,7 +327,7 @@ export class DocumentView extends DocComponent(Docu const targetFocusAfterDocFocus = () => { const where = StrCast(this.Document.followLinkLocation) || followLoc; const hackToCallFinishAfterFocus = () => { - setTimeout(() => finished?.(), 0); // finished() needs to be called right after hackToCallFinishAfterFocus(), but there's no callback for that so we use the hacky timeout. + finished && setTimeout(finished, 0); // finished() needs to be called right after hackToCallFinishAfterFocus(), but there's no callback for that so we use the hacky timeout. return false; // we must return false here so that the zoom to the document is not reversed. If it weren't for needing to call finished(), we wouldn't need this function at all since not having it is equivalent to returning false }; this.props.addDocTab(doc, where) && this.props.focus(doc, true, undefined, hackToCallFinishAfterFocus); // add the target and focus on it. @@ -577,23 +577,23 @@ export class DocumentView extends DocComponent(Docu } @undoBatch - toggleButtonBehavior = (): void => { - if (this.Document.isButton || this.Document.onClick || this.Document.ignoreClick) { - this.Document.isButton = false; + toggleLinkButtonBehavior = (): void => { + if (this.Document.isLinkButton || this.Document.onClick || this.Document.ignoreClick) { + this.Document.isLinkButton = false; this.Document.ignoreClick = false; this.Document.onClick = undefined; } else { - this.Document.isButton = true; + this.Document.isLinkButton = true; this.Document.followLinkLocation = undefined; } } @undoBatch toggleFollowInPlace = (): void => { - if (this.Document.isButton) { - this.Document.isButton = false; + if (this.Document.isLinkButton) { + this.Document.isLinkButton = false; } else { - this.Document.isButton = true; + this.Document.isLinkButton = true; this.Document.followLinkLocation = "inPlace"; } } @@ -642,7 +642,7 @@ export class DocumentView extends DocComponent(Docu const portal = Docs.Create.FreeformDocument([], { _width: (this.layoutDoc._width || 0) + 10, _height: this.layoutDoc._height || 0, title: StrCast(this.props.Document.title) + ".portal" }); DocUtils.MakeLink({ doc: this.props.Document }, { doc: portal }, "portal to"); } - this.Document.isButton = true; + this.Document.isLinkButton = true; } @undoBatch @@ -727,8 +727,8 @@ export class DocumentView extends DocComponent(Docu onClicks.push({ description: "Enter Portal", event: this.makeIntoPortal, icon: "window-restore" }); onClicks.push({ description: "Toggle Detail", event: () => this.Document.onClick = ScriptField.MakeScript(`toggleDetail(this, "${this.props.Document.layoutKey}")`), icon: "window-restore" }); onClicks.push({ description: this.Document.ignoreClick ? "Select" : "Do Nothing", event: () => this.Document.ignoreClick = !this.Document.ignoreClick, icon: this.Document.ignoreClick ? "unlock" : "lock" }); - onClicks.push({ description: this.Document.isButton ? "Remove Follow Behavior" : "Follow Link in Place", event: this.toggleFollowInPlace, icon: "concierge-bell" }); - onClicks.push({ description: this.Document.isButton || this.Document.onClick ? "Remove Click Behavior" : "Follow Link", event: this.toggleButtonBehavior, icon: "concierge-bell" }); + onClicks.push({ description: this.Document.isLinkButton ? "Remove Follow Behavior" : "Follow Link in Place", event: this.toggleFollowInPlace, icon: "concierge-bell" }); + onClicks.push({ description: this.Document.isLinkButton || this.Document.onClick ? "Remove Click Behavior" : "Follow Link", event: this.toggleLinkButtonBehavior, icon: "concierge-bell" }); onClicks.push({ description: "Edit onClick Script", icon: "edit", event: (obj: any) => ScriptBox.EditButtonScript("On Button Clicked ...", this.props.Document, "onClick", obj.x, obj.y) }); !existingOnClick && cm.addItem({ description: "OnClick...", subitems: onClicks, icon: "hand-point-right" }); @@ -861,7 +861,7 @@ export class DocumentView extends DocComponent(Docu await Promise.all(allDocs.map((doc: Doc) => { let isMainDoc: boolean = false; const dataDoc = Doc.GetProto(doc); - if (doc.type === DocumentType.TEXT) { + if (doc.type === DocumentType.RTF) { if (dataDoc === Doc.GetProto(this.props.Document)) { isMainDoc = true; } @@ -964,7 +964,7 @@ export class DocumentView extends DocComponent(Docu const fallback = Cast(this.props.Document.layoutKey, "string"); return typeof fallback === "string" ? fallback : "layout"; } - rootSelected = (outsideReaction: boolean) => { + rootSelected = (outsideReaction?: boolean) => { return this.isSelected(outsideReaction) || (this.props.Document.forceActive && this.props.rootSelected?.(outsideReaction) ? true : false); } childScaling = () => (this.layoutDoc._fitWidth ? this.props.PanelWidth() / this.nativeWidth : this.props.ContentScaling()); @@ -1026,10 +1026,10 @@ export class DocumentView extends DocComponent(Docu @computed get anchors() { TraceMobx(); return DocListCast(this.Document.links).filter(d => !d.hidden && this.isNonTemporalLink).map((d, i) => -
+
(Docu @computed get innards() { TraceMobx(); if (!this.props.PanelWidth()) { // this happens when the document is a tree view label - return
+ return
{StrCast(this.props.Document.title)} {this.anchors}
; diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 37770a2e1..836d95830 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -262,7 +262,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & if (de.complete.docDragData) { const draggedDoc = de.complete.docDragData.draggedDocuments.length && de.complete.docDragData.draggedDocuments[0]; // replace text contents whend dragging with Alt - if (draggedDoc && draggedDoc.type === DocumentType.TEXT && !Doc.AreProtosEqual(draggedDoc, this.props.Document) && de.altKey) { + if (draggedDoc && draggedDoc.type === DocumentType.RTF && !Doc.AreProtosEqual(draggedDoc, this.props.Document) && de.altKey) { if (draggedDoc.data instanceof RichTextField) { Doc.GetProto(this.dataDoc)[this.props.fieldKey] = new RichTextField(draggedDoc.data.Data, draggedDoc.data.Text); e.stopPropagation(); @@ -1206,7 +1206,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps &
{!this.props.Document._showSidebar ? (null) : this.sidebarWidthPercent === "0%" ? diff --git a/src/client/views/nodes/LabelBox.scss b/src/client/views/nodes/LabelBox.scss new file mode 100644 index 000000000..ab5b2c6b3 --- /dev/null +++ b/src/client/views/nodes/LabelBox.scss @@ -0,0 +1,38 @@ +.labelBox-outerDiv { + width: 100%; + height: 100%; + pointer-events: all; + border-radius: inherit; + display: flex; + flex-direction: column; +} + +.labelBox-mainButton { + width: 100%; + height: 100%; + border-radius: inherit; + letter-spacing: 2px; + text-transform: uppercase; + overflow: hidden; + display:flex; +} + +.labelBox-mainButtonCenter { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + display: inline; + align-items: center; + margin: auto; +} + +.labelBox-params { + display: flex; + flex-direction: row; +} + +.labelBox-missingParam { + width: 100%; + background: lightgray; + border: dimGray solid 1px; +} \ No newline at end of file diff --git a/src/client/views/nodes/LabelBox.tsx b/src/client/views/nodes/LabelBox.tsx new file mode 100644 index 000000000..0ec6af93a --- /dev/null +++ b/src/client/views/nodes/LabelBox.tsx @@ -0,0 +1,97 @@ +import { library } from '@fortawesome/fontawesome-svg-core'; +import { faEdit } from '@fortawesome/free-regular-svg-icons'; +import { action, computed } from 'mobx'; +import { observer } from 'mobx-react'; +import * as React from 'react'; +import { Doc, DocListCast } from '../../../new_fields/Doc'; +import { List } from '../../../new_fields/List'; +import { createSchema, makeInterface, listSpec } from '../../../new_fields/Schema'; +import { ScriptField } from '../../../new_fields/ScriptField'; +import { BoolCast, StrCast, Cast, FieldValue } from '../../../new_fields/Types'; +import { DragManager } from '../../util/DragManager'; +import { undoBatch } from '../../util/UndoManager'; +import { DocComponent } from '../DocComponent'; +import './LabelBox.scss'; +import { FieldView, FieldViewProps } from './FieldView'; +import { ContextMenuProps } from '../ContextMenuItem'; +import { ContextMenu } from '../ContextMenu'; +import { documentSchema } from '../../../new_fields/documentSchemas'; + + +library.add(faEdit as any); + +const LabelSchema = createSchema({ + onClick: ScriptField, + buttonParams: listSpec("string"), + text: "string" +}); + +type LabelDocument = makeInterface<[typeof LabelSchema, typeof documentSchema]>; +const LabelDocument = makeInterface(LabelSchema, documentSchema); + +@observer +export class LabelBox extends DocComponent(LabelDocument) { + public static LayoutString(fieldKey: string) { return FieldView.LayoutString(LabelBox, fieldKey); } + private dropDisposer?: DragManager.DragDropDisposer; + + @computed get dataDoc() { + return this.props.DataDoc && + (this.Document.isTemplateForField || BoolCast(this.props.DataDoc.isTemplateForField) || + this.props.DataDoc.layout === this.props.Document) ? this.props.DataDoc : Doc.GetProto(this.props.Document); + } + + + protected createDropTarget = (ele: HTMLDivElement) => { + this.dropDisposer?.(); + if (ele) { + this.dropDisposer = DragManager.MakeDropTarget(ele, this.drop.bind(this)); + } + } + + specificContextMenu = (e: React.MouseEvent): void => { + const funcs: ContextMenuProps[] = []; + funcs.push({ + description: "Clear Script Params", event: () => { + const params = FieldValue(this.Document.buttonParams); + params?.map(p => this.props.Document[p] = undefined); + }, icon: "trash" + }); + + ContextMenu.Instance.addItem({ description: "OnClick...", subitems: funcs, icon: "asterisk" }); + } + + @undoBatch + @action + drop = (e: Event, de: DragManager.DropEvent) => { + const docDragData = de.complete.docDragData; + const params = this.Document.buttonParams; + const missingParams = params?.filter(p => this.props.Document[p] === undefined); + if (docDragData && missingParams?.includes((e.target as any).textContent)) { + this.props.Document[(e.target as any).textContent] = new List(docDragData.droppedDocuments.map((d, i) => + d.onDragStart ? docDragData.draggedDocuments[i] : d)); + e.stopPropagation(); + } + } + // (!missingParams || !missingParams.length ? "" : "(" + missingParams.map(m => m + ":").join(" ") + ")") + render() { + const params = this.Document.buttonParams; + const missingParams = params?.filter(p => this.props.Document[p] === undefined); + params?.map(p => DocListCast(this.props.Document[p])); // bcz: really hacky form of prefetching ... + return ( +
+
+
+ {(this.Document.text || this.Document.title)} +
+
+
+ {!missingParams || !missingParams.length ? (null) : missingParams.map(m =>
{m}
)} +
+
+ ); + } +} \ No newline at end of file diff --git a/src/client/views/nodes/LinkAnchorBox.scss b/src/client/views/nodes/LinkAnchorBox.scss new file mode 100644 index 000000000..7b6093ebd --- /dev/null +++ b/src/client/views/nodes/LinkAnchorBox.scss @@ -0,0 +1,29 @@ +.linkAnchorBox-cont, .linkAnchorBox-cont-small { + cursor: default; + position: absolute; + width: 15; + height: 15; + border-radius: 20px; + pointer-events: all; + user-select: none; + + .linkAnchorBox-linkCloser { + position: absolute; + width: 18; + height: 18; + background: rgb(219, 21, 21); + top: -1px; + left: -1px; + border-radius: 5px; + display: flex; + justify-content: center; + align-items: center; + padding-left: 2px; + padding-top: 1px; + } +} + +.linkAnchorBox-cont-small { + width:5px; + height:5px; +} \ No newline at end of file diff --git a/src/client/views/nodes/LinkAnchorBox.tsx b/src/client/views/nodes/LinkAnchorBox.tsx new file mode 100644 index 000000000..770a3d0d1 --- /dev/null +++ b/src/client/views/nodes/LinkAnchorBox.tsx @@ -0,0 +1,146 @@ +import { action, observable } from "mobx"; +import { observer } from "mobx-react"; +import { Doc, DocListCast } from "../../../new_fields/Doc"; +import { documentSchema } from "../../../new_fields/documentSchemas"; +import { makeInterface } from "../../../new_fields/Schema"; +import { Cast, NumCast, StrCast } from "../../../new_fields/Types"; +import { Utils, setupMoveUpEvents } from '../../../Utils'; +import { DocumentManager } from "../../util/DocumentManager"; +import { DragManager } from "../../util/DragManager"; +import { DocComponent } from "../DocComponent"; +import "./LinkAnchorBox.scss"; +import { FieldView, FieldViewProps } from "./FieldView"; +import React = require("react"); +import { ContextMenuProps } from "../ContextMenuItem"; +import { ContextMenu } from "../ContextMenu"; +import { LinkEditor } from "../linking/LinkEditor"; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { SelectionManager } from "../../util/SelectionManager"; +import { TraceMobx } from "../../../new_fields/util"; +const higflyout = require("@hig/flyout"); +export const { anchorPoints } = higflyout; +export const Flyout = higflyout.default; + +type LinkAnchorSchema = makeInterface<[typeof documentSchema]>; +const LinkAnchorDocument = makeInterface(documentSchema); + +@observer +export class LinkAnchorBox extends DocComponent(LinkAnchorDocument) { + public static LayoutString(fieldKey: string) { return FieldView.LayoutString(LinkAnchorBox, fieldKey); } + _doubleTap = false; + _lastTap: number = 0; + _ref = React.createRef(); + _isOpen = false; + _timeout: NodeJS.Timeout | undefined; + @observable _x = 0; + @observable _y = 0; + @observable _selected = false; + @observable _editing = false; + @observable _forceOpen = false; + + onPointerDown = (e: React.PointerEvent) => { + setupMoveUpEvents(this, e, this.onPointerMove, () => { }, this.onClick); + } + onPointerMove = action((e: PointerEvent, down: number[], delta: number[]) => { + const cdiv = this._ref && this._ref.current && this._ref.current.parentElement; + if (!this._isOpen && cdiv) { + const bounds = cdiv.getBoundingClientRect(); + const pt = Utils.getNearestPointInPerimeter(bounds.left, bounds.top, bounds.width, bounds.height, e.clientX, e.clientY); + const separation = Math.sqrt((pt[0] - e.clientX) * (pt[0] - e.clientX) + (pt[1] - e.clientY) * (pt[1] - e.clientY)); + const dragdist = Math.sqrt((pt[0] - down[0]) * (pt[0] - down[0]) + (pt[1] - down[1]) * (pt[1] - down[1])); + if (separation > 100) { + const dragData = new DragManager.DocumentDragData([this.props.Document]); + dragData.dropAction = "alias"; + dragData.removeDropProperties = ["anchor1_x", "anchor1_y", "anchor2_x", "anchor2_y", "isButton"]; + DragManager.StartDocumentDrag([this._ref.current!], dragData, down[0], down[1]); + return true; + } else if (dragdist > separation) { + this.props.Document[this.props.fieldKey + "_x"] = (pt[0] - bounds.left) / bounds.width * 100; + this.props.Document[this.props.fieldKey + "_y"] = (pt[1] - bounds.top) / bounds.height * 100; + } + } + return false; + }); + @action + onClick = (e: PointerEvent) => { + this._doubleTap = (Date.now() - this._lastTap < 300 && e.button === 0); + this._lastTap = Date.now(); + if ((e.button === 2 || e.ctrlKey || !this.props.Document.isLinkButton)) { + this.props.select(false); + } + if (!this._doubleTap) { + const anchorContainerDoc = this.props.ContainingCollectionDoc; // bcz: hack! need a better prop for passing the anchor's container + this._editing = true; + anchorContainerDoc && this.props.bringToFront(anchorContainerDoc, false); + if (anchorContainerDoc && !this.props.Document.onClick && !this._isOpen) { + this._timeout = setTimeout(action(() => { + DocumentManager.Instance.FollowLink(this.props.Document, anchorContainerDoc, document => this.props.addDocTab(document, StrCast(this.props.Document.linkOpenLocation, "inTab")), false); + this._editing = false; + }), 300 - (Date.now() - this._lastTap)); + } + } else { + this._timeout && clearTimeout(this._timeout); + this._timeout = undefined; + } + } + + openLinkDocOnRight = (e: React.MouseEvent) => { + this.props.addDocTab(this.props.Document, "onRight"); + } + openLinkTargetOnRight = (e: React.MouseEvent) => { + const alias = Doc.MakeAlias(Cast(this.props.Document[this.props.fieldKey], Doc, null)); + alias.isLinkButton = undefined; + alias.isBackground = undefined; + alias.layoutKey = "layout"; + this.props.addDocTab(alias, "onRight"); + } + @action + openLinkEditor = action((e: React.MouseEvent) => { + SelectionManager.DeselectAll(); + this._editing = this._forceOpen = true; + }); + + specificContextMenu = (e: React.MouseEvent): void => { + const funcs: ContextMenuProps[] = []; + funcs.push({ description: "Open Link Target on Right", event: () => this.openLinkTargetOnRight(e), icon: "eye" }); + funcs.push({ description: "Open Link on Right", event: () => this.openLinkDocOnRight(e), icon: "eye" }); + funcs.push({ description: "Open Link Editor", event: () => this.openLinkEditor(e), icon: "eye" }); + + ContextMenu.Instance.addItem({ description: "Link Funcs...", subitems: funcs, icon: "asterisk" }); + } + + render() { + TraceMobx(); + const x = this.props.PanelWidth() > 1 ? NumCast(this.props.Document[this.props.fieldKey + "_x"], 100) : 0; + const y = this.props.PanelWidth() > 1 ? NumCast(this.props.Document[this.props.fieldKey + "_y"], 100) : 0; + const c = StrCast(this.props.Document.backgroundColor, "lightblue"); + const anchor = this.props.fieldKey === "anchor1" ? "anchor2" : "anchor1"; + const anchorScale = (x === 0 || x === 100 || y === 0 || y === 100) ? 1 : .15; + + const timecode = this.props.Document[anchor + "Timecode"]; + const targetTitle = StrCast((this.props.Document[anchor]! as Doc).title) + (timecode !== undefined ? ":" + timecode : ""); + const flyout = ( +
Doc.UnBrushDoc(this.props.Document)}> + { })} /> + {!this._forceOpen ? (null) :
this._isOpen = this._editing = this._forceOpen = false)}> + +
} +
+ ); + const small = this.props.PanelWidth() <= 1; + return
+ {!this._editing && !this._forceOpen ? (null) : + this._isOpen = true} onClose={action(() => this._isOpen = this._forceOpen = this._editing = false)}> + + + + } +
; + } +} diff --git a/src/client/views/nodes/PDFBox.tsx b/src/client/views/nodes/PDFBox.tsx index f8c008a2d..53ad547b6 100644 --- a/src/client/views/nodes/PDFBox.tsx +++ b/src/client/views/nodes/PDFBox.tsx @@ -9,7 +9,6 @@ import { ScriptField } from '../../../new_fields/ScriptField'; import { Cast, NumCast, StrCast } from "../../../new_fields/Types"; import { PdfField, URLField } from "../../../new_fields/URLField"; import { Utils } from '../../../Utils'; -import { KeyCodes } from '../../northstar/utils/KeyCodes'; import { undoBatch } from '../../util/UndoManager'; import { panZoomSchema } from '../collections/collectionFreeForm/CollectionFreeFormView'; import { ContextMenu } from '../ContextMenu'; @@ -18,10 +17,10 @@ import { DocAnnotatableComponent } from "../DocComponent"; import { PDFViewer } from "../pdf/PDFViewer"; import { FieldView, FieldViewProps } from './FieldView'; import { pageSchema } from "./ImageBox"; +import { KeyCodes } from '../../util/KeyCodes'; import "./PDFBox.scss"; import React = require("react"); import { documentSchema } from '../../../new_fields/documentSchemas'; -import { url } from 'inspector'; type PdfDocument = makeInterface<[typeof documentSchema, typeof panZoomSchema, typeof pageSchema]>; const PdfDocument = makeInterface(documentSchema, panZoomSchema, pageSchema); diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index 73d09b4e1..e7434feaa 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -6,7 +6,7 @@ import { action, computed, IReactionDisposer, observable, reaction, runInAction import { observer } from "mobx-react"; import { Doc, DocListCast } from "../../../new_fields/Doc"; import { InkTool } from "../../../new_fields/InkField"; -import { BoolCast, Cast, FieldValue, NumCast } from "../../../new_fields/Types"; +import { BoolCast, Cast, FieldValue, NumCast, StrCast } from "../../../new_fields/Types"; import { returnFalse } from "../../../Utils"; import { DocumentManager } from "../../util/DocumentManager"; import { undoBatch } from "../../util/UndoManager"; @@ -246,7 +246,7 @@ export class PresBox extends React.Component { }); } - updateMinimize = undoBatch(action((e: React.ChangeEvent, mode: number) => { + updateMinimize = undoBatch(action((e: React.ChangeEvent, mode: CollectionViewType) => { if (BoolCast(this.props.Document.inOverlay) !== (mode === CollectionViewType.Invalid)) { if (this.props.Document.inOverlay) { Doc.RemoveDocFromList((Doc.UserDoc().overlays as Doc), undefined, this.props.Document); @@ -261,7 +261,7 @@ export class PresBox extends React.Component { } })); - initializeViewAliases = (docList: Doc[], viewtype: number) => { + initializeViewAliases = (docList: Doc[], viewtype: CollectionViewType) => { const hgt = (viewtype === CollectionViewType.Tree) ? 50 : 46; docList.forEach(doc => { doc.presBox = this.props.Document; // give contained documents a reference to the presentation @@ -283,14 +283,14 @@ export class PresBox extends React.Component { @undoBatch viewChanged = action((e: React.ChangeEvent) => { //@ts-ignore - this.props.Document._viewType = Number(e.target.selectedOptions[0].value); + this.props.Document._viewType = e.target.selectedOptions[0].value; this.props.Document._viewType === CollectionViewType.Stacking && (this.props.Document._pivotField = undefined); // pivot field may be set by the user in timeline view (or some other way) -- need to reset it here this.updateMinimize(e, Number(this.props.Document._viewType)); }); childLayoutTemplate = () => this.props.Document._viewType === CollectionViewType.Stacking ? Cast(Doc.UserDoc().presentationTemplate, Doc, null) : undefined; render() { - const mode = NumCast(this.props.Document._viewType, CollectionViewType.Invalid); + const mode = StrCast(this.props.Document._viewType) as CollectionViewType; this.initializeViewAliases(this.childDocs, mode); return
diff --git a/src/client/views/nodes/ScriptingBox.scss b/src/client/views/nodes/ScriptingBox.scss new file mode 100644 index 000000000..e69de29bb diff --git a/src/client/views/nodes/ScriptingBox.tsx b/src/client/views/nodes/ScriptingBox.tsx new file mode 100644 index 000000000..a2dd134ed --- /dev/null +++ b/src/client/views/nodes/ScriptingBox.tsx @@ -0,0 +1,71 @@ +import { library } from '@fortawesome/fontawesome-svg-core'; +import { faEdit } from '@fortawesome/free-regular-svg-icons'; +import { computed } from 'mobx'; +import { observer } from 'mobx-react'; +import * as React from 'react'; +import { Doc } from '../../../new_fields/Doc'; +import { documentSchema } from '../../../new_fields/documentSchemas'; +import { CompileScript } from "../../util/Scripting"; +import { ScriptBox } from '../ScriptBox'; +import { createSchema, listSpec, makeInterface } from '../../../new_fields/Schema'; +import { ScriptField } from '../../../new_fields/ScriptField'; +import { BoolCast, ScriptCast } from '../../../new_fields/Types'; +import { DocComponent } from '../DocComponent'; +import { FieldView, FieldViewProps } from './FieldView'; +import './ScriptingBox.scss'; +import { DocumentIconContainer } from './DocumentIcon'; + + +library.add(faEdit as any); + +const ScriptingSchema = createSchema({ + onClick: ScriptField, + buttonParams: listSpec("string"), + text: "string" +}); + +type ScriptingDocument = makeInterface<[typeof ScriptingSchema, typeof documentSchema]>; +const ScriptingDocument = makeInterface(ScriptingSchema, documentSchema); + +@observer +export class ScriptingBox extends DocComponent(ScriptingDocument) { + public static LayoutString(fieldKey: string) { return FieldView.LayoutString(ScriptingBox, fieldKey); } + + @computed get dataDoc() { + return this.props.DataDoc && + (this.Document.isTemplateForField || BoolCast(this.props.DataDoc.isTemplateForField) || + this.props.DataDoc.layout === this.props.Document) ? this.props.DataDoc : Doc.GetProto(this.props.Document); + } + + specificContextMenu = (e: React.MouseEvent): void => { } + + render() { + const script = ScriptCast(this.props.Document[this.props.fieldKey]); + let originalText: string | undefined = undefined; + if (script) { + originalText = script.script.originalScript; + } + return !(this.props.Document instanceof Doc) ? (null) : + { }} + onCancel={() => { }} + onSave={(text, onError) => { + if (!text) { + this.dataDoc[this.props.fieldKey] = undefined; + } else { + const script = CompileScript(text, { + params: { this: Doc.name }, + typecheck: false, + editable: true, + transformer: DocumentIconContainer.getTransformer() + }); + if (!script.compiled) { + onError(script.errors.map(error => error.messageText).join("\n")); + } + else { + this.dataDoc[this.props.fieldKey] = new ScriptField(script); + } + } + }} showDocumentIcons />; + } +} \ No newline at end of file diff --git a/src/client/views/nodes/VideoBox.tsx b/src/client/views/nodes/VideoBox.tsx index d384ad12f..a4a330fe6 100644 --- a/src/client/views/nodes/VideoBox.tsx +++ b/src/client/views/nodes/VideoBox.tsx @@ -132,7 +132,7 @@ export class VideoBox extends DocAnnotatableComponent{ return faMusic; case (DocumentType.COL): return faObjectGroup; - case (DocumentType.HIST): - return faChartBar; case (DocumentType.IMG): return faImage; case (DocumentType.LINK): return faLink; case (DocumentType.PDF): return faFilePdf; - case (DocumentType.TEXT): + case (DocumentType.RTF): return faStickyNote; case (DocumentType.VID): return faVideo; @@ -158,15 +156,13 @@ export class IconButton extends React.Component{ return (); case (DocumentType.COL): return (); - case (DocumentType.HIST): - return (); case (DocumentType.IMG): return (); case (DocumentType.LINK): return (); case (DocumentType.PDF): return (); - case (DocumentType.TEXT): + case (DocumentType.RTF): return (); case (DocumentType.VID): return (); diff --git a/src/client/views/search/SearchBox.tsx b/src/client/views/search/SearchBox.tsx index 67af661c9..19a4d558e 100644 --- a/src/client/views/search/SearchBox.tsx +++ b/src/client/views/search/SearchBox.tsx @@ -128,7 +128,7 @@ export class SearchBox extends React.Component { } } - public _allIcons: string[] = [DocumentType.AUDIO, DocumentType.COL, DocumentType.IMG, DocumentType.LINK, DocumentType.PDF, DocumentType.TEXT, DocumentType.VID, DocumentType.WEB]; + public _allIcons: string[] = [DocumentType.AUDIO, DocumentType.COL, DocumentType.IMG, DocumentType.LINK, DocumentType.PDF, DocumentType.RTF, DocumentType.VID, DocumentType.WEB]; //if true, any keywords can be used. if false, all keywords are required. //this also serves as an indicator if the word status filter is applied @observable private _filterOpen: boolean = false; diff --git a/src/client/views/search/SearchItem.tsx b/src/client/views/search/SearchItem.tsx index 0d77026ad..fe2000700 100644 --- a/src/client/views/search/SearchItem.tsx +++ b/src/client/views/search/SearchItem.tsx @@ -68,7 +68,7 @@ export class SelectorContextMenu extends React.Component { getOnClick({ col, target }: { col: Doc, target: Doc }) { return () => { col = Doc.IsPrototype(col) ? Doc.MakeDelegate(col) : col; - if (NumCast(col._viewType, CollectionViewType.Invalid) === CollectionViewType.Freeform) { + if (col._viewType === CollectionViewType.Freeform) { const newPanX = NumCast(target.x) + NumCast(target._width) / 2; const newPanY = NumCast(target.y) + NumCast(target._height) / 2; col._panX = newPanX; @@ -178,14 +178,13 @@ export class SearchItem extends React.Component { } const button = layoutresult.indexOf(DocumentType.PDF) !== -1 ? faFilePdf : layoutresult.indexOf(DocumentType.IMG) !== -1 ? faImage : - layoutresult.indexOf(DocumentType.TEXT) !== -1 ? faStickyNote : + layoutresult.indexOf(DocumentType.RTF) !== -1 ? faStickyNote : layoutresult.indexOf(DocumentType.VID) !== -1 ? faFilm : layoutresult.indexOf(DocumentType.COL) !== -1 ? faObjectGroup : layoutresult.indexOf(DocumentType.AUDIO) !== -1 ? faMusic : layoutresult.indexOf(DocumentType.LINK) !== -1 ? faLink : - layoutresult.indexOf(DocumentType.HIST) !== -1 ? faChartBar : - layoutresult.indexOf(DocumentType.WEB) !== -1 ? faGlobeAsia : - faCaretUp; + layoutresult.indexOf(DocumentType.WEB) !== -1 ? faGlobeAsia : + faCaretUp; return
{ this._useIcons = false; this._displayDim = Number(SEARCH_THUMBNAIL_SIZE); })} >
; diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index d381447c5..4fc4dc1cf 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -80,7 +80,7 @@ export function DocListCastAsync(field: FieldResult, defaultValue?: Doc[]) { } export async function DocCastAsync(field: FieldResult): Promise> { - return await Cast(field, Doc); + return Cast(field, Doc); } export function DocListCast(field: FieldResult): Doc[] { @@ -713,7 +713,7 @@ export namespace Doc { export function SetUserDoc(doc: Doc) { manager._user_doc = doc; } export function IsBrushed(doc: Doc) { return computedFn(function IsBrushed(doc: Doc) { - return brushManager.BrushedDoc.has(doc) || brushManager.BrushedDoc.has(Doc.GetProto(doc)); + return brushManager.BrushedDoc.has(doc) || brushManager.BrushedDoc.has(Doc.GetProto(doc)); })(doc); } // don't bother memoizing (caching) the result if called from a non-reactive context. (plus this avoids a warning message) @@ -919,7 +919,7 @@ Scripting.addGlobal(function curPresentationItem() { Scripting.addGlobal(function selectDoc(doc: any) { Doc.UserDoc().SelectedDocs = new List([doc]); }); Scripting.addGlobal(function selectedDocs(container: Doc, excludeCollections: boolean, prevValue: any) { const docs = DocListCast(Doc.UserDoc().SelectedDocs). - filter(d => !Doc.AreProtosEqual(d, container) && !d.annotationOn && d.type !== DocumentType.DOCUMENT && d.type !== DocumentType.KVP && + filter(d => !Doc.AreProtosEqual(d, container) && !d.annotationOn && d.type !== DocumentType.DOCHOLDER && d.type !== DocumentType.KVP && (!excludeCollections || d.type !== DocumentType.COL || !Cast(d.data, listSpec(Doc), null))); return docs.length ? new List(docs) : prevValue; }); diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts index ad4a5a252..a5a81f4a4 100644 --- a/src/new_fields/RichTextField.ts +++ b/src/new_fields/RichTextField.ts @@ -4,9 +4,6 @@ import { Deserializable } from "../client/util/SerializationHelper"; import { Copy, ToScriptString, ToPlainText, ToString } from "./FieldSymbols"; import { scriptingGlobal } from "../client/util/Scripting"; -const delimiter = "\n"; -const joiner = ""; - @scriptingGlobal @Deserializable("RichTextField") export class RichTextField extends ObjectField { diff --git a/src/new_fields/ScriptField.ts b/src/new_fields/ScriptField.ts index 4a3119aeb..8d0ddf94c 100644 --- a/src/new_fields/ScriptField.ts +++ b/src/new_fields/ScriptField.ts @@ -98,12 +98,15 @@ export class ScriptField extends ObjectField { [Copy](): ObjectField { return new ScriptField(this.script); } + toString() { + return `${this.script.originalScript}`; + } [ToScriptString]() { return "script field"; } [ToString]() { - return "script field"; + return this.script.originalScript; } public static CompileScript(script: string, params: object = {}, addReturn = false, capturedVariables?: { [name: string]: Field }) { const compiled = CompileScript(script, { diff --git a/src/new_fields/documentSchemas.ts b/src/new_fields/documentSchemas.ts index 03519cb94..216b63352 100644 --- a/src/new_fields/documentSchemas.ts +++ b/src/new_fields/documentSchemas.ts @@ -61,7 +61,7 @@ export const documentSchema = createSchema({ fitToBox: "boolean", // whether freeform view contents should be zoomed/panned to fill the area of the document view letterSpacing: "string", textTransform: "string", - childTemplateName: "string" // the name of a template to use to override the layoutKey when rendering a document in DocumentBox + childTemplateName: "string" // the name of a template to use to override the layoutKey when rendering a document in DocHolderBox }); export const positionSchema = createSchema({ diff --git a/src/server/Message.ts b/src/server/Message.ts index 81f63656b..01aae5de7 100644 --- a/src/server/Message.ts +++ b/src/server/Message.ts @@ -19,7 +19,7 @@ export class Message { export enum Types { Number, List, Key, Image, Web, Document, Text, Icon, RichText, DocumentReference, - Html, Video, Audio, Ink, PDF, Tuple, HistogramOp, Boolean, Script, Templates + Html, Video, Audio, Ink, PDF, Tuple, Boolean, Script, Templates } export interface Transferable { diff --git a/src/server/RouteManager.ts b/src/server/RouteManager.ts index a8680c0c9..80e4a6741 100644 --- a/src/server/RouteManager.ts +++ b/src/server/RouteManager.ts @@ -2,7 +2,6 @@ import RouteSubscriber from "./RouteSubscriber"; import { DashUserModel } from "./authentication/models/user_model"; import { Request, Response, Express } from 'express'; import { cyan, red, green } from 'colors'; -import { Utils } from "../client/northstar/utils/Utils"; export enum Method { GET, diff --git a/src/server/Websocket/Websocket.ts b/src/server/Websocket/Websocket.ts index 9f9fc9619..947aa4289 100644 --- a/src/server/Websocket/Websocket.ts +++ b/src/server/Websocket/Websocket.ts @@ -199,7 +199,7 @@ export namespace WebSocket { function setField(socket: Socket, newValue: Transferable) { Database.Instance.update(newValue.id, newValue, () => socket.broadcast.emit(MessageStore.SetField.Message, newValue)); - if (newValue.type === Types.Text) { + if (newValue.type === Types.Text) { // if the newValue has sring type, then it's suitable for searching -- pass it to SOLR Search.updateDocument({ id: newValue.id, data: (newValue as any).data }); } } @@ -221,6 +221,7 @@ export namespace WebSocket { "pdf": ["_t", "url"], "audio": ["_t", "url"], "web": ["_t", "url"], + "script": ["_t", value => value.script.originalScript], "RichTextField": ["_t", value => value.Text], "date": ["_d", value => new Date(value.date).toISOString()], "proxy": ["_i", "fieldId"], diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 529f8d56d..589055fbe 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -2,8 +2,6 @@ import { action, computed, observable, reaction } from "mobx"; import * as rp from 'request-promise'; import { DocServer } from "../../../client/DocServer"; import { Docs, DocumentOptions } from "../../../client/documents/Documents"; -import { Attribute, AttributeGroup, Catalog, Schema } from "../../../client/northstar/model/idea/idea"; -import { ArrayUtil } from "../../../client/northstar/utils/ArrayUtil"; import { UndoManager } from "../../../client/util/UndoManager"; import { Doc, DocListCast } from "../../../new_fields/Doc"; import { List } from "../../../new_fields/List"; @@ -419,77 +417,6 @@ export class CurrentUserUtils { throw new Error("There should be a user id! Why does Dash think there isn't one?"); } }); - // try { - // const getEnvironment = await fetch("/assets/env.json", { redirect: "follow", method: "GET", credentials: "include" }); - // NorthstarSettings.Instance.UpdateEnvironment(await getEnvironment.json()); - // await Gateway.Instance.ClearCatalog(); - // const extraSchemas = Cast(CurrentUserUtils.UserDocument.DBSchemas, listSpec("string"), []); - // let extras = await Promise.all(extraSchemas.map(sc => Gateway.Instance.GetSchema("", sc))); - // let catprom = CurrentUserUtils.SetNorthstarCatalog(await Gateway.Instance.GetCatalog(), extras); - // // if (catprom) await Promise.all(catprom); - // } catch (e) { - - // } - } - - /* Northstar catalog ... really just for testing so this should eventually go away */ - // --------------- Northstar hooks ------------- / - static _northstarSchemas: Doc[] = []; - @observable private static _northstarCatalog?: Catalog; - @computed public static get NorthstarDBCatalog() { return this._northstarCatalog; } - - @action static SetNorthstarCatalog(ctlog: Catalog, extras: Catalog[]) { - CurrentUserUtils.NorthstarDBCatalog = ctlog; - // if (ctlog && ctlog.schemas) { - // extras.map(ex => ctlog.schemas!.push(ex)); - // return ctlog.schemas.map(async schema => { - // let schemaDocuments: Doc[] = []; - // let attributesToBecomeDocs = CurrentUserUtils.GetAllNorthstarColumnAttributes(schema); - // await Promise.all(attributesToBecomeDocs.reduce((promises, attr) => { - // promises.push(DocServer.GetRefField(attr.displayName! + ".alias").then(action((field: Opt) => { - // if (field instanceof Doc) { - // schemaDocuments.push(field); - // } else { - // var atmod = new ColumnAttributeModel(attr); - // let histoOp = new HistogramOperation(schema.displayName!, - // new AttributeTransformationModel(atmod, AggregateFunction.None), - // new AttributeTransformationModel(atmod, AggregateFunction.Count), - // new AttributeTransformationModel(atmod, AggregateFunction.Count)); - // schemaDocuments.push(Docs.Create.HistogramDocument(histoOp, { width: 200, height: 200, title: attr.displayName! })); - // } - // }))); - // return promises; - // }, [] as Promise[])); - // return CurrentUserUtils._northstarSchemas.push(Docs.Create.TreeDocument(schemaDocuments, { width: 50, height: 100, title: schema.displayName! })); - // }); - // } - } - public static set NorthstarDBCatalog(ctlog: Catalog | undefined) { this._northstarCatalog = ctlog; } - - public static AddNorthstarSchema(schema: Schema, schemaDoc: Doc) { - if (this._northstarCatalog && CurrentUserUtils._northstarSchemas) { - this._northstarCatalog.schemas!.push(schema); - CurrentUserUtils._northstarSchemas.push(schemaDoc); - const schemas = Cast(CurrentUserUtils.UserDocument.DBSchemas, listSpec("string"), []); - schemas.push(schema.displayName!); - CurrentUserUtils.UserDocument.DBSchemas = new List(schemas); - } - } - public static GetNorthstarSchema(name: string): Schema | undefined { - return !this._northstarCatalog || !this._northstarCatalog.schemas ? undefined : - ArrayUtil.FirstOrDefault(this._northstarCatalog.schemas, (s: Schema) => s.displayName === name); - } - public static GetAllNorthstarColumnAttributes(schema: Schema) { - const recurs = (attrs: Attribute[], g?: AttributeGroup) => { - if (g && g.attributes) { - attrs.push.apply(attrs, g.attributes); - if (g.attributeGroups) { - g.attributeGroups.forEach(ng => recurs(attrs, ng)); - } - } - return attrs; - }; - return recurs([] as Attribute[], schema ? schema.rootAttributeGroup : undefined); } } diff --git a/src/server/updateProtos.ts b/src/server/updateProtos.ts index 90490eb45..e9860bd61 100644 --- a/src/server/updateProtos.ts +++ b/src/server/updateProtos.ts @@ -1,8 +1,7 @@ import { Database } from "./database"; const protos = - ["text", "histogram", "image", "web", "collection", "kvp", - "video", "audio", "pdf", "icon", "import", "linkdoc"]; + ["text", "image", "web", "collection", "kvp", "video", "audio", "pdf", "icon", "import", "linkdoc"]; (async function () { await Promise.all( -- cgit v1.2.3-70-g09d2 From b21db9d40c1619df5455ba8ffe3ef76913cc92de Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Wed, 8 Apr 2020 19:14:47 -0400 Subject: added scripting box --- src/client/documents/Documents.ts | 4 +- src/client/util/Scripting.ts | 8 +- src/client/views/MainView.tsx | 3 +- src/client/views/nodes/ScriptingBox.scss | 33 +++++ src/client/views/nodes/ScriptingBox.tsx | 137 ++++++++++++--------- .../authentication/models/current_user_utils.ts | 1 + 6 files changed, 123 insertions(+), 63 deletions(-) (limited to 'src/client/views/MainView.tsx') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 5231dbb8c..5eca71ca9 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -509,8 +509,8 @@ export namespace Docs { return InstanceFromProto(Prototypes.get(DocumentType.PRES), initial, options); } - export function ScriptingDocument(url: string, options: DocumentOptions = {}) { - return InstanceFromProto(Prototypes.get(DocumentType.SCRIPTING), new YoutubeField(new URL(url)), options); + export function ScriptingDocument(options: DocumentOptions = {}) { + return InstanceFromProto(Prototypes.get(DocumentType.SCRIPTING), "", options); } export function VideoDocument(url: string, options: DocumentOptions = {}) { diff --git a/src/client/util/Scripting.ts b/src/client/util/Scripting.ts index cf04c44ca..f97d91d10 100644 --- a/src/client/util/Scripting.ts +++ b/src/client/util/Scripting.ts @@ -89,9 +89,9 @@ const _scriptingGlobals: { [name: string]: any } = {}; let scriptingGlobals: { [name: string]: any } = _scriptingGlobals; function Run(script: string | undefined, customParams: string[], diagnostics: any[], originalScript: string, options: ScriptOptions): CompileResult { - const errors = diagnostics.some(diag => diag.category === ts.DiagnosticCategory.Error); - if ((options.typecheck !== false && errors) || !script) { - return { compiled: false, errors: diagnostics }; + const errors = diagnostics.filter(diag => diag.category === ts.DiagnosticCategory.Error); + if ((options.typecheck !== false && errors.length) || !script) { + return { compiled: false, errors }; } const paramNames = Object.keys(scriptingGlobals); @@ -201,7 +201,7 @@ export interface ScriptOptions { capturedVariables?: { [name: string]: Field }; // list of captured variables typecheck?: boolean; // should the compiler perform typechecking editable?: boolean; // can the script edit Docs - traverser?: TraverserParam; + traverser?: TraverserParam; transformer?: Transformer; // does the editor display a text label by each document that can be used as a captured document reference globals?: { [name: string]: any }; } diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 7c9f47fe4..1edfc871f 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -1,5 +1,5 @@ import { library } from '@fortawesome/fontawesome-svg-core'; -import { faArrowDown, faArrowUp, faBolt, faBullseye, faCaretUp, faCat, faCheck, faChevronRight, faClipboard, faClone, faCloudUploadAlt, faCommentAlt, faCompressArrowsAlt, faCut, faEllipsisV, faEraser, faExclamation, faFileAlt, faFileAudio, faFilePdf, faFilm, faFilter, faFont, faGlobeAsia, faHighlighter, faLongArrowAltRight, faMicrophone, faMousePointer, faMusic, faObjectGroup, faPause, faPen, faPenNib, faPhone, faPlay, faPortrait, faRedoAlt, faStamp, faStickyNote, faThumbtack, faTree, faTv, faUndoAlt, faVideo } from '@fortawesome/free-solid-svg-icons'; +import { faTerminal, faArrowDown, faArrowUp, faBolt, faBullseye, faCaretUp, faCat, faCheck, faChevronRight, faClipboard, faClone, faCloudUploadAlt, faCommentAlt, faCompressArrowsAlt, faCut, faEllipsisV, faEraser, faExclamation, faFileAlt, faFileAudio, faFilePdf, faFilm, faFilter, faFont, faGlobeAsia, faHighlighter, faLongArrowAltRight, faMicrophone, faMousePointer, faMusic, faObjectGroup, faPause, faPen, faPenNib, faPhone, faPlay, faPortrait, faRedoAlt, faStamp, faStickyNote, faThumbtack, faTree, faTv, faUndoAlt, faVideo } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { action, computed, configure, observable, reaction, runInAction } from 'mobx'; import { observer } from 'mobx-react'; @@ -101,6 +101,7 @@ export class MainView extends React.Component { } } + library.add(faTerminal); library.add(faFileAlt); library.add(faStickyNote); library.add(faFont); diff --git a/src/client/views/nodes/ScriptingBox.scss b/src/client/views/nodes/ScriptingBox.scss index e69de29bb..f31c72bb2 100644 --- a/src/client/views/nodes/ScriptingBox.scss +++ b/src/client/views/nodes/ScriptingBox.scss @@ -0,0 +1,33 @@ +.scriptingBox-outerDiv { + width: 100%; + height: 100%; + display: flex; + flex-direction: column; + pointer-events: all; + background-color: rgb(241, 239, 235); + padding: 10px; + .scriptingBox-inputDiv { + display: flex; + flex-direction: column; + height: calc(100% - 30px); + .scriptingBox-errorMessage { + overflow: auto; + } + .scriptingBox-textArea { + width: 100%; + height: 100%; + box-sizing: border-box; + resize: none; + padding: 7px; + } + } + + .scriptingBox-toolbar { + width: 100%; + height: 30px; + .scriptingBox-button { + width: 50% + } + } +} + diff --git a/src/client/views/nodes/ScriptingBox.tsx b/src/client/views/nodes/ScriptingBox.tsx index a2dd134ed..74d9c2e94 100644 --- a/src/client/views/nodes/ScriptingBox.tsx +++ b/src/client/views/nodes/ScriptingBox.tsx @@ -1,71 +1,96 @@ -import { library } from '@fortawesome/fontawesome-svg-core'; -import { faEdit } from '@fortawesome/free-regular-svg-icons'; -import { computed } from 'mobx'; -import { observer } from 'mobx-react'; -import * as React from 'react'; -import { Doc } from '../../../new_fields/Doc'; -import { documentSchema } from '../../../new_fields/documentSchemas'; +import { action, observable, computed } from "mobx"; +import { observer } from "mobx-react"; +import * as React from "react"; +import { Opt } from "../../../new_fields/Doc"; +import { documentSchema } from "../../../new_fields/documentSchemas"; +import { createSchema, makeInterface } from "../../../new_fields/Schema"; +import { ScriptField } from "../../../new_fields/ScriptField"; +import { StrCast, ScriptCast } from "../../../new_fields/Types"; +import { returnTrue } from "../../../Utils"; +import { InteractionUtils } from "../../util/InteractionUtils"; import { CompileScript } from "../../util/Scripting"; -import { ScriptBox } from '../ScriptBox'; -import { createSchema, listSpec, makeInterface } from '../../../new_fields/Schema'; -import { ScriptField } from '../../../new_fields/ScriptField'; -import { BoolCast, ScriptCast } from '../../../new_fields/Types'; -import { DocComponent } from '../DocComponent'; -import { FieldView, FieldViewProps } from './FieldView'; -import './ScriptingBox.scss'; -import { DocumentIconContainer } from './DocumentIcon'; - - -library.add(faEdit as any); +import { DocAnnotatableComponent } from "../DocComponent"; +import { EditableView } from "../EditableView"; +import { FieldView, FieldViewProps } from "../nodes/FieldView"; +import "./ScriptingBox.scss"; const ScriptingSchema = createSchema({ - onClick: ScriptField, - buttonParams: listSpec("string"), - text: "string" }); type ScriptingDocument = makeInterface<[typeof ScriptingSchema, typeof documentSchema]>; const ScriptingDocument = makeInterface(ScriptingSchema, documentSchema); @observer -export class ScriptingBox extends DocComponent(ScriptingDocument) { - public static LayoutString(fieldKey: string) { return FieldView.LayoutString(ScriptingBox, fieldKey); } +export class ScriptingBox extends DocAnnotatableComponent(ScriptingDocument) { + protected multiTouchDisposer?: InteractionUtils.MultiTouchEventDisposer | undefined; + public static LayoutString(fieldStr: string) { return FieldView.LayoutString(ScriptingBox, fieldStr); } - @computed get dataDoc() { - return this.props.DataDoc && - (this.Document.isTemplateForField || BoolCast(this.props.DataDoc.isTemplateForField) || - this.props.DataDoc.layout === this.props.Document) ? this.props.DataDoc : Doc.GetProto(this.props.Document); + @observable private _errorMessage: string = ""; + @computed get rawScript() { return StrCast(this.dataDoc[this.props.fieldKey + "-raw"]); } + set rawScript(value) { this.dataDoc[this.props.fieldKey + "-raw"] = value; } + + @action + componentDidMount() { + this.rawScript = ScriptCast(this.dataDoc[this.props.fieldKey])?.script?.originalScript || this.rawScript; } - specificContextMenu = (e: React.MouseEvent): void => { } + @action + onChange = (e: React.ChangeEvent) => { + this.rawScript = e.target.value; + } - render() { - const script = ScriptCast(this.props.Document[this.props.fieldKey]); - let originalText: string | undefined = undefined; - if (script) { - originalText = script.script.originalScript; + @action + onError = (error: any) => { + this._errorMessage = (error as any).map((e: any) => e.messageText).join(" "); + } + + @action + onCompile = () => { + const result = CompileScript(this.rawScript, {}); + this._errorMessage = ""; + if (result.compiled) { + this._errorMessage = ""; + this.dataDoc[this.props.fieldKey] = new ScriptField(result); } - return !(this.props.Document instanceof Doc) ? (null) : - { }} - onCancel={() => { }} - onSave={(text, onError) => { - if (!text) { - this.dataDoc[this.props.fieldKey] = undefined; - } else { - const script = CompileScript(text, { - params: { this: Doc.name }, - typecheck: false, - editable: true, - transformer: DocumentIconContainer.getTransformer() - }); - if (!script.compiled) { - onError(script.errors.map(error => error.messageText).join("\n")); - } - else { - this.dataDoc[this.props.fieldKey] = new ScriptField(script); - } - } - }} showDocumentIcons />; + else { + this.dataDoc[this.props.fieldKey] = undefined; + this.onError(result.errors); + } + } + + @action + onRun = () => { + this.onCompile(); + ScriptCast(this.dataDoc[this.props.fieldKey])?.script.run({}, + (err: any) => { + this._errorMessage = ""; + this.onError(err); + }); + } + + render() { + let onFocus: Opt<() => void> = undefined, onBlur: Opt<() => void> = undefined; + const params = ""} + SetValue={returnTrue} + />; + return ( +
this.props.isSelected() && e.stopPropagation()} onWheel={(e) => this.props.isSelected() && e.stopPropagation()}> +
+