From d1b9049fe50e401ac1a33177babd0cfa4b32f6a0 Mon Sep 17 00:00:00 2001 From: andrewdkim Date: Wed, 12 Feb 2020 03:37:51 -0500 Subject: can select text from web node and upload from mobile --- src/client/views/nodes/FormattedTextBox.tsx | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) (limited to 'src/client/views/nodes/FormattedTextBox.tsx') diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 0d97c3029..213af43c6 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -700,7 +700,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & setTimeout(async () => { const targetField = Doc.LayoutFieldKey(pdfDoc); const targetAnnotations = await DocListCastAsync(pdfDoc[DataSym][targetField + "-annotations"]);// bcz: better to have the PDF's view handle updating its own annotations - targetAnnotations?.push(pdfRegion); + targetAnnotations ?.push(pdfRegion); }); const link = DocUtils.MakeLink({ doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, { doc: pdfRegion, ctx: pdfDoc }, "note on " + pdfDoc.title, "pasted PDF link"); @@ -742,14 +742,14 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & const rtfField = Cast(this.props.Document._textTemplate || this.dataDoc[fieldKey], RichTextField); if (this.ProseRef) { const self = this; - this._editorView?.destroy(); + this._editorView ?.destroy(); this._editorView = new EditorView(this.ProseRef, { - state: rtfField?.Data ? EditorState.fromJSON(config, JSON.parse(rtfField.Data)) : EditorState.create(config), + state: rtfField ?.Data ? EditorState.fromJSON(config, JSON.parse(rtfField.Data)) : EditorState.create(config), handleScrollToSelection: (editorView) => { const ref = editorView.domAtPos(editorView.state.selection.from); let refNode = ref.node as any; while (refNode && !("getBoundingClientRect" in refNode)) refNode = refNode.parentElement; - const r1 = refNode?.getBoundingClientRect(); + const r1 = refNode ?.getBoundingClientRect(); const r3 = self._ref.current!.getBoundingClientRect(); if (r1.top < r3.top || r1.top > r3.bottom) { r1 && (self._scrollRef.current!.scrollTop += (r1.top - r3.top) * self.props.ScreenToLocalTransform().Scale); @@ -848,11 +848,11 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & this.tryUpdateHeight(); // see if we need to preserve the insertion point - const prosediv = this.ProseRef?.children?.[0] as any; - const keeplocation = prosediv?.keeplocation; + const prosediv = this.ProseRef ?.children ?.[0] as any; + const keeplocation = prosediv ?.keeplocation; prosediv && (prosediv.keeplocation = undefined); - const pos = this._editorView?.state.selection.$from.pos || 1; - keeplocation && setTimeout(() => this._editorView?.dispatch(this._editorView?.state.tr.setSelection(TextSelection.create(this._editorView.state.doc, pos)))); + const pos = this._editorView ?.state.selection.$from.pos || 1; + keeplocation && setTimeout(() => this._editorView ?.dispatch(this._editorView ?.state.tr.setSelection(TextSelection.create(this._editorView.state.doc, pos)))); // jump rich text menu to this textbox const { current } = this._ref; @@ -876,13 +876,13 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & if ((this._editorView!.root as any).getSelection().isCollapsed) { // this is a hack to allow the cursor to be placed at the end of a document when the document ends in an inline dash comment. Apparently Chrome on Windows has a bug/feature which breaks this when clicking after the end of the text. const pcords = this._editorView!.posAtCoords({ left: e.clientX, top: e.clientY }); const node = pcords && this._editorView!.state.doc.nodeAt(pcords.pos); // get what prosemirror thinks the clicked node is (if it's null, then we didn't click on any text) - if (pcords && node?.type === this._editorView!.state.schema.nodes.dashComment) { + if (pcords && node ?.type === this._editorView!.state.schema.nodes.dashComment) { this._editorView!.dispatch(this._editorView!.state.tr.setSelection(TextSelection.create(this._editorView!.state.doc, pcords.pos + 2))); e.preventDefault(); } if (!node && this.ProseRef) { const lastNode = this.ProseRef.children[this.ProseRef.children.length - 1].children[this.ProseRef.children[this.ProseRef.children.length - 1].children.length - 1]; // get the last prosemirror div - if (e.clientY > lastNode?.getBoundingClientRect().bottom) { // if we clicked below the last prosemirror div, then set the selection to be the end of the document + if (e.clientY > lastNode ?.getBoundingClientRect().bottom) { // if we clicked below the last prosemirror div, then set the selection to be the end of the document this._editorView!.dispatch(this._editorView!.state.tr.setSelection(TextSelection.create(this._editorView!.state.doc, this._editorView!.state.doc.content.size))); } } @@ -939,7 +939,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & for (let off = 1; off < 100; off++) { const pos = this._editorView!.posAtCoords({ left: x + off, top: y }); const node = pos && this._editorView!.state.doc.nodeAt(pos.pos); - if (node?.type === schema.nodes.list_item) { + if (node ?.type === schema.nodes.list_item) { list_node = node; break; } @@ -984,7 +984,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & const self = FormattedTextBox; return new Plugin({ view(newView) { - RichTextMenu.Instance.changeView(newView); + RichTextMenu.Instance && RichTextMenu.Instance.changeView(newView); return RichTextMenu.Instance; } }); @@ -1021,7 +1021,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & } if (e.key === "Escape") { this._editorView!.dispatch(state.tr.setSelection(TextSelection.create(state.doc, state.selection.from, state.selection.from))); - (document.activeElement as any).blur?.(); + (document.activeElement as any).blur ?.(); SelectionManager.DeselectAll(); } e.stopPropagation(); @@ -1043,7 +1043,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & @action tryUpdateHeight(limitHeight?: number) { - let scrollHeight = this._ref.current?.scrollHeight; + let scrollHeight = this._ref.current ?.scrollHeight; if (!this.layoutDoc.animateToPos && this.layoutDoc._autoHeight && scrollHeight && getComputedStyle(this._ref.current!.parentElement!).top === "0px") { // if top === 0, then the text box is growing upward (as the overlay caption) which doesn't contribute to the height computation if (limitHeight && scrollHeight > limitHeight) { -- cgit v1.2.3-70-g09d2 From dbdf81e191107240a62086ebe65d1dc5e3b503c6 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 3 Mar 2020 00:18:36 -0500 Subject: several fixes to templates (simplified expanding, notes use 'text' field now, collections show documents when their data field is not a list). multicol/row resizers select their doc. --- package-lock.json | 95 +++++++++------------- src/client/documents/Documents.ts | 23 ++++-- src/client/util/DropConverter.ts | 12 ++- src/client/views/collections/CollectionSubView.tsx | 4 +- .../collections/collectionFreeForm/MarqueeView.tsx | 7 +- .../CollectionMulticolumnView.tsx | 9 +- .../collectionMulticolumn/MulticolumnResizer.tsx | 2 + src/client/views/nodes/DocumentContentsView.tsx | 16 +--- src/client/views/nodes/FormattedTextBox.tsx | 2 +- src/new_fields/Doc.ts | 9 +- .../authentication/models/current_user_utils.ts | 15 ++-- 11 files changed, 88 insertions(+), 106 deletions(-) (limited to 'src/client/views/nodes/FormattedTextBox.tsx') diff --git a/package-lock.json b/package-lock.json index 827fb05b8..ef3ecc9f3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -832,7 +832,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": "*" @@ -2226,7 +2226,7 @@ }, "util": { "version": "0.10.3", - "resolved": "http://registry.npmjs.org/util/-/util-0.10.3.tgz", + "resolved": "https://registry.npmjs.org/util/-/util-0.10.3.tgz", "integrity": "sha1-evsa/lCAUkZInj23/g7TeTNqwPk=", "dev": true, "requires": { @@ -2846,7 +2846,7 @@ }, "browserify-aes": { "version": "1.2.0", - "resolved": "http://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", + "resolved": "https://registry.npmjs.org/browserify-aes/-/browserify-aes-1.2.0.tgz", "integrity": "sha512-+7CHXqGuspUn/Sl5aO7Ea0xWGAtETPXNSAjHo48JfLdPWcMng33Xe4znFvQweqc/uzk5zSOI3H52CYnjCfb5hA==", "requires": { "buffer-xor": "^1.0.3", @@ -2880,7 +2880,7 @@ }, "browserify-rsa": { "version": "4.0.1", - "resolved": "http://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", + "resolved": "https://registry.npmjs.org/browserify-rsa/-/browserify-rsa-4.0.1.tgz", "integrity": "sha1-IeCr+vbyApzy+vsTNWenAdQTVSQ=", "requires": { "bn.js": "^4.1.0", @@ -3051,7 +3051,7 @@ }, "camelcase-keys": { "version": "2.1.0", - "resolved": "http://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", + "resolved": "https://registry.npmjs.org/camelcase-keys/-/camelcase-keys-2.1.0.tgz", "integrity": "sha1-MIvur/3ygRkFHvodkyITyRuPkuc=", "requires": { "camelcase": "^2.0.0", @@ -3844,7 +3844,7 @@ }, "create-hash": { "version": "1.2.0", - "resolved": "http://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", + "resolved": "https://registry.npmjs.org/create-hash/-/create-hash-1.2.0.tgz", "integrity": "sha512-z00bCGNHDG8mHAkP7CtT1qVu+bFQUPjYq/4Iv3C3kWjTFV10zIjfSoeqXo9Asws8gwSHDGj/hl2u4OGIjapeCg==", "requires": { "cipher-base": "^1.0.1", @@ -3856,7 +3856,7 @@ }, "create-hmac": { "version": "1.1.7", - "resolved": "http://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", + "resolved": "https://registry.npmjs.org/create-hmac/-/create-hmac-1.1.7.tgz", "integrity": "sha512-MJG9liiZ+ogc4TzUwuvbER1JRdgvUFSB5+VR/g5h82fGaIRWMWddtKBHi7/sVhfjQZ6SehlyhvQYrcYkaUIpLg==", "requires": { "cipher-base": "^1.0.3", @@ -4398,7 +4398,7 @@ }, "diffie-hellman": { "version": "5.0.3", - "resolved": "http://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", + "resolved": "https://registry.npmjs.org/diffie-hellman/-/diffie-hellman-5.0.3.tgz", "integrity": "sha512-kqag/Nl+f3GwyK25fhUMYj81BUOrZ9IuJsjIcDE5icNM9FJHAVm3VcUDxdLPoQtTuUylWm6ZIknYJwwaPxsUzg==", "requires": { "bn.js": "^4.1.0", @@ -5697,8 +5697,7 @@ }, "ansi-regex": { "version": "2.1.1", - "bundled": true, - "optional": true + "bundled": true }, "aproba": { "version": "1.2.0", @@ -5716,13 +5715,11 @@ }, "balanced-match": { "version": "1.0.0", - "bundled": true, - "optional": true + "bundled": true }, "brace-expansion": { "version": "1.1.11", "bundled": true, - "optional": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -5735,18 +5732,15 @@ }, "code-point-at": { "version": "1.1.0", - "bundled": true, - "optional": true + "bundled": true }, "concat-map": { "version": "0.0.1", - "bundled": true, - "optional": true + "bundled": true }, "console-control-strings": { "version": "1.1.0", - "bundled": true, - "optional": true + "bundled": true }, "core-util-is": { "version": "1.0.2", @@ -5849,8 +5843,7 @@ }, "inherits": { "version": "2.0.4", - "bundled": true, - "optional": true + "bundled": true }, "ini": { "version": "1.3.5", @@ -5860,7 +5853,6 @@ "is-fullwidth-code-point": { "version": "1.0.0", "bundled": true, - "optional": true, "requires": { "number-is-nan": "^1.0.0" } @@ -5873,20 +5865,17 @@ "minimatch": { "version": "3.0.4", "bundled": true, - "optional": true, "requires": { "brace-expansion": "^1.1.7" } }, "minimist": { "version": "0.0.8", - "bundled": true, - "optional": true + "bundled": true }, "minipass": { "version": "2.9.0", "bundled": true, - "optional": true, "requires": { "safe-buffer": "^5.1.2", "yallist": "^3.0.0" @@ -5903,7 +5892,6 @@ "mkdirp": { "version": "0.5.1", "bundled": true, - "optional": true, "requires": { "minimist": "0.0.8" } @@ -5984,8 +5972,7 @@ }, "number-is-nan": { "version": "1.0.1", - "bundled": true, - "optional": true + "bundled": true }, "object-assign": { "version": "4.1.1", @@ -5995,7 +5982,6 @@ "once": { "version": "1.4.0", "bundled": true, - "optional": true, "requires": { "wrappy": "1" } @@ -6071,8 +6057,7 @@ }, "safe-buffer": { "version": "5.1.2", - "bundled": true, - "optional": true + "bundled": true }, "safer-buffer": { "version": "2.1.2", @@ -6102,7 +6087,6 @@ "string-width": { "version": "1.0.2", "bundled": true, - "optional": true, "requires": { "code-point-at": "^1.0.0", "is-fullwidth-code-point": "^1.0.0", @@ -6120,7 +6104,6 @@ "strip-ansi": { "version": "3.0.1", "bundled": true, - "optional": true, "requires": { "ansi-regex": "^2.0.0" } @@ -6159,13 +6142,11 @@ }, "wrappy": { "version": "1.0.2", - "bundled": true, - "optional": true + "bundled": true }, "yallist": { "version": "3.1.1", - "bundled": true, - "optional": true + "bundled": true } } }, @@ -7383,7 +7364,7 @@ }, "is-accessor-descriptor": { "version": "0.1.6", - "resolved": "http://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", + "resolved": "https://registry.npmjs.org/is-accessor-descriptor/-/is-accessor-descriptor-0.1.6.tgz", "integrity": "sha1-qeEss66Nh2cn7u84Q/igiXtcmNY=", "requires": { "kind-of": "^3.0.2" @@ -7438,7 +7419,7 @@ }, "is-data-descriptor": { "version": "0.1.4", - "resolved": "http://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", + "resolved": "https://registry.npmjs.org/is-data-descriptor/-/is-data-descriptor-0.1.4.tgz", "integrity": "sha1-C17mSDiOLIYCgueT8YVv7D8wG1Y=", "requires": { "kind-of": "^3.0.2" @@ -8169,7 +8150,7 @@ }, "load-json-file": { "version": "1.1.0", - "resolved": "http://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", + "resolved": "https://registry.npmjs.org/load-json-file/-/load-json-file-1.1.0.tgz", "integrity": "sha1-lWkFcI1YtLq0wiYbBPWfMcmTdMA=", "requires": { "graceful-fs": "^4.1.2", @@ -8506,7 +8487,7 @@ }, "media-typer": { "version": "0.3.0", - "resolved": "http://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", "integrity": "sha1-hxDXrwqmJvj/+hzgAWhUUmMlV0g=" }, "mem": { @@ -8538,7 +8519,7 @@ }, "meow": { "version": "3.7.0", - "resolved": "http://registry.npmjs.org/meow/-/meow-3.7.0.tgz", + "resolved": "https://registry.npmjs.org/meow/-/meow-3.7.0.tgz", "integrity": "sha1-cstmi0JSKCkKu/qFaJJYcwioAfs=", "requires": { "camelcase-keys": "^2.0.0", @@ -8713,7 +8694,7 @@ }, "mkdirp": { "version": "0.5.1", - "resolved": "http://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", "requires": { "minimist": "0.0.8" @@ -9051,7 +9032,7 @@ }, "next-tick": { "version": "1.0.0", - "resolved": "http://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz", + "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.0.0.tgz", "integrity": "sha1-yobR/ogoFpsBICCOPchCS524NCw=" }, "nice-try": { @@ -9134,7 +9115,7 @@ }, "semver": { "version": "5.3.0", - "resolved": "http://registry.npmjs.org/semver/-/semver-5.3.0.tgz", + "resolved": "https://registry.npmjs.org/semver/-/semver-5.3.0.tgz", "integrity": "sha1-myzl094C0XxgEq0yaqa00M9U+U8=" }, "tar": { @@ -12785,7 +12766,7 @@ }, "os-homedir": { "version": "1.0.2", - "resolved": "http://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/os-homedir/-/os-homedir-1.0.2.tgz", "integrity": "sha1-/7xJiDNuDoM94MFox+8VISGqf7M=" }, "os-locale": { @@ -12798,7 +12779,7 @@ }, "os-tmpdir": { "version": "1.0.2", - "resolved": "http://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", + "resolved": "https://registry.npmjs.org/os-tmpdir/-/os-tmpdir-1.0.2.tgz", "integrity": "sha1-u+Z0BseaqFxc/sdm/lc0VV36EnQ=" }, "osenv": { @@ -13038,7 +13019,7 @@ }, "path-is-absolute": { "version": "1.0.1", - "resolved": "http://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=" }, "path-is-inside": { @@ -14464,7 +14445,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", @@ -14906,7 +14887,7 @@ }, "safe-regex": { "version": "1.1.0", - "resolved": "http://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", + "resolved": "https://registry.npmjs.org/safe-regex/-/safe-regex-1.1.0.tgz", "integrity": "sha1-QKNmnzsHfR6UPURinhV91IAjvy4=", "requires": { "ret": "~0.1.10" @@ -15186,7 +15167,7 @@ }, "sha.js": { "version": "2.4.11", - "resolved": "http://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", + "resolved": "https://registry.npmjs.org/sha.js/-/sha.js-2.4.11.tgz", "integrity": "sha512-QMEp5B7cftE7APOjk5Y6xgrbWu+WkLVQwk8JNjZ8nKRciZaByEW6MubieAiToS7+dwvrjGhH8jRXz3MVd0AYqQ==", "requires": { "inherits": "^2.0.1", @@ -16048,7 +16029,7 @@ }, "string_decoder": { "version": "1.1.1", - "resolved": "http://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", "requires": { "safe-buffer": "~5.1.0" @@ -16078,7 +16059,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" @@ -16094,7 +16075,7 @@ }, "strip-eof": { "version": "1.0.0", - "resolved": "http://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", + "resolved": "https://registry.npmjs.org/strip-eof/-/strip-eof-1.0.0.tgz", "integrity": "sha1-u0P/VZim6wXYm1n80SnJgzE2Br8=" }, "strip-indent": { @@ -16911,7 +16892,7 @@ }, "tty-browserify": { "version": "0.0.0", - "resolved": "http://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", + "resolved": "https://registry.npmjs.org/tty-browserify/-/tty-browserify-0.0.0.tgz", "integrity": "sha1-oVe6QC2iTpv5V/mqadUk7tQpAaY=", "dev": true }, @@ -18383,7 +18364,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/documents/Documents.ts b/src/client/documents/Documents.ts index abef72f21..4df90ceb8 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -94,6 +94,7 @@ export interface DocumentOptions { layoutKey?: string; type?: string; title?: string; + style?: string; page?: number; scale?: number; isDisplayPanel?: boolean; // whether the panel functions as GoldenLayout "stack" used to display documents @@ -183,7 +184,7 @@ export namespace Docs { const TemplateMap: TemplateMap = new Map([ [DocumentType.TEXT, { - layout: { view: FormattedTextBox, dataField: data }, + layout: { view: FormattedTextBox, dataField: "text" }, options: { _height: 150, _xMargin: 10, _yMargin: 10 } }], [DocumentType.HIST, { @@ -442,7 +443,7 @@ export namespace Docs { * only when creating a DockDocument from the current user's already existing * main document. */ - export function InstanceFromProto(proto: Doc, data: Field | undefined, options: DocumentOptions, delegId?: string) { + export function InstanceFromProto(proto: Doc, data: Field | undefined, options: DocumentOptions, delegId?: string, fieldKey: string = "data") { const { omit: protoProps, extract: delegateProps } = OmitKeys(options, delegateKeys); if (!("author" in protoProps)) { @@ -455,7 +456,7 @@ export namespace Docs { protoProps.isPrototype = true; - const dataDoc = MakeDataDelegate(proto, protoProps, data); + const dataDoc = MakeDataDelegate(proto, protoProps, data, fieldKey); const viewDoc = Doc.MakeDelegate(dataDoc, delegId); AudioBox.ActiveRecordings.map(d => DocUtils.MakeLink({ doc: viewDoc }, { doc: d }, "audio link", "link to audio: " + d.title)); @@ -473,10 +474,10 @@ export namespace Docs { * @param options initial values to apply to this new delegate * @param value the data to store in this new delegate */ - function MakeDataDelegate(proto: Doc, options: DocumentOptions, value?: D) { + function MakeDataDelegate(proto: Doc, options: DocumentOptions, value?: D, fieldKey: string = "data") { const deleg = Doc.MakeDelegate(proto); if (value !== undefined) { - deleg.data = value; + deleg[fieldKey] = value; } return Doc.assign(deleg, options); } @@ -535,7 +536,7 @@ export namespace Docs { } export function TextDocument(text: string, options: DocumentOptions = {}) { - return InstanceFromProto(Prototypes.get(DocumentType.TEXT), text, options); + return InstanceFromProto(Prototypes.get(DocumentType.TEXT), text, options, undefined, "text"); } export function LinkDocument(source: { doc: Doc, ctx?: Doc }, target: { doc: Doc, ctx?: Doc }, options: DocumentOptions = {}, id?: string) { @@ -929,7 +930,15 @@ export namespace DocUtils { description: "Add Note ...", subitems: DocListCast((Doc.UserDoc().noteTypes as Doc).data).map((note, i) => ({ description: ":" + StrCast(note.title), - event: (args: { x: number, y: number }) => docTextAdder(Docs.Create.TextDocument("", { _width: 200, x, y, _autoHeight: note._autoHeight !== false, layout: note, title: StrCast(note.title) + "#" + (note.aliasCount = NumCast(note.aliasCount) + 1) })), + event: (args: { x: number, y: number }) => { + const textDoc = Docs.Create.TextDocument("", { + _width: 200, x, y, _autoHeight: note._autoHeight !== false, + title: StrCast(note.title) + "#" + (note.aliasCount = NumCast(note.aliasCount) + 1) + }); + textDoc.layoutKey = "layout_" + note.title; + textDoc[textDoc.layoutKey] = note; + docTextAdder(textDoc); + }, icon: "eye" })) as ContextMenuProps[], icon: "eye" diff --git a/src/client/util/DropConverter.ts b/src/client/util/DropConverter.ts index 3c7caa60b..393e39687 100644 --- a/src/client/util/DropConverter.ts +++ b/src/client/util/DropConverter.ts @@ -1,5 +1,5 @@ import { DragManager } from "./DragManager"; -import { Doc, DocListCast } from "../../new_fields/Doc"; +import { Doc, DocListCast, Opt } from "../../new_fields/Doc"; import { DocumentType } from "../documents/DocumentTypes"; import { ObjectField } from "../../new_fields/ObjectField"; import { StrCast } from "../../new_fields/Types"; @@ -8,7 +8,12 @@ import { ScriptField, ComputedField } from "../../new_fields/ScriptField"; import { RichTextField } from "../../new_fields/RichTextField"; import { ImageField } from "../../new_fields/URLField"; -export function makeTemplate(doc: Doc, first: boolean = true): boolean { +// +// converts 'doc' into a template that can be used to render other documents. +// the title of doc is used to determine which field is being templated, so +// passing a value for 'rename' allows the doc to be given a meangingful name +// after it has been converted to +export function makeTemplate(doc: Doc, first: boolean = true, rename: Opt = undefined): boolean { const layoutDoc = doc.layout instanceof Doc && doc.layout.isTemplateForField ? doc.layout : doc; const layout = StrCast(layoutDoc.layout).match(/fieldKey={'[^']*'}/)![0]; const fieldKey = layout.replace("fieldKey={'", "").replace(/'}$/, ""); @@ -29,6 +34,7 @@ export function makeTemplate(doc: Doc, first: boolean = true): boolean { any = Doc.MakeMetadataFieldTemplate(layoutDoc, Doc.GetProto(layoutDoc)); } } + rename && (doc.title = rename); return any; } export function convertDropDataToButtons(data: DragManager.DocumentDragData) { @@ -38,7 +44,7 @@ export function convertDropDataToButtons(data: DragManager.DocumentDragData) { if (!doc.onDragStart && !doc.onClick && !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) { - makeTemplate(layoutDoc); + !layoutDoc.isTemplateDoc && makeTemplate(layoutDoc); } else { (layoutDoc.layout instanceof Doc) && !data.userDropAction; } diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index aa31d604e..527623ad4 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -113,7 +113,9 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T) { return Cast(this.dataField, listSpec(Doc)); } get childDocs() { - const docs = DocListCast(this.dataField); + const dfield = this.dataField; + const rawdocs = (dfield instanceof Doc) ? [dfield] : Cast(dfield, listSpec(Doc), this.props.Document.expandedTemplate && !this.props.annotationsKey ? [Cast(this.props.Document.expandedTemplate, Doc, null)] : []); + const docs = rawdocs.filter(d => !(d instanceof Promise)).map(d => d as Doc); const viewSpecScript = Cast(this.props.Document.viewSpecScript, ScriptField); return viewSpecScript ? docs.filter(d => viewSpecScript.script.run({ doc: d }, console.log).result) : docs; } diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index d4f1a5444..af701347f 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -109,12 +109,7 @@ export class MarqueeView extends React.Component 48 && e.keyCode <= 57) { - const notes = DocListCast((CurrentUserUtils.UserDocument.noteTypes as Doc).data); - const text = Docs.Create.TextDocument("", { _width: 200, _height: 100, x: x, y: y, _autoHeight: true, title: "-typed text-" }); - text.layout = notes[(e.keyCode - 49) % notes.length]; - this.props.addLiveTextDocument(text); - } + } e.stopPropagation(); } //heuristically converts pasted text into a table. diff --git a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx index 82175c0b5..bd20781dc 100644 --- a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx +++ b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx @@ -223,17 +223,13 @@ export class CollectionMulticolumnView extends CollectionSubView(MulticolumnDocu */ @computed private get contents(): JSX.Element[] | null { - // bcz: feels like a hack ... trying to show something useful when there's no list document in the data field of a templated object - const expanded = Cast(this.props.Document.expandedTemplate, Doc, null); - let { childLayoutPairs } = this.dataDoc[this.props.fieldKey] instanceof List || !expanded ? this : { childLayoutPairs: [] } as { childLayoutPairs: { layout: Doc, data: Doc }[] }; - const replaced = !childLayoutPairs.length && !Cast(expanded?.layout, Doc, null) && expanded; - childLayoutPairs = childLayoutPairs.length || !replaced ? childLayoutPairs : [{ layout: replaced, data: replaced }]; + let { childLayoutPairs } = this; const { Document, PanelHeight } = this.props; const collector: JSX.Element[] = []; for (let i = 0; i < childLayoutPairs.length; i++) { const { layout } = childLayoutPairs[i]; const dxf = () => this.lookupIndividualTransform(layout).translate(-NumCast(Document._xMargin), -NumCast(Document._yMargin)); - const width = () => expanded ? this.props.PanelWidth() : this.lookupPixels(layout); + const width = () => this.lookupPixels(layout); const height = () => PanelHeight() - 2 * NumCast(Document._yMargin) - (BoolCast(Document.showWidthLabels) ? 20 : 0); collector.push(
void; } const resizerOpacity = 1; @@ -23,6 +24,7 @@ export default class ResizeBar extends React.Component { @action private registerResizing = (e: React.PointerEvent) => { + this.props.select(false); e.stopPropagation(); e.preventDefault(); window.removeEventListener("pointermove", this.onPointerMove); diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index 41478a3c5..dcb6d4a31 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -73,21 +73,11 @@ export class DocumentContentsView extends React.Component { - if ((this.props.Document.isTemplateForField === "data" || !this.props.Document.isTemplateForField) && // only update the title if the data document's data field is changing + if ((this.props.Document.isTemplateForField === "text" || !this.props.Document.isTemplateForField) && // only update the title if the data document's data field is changing StrCast(this.dataDoc.title).startsWith("-") && this._editorView && !this.Document.customTitle) { const str = this._editorView.state.doc.textContent; const titlestr = str.substr(0, Math.min(40, str.length)); diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index dcd97f079..0f3896055 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -449,12 +449,11 @@ export namespace Doc { } // - // Determines whether the combination of the layoutDoc and dataDoc represents - // a template relationship : there is a dataDoc and it doesn't match the layoutDoc an - // the lyouatDoc's layout is layout string (not a document) + // Determines whether the layout needs to be expanded (as a template). + // template expansion is rquired when the layout is a template doc/field and there's a datadoc which isn't equal to the layout template // export function WillExpandTemplateLayout(layoutDoc: Doc, dataDoc?: Doc) { - return (layoutDoc.isTemplateForField || layoutDoc.isTemplateDoc) && dataDoc && layoutDoc !== dataDoc && !(Doc.LayoutField(layoutDoc) instanceof Doc); + return (layoutDoc.isTemplateForField || layoutDoc.isTemplateDoc) && dataDoc && layoutDoc !== dataDoc; } // @@ -610,7 +609,7 @@ export namespace Doc { export function MakeMetadataFieldTemplate(templateField: Doc, templateDoc: Opt): boolean { // find the metadata field key that this template field doc will display (indicated by its title) - const metadataFieldKey = StrCast(templateField.title).replace(/^-/, ""); + const metadataFieldKey = StrCast(templateField.isTemplateForField) || StrCast(templateField.title).replace(/^-/, ""); // update the original template to mark it as a template templateField.isTemplateForField = metadataFieldKey; diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index dc63f8a89..6216ab7e6 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -43,15 +43,15 @@ export class CurrentUserUtils { Docs.Create.TextDocument("completed", { title: "completed", _backgroundColor: "green", color: "white" }) ]; const noteTemplates = [ - Docs.Create.TextDocument("", { title: "Note", isTemplateDoc: true, backgroundColor: "yellow" }), - Docs.Create.TextDocument("", { title: "Idea", isTemplateDoc: true, backgroundColor: "pink" }), - Docs.Create.TextDocument("", { title: "Topic", isTemplateDoc: true, backgroundColor: "lightBlue" }), - Docs.Create.TextDocument("", { title: "Person", isTemplateDoc: true, backgroundColor: "lightGreen" }), - Docs.Create.TextDocument("", { title: "Todo", isTemplateDoc: true, backgroundColor: "orange", _autoHeight: false, _height: 100, _showCaption: "caption" }) + Docs.Create.TextDocument("", { title: "text", style: "Note", isTemplateDoc: true, backgroundColor: "yellow" }), + Docs.Create.TextDocument("", { title: "text", style: "Idea", isTemplateDoc: true, backgroundColor: "pink" }), + Docs.Create.TextDocument("", { title: "text", style: "Topic", isTemplateDoc: true, backgroundColor: "lightBlue" }), + Docs.Create.TextDocument("", { title: "text", style: "Person", isTemplateDoc: true, backgroundColor: "lightGreen" }), + Docs.Create.TextDocument("", { title: "text", style: "Todo", isTemplateDoc: true, backgroundColor: "orange", _autoHeight: false, _height: 100, _showCaption: "caption" }) ]; doc.fieldTypes = Docs.Create.TreeDocument([], { title: "field enumerations" }); Doc.enumeratedTextTemplate(Doc.GetProto(noteTemplates[4]), FormattedTextBox.LayoutString("Todo"), "taskStatus", taskStatusValues); - doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates.map(nt => makeTemplate(nt) ? nt : nt), { title: "Note Types", _height: 75 })); + doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates.map(nt => makeTemplate(nt, true, StrCast(nt.style)) ? nt : nt), { title: "Note Types", _height: 75 })); } // setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools @@ -285,7 +285,8 @@ export class CurrentUserUtils { { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: slideTemplate, removeDropProperties: new List(["dropAction"]), title: "presentation slide", icon: "sticky-note" }); doc.descriptionBtn = Docs.Create.FontIconDocument( { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: descriptionTemplate, removeDropProperties: new List(["dropAction"]), title: "description view", icon: "sticky-note" }); - doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.slidesBtn as Doc, doc.descriptionBtn as Doc], { + doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.slidesBtn as Doc, doc.descriptionBtn as Doc, + ...DocListCast(Cast(doc.noteTypes, Doc, null))], { title: "expanding buttons", _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", backgroundColor: "black", treeViewPreventOpen: true, forceActive: true, lockedPosition: true, dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }) -- cgit v1.2.3-70-g09d2 From ef58bdb2f6e9bffe377239d77b3360ed8b3132a1 Mon Sep 17 00:00:00 2001 From: bob Date: Tue, 3 Mar 2020 18:14:37 -0500 Subject: a bunch of small fixes to link naming and fixes to audio links. --- src/client/documents/Documents.ts | 8 ++++---- src/client/util/RichTextMenu.tsx | 2 +- src/client/util/RichTextRules.ts | 2 +- src/client/util/RichTextSchema.tsx | 3 ++- src/client/views/DocumentButtonBar.tsx | 4 +--- src/client/views/RecommendationsBox.tsx | 2 +- src/client/views/collections/CollectionTreeView.tsx | 2 +- .../collectionFreeForm/CollectionFreeFormLinkView.tsx | 4 ++-- .../views/collections/collectionFreeForm/MarqueeView.tsx | 11 ++++++----- src/client/views/nodes/AudioBox.scss | 3 ++- src/client/views/nodes/AudioBox.tsx | 1 + src/client/views/nodes/DocumentView.tsx | 10 +++++----- src/client/views/nodes/FormattedTextBox.tsx | 4 ++-- src/client/views/nodes/VideoBox.tsx | 2 +- src/client/views/pdf/PDFViewer.tsx | 4 ++-- 15 files changed, 32 insertions(+), 30 deletions(-) (limited to 'src/client/views/nodes/FormattedTextBox.tsx') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 67e037286..6b25b3897 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -459,7 +459,7 @@ export namespace Docs { const dataDoc = MakeDataDelegate(proto, protoProps, data, fieldKey); const viewDoc = Doc.MakeDelegate(dataDoc, delegId); - viewDoc.type !== DocumentType.LINK && AudioBox.ActiveRecordings.map(d => DocUtils.MakeLink({ doc: viewDoc }, { doc: d }, "audio link", "link to audio: " + d.title)); + viewDoc.type !== DocumentType.LINK && AudioBox.ActiveRecordings.map(d => DocUtils.MakeLink({ doc: viewDoc }, { doc: d }, "audio link", "audio timeline")); return Doc.assign(viewDoc, delegateProps, true); } @@ -914,13 +914,13 @@ export namespace DocUtils { }); } - export function MakeLink(source: { doc: Doc, ctx?: Doc }, target: { doc: Doc, ctx?: Doc }, title: string = "", linkRelationship: string = "", id?: string) { + export function MakeLink(source: { doc: Doc, ctx?: Doc }, target: { doc: Doc, ctx?: Doc }, linkRelationship: string = "", id?: string) { const sv = DocumentManager.Instance.getDocumentView(source.doc); if (sv && sv.props.ContainingCollectionDoc === target.doc) return; if (target.doc === CurrentUserUtils.UserDocument) return undefined; - const linkDoc = Docs.Create.LinkDocument(source, target, { title, linkRelationship }, id); - Doc.GetProto(linkDoc).title = ComputedField.MakeFunction('this.anchor1.title +" " + (this.linkRelationship||"to") +" " + this.anchor2.title'); + const linkDoc = Docs.Create.LinkDocument(source, target, { linkRelationship }, id); + Doc.GetProto(linkDoc).title = ComputedField.MakeFunction('this.anchor1.title +" (" + (this.linkRelationship||"to") +") " + this.anchor2.title'); Doc.GetProto(source.doc).links = ComputedField.MakeFunction("links(this)"); Doc.GetProto(target.doc).links = ComputedField.MakeFunction("links(this)"); diff --git a/src/client/util/RichTextMenu.tsx b/src/client/util/RichTextMenu.tsx index 460f1fa37..3f0ec7aa5 100644 --- a/src/client/util/RichTextMenu.tsx +++ b/src/client/util/RichTextMenu.tsx @@ -146,7 +146,7 @@ export default class RichTextMenu extends AntimodeMenu { public MakeLinkToSelection = (linkDocId: string, title: string, location: string, targetDocId: string): string => { if (this.view) { - const link = this.view.state.schema.marks.link.create({ href: Utils.prepend("/doc/" + linkDocId), title: title, location: location, targetId: targetDocId }); + const link = this.view.state.schema.marks.link.create({ href: Utils.prepend("/doc/" + linkDocId), title: title, location: location, linkId: linkDocId, targetId: targetDocId }); this.view.dispatch(this.view.state.tr.removeMark(this.view.state.selection.from, this.view.state.selection.to, this.view.state.schema.marks.link). addMark(this.view.state.selection.from, this.view.state.selection.to, link)); return this.view.state.selection.$from.nodeAfter?.text || ""; diff --git a/src/client/util/RichTextRules.ts b/src/client/util/RichTextRules.ts index 7ffc2dd9c..e5b20a79b 100644 --- a/src/client/util/RichTextRules.ts +++ b/src/client/util/RichTextRules.ts @@ -91,7 +91,7 @@ export class RichTextRules { DocServer.GetRefField(docid).then(docx => { const target = ((docx instanceof Doc) && docx) || Docs.Create.FreeformDocument([], { title: docid, _width: 500, _height: 500, _LODdisable: true, }, docid); DocUtils.Publish(target, docid, returnFalse, returnFalse); - DocUtils.MakeLink({ doc: this.Document }, { doc: target }, "portal link", ""); + DocUtils.MakeLink({ doc: this.Document }, { doc: target }, "portal to"); }); const link = state.schema.marks.link.create({ href: Utils.prepend("/doc/" + docid), location: "onRight", title: docid, targetId: docid }); return state.tr.deleteRange(end - 1, end).deleteRange(start, start + 2).addMark(start, end - 3, link); diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index 034f5d55a..2c3714310 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -301,6 +301,7 @@ export const marks: { [index: string]: MarkSpec } = { attrs: { href: {}, targetId: { default: "" }, + linkId: { default: "" }, showPreview: { default: true }, location: { default: null }, title: { default: null }, @@ -315,7 +316,7 @@ export const marks: { [index: string]: MarkSpec } = { toDOM(node: any) { return node.attrs.docref && node.attrs.title ? ["div", ["span", `"`], ["span", 0], ["span", `"`], ["br"], ["a", { ...node.attrs, class: "prosemirror-attribution", title: `${node.attrs.title}` }, node.attrs.title], ["br"]] : - ["a", { ...node.attrs, id: node.attrs.targetId, title: `${node.attrs.title}` }, 0]; + ["a", { ...node.attrs, id: node.attrs.linkId + node.attrs.targetId, title: `${node.attrs.title}` }, 0]; } }, diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index a3d313224..52544d3c9 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -122,13 +122,11 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView | if (this.view0 && linkDoc) { const proto = Doc.GetProto(linkDoc); proto.anchor1Context = this.view0.props.ContainingCollectionDoc; + Doc.GetProto(linkDoc).linkRelationship = "hyperlink"; const anchor2Title = linkDoc.anchor2 instanceof Doc ? StrCast(linkDoc.anchor2.title) : "-untitled-"; const anchor2Id = linkDoc.anchor2 instanceof Doc ? linkDoc.anchor2[Id] : ""; const text = RichTextMenu.Instance.MakeLinkToSelection(linkDoc[Id], anchor2Title, e.ctrlKey ? "onRight" : "inTab", anchor2Id); - if (linkDoc.anchor2 instanceof Doc && !proto.title) { - proto.title = Doc.GetProto(linkDoc).title = ComputedField.MakeFunction('this.anchor1.title +" " + (this.linkRelationship||"to") +" " + this.anchor2.title'); - } } linkDrag?.end(); }, diff --git a/src/client/views/RecommendationsBox.tsx b/src/client/views/RecommendationsBox.tsx index 0e3cfd729..262226bac 100644 --- a/src/client/views/RecommendationsBox.tsx +++ b/src/client/views/RecommendationsBox.tsx @@ -167,7 +167,7 @@ export class RecommendationsBox extends React.Component {
DocumentManager.Instance.jumpToDocument(doc, false)}>
-
DocUtils.MakeLink({ doc: this.props.Document.sourceDoc as Doc }, { doc: doc }, "User Selected Link", "Generated from Recommender", undefined)}> +
DocUtils.MakeLink({ doc: this.props.Document.sourceDoc as Doc }, { doc: doc }, "Recommender", undefined)}>
diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index 7eeeb6ff1..28f620157 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -231,7 +231,7 @@ class TreeView extends React.Component { if (de.complete.linkDragData) { const sourceDoc = de.complete.linkDragData.linkSourceDocument; const destDoc = this.props.document; - DocUtils.MakeLink({ doc: sourceDoc }, { doc: destDoc }, "tree drop link"); + DocUtils.MakeLink({ doc: sourceDoc }, { doc: destDoc }, "tree link"); e.stopPropagation(); } if (de.complete.docDragData) { diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx index 1038347d4..a33146388 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx @@ -46,8 +46,8 @@ export class CollectionFreeFormLinkView extends React.Component(selected); - Doc.GetProto(summary).layout_portal = CollectionView.LayoutString("data-annotations"); + Doc.GetProto(summary)[Doc.LayoutFieldKey(summary) + "-annotations"] = new List(selected); + Doc.GetProto(summary).layout_portal = CollectionView.LayoutString(Doc.LayoutFieldKey(summary) + "-annotations"); summary._backgroundColor = "#e2ad32"; portal.layoutKey = "layout_portal"; - DocUtils.MakeLink({ doc: summary, ctx: this.props.ContainingCollectionDoc }, { doc: portal }, "portal link", "portal link"); + portal.title = "document collection"; + DocUtils.MakeLink({ doc: summary, ctx: this.props.ContainingCollectionDoc }, { doc: portal }, "summarizing"); this.props.addLiveTextDocument(summary); MarqueeOptionsMenu.Instance.fadeOut(true); diff --git a/src/client/views/nodes/AudioBox.scss b/src/client/views/nodes/AudioBox.scss index 0c363f0c1..4516418a7 100644 --- a/src/client/views/nodes/AudioBox.scss +++ b/src/client/views/nodes/AudioBox.scss @@ -72,6 +72,7 @@ margin-left:-2.55px; background:gray; border-radius: 100%; + opacity:0.9; background-color: transparent; box-shadow: black 2px 2px 1px; .docuLinkBox-cont { @@ -98,7 +99,7 @@ } } .audiobox-linker:hover, .audiobox-linker-mini:hover { - transform:scale(1.5); + opacity:1; } .audiobox-marker-container, .audiobox-marker-minicontainer { position:absolute; diff --git a/src/client/views/nodes/AudioBox.tsx b/src/client/views/nodes/AudioBox.tsx index 862578e40..c4c6365e3 100644 --- a/src/client/views/nodes/AudioBox.tsx +++ b/src/client/views/nodes/AudioBox.tsx @@ -249,6 +249,7 @@ export class AudioBox extends DocExtendableComponent
diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 64d85589f..782a9ce08 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -569,8 +569,7 @@ export class DocumentView extends DocComponent(Docu e.stopPropagation(); de.complete.annoDragData.linkedToDoc = true; - DocUtils.MakeLink({ doc: de.complete.annoDragData.annotationDocument }, { doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, - `Link from ${StrCast(de.complete.annoDragData.annotationDocument.title)}`); + DocUtils.MakeLink({ doc: de.complete.annoDragData.annotationDocument }, { doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, "link"); } if (de.complete.docDragData) { if (de.complete.docDragData.applyAsTemplate) { @@ -601,13 +600,14 @@ export class DocumentView extends DocComponent(Docu // const views = docs.map(d => DocumentManager.Instance.getDocumentView(d)).filter(d => d).map(d => d as DocumentView); de.complete.linkDragData.linkSourceDocument !== this.props.Document && (de.complete.linkDragData.linkDocument = DocUtils.MakeLink({ doc: de.complete.linkDragData.linkSourceDocument }, - { doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, `link from ${de.complete.linkDragData.linkSourceDocument.title} to ${this.props.Document.title}`)); // TODODO this is where in text links get passed + { doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, `link`)); // TODODO this is where in text links get passed } } @undoBatch @action public static unfreezeNativeDimensions(layoutDoc: Doc) { + m layoutDoc._nativeWidth = undefined; layoutDoc._nativeHeight = undefined; } @@ -627,7 +627,7 @@ export class DocumentView extends DocComponent(Docu const portalLink = DocListCast(this.Document.links).find(d => d.anchor1 === this.props.Document); if (!portalLink) { 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, ctx: this.props.ContainingCollectionDoc }, { doc: portal }, "portal link", "portal link"); + DocUtils.MakeLink({ doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, { doc: portal }, "portal to"); } this.Document.isButton = true; } @@ -1118,7 +1118,7 @@ export class DocumentView extends DocComponent(Docu const highlightStyles = ["solid", "dashed", "solid", "solid", "solid", "solid", "solid"]; let highlighting = fullDegree && this.layoutDoc.type !== DocumentType.FONTICON && this.layoutDoc._viewType !== CollectionViewType.Linear; highlighting = highlighting && this.props.focus !== emptyFunction; // bcz: hack to turn off highlighting onsidebar panel documents. need to flag a document as not highlightable in a more direct way - return
Doc.BrushDoc(this.props.Document)} onPointerLeave={e => Doc.UnBrushDoc(this.props.Document)} style={{ diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 7b434ebc1..8f4cefbf4 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -150,7 +150,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & this.dataDoc[key] = doc || Docs.Create.FreeformDocument([], { title: value, _width: 500, _height: 500 }, value); DocUtils.Publish(this.dataDoc[key] as Doc, value, this.props.addDocument, this.props.removeDocument); if (linkDoc) { (linkDoc as Doc).anchor2 = this.dataDoc[key] as Doc; } - else DocUtils.MakeLink({ doc: this.dataDoc, ctx: this.props.ContainingCollectionDoc }, { doc: this.dataDoc[key] as Doc }, "Ref:" + value, "link to named target", id); + else DocUtils.MakeLink({ doc: this.dataDoc, ctx: this.props.ContainingCollectionDoc }, { doc: this.dataDoc[key] as Doc }, "link to named target", id); }); }); }); @@ -723,7 +723,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & targetAnnotations?.push(pdfRegion); }); - const link = DocUtils.MakeLink({ doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, { doc: pdfRegion, ctx: pdfDoc }, "note on " + pdfDoc.title, "pasted PDF link"); + const link = DocUtils.MakeLink({ doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, { doc: pdfRegion, ctx: pdfDoc }, "PDF pasted"); if (link) { cbe.clipboardData!.setData("dash/linkDoc", link[Id]); const linkId = link[Id]; diff --git a/src/client/views/nodes/VideoBox.tsx b/src/client/views/nodes/VideoBox.tsx index 69c6f2617..7ab650dc9 100644 --- a/src/client/views/nodes/VideoBox.tsx +++ b/src/client/views/nodes/VideoBox.tsx @@ -134,7 +134,7 @@ export class VideoBox extends DocAnnotatableComponent Cast(this.props.Document._scrollTop, "number", null), - (stop) => (stop !== undefined) && this._mainCont.current && smoothScroll(500, this._mainCont.current, stop) , { fireImmediately: true }); + (stop) => (stop !== undefined) && this._mainCont.current && smoothScroll(500, this._mainCont.current, stop), { fireImmediately: true }); this._annotationReactionDisposer = reaction( () => DocListCast(this.dataDoc[this.props.fieldKey + "-annotations"]), annotations => annotations?.length && (this._annotations = annotations), @@ -582,7 +582,7 @@ export class PDFViewer extends DocAnnotatableComponent { if (!e.aborted && e.annoDragData && !e.annoDragData.linkedToDoc) { - const link = DocUtils.MakeLink({ doc: annotationDoc }, { doc: e.annoDragData.dropDocument, ctx: e.annoDragData.targetContext }, `Annotation from ${this.Document.title}`, "link from PDF"); + const link = DocUtils.MakeLink({ doc: annotationDoc }, { doc: e.annoDragData.dropDocument, ctx: e.annoDragData.targetContext }, "Annotation"); if (link) link.maximizeLocation = "onRight"; } } -- cgit v1.2.3-70-g09d2 From 26c973ecb47de86d94c39d71ad00ece38a85d623 Mon Sep 17 00:00:00 2001 From: bob Date: Wed, 4 Mar 2020 18:20:46 -0500 Subject: changed text sampling to marking every second to get audio to synchronize better --- src/client/util/InteractionUtils.tsx | 1 - src/client/util/RichTextSchema.tsx | 4 +- src/client/views/nodes/AudioBox.scss | 2 + src/client/views/nodes/AudioBox.tsx | 66 +++++++++++++++------- src/client/views/nodes/FormattedTextBox.tsx | 85 ++++++++++++++++++++--------- src/client/views/nodes/PresBox.tsx | 3 +- src/new_fields/Doc.ts | 1 + 7 files changed, 112 insertions(+), 50 deletions(-) (limited to 'src/client/views/nodes/FormattedTextBox.tsx') diff --git a/src/client/util/InteractionUtils.tsx b/src/client/util/InteractionUtils.tsx index cf51b8e89..2eec02a42 100644 --- a/src/client/util/InteractionUtils.tsx +++ b/src/client/util/InteractionUtils.tsx @@ -108,7 +108,6 @@ export namespace InteractionUtils { } export function IsType(e: PointerEvent | React.PointerEvent, type: string): boolean { - console.log(e.button); switch (type) { // pen and eraser are both pointer type 'pen', but pen is button 0 and eraser is button 5. -syip2 case PENTYPE: diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index a854406f4..0adf060ec 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -511,7 +511,7 @@ export const marks: { [index: string]: MarkSpec } = { user_mark: { attrs: { userid: { default: "" }, - modified: { default: "when?" }, // 5 second intervals since 1970 + modified: { default: "when?" }, // 1 second intervals since 1970 }, group: "inline", toDOM(node: any) { @@ -527,7 +527,7 @@ export const marks: { [index: string]: MarkSpec } = { user_tag: { attrs: { userid: { default: "" }, - modified: { default: "when?" }, // 5 second intervals since 1970 + modified: { default: "when?" }, // 1 second intervals since 1970 tag: { default: "" } }, group: "inline", diff --git a/src/client/views/nodes/AudioBox.scss b/src/client/views/nodes/AudioBox.scss index 4516418a7..83cdf3574 100644 --- a/src/client/views/nodes/AudioBox.scss +++ b/src/client/views/nodes/AudioBox.scss @@ -29,6 +29,8 @@ } .audiobox-record-interactive { pointer-events: all; + width:100%; + height:100%; } .audiobox-controls { width:100%; diff --git a/src/client/views/nodes/AudioBox.tsx b/src/client/views/nodes/AudioBox.tsx index c4c6365e3..e2002a596 100644 --- a/src/client/views/nodes/AudioBox.tsx +++ b/src/client/views/nodes/AudioBox.tsx @@ -17,6 +17,8 @@ import { ContextMenu } from "../ContextMenu"; import { Id } from "../../../new_fields/FieldSymbols"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { DocumentView } from "./DocumentView"; +import { Docs } from "../../documents/Documents"; +import { ComputedField } from "../../../new_fields/ScriptField"; interface Window { MediaRecorder: MediaRecorder; @@ -45,12 +47,15 @@ export class AudioBox extends DocExtendableComponent AudioBox._scrubTime = timeInMillisFrom1970); + @computed get audioState(): undefined | "recording" | "paused" | "playing" { return this.dataDoc.audioState as (undefined | "recording" | "paused" | "playing"); } + set audioState(value) { this.dataDoc.audioState = value; } + public static SetScrubTime = (timeInMillisFrom1970: number) => { runInAction(() => AudioBox._scrubTime = 0); runInAction(() => AudioBox._scrubTime = timeInMillisFrom1970); }; public static ActiveRecordings: Doc[] = []; @computed get recordingStart() { return Cast(this.dataDoc[this.props.fieldKey + "-recordingStart"], DateField)?.date.getTime(); } + async slideTemplate() { return (await Cast((await Cast(Doc.UserDoc().slidesBtn, Doc) as Doc).dragFactory, Doc) as Doc); } componentWillUnmount() { this._reactionDisposer?.(); @@ -58,7 +63,7 @@ export class AudioBox extends DocExtendableComponent this._audioState = this.path ? "recorded" : "unrecorded"); + runInAction(() => this.audioState = this.path ? "paused" : undefined); this._linkPlayDisposer = reaction(() => this.layoutDoc.scrollToLinkID, scrollLinkId => { if (scrollLinkId) { @@ -73,13 +78,14 @@ export class AudioBox extends DocExtendableComponent { const sel = selected.length ? selected[0].props.Document : undefined; this.Document.playOnSelect && this.recordingStart && sel && !Doc.AreProtosEqual(sel, this.props.Document) && this.playFromTime(DateCast(sel.creationDate).date.getTime()); + this.Document.playOnSelect && this.recordingStart && !sel && this.pause(); }); this._scrubbingDisposer = reaction(() => AudioBox._scrubTime, (time) => this.Document.playOnSelect && this.playFromTime(AudioBox._scrubTime)); } timecodeChanged = () => { const htmlEle = this._ele; - if (this._audioState === "recorded" && htmlEle) { + if (this.audioState !== "recording" && htmlEle) { htmlEle.duration && htmlEle.duration !== Infinity && runInAction(() => this.dataDoc.duration = htmlEle.duration); DocListCast(this.dataDoc.links).map(l => { let la1 = l.anchor1 as Doc; @@ -98,7 +104,7 @@ export class AudioBox extends DocExtendableComponent { this._ele!.pause(); - this.props.Document._audioState = "paused"; + this.audioState = "paused"; }); playFromTime = (absoluteTime: number) => { @@ -107,11 +113,15 @@ export class AudioBox extends DocExtendableComponent { if (this._ele && AudioBox.Enabled) { if (seekTimeInSeconds < 0) { - this.pause(); + if (seekTimeInSeconds > -1) { + setTimeout(() => this.playFrom(0), -seekTimeInSeconds * 1000); + } else { + this.pause(); + } } else if (seekTimeInSeconds <= this._ele.duration) { this._ele.currentTime = seekTimeInSeconds; this._ele.play(); - runInAction(() => this.props.Document._audioState = "playing"); + runInAction(() => this.audioState = "playing"); } else { this.pause(); } @@ -120,7 +130,7 @@ export class AudioBox extends DocExtendableComponent { - if (this._audioState === "recording") { + if (this.audioState === "recording") { setTimeout(this.updateRecordTime, 30); this.Document.currentTimecode = (new Date().getTime() - this._recordStart) / 1000; } @@ -135,6 +145,7 @@ export class AudioBox extends DocExtendableComponent self._audioState = "recording"); self._recordStart = new Date().getTime(); + console.log("RECORD START = " + self._recordStart); + runInAction(() => self.audioState = "recording"); setTimeout(self.updateRecordTime, 0); self._recorder.start(); setTimeout(() => { @@ -172,7 +184,7 @@ export class AudioBox extends DocExtendableComponent { this._recorder.stop(); this.dataDoc.duration = (new Date().getTime() - this._recordStart) / 1000; - this._audioState = "recorded"; + this.audioState = "paused"; const ind = AudioBox.ActiveRecordings.indexOf(this.props.Document); ind !== -1 && (AudioBox.ActiveRecordings.splice(ind, 1)); }); @@ -189,8 +201,19 @@ export class AudioBox extends DocExtendableComponent { - this.pause(); - this._ele!.currentTime = 0; + this.Document.playOnSelect = !this.Document.playOnSelect; + e.stopPropagation(); + } + onFile = (e: any) => { + const newDoc = Docs.Create.TextDocument("", { + title: "", _chromeStatus: "disabled", + x: NumCast(this.props.Document.x), y: NumCast(this.props.Document.y) + NumCast(this.props.Document._height) + 10, + _width: NumCast(this.props.Document._width), _height: 3 * NumCast(this.props.Document._height) + }); + Doc.GetProto(newDoc).recordingSource = this.dataDoc; + Doc.GetProto(newDoc).recordingStart = 0; + Doc.GetProto(newDoc).audioState = ComputedField.MakeFunction("this.recordingSource.audioState"); + this.props.addDocument?.(newDoc); e.stopPropagation(); } @@ -218,21 +241,26 @@ export class AudioBox extends DocExtendableComponent -
{!this.path ? - : +
+
+ +
+ +
:
-
-
+
+
e.stopPropagation()} onPointerDown={e => { if (e.button === 0 && !e.ctrlKey) { const rect = (e.target as any).getBoundingClientRect(); + const wasPaused = this.audioState === "paused"; this._ele!.currentTime = this.Document.currentTimecode = (e.clientX - rect.x) / rect.width * NumCast(this.dataDoc.duration); - this.pause(); + wasPaused && this.pause(); e.stopPropagation(); } }} > diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 8f4cefbf4..f18183600 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -20,7 +20,7 @@ import { InkTool } from '../../../new_fields/InkField'; import { RichTextField } from "../../../new_fields/RichTextField"; import { RichTextUtils } from '../../../new_fields/RichTextUtils'; import { createSchema, makeInterface } from "../../../new_fields/Schema"; -import { Cast, NumCast, StrCast } from "../../../new_fields/Types"; +import { Cast, NumCast, StrCast, BoolCast } from "../../../new_fields/Types"; import { TraceMobx } from '../../../new_fields/util'; import { addStyleSheet, addStyleSheetRule, clearStyleSheetRules, emptyFunction, numberRange, returnOne, Utils } from '../../../Utils'; import { GoogleApiClientUtils, Pulls, Pushes } from '../../apis/google_docs/GoogleApiClientUtils'; @@ -82,6 +82,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & private _lastY = 0; private _undoTyping?: UndoManager.Batch; private _searchReactionDisposer?: Lambda; + private _recordReactionDisposer: Opt; private _scrollToRegionReactionDisposer: Opt; private _reactionDisposer: Opt; private _heightReactionDisposer: Opt; @@ -92,6 +93,9 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & private _scrollDisposer: Opt; private dropDisposer?: DragManager.DragDropDisposer; + @computed get _recording() { return this.dataDoc.audioState === "recording"; } + set _recording(value) { this.dataDoc.audioState = value ? "recording" : undefined; } + @observable private _entered = false; public static FocusedBox: FormattedTextBox | undefined; @@ -186,7 +190,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & (tx.storedMarks && !this._editorView.state.storedMarks) && (this._editorView.state.storedMarks = tx.storedMarks); const tsel = this._editorView.state.selection.$from; - tsel.marks().filter(m => m.type === this._editorView!.state.schema.marks.user_mark).map(m => AudioBox.SetScrubTime(Math.max(0, m.attrs.modified * 5000 - 1000))); + tsel.marks().filter(m => m.type === this._editorView!.state.schema.marks.user_mark).map(m => AudioBox.SetScrubTime(Math.max(0, m.attrs.modified * 1000))); const curText = state.doc.textBetween(0, state.doc.content.size, "\n\n"); const curTemp = Cast(this.props.Document[this.props.fieldKey + "-textTemplate"], RichTextField); if (!this._applyingChange) { @@ -387,7 +391,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & !this.props.Document.expandedTemplate && funcs.push({ description: "Make Template", event: () => { this.props.Document.isTemplateDoc = true; Doc.AddDocToList(Cast(Doc.UserDoc().noteTypes, Doc, null), "data", this.props.Document); }, icon: "eye" }); funcs.push({ description: "Toggle Single Line", event: () => this.props.Document._singleLine = !this.props.Document._singleLine, icon: "expand-arrows-alt" }); funcs.push({ description: "Toggle Sidebar", event: () => this.props.Document._showSidebar = !this.props.Document._showSidebar, icon: "expand-arrows-alt" }); - funcs.push({ description: "Record Bullet", event: () => this.recordBullet(), icon: "expand-arrows-alt" }); + funcs.push({ description: "Toggle Audio", event: () => this.props.Document._showAudio = !this.props.Document._showAudio, icon: "expand-arrows-alt" }); funcs.push({ description: "Toggle Menubar", event: () => this.toggleMenubar(), icon: "expand-arrows-alt" }); ["My Text", "Text from Others", "Todo Items", "Important Items", "Ignore Items", "Disagree Items", "By Recent Minute", "By Recent Hour"].forEach(option => funcs.push({ @@ -405,12 +409,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & ContextMenu.Instance.addItem({ description: "Text Funcs...", subitems: funcs, icon: "asterisk" }); } - @observable _recording = false; - recordDictation = () => { - //this._editorView!.focus(); - if (this._recording) return; - runInAction(() => this._recording = true); DictationManager.Controls.listen({ interimHandler: this.setCurrentBulletContent, continuous: { indefinite: false }, @@ -418,13 +417,10 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & if (results && [DictationManager.Controls.Infringed].includes(results)) { DictationManager.Controls.stop(); } - this._editorView!.focus(); + //this._editorView!.focus(); }); } - stopDictation = (abort: boolean) => { - runInAction(() => this._recording = false); - DictationManager.Controls.stop(!abort); - } + stopDictation = (abort: boolean) => { DictationManager.Controls.stop(!abort); } @action toggleMenubar = () => { @@ -449,12 +445,28 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & setCurrentBulletContent = (value: string) => { if (this._editorView) { let state = this._editorView.state; + let now = Date.now(); + if (NumCast(this.props.Document.recordingStart, -1) === 0) { + this.props.Document.recordingStart = now = AudioBox.START; + } + console.log("NOW = " + (now - AudioBox.START) / 1000); + let mark = schema.marks.user_mark.create({ userid: Doc.CurrentUserEmail, modified: Math.floor(now / 1000) }); + if (!this._break && state.selection.to !== state.selection.from) { + for (let i = state.selection.from; i <= state.selection.to; i++) { + const pos = state.doc.resolve(i); + const um = Array.from(pos.marks()).find(m => m.type === schema.marks.user_mark); + if (um) { + mark = um; + break; + } + } + } + this._break = false; + console.log("start = " + (mark.attrs.modified * 1000 - AudioBox.START) / 1000); + value = "" + (mark.attrs.modified * 1000 - AudioBox.START) / 1000 + value; const from = state.selection.from; - const to = state.selection.to; - this._editorView.dispatch(state.tr.insertText(value, from, to)); - state = this._editorView.state; - const updated = TextSelection.create(state.doc, from, from + value.length); - this._editorView.dispatch(state.tr.setSelection(updated)); + const inserted = state.tr.insertText(value).addMark(from, from + value.length + 1, mark); + this._editorView.dispatch(inserted.setSelection(TextSelection.create(inserted.doc, from, from + value.length + 1))); } } @@ -558,6 +570,17 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & search => search ? this.highlightSearchTerms([Doc.SearchQuery()]) : this.unhighlightSearchTerms(), { fireImmediately: true }); + this._recordReactionDisposer = reaction(() => this._recording, + () => { + if (this._recording) { + setTimeout(action(() => { + this.stopDictation(true); + setTimeout(() => this.recordDictation(), 500); + }), 500); + } else setTimeout(() => this.stopDictation(true), 0); + } + ); + this._scrollToRegionReactionDisposer = reaction( () => StrCast(this.layoutDoc.scrollToLinkID), async (scrollToLinkID) => { @@ -807,7 +830,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & } (selectOnLoad /* || !rtfField?.Text*/) && this._editorView!.focus(); // add user mark for any first character that was typed since the user mark that gets set in KeyPress won't have been called yet. - this._editorView!.state.storedMarks = [...(this._editorView!.state.storedMarks ? this._editorView!.state.storedMarks : []), schema.marks.user_mark.create({ userid: Doc.CurrentUserEmail, modified: Math.round(Date.now() / 1000 / 5) })]; + this._editorView!.state.storedMarks = [...(this._editorView!.state.storedMarks ? this._editorView!.state.storedMarks : []), schema.marks.user_mark.create({ userid: Doc.CurrentUserEmail, modified: Math.floor(Date.now() / 1000) })]; } getFont(font: string) { switch (font) { @@ -831,6 +854,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & this._pullReactionDisposer?.(); this._heightReactionDisposer?.(); this._searchReactionDisposer?.(); + this._recordReactionDisposer?.(); this._buttonBarReactionDisposer?.(); this._editorView?.destroy(); } @@ -838,7 +862,19 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & static _downEvent: any; _downX = 0; _downY = 0; + _break = false; onPointerDown = (e: React.PointerEvent): void => { + if (this._recording && !e.ctrlKey && e.button === 0) { + this.stopDictation(true); + this._break = true; + let state = this._editorView!.state; + const to = state.selection.to; + const updated = TextSelection.create(state.doc, to, to); + this._editorView!.dispatch(this._editorView!.state.tr.setSelection(updated).insertText("\n", to)); + e.preventDefault(); + e.stopPropagation(); + if (this._recording) setTimeout(() => this.recordDictation(), 500); + } this._downX = e.clientX; this._downY = e.clientY; this.doLinkOnDeselect(); @@ -955,7 +991,6 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & this.props.select(e.ctrlKey); this.hitBulletTargets(e.clientX, e.clientY, e.shiftKey, false); } - if (this._recording) setTimeout(() => { this.stopDictation(true); setTimeout(() => this.recordDictation(), 500); }, 500); } // this hackiness handles clicking on the list item bullets to do expand/collapse. the bullets are ::before pseudo elements so there's no real way to hit test against them. @@ -1062,17 +1097,13 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & if (e.key === "Tab" || e.key === "Enter") { e.preventDefault(); } - const mark = e.key !== " " && this._lastTimedMark ? this._lastTimedMark : schema.marks.user_mark.create({ userid: Doc.CurrentUserEmail, modified: Math.round(Date.now() / 1000 / 5) }); + const mark = e.key !== " " && this._lastTimedMark ? this._lastTimedMark : schema.marks.user_mark.create({ userid: Doc.CurrentUserEmail, modified: Math.floor(Date.now() / 1000) }); this._lastTimedMark = mark; this._editorView!.dispatch(this._editorView!.state.tr.removeStoredMark(schema.marks.user_mark.create({})).addStoredMark(mark)); if (!this._undoTyping) { this._undoTyping = UndoManager.StartBatch("undoTyping"); } - if (this._recording) { - this.stopDictation(true); - setTimeout(() => this.recordDictation(), 250); - } } onscrolled = (ev: React.UIEvent) => { @@ -1169,8 +1200,8 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps &
} {!this.props.Document._showAudio ? (null) :
{ - this._recording ? this.stopDictation(true) : this.recordDictation(); + onPointerDown={e => { + runInAction(() => this._recording = !this._recording); setTimeout(() => this._editorView!.focus(), 500); e.stopPropagation(); }} > diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index 27c2d6957..d43df0bfb 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -1,6 +1,6 @@ import React = require("react"); import { library } from '@fortawesome/fontawesome-svg-core'; -import { faArrowLeft, faArrowRight, faEdit, faMinus, faPlay, faPlus, faStop, faTimes } from '@fortawesome/free-solid-svg-icons'; +import { faArrowLeft, faArrowRight, faEdit, faMinus, faPlay, faPlus, faStop, faHandPointLeft, faTimes } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { action, computed, IReactionDisposer, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; @@ -24,6 +24,7 @@ library.add(faArrowLeft); library.add(faArrowRight); library.add(faPlay); library.add(faStop); +library.add(faHandPointLeft); library.add(faPlus); library.add(faTimes); library.add(faMinus); diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index e9fdf42b9..141a01ed2 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -859,6 +859,7 @@ export namespace Doc { const targetDoc = doc && Doc.GetProto(Cast(doc.expandedTemplate, Doc, null) || doc); targetDoc && (targetDoc.backgroundColor = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.expandedTemplate||this)["${enumeratedFieldKey}"])?._backgroundColor || "white"`, undefined, { options })); targetDoc && (targetDoc.color = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.expandedTemplate||this)["${enumeratedFieldKey}"]).color || "black"`, undefined, { options })); + targetDoc && (targetDoc.color = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.expandedTemplate||this)["${enumeratedFieldKey}"]).borderRounding`, undefined, { options })); enumerations.map(enumeration => { const found = DocListCast(options.data).find(d => d.title === enumeration.title); if (found) { -- cgit v1.2.3-70-g09d2 From adc6a86ca44d74d3efd4439a344929ca09815362 Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 9 Mar 2020 11:49:53 -0400 Subject: added dontRegisterView prop to fieldview so that intended textBox would selectonoad, not documentBox textbox that shows current selection --- src/client/views/nodes/DocumentBox.tsx | 3 +++ src/client/views/nodes/DocumentView.tsx | 26 ++------------------------ src/client/views/nodes/FieldView.tsx | 1 + src/client/views/nodes/FormattedTextBox.tsx | 4 ++-- 4 files changed, 8 insertions(+), 26 deletions(-) (limited to 'src/client/views/nodes/FormattedTextBox.tsx') diff --git a/src/client/views/nodes/DocumentBox.tsx b/src/client/views/nodes/DocumentBox.tsx index f04962db9..bd239491b 100644 --- a/src/client/views/nodes/DocumentBox.tsx +++ b/src/client/views/nodes/DocumentBox.tsx @@ -14,6 +14,7 @@ import { ContentFittingDocumentView } from "./ContentFittingDocumentView"; import "./DocumentBox.scss"; import { FieldView, FieldViewProps } from "./FieldView"; import React = require("react"); +import { TraceMobx } from "../../../new_fields/util"; type DocBoxSchema = makeInterface<[typeof documentSchema]>; const DocBoxDocument = makeInterface(documentSchema); @@ -97,6 +98,7 @@ export class DocumentBox extends DocAnnotatableComponent this.props.PanelHeight() - 30; getTransform = () => this.props.ScreenToLocalTransform().translate(-15, -15); render() { + TraceMobx(); const containedDoc = this.contentDoc[this.props.fieldKey]; return
}
; diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 5d64c25f9..e176f0990 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -956,30 +956,8 @@ export class DocumentView extends DocComponent(Docu childScaling = () => (this.layoutDoc._fitWidth ? this.props.PanelWidth() / this.nativeWidth : this.props.ContentScaling()); @computed get contents() { TraceMobx(); - return ((Docu @computed get innards() { TraceMobx(); if (!this.props.PanelWidth()) { - return
+ return
{StrCast(this.props.Document.title)} {this.Document.links && DocListCast(this.Document.links).filter(d => !d.hidden).filter(this.isNonTemporalLink).map((d, i) =>
diff --git a/src/client/views/nodes/FieldView.tsx b/src/client/views/nodes/FieldView.tsx index 38fcbd211..d030d1f4d 100644 --- a/src/client/views/nodes/FieldView.tsx +++ b/src/client/views/nodes/FieldView.tsx @@ -38,6 +38,7 @@ export interface FieldViewProps { bringToFront: (doc: Doc, sendToBack?: boolean) => void; active: (outsideReaction?: boolean) => boolean; whenActiveChanged: (isActive: boolean) => void; + dontRegisterView?: boolean; focus: (doc: Doc) => void; PanelWidth: () => number; PanelHeight: () => number; diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index f18183600..7f5f8538a 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 } from "../../../new_fields/Types"; import { TraceMobx } from '../../../new_fields/util'; -import { addStyleSheet, addStyleSheetRule, clearStyleSheetRules, emptyFunction, numberRange, returnOne, Utils } from '../../../Utils'; +import { addStyleSheet, addStyleSheetRule, clearStyleSheetRules, emptyFunction, numberRange, returnOne, Utils, returnTrue } from '../../../Utils'; import { GoogleApiClientUtils, Pulls, Pushes } from '../../apis/google_docs/GoogleApiClientUtils'; import { DocServer } from "../../DocServer"; import { Docs, DocUtils } from '../../documents/Documents'; @@ -821,7 +821,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & } const selectOnLoad = (Cast(this.props.Document.expandedTemplate, Doc, null) || this.props.Document)[Id] === FormattedTextBox.SelectOnLoad; - if (selectOnLoad) { + if (selectOnLoad && !this.props.dontRegisterView) { FormattedTextBox.SelectOnLoad = ""; this.props.select(false); FormattedTextBox.SelectOnLoadChar && this._editorView!.dispatch(this._editorView!.state.tr.insertText(FormattedTextBox.SelectOnLoadChar)); -- cgit v1.2.3-70-g09d2 From 636e6880a52d3a1a3e24437f47194a902731401d Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Mon, 9 Mar 2020 16:39:42 -0400 Subject: cleanup of warnings --- src/client/cognitive_services/CognitiveServices.ts | 8 ++++---- src/client/util/DocumentManager.ts | 2 +- src/client/util/DragManager.ts | 2 +- src/client/util/ProsemirrorExampleTransfer.ts | 2 +- src/client/util/RichTextSchema.tsx | 14 +++++++------- src/client/util/SearchUtil.ts | 4 ++-- src/client/views/KeyphraseQueryView.tsx | 4 ++-- .../views/collections/CollectionDockingView.tsx | 4 ++-- src/client/views/collections/CollectionSubView.tsx | 2 +- .../collectionFreeForm/CollectionFreeFormView.tsx | 2 +- .../CollectionMulticolumnView.tsx | 2 +- src/client/views/linking/LinkEditor.tsx | 4 ++-- src/client/views/nodes/AudioBox.tsx | 6 ++---- src/client/views/nodes/DocuLinkBox.tsx | 4 ++-- src/client/views/nodes/DocumentView.tsx | 14 +++++++------- src/client/views/nodes/FormattedTextBox.tsx | 20 ++++++++------------ src/client/views/nodes/PDFBox.tsx | 10 +++++----- 17 files changed, 49 insertions(+), 55 deletions(-) (limited to 'src/client/views/nodes/FormattedTextBox.tsx') diff --git a/src/client/cognitive_services/CognitiveServices.ts b/src/client/cognitive_services/CognitiveServices.ts index ce829eb1e..542ccf04d 100644 --- a/src/client/cognitive_services/CognitiveServices.ts +++ b/src/client/cognitive_services/CognitiveServices.ts @@ -371,9 +371,9 @@ export namespace CognitiveServices { let args = { method: 'POST', uri: Utils.prepend("/recommender"), body: { keyphrases: keyterms }, json: true }; await requestPromise.post(args).then(async (wordvecs) => { if (wordvecs) { - let indices = Object.keys(wordvecs); + const indices = Object.keys(wordvecs); console.log("successful vectorization!"); - var vectorValues = new List(); + const vectorValues = new List(); indices.forEach((ind: any) => { //console.log(wordvec.word); vectorValues.push(wordvecs[ind]); @@ -389,9 +389,9 @@ export namespace CognitiveServices { } export const analyzer = async (dataDoc: Doc, target: Doc, keys: string[], data: string, converter: TextConverter, isMainDoc: boolean = false, isInternal: boolean = true) => { - let results = await ExecuteQuery(Service.Text, Manager, data); + const results = await ExecuteQuery(Service.Text, Manager, data); console.log("Cognitive Services keyphrases: ", results); - let { keyterms, external_recommendations, kp_string } = await converter(results, data); + const { keyterms, external_recommendations, kp_string } = await converter(results, data); target[keys[0]] = keyterms; if (isInternal) { //await vectorize([data], dataDoc, isMainDoc); diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts index 162a8fffe..c41304b9f 100644 --- a/src/client/util/DocumentManager.ts +++ b/src/client/util/DocumentManager.ts @@ -209,7 +209,7 @@ export class DocumentManager { const maxLocation = StrCast(linkDoc.maximizeLocation, "inTab"); const targetContext = !Doc.AreProtosEqual(linkFollowDocContexts[reverse ? 1 : 0], currentContext) ? linkFollowDocContexts[reverse ? 1 : 0] : undefined; const target = linkFollowDocs[reverse ? 1 : 0]; - let annotatedDoc = await Cast(target.annotationOn, Doc); + const annotatedDoc = await Cast(target.annotationOn, Doc); if (annotatedDoc) { annotatedDoc.currentTimecode !== undefined && (target.currentTimecode = linkFollowTimecodes[reverse ? 1 : 0]); } else { diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index dab5c842c..c11675894 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -198,7 +198,7 @@ export namespace DragManager { dropDoc && !dropDoc.creationDate && (dropDoc.creationDate = new DateField); dropDoc instanceof Doc && AudioBox.ActiveRecordings.map(d => DocUtils.MakeLink({ doc: dropDoc }, { doc: d }, "audio link", "audio timeline")); return dropDoc; - } + }; const finishDrag = (e: DragCompleteEvent) => { e.docDragData && (e.docDragData.droppedDocuments = dragData.draggedDocuments.map(d => !dragData.isSelectionMove && !dragData.userDropAction && ScriptCast(d.onDragStart) ? addAudioTag(ScriptCast(d.onDragStart).script.run({ this: d }).result) : diff --git a/src/client/util/ProsemirrorExampleTransfer.ts b/src/client/util/ProsemirrorExampleTransfer.ts index ec5d1e72a..5cbf401d4 100644 --- a/src/client/util/ProsemirrorExampleTransfer.ts +++ b/src/client/util/ProsemirrorExampleTransfer.ts @@ -180,7 +180,7 @@ export default function buildKeymap>(schema: S, props: any return true; } return false; - } + }; bind("Alt-Enter", (state: EditorState, dispatch: (tx: Transaction>) => void) => { return addTextOnRight(true); }); diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index 0adf060ec..31935df3e 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -889,10 +889,10 @@ export class DashFieldView { e.stopPropagation(); const collview = await Doc.addFieldEnumerations(self._textBoxDoc, node.attrs.fieldKey, [{ title: self._fieldSpan.innerText }]); collview instanceof Doc && tbox.props.addDocTab(collview, "onRight"); - } + }; const updateText = (forceMatch: boolean) => { self._enumerables.style.display = "none"; - let newText = self._fieldSpan.innerText.startsWith(":=") || self._fieldSpan.innerText.startsWith("=:=") ? ":=-computed-" : self._fieldSpan.innerText; + const newText = self._fieldSpan.innerText.startsWith(":=") || self._fieldSpan.innerText.startsWith("=:=") ? ":=-computed-" : self._fieldSpan.innerText; // look for a document whose id === the fieldKey being displayed. If there's a match, then that document // holds the different enumerated values for the field in the titles of its collected documents. @@ -909,12 +909,12 @@ export class DashFieldView { // if the text starts with a ':=' then treat it as an expression by making a computed field from its value storing it in the key if (self._fieldSpan.innerText.startsWith(":=") && self._dashDoc) { - self._dashDoc![self._fieldKey] = ComputedField.MakeFunction(self._fieldSpan.innerText.substring(2)); + self._dashDoc[self._fieldKey] = ComputedField.MakeFunction(self._fieldSpan.innerText.substring(2)); } else if (self._fieldSpan.innerText.startsWith("=:=") && self._dashDoc) { Doc.Layout(tbox.props.Document)[self._fieldKey] = ComputedField.MakeFunction(self._fieldSpan.innerText.substring(3)); } }); - } + }; this._fieldSpan = document.createElement("div"); this._fieldSpan.id = Utils.GenerateGuid(); @@ -926,14 +926,14 @@ export class DashFieldView { this._fieldSpan.onkeypress = function (e: any) { e.stopPropagation(); }; this._fieldSpan.onkeyup = function (e: any) { e.stopPropagation(); }; this._fieldSpan.onmousedown = function (e: any) { e.stopPropagation(); self._enumerables.style.display = "inline-block"; }; - this._fieldSpan.onblur = function (e: any) { updateText(false); } + this._fieldSpan.onblur = function (e: any) { updateText(false); }; const setDashDoc = (doc: Doc) => { self._dashDoc = doc; if (self._dashDoc && self._options?.length && !self._dashDoc[node.attrs.fieldKey]) { self._dashDoc[node.attrs.fieldKey] = StrCast(self._options[0].title); } - } + }; this._fieldSpan.onkeydown = function (e: any) { e.stopPropagation(); if ((e.key === "a" && e.ctrlKey) || (e.key === "a" && e.metaKey)) { @@ -976,7 +976,7 @@ export class DashFieldView { alias._pivotField = self._fieldKey; tbox.props.addDocTab(alias, "onRight"); } - } + }; this._labelSpan.innerHTML = `${node.attrs.fieldKey}: `; if (node.attrs.docid) { DocServer.GetRefField(node.attrs.docid).then(async dashDoc => dashDoc instanceof Doc && runInAction(() => setDashDoc(dashDoc))); diff --git a/src/client/util/SearchUtil.ts b/src/client/util/SearchUtil.ts index 64874b994..2d9c807dd 100644 --- a/src/client/util/SearchUtil.ts +++ b/src/client/util/SearchUtil.ts @@ -121,12 +121,12 @@ export namespace SearchUtil { export async function GetAllDocs() { const query = "*"; - let response = await rp.get(Utils.prepend('/search'), { + const response = await rp.get(Utils.prepend('/search'), { qs: { start: 0, rows: 10000, q: query }, }); - let result: IdSearchResult = JSON.parse(response); + const result: IdSearchResult = JSON.parse(response); const { ids, numFound, highlighting } = result; //console.log(ids.length); const docMap = await DocServer.GetRefFields(ids); diff --git a/src/client/views/KeyphraseQueryView.tsx b/src/client/views/KeyphraseQueryView.tsx index a9dafc4a4..1dc156968 100644 --- a/src/client/views/KeyphraseQueryView.tsx +++ b/src/client/views/KeyphraseQueryView.tsx @@ -15,8 +15,8 @@ export class KeyphraseQueryView extends React.Component{ } render() { - let kps = this.props.keyphrases.toString(); - let keyterms = this.props.keyphrases.split(','); + const kps = this.props.keyphrases.toString(); + const keyterms = this.props.keyphrases.split(','); return (
Select queries to send:
diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index db8f7d5e4..00e22d6fb 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -138,8 +138,8 @@ export class CollectionDockingView extends React.Component Array.from(child.contentItems).some(tryClose)); retVal && instance.stateChanged(); diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index 527623ad4..b995fc7d5 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -107,7 +107,7 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T) { 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: data!, layout: layout! })); // this mapping is a bit of a hack to coerce types + return validPairs.map(({ data, layout }) => ({ data, 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/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 28f8bc048..7adafea0e 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -801,7 +801,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { this.props.Document.scrollY = NumCast(doc.y) - offset; } - afterFocus && setTimeout(() => afterFocus?.(), 1000); + afterFocus && setTimeout(afterFocus, 1000); } else { const layoutdoc = Doc.Layout(doc); const newPanX = NumCast(doc.x) + NumCast(layoutdoc._width) / 2; diff --git a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx index bd20781dc..aa8e1fb43 100644 --- a/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx +++ b/src/client/views/collections/collectionMulticolumn/CollectionMulticolumnView.tsx @@ -223,7 +223,7 @@ export class CollectionMulticolumnView extends CollectionSubView(MulticolumnDocu */ @computed private get contents(): JSX.Element[] | null { - let { childLayoutPairs } = this; + const { childLayoutPairs } = this; const { Document, PanelHeight } = this.props; const collector: JSX.Element[] = []; for (let i = 0; i < childLayoutPairs.length; i++) { diff --git a/src/client/views/linking/LinkEditor.tsx b/src/client/views/linking/LinkEditor.tsx index ac4f8a3cf..b7f3dd995 100644 --- a/src/client/views/linking/LinkEditor.tsx +++ b/src/client/views/linking/LinkEditor.tsx @@ -253,8 +253,8 @@ export class LinkGroupEditor extends React.Component { render() { const groupType = StrCast(this.props.groupDoc.linkRelationship); // if ((groupType && LinkManager.Instance.getMetadataKeysInGroup(groupType).length > 0) || groupType === "") { - let buttons = ; - let addButton = ; + const buttons = ; + const addButton = ; return (
diff --git a/src/client/views/nodes/AudioBox.tsx b/src/client/views/nodes/AudioBox.tsx index 3c8b1c3b8..47883db4e 100644 --- a/src/client/views/nodes/AudioBox.tsx +++ b/src/client/views/nodes/AudioBox.tsx @@ -50,7 +50,6 @@ export class AudioBox extends DocExtendableComponent(Doc openLinkEditor = action((e: React.MouseEvent) => { SelectionManager.DeselectAll(); this._editing = this._forceOpen = true; - }) + }); specificContextMenu = (e: React.MouseEvent): void => { const funcs: ContextMenuProps[] = []; @@ -135,7 +135,7 @@ export class DocuLinkBox extends DocComponent(Doc 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)}>
} diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 63c6b9f88..a1cba4c2e 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -571,9 +571,9 @@ export class DocumentView extends DocComponent(Docu else if (de.complete.docDragData.draggedDocuments[0].type === "text") { const text = Cast(de.complete.docDragData.draggedDocuments[0].data, RichTextField)?.Text; if (text && text[0] === "{" && text[text.length - 1] === "}" && text.includes(":")) { - let loc = text.indexOf(":"); - let key = text.slice(1, loc); - let value = text.slice(loc + 1, text.length - 1); + const loc = text.indexOf(":"); + const key = text.slice(1, loc); + const value = text.slice(loc + 1, text.length - 1); console.log(key); console.log(value); console.log(this.props.Document); @@ -756,7 +756,7 @@ export class DocumentView extends DocComponent(Docu // a.download = `DocExport-${this.props.Document[Id]}.zip`; // a.click(); }); - let recommender_subitems: ContextMenuProps[] = []; + const recommender_subitems: ContextMenuProps[] = []; recommender_subitems.push({ description: "Internal recommendations", @@ -764,7 +764,7 @@ export class DocumentView extends DocComponent(Docu icon: "brain" }); - let ext_recommender_subitems: ContextMenuProps[] = []; + const ext_recommender_subitems: ContextMenuProps[] = []; ext_recommender_subitems.push({ description: "arXiv", @@ -872,7 +872,7 @@ export class DocumentView extends DocComponent(Docu } })); const doclist = ClientRecommender.Instance.computeSimilarities("cosine"); - let recDocs: { preview: Doc, score: number }[] = []; + const recDocs: { preview: Doc, score: number }[] = []; // tslint:disable-next-line: prefer-for-of for (let i = 0; i < doclist.length; i++) { recDocs.push({ preview: doclist[i].actualDoc, score: doclist[i].score }); @@ -1113,7 +1113,7 @@ export class DocumentView extends DocComponent(Docu : this.innards}
; - { this._showKPQuery ? : undefined } + { this._showKPQuery ? : undefined; } } } diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 7f5f8538a..1fa603cbd 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -20,7 +20,7 @@ import { InkTool } from '../../../new_fields/InkField'; import { RichTextField } from "../../../new_fields/RichTextField"; import { RichTextUtils } from '../../../new_fields/RichTextUtils'; import { createSchema, makeInterface } from "../../../new_fields/Schema"; -import { Cast, NumCast, StrCast, BoolCast } from "../../../new_fields/Types"; +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 { GoogleApiClientUtils, Pulls, Pushes } from '../../apis/google_docs/GoogleApiClientUtils'; @@ -420,11 +420,11 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & //this._editorView!.focus(); }); } - stopDictation = (abort: boolean) => { DictationManager.Controls.stop(!abort); } + stopDictation = (abort: boolean) => { DictationManager.Controls.stop(!abort); }; @action toggleMenubar = () => { - this.props.Document._chromeStatus = this.props.Document._chromeStatus == "disabled" ? "enabled" : "disabled"; + this.props.Document._chromeStatus = this.props.Document._chromeStatus === "disabled" ? "enabled" : "disabled"; } recordBullet = async () => { @@ -444,12 +444,8 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & setCurrentBulletContent = (value: string) => { if (this._editorView) { - let state = this._editorView.state; - let now = Date.now(); - if (NumCast(this.props.Document.recordingStart, -1) === 0) { - this.props.Document.recordingStart = now = AudioBox.START; - } - console.log("NOW = " + (now - AudioBox.START) / 1000); + const state = this._editorView.state; + const now = Date.now(); let mark = schema.marks.user_mark.create({ userid: Doc.CurrentUserEmail, modified: Math.floor(now / 1000) }); if (!this._break && state.selection.to !== state.selection.from) { for (let i = state.selection.from; i <= state.selection.to; i++) { @@ -461,9 +457,9 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & } } } + const recordingStart = DateCast(this.props.Document.recordingStart).date.getTime(); this._break = false; - console.log("start = " + (mark.attrs.modified * 1000 - AudioBox.START) / 1000); - value = "" + (mark.attrs.modified * 1000 - AudioBox.START) / 1000 + value; + value = "" + (mark.attrs.modified * 1000 - recordingStart) / 1000 + value; const from = state.selection.from; const inserted = state.tr.insertText(value).addMark(from, from + value.length + 1, mark); this._editorView.dispatch(inserted.setSelection(TextSelection.create(inserted.doc, from, from + value.length + 1))); @@ -867,7 +863,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & if (this._recording && !e.ctrlKey && e.button === 0) { this.stopDictation(true); this._break = true; - let state = this._editorView!.state; + const state = this._editorView!.state; const to = state.selection.to; const updated = TextSelection.create(state.doc, to, to); this._editorView!.dispatch(this._editorView!.state.tr.setSelection(updated).insertText("\n", to)); diff --git a/src/client/views/nodes/PDFBox.tsx b/src/client/views/nodes/PDFBox.tsx index f47620c24..4076128b2 100644 --- a/src/client/views/nodes/PDFBox.tsx +++ b/src/client/views/nodes/PDFBox.tsx @@ -94,11 +94,11 @@ export class PDFBox extends DocAnnotatableComponent !this.Document._fitWidth && (this.Document._height = this.Document[WidthSym]() * (nh / nw)); } - public search = (string: string, fwd: boolean) => { this._pdfViewer?.search(string, fwd); } - public prevAnnotation = () => { this._pdfViewer?.prevAnnotation(); } - public nextAnnotation = () => { this._pdfViewer?.nextAnnotation(); } - public backPage = () => { this._pdfViewer!.gotoPage((this.Document.curPage || 1) - 1); } - public forwardPage = () => { this._pdfViewer!.gotoPage((this.Document.curPage || 1) + 1); } + public search = (string: string, fwd: boolean) => { this._pdfViewer?.search(string, fwd); }; + public prevAnnotation = () => { this._pdfViewer?.prevAnnotation(); }; + public nextAnnotation = () => { this._pdfViewer?.nextAnnotation(); }; + public backPage = () => { this._pdfViewer!.gotoPage((this.Document.curPage || 1) - 1); }; + public forwardPage = () => { this._pdfViewer!.gotoPage((this.Document.curPage || 1) + 1); }; public gotoPage = (p: number) => { this._pdfViewer!.gotoPage(p); }; @undoBatch -- cgit v1.2.3-70-g09d2 From 786572f3cd674459f55b7f66e8eb257026f373ef Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Mon, 23 Mar 2020 21:24:50 -0400 Subject: fixed RichTextMenu to not obscure selection. fixed templateMenu to display a TreeView document of options. fixed resize in docDecorations for dragging corners other than bottom-right. --- src/client/util/DropConverter.ts | 2 +- src/client/views/DocumentButtonBar.tsx | 4 +- src/client/views/DocumentDecorations.scss | 3 + src/client/views/DocumentDecorations.tsx | 6 +- src/client/views/TemplateMenu.tsx | 94 ++++++++++++++++++---- .../views/collections/CollectionDockingView.tsx | 27 +++++-- .../views/collections/CollectionLinearView.tsx | 20 ++--- .../views/collections/CollectionTreeView.scss | 1 + .../views/collections/CollectionTreeView.tsx | 7 +- .../views/collections/ParentDocumentSelector.tsx | 22 ++--- .../collections/collectionFreeForm/MarqueeView.tsx | 12 ++- src/client/views/nodes/DocumentView.tsx | 15 ++-- src/client/views/nodes/FormattedTextBox.tsx | 25 ++++-- src/client/views/search/SearchItem.tsx | 2 +- src/new_fields/Doc.ts | 2 - src/new_fields/ScriptField.ts | 4 +- src/new_fields/util.ts | 1 - .../authentication/models/current_user_utils.ts | 16 +++- 18 files changed, 189 insertions(+), 74 deletions(-) (limited to 'src/client/views/nodes/FormattedTextBox.tsx') diff --git a/src/client/util/DropConverter.ts b/src/client/util/DropConverter.ts index 861cde5de..a6a43d06a 100644 --- a/src/client/util/DropConverter.ts +++ b/src/client/util/DropConverter.ts @@ -49,7 +49,7 @@ export function convertDropDataToButtons(data: DragManager.DocumentDragData) { (layoutDoc.layout instanceof Doc) && !data.userDropAction; } layoutDoc.isTemplateDoc = true; - dbox = Docs.Create.FontIconDocument({ _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, backgroundColor: StrCast(doc.backgroundColor), title: "Custom", icon: layoutDoc.isTemplateDoc ? "font" : "bolt" }); + dbox = Docs.Create.FontIconDocument({ _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, backgroundColor: StrCast(doc.backgroundColor), title: StrCast(layoutDoc.title), icon: layoutDoc.isTemplateDoc ? "font" : "bolt" }); dbox.dragFactory = layoutDoc; dbox.removeDropProperties = doc.removeDropProperties instanceof ObjectField ? ObjectField.MakeCopy(doc.removeDropProperties) : undefined; dbox.onDragStart = ScriptField.MakeFunction('getCopy(this.dragFactory, true)'); diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index 23875fa33..8a33232b4 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -108,7 +108,7 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView | this._pullColorAnimating = false; }); - get view0() { return this.props.views && this.props.views.length ? this.props.views[0] : undefined; } + get view0() { return this.props.views?.[0]; } @action onLinkButtonMoved = (e: PointerEvent): void => { @@ -250,7 +250,7 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView | @computed get contextButton() { - return !this.view0 ? (null) : v).map(v => v as DocumentView)} Document={this.view0.props.Document} addDocTab={(doc, where) => { + return !this.view0 ? (null) : { where === "onRight" ? CollectionDockingView.AddRightSplit(doc) : this.props.stack ? CollectionDockingView.Instance.AddTab(this.props.stack, doc) : this.view0?.props.addDocTab(doc, "onRight"); diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 8d6002f8f..353520026 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -80,6 +80,7 @@ $linkGap : 3px; #documentDecorations-topLeftResizer, #documentDecorations-bottomRightResizer { cursor: nwse-resize; + background: dimGray; } #documentDecorations-bottomRightResizer { @@ -89,6 +90,7 @@ $linkGap : 3px; #documentDecorations-topRightResizer, #documentDecorations-bottomLeftResizer { cursor: nesw-resize; + background: dimGray; } #documentDecorations-topResizer, @@ -158,6 +160,7 @@ $linkGap : 3px; padding-top: 5px; width: $MINIMIZED_ICON_SIZE; height: $MINIMIZED_ICON_SIZE; + max-height: 20px; } .documentDecorations-background { diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index c4abc935f..ff72592d8 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -266,7 +266,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> let dist = Math.sqrt((e.clientX - down[0]) * (e.clientX - down[0]) + (e.clientY - down[1]) * (e.clientY - down[1])); dist = dist < 3 ? 0 : dist; SelectionManager.SelectedDocuments().map(dv => dv.props.Document).map(doc => doc.layout instanceof Doc ? doc.layout : doc.isTemplateForField ? doc : Doc.GetProto(doc)). - map(d => d.borderRounding = `${Math.max(0, dist)}px`); + map(d => d.borderRounding = `${Math.max(0, dist)}%`); return false; } @@ -330,6 +330,10 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> const width = (layoutDoc._width || 0); const height = (layoutDoc._height || (nheight / nwidth * width)); const scale = element.props.ScreenToLocalTransform().Scale * element.props.ContentScaling(); + if (nwidth && nheight) { + if (Math.abs(dW) > Math.abs(dH)) dH = dW * nheight / nwidth; + else dW = dH * nwidth / nheight; + } const actualdW = Math.max(width + (dW * scale), 20); const actualdH = Math.max(height + (dH * scale), 20); doc.x = (doc.x || 0) + dX * (actualdW - width); diff --git a/src/client/views/TemplateMenu.tsx b/src/client/views/TemplateMenu.tsx index 5029b4074..cf6ce2c6f 100644 --- a/src/client/views/TemplateMenu.tsx +++ b/src/client/views/TemplateMenu.tsx @@ -1,4 +1,4 @@ -import { action, observable, runInAction, ObservableSet } from "mobx"; +import { action, observable, runInAction, ObservableSet, trace, computed } from "mobx"; import { observer } from "mobx-react"; import { SelectionManager } from "../util/SelectionManager"; import { undoBatch } from "../util/UndoManager"; @@ -7,8 +7,13 @@ import { DocumentView } from "./nodes/DocumentView"; import { Template } from "./Templates"; import React = require("react"); import { Doc, DocListCast } from "../../new_fields/Doc"; +import { Docs, } from "../documents/Documents"; import { StrCast, Cast } from "../../new_fields/Types"; -import { CurrentUserUtils } from "../../server/authentication/models/current_user_utils"; +import { CollectionTreeView } from "./collections/CollectionTreeView"; +import { returnTrue, emptyFunction, returnFalse, returnOne, emptyPath } from "../../Utils"; +import { Transform } from "../util/Transform"; +import { ScriptField, ComputedField } from "../../new_fields/ScriptField"; +import { Scripting } from "../util/Scripting"; @observer class TemplateToggle extends React.Component<{ template: Template, checked: boolean, toggle: (event: React.ChangeEvent, template: Template) => void }> { @@ -50,7 +55,10 @@ export class TemplateMenu extends React.Component { @observable private _hidden: boolean = true; toggleLayout = (e: React.ChangeEvent, layout: string): void => { - this.props.docViews.map(dv => dv.switchViews(e.target.checked, layout));//.setCustomView(e.target.checked, layout)); + this.props.docViews.map(dv => dv.switchViews(e.target.checked, layout)); + } + toggleDefault = (e: React.ChangeEvent): void => { + this.props.docViews.map(dv => dv.switchViews(false, "layout")); } toggleFloat = (e: React.ChangeEvent): void => { @@ -94,27 +102,81 @@ export class TemplateMenu extends React.Component { Array.from(Object.keys(Doc.GetProto(this.props.docViews[0].props.Document))). filter(key => key.startsWith("layout_")). map(key => runInAction(() => this._addedKeys.add(key.replace("layout_", "")))); - DocListCast(Cast(CurrentUserUtils.UserDocument.expandingButtons, Doc, null)?.data)?.map(btnDoc => { - if (StrCast(Cast(btnDoc?.dragFactory, Doc, null)?.title)) { - runInAction(() => this._addedKeys.add(StrCast(Cast(btnDoc?.dragFactory, Doc, null)?.title))); - } - }); } + return100 = () => 100; + @computed get scriptField() { + return ScriptField.MakeScript("switchView(firstDoc, this)", { this: Doc.name, heading: "string", checked: "string", containingTreeView: Doc.name, firstDoc: Doc.name }, + { firstDoc: this.props.docViews[0].props.Document }); + } render() { - const layout = Doc.Layout(this.props.docViews[0].Document); + const firstDoc = this.props.docViews[0].props.Document; + 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 layout = Doc.Layout(firstDoc); const templateMenu: Array = []; this.props.templates.forEach((checked, template) => templateMenu.push()); - templateMenu.push(); - templateMenu.push(); + templateMenu.push(); + templateMenu.push(); templateMenu.push(); - this._addedKeys && Array.from(this._addedKeys).map(layout => - templateMenu.push( this.toggleLayout(e, layout)} />) - ); + templateMenu.push(); + if (noteTypesDoc) { + addedTypes.concat(noteTypes).map(template => template.treeViewChecked = ComputedField.MakeFunction("templateIsUsed(this, firstDoc)", { firstDoc: "string" }, { firstDoc: StrCast(firstDoc.title) })); + this._addedKeys && Array.from(this._addedKeys).filter(key => !noteTypes.some(nt => nt.title === key)).forEach(template => templateMenu.push( + this.toggleLayout(e, template)} />)); + templateMenu.push( + false} + removeDocument={(doc: Doc) => false} + addDocument={(doc: Doc) => false} /> + ); + } return
    - {templateMenu} + {templateMenu}
; } -} \ No newline at end of file +} + +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) +}); + +Scripting.addGlobal(function templateIsUsed(templateDoc: Doc, firstDocTitlte: string) { + const firstDoc = SelectionManager.SelectedDocuments()[0].props.Document; + 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 diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 00e22d6fb..1fb78f625 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -2,7 +2,7 @@ import { library } from '@fortawesome/fontawesome-svg-core'; import { faFile } from '@fortawesome/free-solid-svg-icons'; import 'golden-layout/src/css/goldenlayout-base.css'; import 'golden-layout/src/css/goldenlayout-dark-theme.css'; -import { action, computed, Lambda, observable, reaction, runInAction } from "mobx"; +import { action, computed, Lambda, observable, reaction, runInAction, trace } from "mobx"; import { observer } from "mobx-react"; import * as ReactDOM from 'react-dom'; import Measure from "react-measure"; @@ -20,7 +20,7 @@ import { DocServer } from "../../DocServer"; import { Docs } from '../../documents/Documents'; import { DocumentType } from '../../documents/DocumentTypes'; import { DocumentManager } from '../../util/DocumentManager'; -import { DragManager } from "../../util/DragManager"; +import { DragManager, dropActionType } from "../../util/DragManager"; import { Scripting } from '../../util/Scripting'; import { SelectionManager } from '../../util/SelectionManager'; import { Transform } from '../../util/Transform'; @@ -504,15 +504,25 @@ export class CollectionDockingView extends React.Component { + const onDown = (e: React.PointerEvent) => { + if (!(e.nativeEvent as any).defaultPrevented) { e.preventDefault(); e.stopPropagation(); const dragData = new DragManager.DocumentDragData([doc]); - dragData.dropAction = doc.dropAction === "alias" ? "alias" : doc.dropAction === "copy" ? "copy" : undefined; + dragData.dropAction = doc.dropAction as dropActionType; DragManager.StartDocumentDrag([gearSpan], dragData, e.clientX, e.clientY); - }}>, gearSpan); + } + } + let rendered = false; + tab.buttonDisposer = reaction(() => ((view: Opt) => view ? [view] : [])(DocumentManager.Instance.getDocumentView(doc)), + (views) => { + !rendered && ReactDOM.render( + + , + gearSpan); + rendered = true; + }); + tab.reactComponents = [gearSpan]; tab.element.append(gearSpan); tab.reactionDisposer = reaction(() => ({ title: doc.title, degree: Doc.IsBrushedDegree(doc) }), ({ title, degree }) => { @@ -526,7 +536,8 @@ export class CollectionDockingView extends React.Component this.isCurrent(pair.layout)).map((pair, ind) => { + this.childLayoutPairs.map((pair, ind) => { Cast(pair.layout.proto?.onPointerUp, ScriptField)?.script.run({ this: pair.layout.proto }, console.log); }); } @@ -48,7 +48,7 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { (i) => runInAction(() => { this._selectedIndex = i; let selected: any = undefined; - this.childLayoutPairs.filter((pair) => this.isCurrent(pair.layout)).map(async (pair, ind) => { + this.childLayoutPairs.map(async (pair, ind) => { const isSelected = this._selectedIndex === ind; if (isSelected) { selected = pair; @@ -71,8 +71,6 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) { } } - public isCurrent(doc: Doc) { return (Math.abs(NumCast(doc.displayTimecode, -1) - NumCast(this.Document.currentTimecode, -1)) < 1.5 || NumCast(doc.displayTimecode, -1) === -1); } - dimension = () => NumCast(this.props.Document._height); // 2 * the padding getTransform = (ele: React.RefObject) => () => { if (!ele.current) return Transform.Identity(); @@ -87,17 +85,21 @@ export class CollectionLinearView extends CollectionSubView(LinearDocument) {
this.props.Document.linearViewIsExpanded = this.addMenuToggle.current!.checked)} /> - + -
- {this.childLayoutPairs.filter((pair) => this.isCurrent(pair.layout)).map((pair, ind) => { +
+ {this.childLayoutPairs.map((pair, ind) => { const nested = pair.layout._viewType === CollectionViewType.Linear; const dref = React.createRef(); const nativeWidth = NumCast(pair.layout._nativeWidth, this.dimension()); const deltaSize = nativeWidth * .15 / 2; - return
this._mainEle && this._mainEle.scrollHeight > this._mainEle.clientHeight && e.stopPropagation()} onDrop={this.onTreeDrop} diff --git a/src/client/views/collections/ParentDocumentSelector.tsx b/src/client/views/collections/ParentDocumentSelector.tsx index 43ba5c614..35e3a8958 100644 --- a/src/client/views/collections/ParentDocumentSelector.tsx +++ b/src/client/views/collections/ParentDocumentSelector.tsx @@ -2,7 +2,7 @@ import * as React from "react"; import './ParentDocumentSelector.scss'; import { Doc } from "../../../new_fields/Doc"; import { observer } from "mobx-react"; -import { observable, action, runInAction } from "mobx"; +import { observable, action, runInAction, trace, computed } from "mobx"; import { Id } from "../../../new_fields/FieldSymbols"; import { SearchUtil } from "../../util/SearchUtil"; import { CollectionDockingView } from "./CollectionDockingView"; @@ -14,6 +14,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faCog, faChevronCircleUp } from "@fortawesome/free-solid-svg-icons"; import { library } from "@fortawesome/fontawesome-svg-core"; import { DocumentView } from "../nodes/DocumentView"; +import { SelectionManager } from "../../util/SelectionManager"; const higflyout = require("@hig/flyout"); export const { anchorPoints } = higflyout; export const Flyout = higflyout.default; @@ -22,7 +23,6 @@ library.add(faCog); type SelectorProps = { Document: Doc, - Views: DocumentView[], Stack?: any, addDocTab(doc: Doc, location: string): void }; @@ -93,7 +93,7 @@ export class ParentDocSelector extends React.Component { } @observer -export class DockingViewButtonSelector extends React.Component<{ Document: Doc, Stack: any }> { +export class DockingViewButtonSelector extends React.Component<{ views: DocumentView[], Stack: any }> { @observable hover = false; customStylesheet(styles: any) { @@ -106,15 +106,19 @@ export class DockingViewButtonSelector extends React.Component<{ Document: Doc, }; } - render() { - const view = DocumentManager.Instance.getDocumentView(this.props.Document); - const flyout = ( + @computed get flyout() { + trace(); + return (
- +
); - return !this.props.Stack && e.stopPropagation()} className="buttonSelector"> - + } + + render() { + trace(); + return { this.props.views[0].select(false); e.stopPropagation(); }} className="buttonSelector"> + ; diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index 4bf3329eb..17bba9568 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -107,8 +107,14 @@ export class MarqueeView extends React.Component(Docu static makeCustomViewClicked = (doc: Doc, dataDoc: Opt, creator: (documents: Array, options: DocumentOptions, id?: string) => Doc, name: string = "custom", docLayoutTemplate?: Doc) => { const batch = UndoManager.StartBatch("CustomViewClicked"); const customName = "layout_" + name; - if (!StrCast(doc.title).endsWith(name)) doc.title = doc.title + "_" + name; if (doc[customName] === undefined) { const _width = NumCast(doc._width); const _height = NumCast(doc._height); @@ -634,13 +633,15 @@ export class DocumentView extends DocComponent(Docu // } else if (custom) { DocumentView.makeNativeViewClicked(this.props.Document); + const userDoc = Doc.UserDoc(); - const imgView = Cast(Doc.UserDoc().iconView, Doc, null); - const iconImgView = Cast(Doc.UserDoc().iconImageView, Doc, null); - const iconColView = Cast(Doc.UserDoc().iconColView, Doc, null); + const imgView = Cast(userDoc.iconView, Doc, null); + const iconImgView = Cast(userDoc.iconImageView, Doc, null); + const iconColView = Cast(userDoc.iconColView, Doc, null); const iconViews = [imgView, iconImgView, iconColView]; - const expandingButtons = DocListCast(Cast(Doc.UserDoc().expandingButtons, Doc, null)?.data); - const allTemplates = iconViews.concat(expandingButtons); + const templateButtons = DocListCast(Cast(userDoc.templateButtons, Doc, null)?.data); + const noteTypes = DocListCast(Cast(userDoc.noteTypes, Doc, null)?.data); + const allTemplates = iconViews.concat(templateButtons).concat(noteTypes); let foundLayout: Opt; allTemplates.map(btnDoc => (btnDoc.dragFactory as Doc) || btnDoc).filter(doc => doc.isTemplateDoc).forEach(tempDoc => { if (StrCast(tempDoc.title) === this.props.Document.type + "_" + layout) { @@ -1028,7 +1029,7 @@ export class DocumentView extends DocComponent(Docu
); const captionView = (!showCaption ? (null) :
- { this.ProseRef = ele; - this.dropDisposer && this.dropDisposer(); + this.dropDisposer?.(); ele && (this.dropDisposer = DragManager.MakeDropTarget(ele, this.drop.bind(this))); } @@ -386,9 +387,14 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & } specificContextMenu = (e: React.MouseEvent): void => { const funcs: ContextMenuProps[] = []; - this.props.Document.isTemplateDoc && funcs.push({ description: "Make Default Layout", event: async () => Doc.UserDoc().defaultTextLayout = new PrefetchProxy(this.props.Document.proto as Doc), icon: "eye" }); + this.props.Document.isTemplateDoc && funcs.push({ description: "Make Default Layout", event: async () => Doc.UserDoc().defaultTextLayout = new PrefetchProxy(this.props.Document), icon: "eye" }); funcs.push({ description: "Reset Default Layout", event: () => Doc.UserDoc().defaultTextLayout = undefined, icon: "eye" }); - !this.props.Document.expandedTemplate && funcs.push({ description: "Make Template", event: () => { this.props.Document.isTemplateDoc = true; Doc.AddDocToList(Cast(Doc.UserDoc().noteTypes, Doc, null), "data", this.props.Document); }, icon: "eye" }); + !this.props.Document.expandedTemplate && funcs.push({ + description: "Make Template", event: () => { + this.props.Document.isTemplateDoc = makeTemplate(this.props.Document, true); + Doc.AddDocToList(Cast(Doc.UserDoc().noteTypes, Doc, null), "data", this.props.Document); + }, icon: "eye" + }); funcs.push({ description: "Toggle Single Line", event: () => this.props.Document._singleLine = !this.props.Document._singleLine, icon: "expand-arrows-alt" }); funcs.push({ description: "Toggle Sidebar", event: () => this.props.Document._showSidebar = !this.props.Document._showSidebar, icon: "expand-arrows-alt" }); funcs.push({ description: "Toggle Audio", event: () => this.props.Document._showAudio = !this.props.Document._showAudio, icon: "expand-arrows-alt" }); @@ -901,6 +907,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & if (e.buttons === 1 && this.props.isSelected(true) && !e.altKey) { e.stopPropagation(); } + this._downX = this._downY = Number.NaN; } @action @@ -914,12 +921,16 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & prosediv && (prosediv.keeplocation = undefined); const pos = this._editorView?.state.selection.$from.pos || 1; keeplocation && setTimeout(() => this._editorView?.dispatch(this._editorView?.state.tr.setSelection(TextSelection.create(this._editorView.state.doc, pos)))); + const coords = !Number.isNaN(this._downX) ? { left: this._downX, top: this._downY, bottom: this._downY, right: this._downX } : this._editorView?.coordsAtPos(pos); // jump rich text menu to this textbox - const { current } = this._ref; - if (current && this.props.Document._chromeStatus !== "disabled") { - const x = Math.min(Math.max(current.getBoundingClientRect().left, 0), window.innerWidth - RichTextMenu.Instance.width); - const y = this._ref.current!.getBoundingClientRect().top - RichTextMenu.Instance.height - 50; + const bounds = this._ref.current?.getBoundingClientRect(); + if (bounds && this.props.Document._chromeStatus !== "disabled") { + const x = Math.min(Math.max(bounds.left, 0), window.innerWidth - RichTextMenu.Instance.width); + let y = Math.min(Math.max(0, bounds.top - RichTextMenu.Instance.height - 50), window.innerHeight - RichTextMenu.Instance.height); + if (coords && coords.left > x && coords.left < x + RichTextMenu.Instance.width && coords.top > y && coords.top < y + RichTextMenu.Instance.height + 50) { + y = Math.min(bounds.bottom, window.innerHeight - RichTextMenu.Instance.height); + } RichTextMenu.Instance.jumpTo(x, y); } } diff --git a/src/client/views/search/SearchItem.tsx b/src/client/views/search/SearchItem.tsx index 2cbb24da7..63cef5101 100644 --- a/src/client/views/search/SearchItem.tsx +++ b/src/client/views/search/SearchItem.tsx @@ -272,7 +272,7 @@ export class SearchItem extends React.Component { @computed get contextButton() { - return CollectionDockingView.AddRightSplit(doc)} />; + return CollectionDockingView.AddRightSplit(doc)} />; } render() { diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 50adf0392..322b57272 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -795,8 +795,6 @@ export namespace Doc { const prevLayout = StrCast(doc.layoutKey).split("_")[1]; const deiconify = prevLayout === "icon" && StrCast(doc.deiconifyLayout) ? "layout_" + StrCast(doc.deiconifyLayout) : ""; prevLayout === "icon" && (doc.deiconifyLayout = undefined); - if (StrCast(doc.title).endsWith("_" + prevLayout) && deiconify) doc.title = StrCast(doc.title).replace("_" + prevLayout, deiconify); - else doc.title = undefined; doc.layoutKey = deiconify || "layout"; } export function setDocFilterRange(target: Doc, key: string, range?: number[]) { diff --git a/src/new_fields/ScriptField.ts b/src/new_fields/ScriptField.ts index 9288fea9e..606f55b7c 100644 --- a/src/new_fields/ScriptField.ts +++ b/src/new_fields/ScriptField.ts @@ -119,8 +119,8 @@ export class ScriptField extends ObjectField { return compiled.compiled ? new ScriptField(compiled) : undefined; } - public static MakeScript(script: string, params: object = {}) { - const compiled = ScriptField.CompileScript(script, params, false); + public static MakeScript(script: string, params: object = {}, capturedVariables?: { [name: string]: Field }) { + const compiled = ScriptField.CompileScript(script, params, false, capturedVariables); return compiled.compiled ? new ScriptField(compiled) : undefined; } } diff --git a/src/new_fields/util.ts b/src/new_fields/util.ts index 6d7f6b56e..3ab1b299b 100644 --- a/src/new_fields/util.ts +++ b/src/new_fields/util.ts @@ -7,7 +7,6 @@ import { ObjectField } from "./ObjectField"; import { action, trace } from "mobx"; import { Parent, OnUpdate, Update, Id, SelfProxy, Self } from "./FieldSymbols"; import { DocServer } from "../client/DocServer"; -import { props } from "bluebird"; function _readOnlySetter(): never { throw new Error("Documents can't be modified in read-only mode"); diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 31588bf82..9c39ce7de 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -53,7 +53,7 @@ export class CurrentUserUtils { ]; doc.fieldTypes = Docs.Create.TreeDocument([], { title: "field enumerations" }); Doc.addFieldEnumerations(Doc.GetProto(noteTemplates[4]), "taskStatus", taskStatusValues); - doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates.map(nt => makeTemplate(nt, true, StrCast(nt.style)) ? nt : nt), { title: "Note Types", _height: 75 })); + doc.noteTypes = new PrefetchProxy(Docs.Create.TreeDocument(noteTemplates.map(nt => makeTemplate(nt, true, StrCast(nt.style)) ? nt : nt), { title: "Note Layouts", _height: 75 })); } // setup the "creator" buttons for the sidebar-- eg. the default set of draggable document creation tools @@ -292,12 +292,20 @@ export class CurrentUserUtils { { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: slideTemplate, removeDropProperties: new List(["dropAction"]), title: "presentation slide", icon: "sticky-note" }); doc.descriptionBtn = Docs.Create.FontIconDocument( { _nativeWidth: 100, _nativeHeight: 100, _width: 100, _height: 100, dropAction: "alias", onDragStart: ScriptField.MakeFunction('getCopy(this.dragFactory, true)'), dragFactory: descriptionTemplate, removeDropProperties: new List(["dropAction"]), title: "description view", icon: "sticky-note" }); - doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.slidesBtn as Doc, doc.descriptionBtn as Doc, - ...DocListCast(Cast(doc.noteTypes, Doc, null))], { + doc.templateButtons = Docs.Create.LinearDocument([doc.slidesBtn as Doc, doc.descriptionBtn as Doc], { + title: "template buttons", _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", dontSelect: true, + backgroundColor: "black", treeViewPreventOpen: true, forceActive: true, lockedPosition: true, _chromeStatus: "disabled", linearViewIsExpanded: true, + dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }) + }); + doc.expandingButtons = Docs.Create.LinearDocument([doc.undoBtn as Doc, doc.redoBtn as Doc, doc.templateButtons as Doc], { title: "expanding buttons", _gridGap: 5, _xMargin: 5, _yMargin: 5, _height: 42, _width: 100, boxShadow: "0 0", - backgroundColor: "black", treeViewPreventOpen: true, forceActive: true, lockedPosition: true, + backgroundColor: "black", treeViewPreventOpen: true, forceActive: true, lockedPosition: true, linearViewIsExpanded: true, dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", { dragData: DragManager.DocumentDragData.name }) }); + doc.templateDocs = new PrefetchProxy(Docs.Create.TreeDocument([doc.noteTypes as Doc, doc.templateButtons as Doc], { + title: "template layouts", _xPadding: 0, dropConverter: ScriptField.MakeScript("convertToButtons(dragData)", + { dragData: DragManager.DocumentDragData.name }) + })); } // sets up the default set of documents to be shown in the Overlay layer -- cgit v1.2.3-70-g09d2 From 4ae6b564896dd216c37fa38ffeee70ba0e671221 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sat, 28 Mar 2020 02:40:17 -0400 Subject: simplified linkDocs to not keep a context -- instead, link are made between aliases which have a context. fixed clippings of PDFs to scroll correctly and resize in slideViews. fixed slideViews to render 'text' and 'data' instead of 'contents' and 'data' --- src/client/documents/Documents.ts | 6 ++---- src/client/util/DocumentManager.ts | 2 +- src/client/views/DocumentButtonBar.tsx | 2 -- src/client/views/collections/CollectionView.tsx | 4 +++- .../collections/collectionFreeForm/MarqueeView.tsx | 4 ++-- src/client/views/nodes/DocuLinkBox.tsx | 3 ++- src/client/views/nodes/DocumentView.tsx | 7 +++---- src/client/views/nodes/FormattedTextBox.tsx | 4 ++-- src/client/views/nodes/PDFBox.tsx | 2 +- src/client/views/nodes/PresBox.tsx | 2 +- src/client/views/pdf/PDFViewer.tsx | 18 +++++++++++------- src/server/authentication/models/current_user_utils.ts | 2 +- 12 files changed, 29 insertions(+), 27 deletions(-) (limited to 'src/client/views/nodes/FormattedTextBox.tsx') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index b5cffaddd..dbea8062e 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -558,15 +558,13 @@ export namespace Docs { const linkDocProto = Doc.GetProto(doc); linkDocProto.anchor1 = source.doc; linkDocProto.anchor2 = target.doc; - linkDocProto.anchor1_context = source.ctx; - linkDocProto.anchor2_context = target.ctx; linkDocProto.anchor1_timecode = source.doc.currentTimecode || source.doc.displayTimecode; linkDocProto.anchor2_timecode = target.doc.currentTimecode || source.doc.displayTimecode; 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).linkBoxExcludedKeys = new List(["treeViewExpandedView", "treeViewHideTitle", "removeDropProperties", "linkBoxExcludedKeys", "treeViewOpen", "proto", "aliasNumber", "isPrototype", "lastOpened", "creationDate", "author"]); + 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; } @@ -926,7 +924,7 @@ export namespace DocUtils { }); } - export function MakeLink(source: { doc: Doc, ctx?: Doc }, target: { doc: Doc, ctx?: Doc }, linkRelationship: string = "", id?: string) { + export function MakeLink(source: { doc: Doc }, target: { doc: Doc }, linkRelationship: string = "", id?: string) { const sv = DocumentManager.Instance.getDocumentView(source.doc); if (sv && sv.props.ContainingCollectionDoc === target.doc) return; if (target.doc === CurrentUserUtils.UserDocument) return undefined; diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts index c41304b9f..0c410c4ce 100644 --- a/src/client/util/DocumentManager.ts +++ b/src/client/util/DocumentManager.ts @@ -203,7 +203,7 @@ export class DocumentManager { const second = secondDocWithoutView ? [secondDocWithoutView] : secondDocs; const linkDoc = first.length ? first[0] : second.length ? second[0] : undefined; const linkFollowDocs = first.length ? [await first[0].anchor2 as Doc, await first[0].anchor1 as Doc] : second.length ? [await second[0].anchor1 as Doc, await second[0].anchor2 as Doc] : undefined; - const linkFollowDocContexts = first.length ? [await first[0].anchor2_context as Doc, await first[0].anchor1_context as Doc] : second.length ? [await second[0].anchor1_context as Doc, await second[0].anchor2_context as Doc] : [undefined, undefined]; + const linkFollowDocContexts = first.length ? [await first[0].context as Doc, await first[0].context as Doc] : second.length ? [await second[0].context as Doc, await second[0].context as Doc] : [undefined, undefined]; const linkFollowTimecodes = first.length ? [NumCast(first[0].anchor2_timecode), NumCast(first[0].anchor1_timecode)] : second.length ? [NumCast(second[0].anchor1_timecode), NumCast(second[0].anchor2_timecode)] : [undefined, undefined]; if (linkFollowDocs && linkDoc) { const maxLocation = StrCast(linkDoc.maximizeLocation, "inTab"); diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index 8a33232b4..ef1d20e44 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -120,8 +120,6 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView | dragComplete: dropEv => { const linkDoc = dropEv.linkDragData?.linkDocument as Doc; // equivalent to !dropEve.aborted since linkDocument is only assigned on a completed drop if (this.view0 && linkDoc) { - const proto = Doc.GetProto(linkDoc); - proto.anchor1_context = this.view0.props.ContainingCollectionDoc; Doc.GetProto(linkDoc).linkRelationship = "hyperlink"; const anchor2Title = linkDoc.anchor2 instanceof Doc ? StrCast(linkDoc.anchor2.title) : "-untitled-"; diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 2386f2d5d..1542988e7 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -127,6 +127,7 @@ export class CollectionView extends Touchable { const docList = DocListCast(targetDataDoc[this.props.fieldKey]); !docList.includes(doc) && (targetDataDoc[this.props.fieldKey] = new List([...docList, doc])); // DocAddToList may write to targetdataDoc's parent ... we don't want this. should really change GetProto to GetDataDoc and test for resolvedDataDoc there // Doc.AddDocToList(targetDataDoc, this.props.fieldKey, doc); + doc.context = this.props.Document; targetDataDoc[this.props.fieldKey + "-lastModified"] = new DateField(new Date(Date.now())); Doc.GetProto(doc).lastOpened = new DateField; return true; @@ -141,7 +142,8 @@ export class CollectionView extends Touchable { let index = value.reduce((p, v, i) => (v instanceof Doc && v === doc) ? i : p, -1); index = index !== -1 ? index : value.reduce((p, v, i) => (v instanceof Doc && Doc.AreProtosEqual(v, doc)) ? i : p, -1); - ContextMenu.Instance && ContextMenu.Instance.clearItems(); + doc.context = undefined; + ContextMenu.Instance?.clearItems(); if (index !== -1) { value.splice(index, 1); targetDataDoc[this.props.fieldKey] = new List(value); diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index 17bba9568..0f94bffd6 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -111,7 +111,7 @@ export class MarqueeView extends React.Component(Doc if (!this._doubleTap) { this._editing = true; this.props.ContainingCollectionDoc && this.props.bringToFront(this.props.ContainingCollectionDoc, false); + const {clientX, clientY} = e; if (!this.props.Document.onClick && !this._isOpen) { this._timeout = setTimeout(action(() => { - if (Math.abs(e.clientX - this._downX) < 3 && Math.abs(e.clientY - this._downY) < 3 && (e.button !== 2 && !e.ctrlKey && this.props.Document.isButton)) { + if (Math.abs(clientX - this._downX) < 3 && Math.abs(clientY - this._downY) < 3 && (e.button !== 2 && !e.ctrlKey && this.props.Document.isButton)) { DocumentManager.Instance.FollowLink(this.props.Document, this.props.ContainingCollectionDoc as Doc, document => this.props.addDocTab(document, StrCast(this.props.Document.linkOpenLocation, "inTab")), false); } this._editing = false; diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 544c0a961..4968dd7fc 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -229,7 +229,6 @@ export class DocumentView extends DocComponent(Docu dragData.dropAction = dropAction; dragData.moveDocument = this.props.moveDocument;// this.Document.onDragStart ? undefined : this.props.moveDocument; dragData.dragDivName = this.props.dragDivName; - this.props.Document.anchor1_context = this.props.ContainingCollectionDoc; // bcz: !! shouldn't need this ... use search find the document's context dynamically DragManager.StartDocumentDrag([this._mainCont.current], dragData, x, y, { hideSource: !dropAction && !this.Document.onDragStart }); } } @@ -582,7 +581,7 @@ export class DocumentView extends DocComponent(Docu e.stopPropagation(); de.complete.annoDragData.linkedToDoc = true; - DocUtils.MakeLink({ doc: de.complete.annoDragData.annotationDocument }, { doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, "link"); + DocUtils.MakeLink({ doc: de.complete.annoDragData.annotationDocument }, { doc: this.props.Document }, "link"); } if (de.complete.docDragData) { if (de.complete.docDragData.applyAsTemplate) { @@ -613,7 +612,7 @@ export class DocumentView extends DocComponent(Docu // const views = docs.map(d => DocumentManager.Instance.getDocumentView(d)).filter(d => d).map(d => d as DocumentView); de.complete.linkDragData.linkSourceDocument !== this.props.Document && (de.complete.linkDragData.linkDocument = DocUtils.MakeLink({ doc: de.complete.linkDragData.linkSourceDocument }, - { doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, `link`)); // TODODO this is where in text links get passed + { doc: this.props.Document }, `link`)); // TODODO this is where in text links get passed } } @@ -639,7 +638,7 @@ export class DocumentView extends DocComponent(Docu const portalLink = DocListCast(this.Document.links).find(d => d.anchor1 === this.props.Document); if (!portalLink) { 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, ctx: this.props.ContainingCollectionDoc }, { doc: portal }, "portal to"); + DocUtils.MakeLink({ doc: this.props.Document }, { doc: portal }, "portal to"); } this.Document.isButton = true; } diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index e7c9e5e6b..f83beade3 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -155,7 +155,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & this.dataDoc[key] = doc || Docs.Create.FreeformDocument([], { title: value, _width: 500, _height: 500 }, value); DocUtils.Publish(this.dataDoc[key] as Doc, value, this.props.addDocument, this.props.removeDocument); if (linkDoc) { (linkDoc as Doc).anchor2 = this.dataDoc[key] as Doc; } - else DocUtils.MakeLink({ doc: this.dataDoc, ctx: this.props.ContainingCollectionDoc }, { doc: this.dataDoc[key] as Doc }, "link to named target", id); + else DocUtils.MakeLink({ doc: this.props.Document }, { doc: this.dataDoc[key] as Doc }, "link to named target", id); }); }); }); @@ -748,7 +748,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & targetAnnotations?.push(pdfRegion); }); - const link = DocUtils.MakeLink({ doc: this.props.Document, ctx: this.props.ContainingCollectionDoc }, { doc: pdfRegion, ctx: pdfDoc }, "PDF pasted"); + const link = DocUtils.MakeLink({ doc: this.props.Document }, { doc: pdfRegion }, "PDF pasted"); if (link) { cbe.clipboardData!.setData("dash/linkDoc", link[Id]); const linkId = link[Id]; diff --git a/src/client/views/nodes/PDFBox.tsx b/src/client/views/nodes/PDFBox.tsx index 4076128b2..f8c008a2d 100644 --- a/src/client/views/nodes/PDFBox.tsx +++ b/src/client/views/nodes/PDFBox.tsx @@ -231,7 +231,7 @@ export class PDFBox extends DocAnnotatableComponent isChildActive = (outsideReaction?: boolean) => this._isChildActive; @computed get renderPdfView() { const pdfUrl = Cast(this.dataDoc[this.props.fieldKey], PdfField); - return
+ return
{ //docToJump stayed same meaning, it was not in the group or was the last element in the group const aliasOf = await Cast(docToJump.aliasOf, Doc); - const srcContext = aliasOf && await Cast(aliasOf.anchor1_context, Doc); + const srcContext = aliasOf && await Cast(aliasOf.context, Doc); if (docToJump === curDoc) { //checking if curDoc has navigation open const target = await Cast(curDoc.presentationTargetDoc, Doc); diff --git a/src/client/views/pdf/PDFViewer.tsx b/src/client/views/pdf/PDFViewer.tsx index af06a2646..a1e7d5c2a 100644 --- a/src/client/views/pdf/PDFViewer.tsx +++ b/src/client/views/pdf/PDFViewer.tsx @@ -7,7 +7,7 @@ import { Doc, DocListCast, FieldResult, WidthSym, Opt, HeightSym } from "../../. import { Id, Copy } from "../../../new_fields/FieldSymbols"; import { List } from "../../../new_fields/List"; import { makeInterface, createSchema } from "../../../new_fields/Schema"; -import { ScriptField } from "../../../new_fields/ScriptField"; +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 { Docs, DocUtils } from "../../documents/Documents"; @@ -33,6 +33,7 @@ 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"); @@ -210,7 +211,7 @@ export class PDFViewer extends DocAnnotatableComponent Cast(this.props.Document._scrollTop, "number", null), + this._scrollTopReactionDisposer = reaction(() => Cast(this.layoutDoc._scrollTop, "number", null), (stop) => (stop !== undefined) && this._mainCont.current && smoothScroll(500, this._mainCont.current, stop), { fireImmediately: true }); this._annotationReactionDisposer = reaction( () => DocListCast(this.dataDoc[this.props.fieldKey + "-annotations"]), @@ -567,12 +568,14 @@ export class PDFViewer extends DocAnnotatableComponent([clipDoc]); - Doc.GetProto(targetDoc).layout_slideView = (await Cast(Doc.UserDoc().slidesBtn, Doc))?.dragFactory; - targetDoc.layoutKey = "layout_slideView"; + DocumentView.makeCustomViewClicked(targetDoc, undefined, Docs.Create.StackingDocument, "slideView", undefined); // const targetDoc = Docs.Create.TextDocument("", { _width: 200, _height: 200, title: "Note linked to " + this.props.Document.title }); // Doc.GetProto(targetDoc).snipped = this.dataDoc[this.props.fieldKey][Copy](); // const snipLayout = Docs.Create.PdfDocument("http://www.msn.com", { title: "snippetView", isTemplateDoc: true, isTemplateForField: "snipped", _fitWidth: true, _width: this.marqueeWidth(), _height: this.marqueeHeight(), _scrollTop: this.marqueeY() }); @@ -582,7 +585,7 @@ export class PDFViewer extends DocAnnotatableComponent { if (!e.aborted && e.annoDragData && !e.annoDragData.linkedToDoc) { - const link = DocUtils.MakeLink({ doc: annotationDoc }, { doc: e.annoDragData.dropDocument, ctx: e.annoDragData.targetContext }, "Annotation"); + const link = DocUtils.MakeLink({ doc: annotationDoc }, { doc: e.annoDragData.dropDocument }, "Annotation"); if (link) link.maximizeLocation = "onRight"; } } @@ -646,6 +649,7 @@ export class PDFViewer extends DocAnnotatableComponent Date: Mon, 30 Mar 2020 14:19:03 -0400 Subject: changed expandedTemplate to rootDocument --- src/client/util/ProsemirrorExampleTransfer.ts | 6 +++--- src/client/util/RichTextSchema.tsx | 2 +- src/client/views/collections/CollectionSubView.tsx | 2 +- src/client/views/collections/CollectionView.tsx | 2 +- src/client/views/nodes/DocumentView.tsx | 2 +- src/client/views/nodes/FormattedTextBox.tsx | 4 ++-- src/client/views/presentationview/PresElementBox.tsx | 2 +- src/new_fields/Doc.ts | 18 +++++++++--------- src/new_fields/ScriptField.ts | 2 +- 9 files changed, 20 insertions(+), 20 deletions(-) (limited to 'src/client/views/nodes/FormattedTextBox.tsx') diff --git a/src/client/util/ProsemirrorExampleTransfer.ts b/src/client/util/ProsemirrorExampleTransfer.ts index 5cbf401d4..42247f177 100644 --- a/src/client/util/ProsemirrorExampleTransfer.ts +++ b/src/client/util/ProsemirrorExampleTransfer.ts @@ -151,14 +151,14 @@ export default function buildKeymap>(schema: S, props: any }); bind("Ctrl-Enter", (state: EditorState, dispatch: (tx: Transaction) => void) => { const layoutDoc = props.Document; - const originalDoc = layoutDoc.expandedTemplate || layoutDoc; + const originalDoc = layoutDoc.rootDocument || layoutDoc; if (originalDoc instanceof Doc) { const newDoc = Docs.Create.TextDocument("", { title: "", layout: Cast(originalDoc.layout, Doc, null) || FormattedTextBox.DefaultLayout, _singleLine: BoolCast(originalDoc._singleLine), x: NumCast(originalDoc.x), y: NumCast(originalDoc.y) + NumCast(originalDoc._height) + 10, _width: NumCast(layoutDoc._width), _height: NumCast(layoutDoc._height) }); FormattedTextBox.SelectOnLoad = newDoc[Id]; - originalDoc instanceof Doc && props.addDocument(newDoc); + props.addDocument(newDoc); } }); @@ -169,7 +169,7 @@ export default function buildKeymap>(schema: S, props: any }; const addTextOnRight = (force: boolean) => { const layoutDoc = props.Document; - const originalDoc = layoutDoc.expandedTemplate || layoutDoc; + const originalDoc = layoutDoc.rootDocument || layoutDoc; if (force || props.Document._singleLine) { const newDoc = Docs.Create.TextDocument("", { title: "", layout: Cast(originalDoc.layout, Doc, null) || FormattedTextBox.DefaultLayout, _singleLine: BoolCast(originalDoc._singleLine), diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index 1c637cfbe..b612c82ae 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -849,7 +849,7 @@ export class DashDocView { this._renderDisposer?.(); this._renderDisposer = reaction(() => { if (!Doc.AreProtosEqual(finalLayout, dashDoc)) { - finalLayout.expandedTemplate = dashDoc.aliasOf; + finalLayout.rootDocument = dashDoc.aliasOf; } const layoutKey = StrCast(finalLayout.layoutKey); const finalKey = layoutKey && StrCast(finalLayout[layoutKey]).split("'")?.[1]; diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index 8b7136876..39621b75c 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -125,7 +125,7 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T, moreProps?: } const dfield = this.dataField; - const rawdocs = (dfield instanceof Doc) ? [dfield] : Cast(dfield, listSpec(Doc), this.props.Document.expandedTemplate && !this.props.annotationsKey ? [Cast(this.props.Document.expandedTemplate, Doc, null)] : []); + const rawdocs = (dfield instanceof Doc) ? [dfield] : Cast(dfield, listSpec(Doc), this.props.Document.rootDocument && !this.props.annotationsKey ? [Cast(this.props.Document.rootDocument, Doc, null)] : []); const docs = rawdocs.filter(d => !(d instanceof Promise)).map(d => d as Doc); const viewSpecScript = Cast(this.props.Document.viewSpecScript, ScriptField); const childDocs = viewSpecScript ? docs.filter(d => viewSpecScript.script.run({ doc: d }, console.log).result) : docs; diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 324417cf8..edb9fd930 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -306,7 +306,7 @@ export class CollectionView extends Touchable { } get childDocs() { const dfield = this.dataField; - const rawdocs = (dfield instanceof Doc) ? [dfield] : Cast(dfield, listSpec(Doc), Cast(this.props.Document.expandedTemplate, Doc, null) ? [Cast(this.props.Document.expandedTemplate, Doc, null)] : []); + const rawdocs = (dfield instanceof Doc) ? [dfield] : Cast(dfield, listSpec(Doc), Cast(this.props.Document.rootDocument, Doc, null) ? [Cast(this.props.Document.rootDocument, Doc, null)] : []); const docs = rawdocs.filter(d => !(d instanceof Promise)).map(d => d as Doc); const viewSpecScript = Cast(this.props.Document.viewSpecScript, ScriptField); return viewSpecScript ? docs.filter(d => viewSpecScript.script.run({ doc: d }, console.log).result) : docs; diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 63e3e0431..080c722b2 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -291,7 +291,7 @@ export class DocumentView extends DocComponent(Docu SelectionManager.DeselectAll(); UndoManager.RunInBatch(() => this.onClickHandler!.script.run({ this: this.props.Document, - self: Cast(this.props.Document.expandedTemplate, Doc, null) || this.props.Document, + self: Cast(this.props.Document.rootDocument, Doc, null) || this.props.Document, containingCollection: this.props.ContainingCollectionDoc, shiftKey: e.shiftKey }, console.log) && !this.props.Document.dontSelect && !this.props.Document.isButton && this.select(false), "on click"); } else if (this.Document.type === DocumentType.BUTTON) { diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index f83beade3..bc43beab9 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -389,7 +389,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & const funcs: ContextMenuProps[] = []; this.props.Document.isTemplateDoc && funcs.push({ description: "Make Default Layout", event: async () => Doc.UserDoc().defaultTextLayout = new PrefetchProxy(this.props.Document), icon: "eye" }); funcs.push({ description: "Reset Default Layout", event: () => Doc.UserDoc().defaultTextLayout = undefined, icon: "eye" }); - !this.props.Document.expandedTemplate && funcs.push({ + !this.props.Document.rootDocument && funcs.push({ description: "Make Template", event: () => { this.props.Document.isTemplateDoc = makeTemplate(this.props.Document, true); Doc.AddDocToList(Cast(Doc.UserDoc().noteTypes, Doc, null), "data", this.props.Document); @@ -822,7 +822,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & } } - const selectOnLoad = (Cast(this.props.Document.expandedTemplate, Doc, null) || this.props.Document)[Id] === FormattedTextBox.SelectOnLoad; + const selectOnLoad = (Cast(this.props.Document.rootDocument, Doc, null) || this.props.Document)[Id] === FormattedTextBox.SelectOnLoad; if (selectOnLoad && !this.props.dontRegisterView) { FormattedTextBox.SelectOnLoad = ""; this.props.select(false); diff --git a/src/client/views/presentationview/PresElementBox.tsx b/src/client/views/presentationview/PresElementBox.tsx index 9329a5aa1..758795ed5 100644 --- a/src/client/views/presentationview/PresElementBox.tsx +++ b/src/client/views/presentationview/PresElementBox.tsx @@ -50,7 +50,7 @@ export class PresElementBox extends DocExtendableComponent and then arguments would be passed in the layout key as: // layout_mytemplate(somparam=somearg). - // then any references to @someparam would be rewritten as accesses to 'somearg' on the expandedTemplate + // then any references to @someparam would be rewritten as accesses to 'somearg' on the rootDocument export function expandTemplateLayout(templateLayoutDoc: Doc, targetDoc?: Doc, templateArgs?: string) { const args = templateArgs?.match(/\(([a-zA-Z0-9._\-]*)\)/)?.[1].replace("()", "") || StrCast(templateLayoutDoc.PARAMS); if (!args && !WillExpandTemplateLayout(templateLayoutDoc, targetDoc) || !targetDoc) return templateLayoutDoc; @@ -499,8 +499,8 @@ export namespace Doc { const newLayoutDoc = Doc.MakeDelegate(templateLayoutDoc, undefined, "[" + templateLayoutDoc.title + "]"); // the template's arguments are stored in params which is derefenced to find // the actual field key where the parameterized template data is stored. - newLayoutDoc[params] = args !== "..." ? args : ""; // ... signifies the layout has sub template(s) -- so we have to expand the layout for them so that they can get the correct 'expandedTemplate' field, but we don't need to reassign their params. it would be better if the 'expandedTemplate' field could be passed dynamically to avoid have to create instances - newLayoutDoc.expandedTemplate = targetDoc; + newLayoutDoc[params] = args !== "..." ? args : ""; // ... signifies the layout has sub template(s) -- so we have to expand the layout for them so that they can get the correct 'rootDocument' field, but we don't need to reassign their params. it would be better if the 'rootDocument' field could be passed dynamically to avoid have to create instances + newLayoutDoc.rootDocument = targetDoc; targetDoc[expandedLayoutFieldKey] = newLayoutDoc; const dataDoc = Doc.GetProto(targetDoc); newLayoutDoc.resolvedDataDoc = dataDoc; @@ -511,7 +511,7 @@ export namespace Doc { }), 0); } } - return expandedTemplateLayout instanceof Doc ? expandedTemplateLayout : undefined; // layout is undefined if the expandedTemplate is pending. + return expandedTemplateLayout instanceof Doc ? expandedTemplateLayout : undefined; // layout is undefined if the expandedTemplateLayout is pending. } // if the childDoc is a template for a field, then this will return the expanded layout with its data doc. @@ -882,10 +882,10 @@ export namespace Doc { Doc.AddDocToList((Doc.UserDoc().fieldTypes as Doc), "data", optionsCollection as Doc); } const options = optionsCollection as Doc; - const targetDoc = doc && Doc.GetProto(Cast(doc.expandedTemplate, Doc, null) || doc); - targetDoc && (targetDoc.backgroundColor = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.expandedTemplate||this)["${enumeratedFieldKey}"])?._backgroundColor || "white"`, undefined, { options })); - targetDoc && (targetDoc.color = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.expandedTemplate||this)["${enumeratedFieldKey}"]).color || "black"`, undefined, { options })); - targetDoc && (targetDoc.borderRounding = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.expandedTemplate||this)["${enumeratedFieldKey}"]).borderRounding`, undefined, { options })); + const targetDoc = doc && Doc.GetProto(Cast(doc.rootDocument, Doc, null) || doc); + targetDoc && (targetDoc.backgroundColor = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.rootDocument||this)["${enumeratedFieldKey}"])?._backgroundColor || "white"`, undefined, { options })); + targetDoc && (targetDoc.color = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.rootDocument||this)["${enumeratedFieldKey}"]).color || "black"`, undefined, { options })); + targetDoc && (targetDoc.borderRounding = ComputedField.MakeFunction(`options.data.find(doc => doc.title === (this.rootDocument||this)["${enumeratedFieldKey}"]).borderRounding`, undefined, { options })); enumerations.map(enumeration => { const found = DocListCast(options.data).find(d => d.title === enumeration.title); if (found) { diff --git a/src/new_fields/ScriptField.ts b/src/new_fields/ScriptField.ts index 954c22a8d..148886848 100644 --- a/src/new_fields/ScriptField.ts +++ b/src/new_fields/ScriptField.ts @@ -131,7 +131,7 @@ export class ScriptField extends ObjectField { export class ComputedField extends ScriptField { _lastComputedResult: any; //TODO maybe add an observable cache based on what is passed in for doc, considering there shouldn't really be that many possible values for doc - value = computedFn((doc: Doc) => this._lastComputedResult = this.script.run({ this: doc, self: Cast(doc.expandedTemplate, Doc, null) || doc, _last_: this._lastComputedResult }, console.log).result); + value = computedFn((doc: Doc) => this._lastComputedResult = this.script.run({ this: doc, self: Cast(doc.rootDocument, Doc, null) || doc, _last_: this._lastComputedResult }, console.log).result); public static MakeScript(script: string, params: object = {}) { const compiled = ScriptField.CompileScript(script, params, false); return compiled.compiled ? new ComputedField(compiled) : undefined; -- cgit v1.2.3-70-g09d2 From cf77e5f861c0927956e5453873839c81f0229374 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Wed, 1 Apr 2020 23:24:12 -0400 Subject: made it possible to link from one text selection to another --- src/client/util/DragManager.ts | 1 + src/client/views/DocumentButtonBar.tsx | 9 +++----- src/client/views/nodes/DocumentContentsView.tsx | 4 +++- src/client/views/nodes/DocumentView.tsx | 7 +++++- src/client/views/nodes/FormattedTextBox.tsx | 29 +++++++++++++++++++++++++ 5 files changed, 42 insertions(+), 8 deletions(-) (limited to 'src/client/views/nodes/FormattedTextBox.tsx') diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index 63a11c85a..8d3f6751e 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -148,6 +148,7 @@ export namespace DragManager { linkSourceDocument: Doc; dontClearTextBox?: boolean; linkDocument?: Doc; + linkDropCallback?: (data: LinkDragData) => void; } export class ColumnDragData { constructor(colKey: SchemaHeaderField) { diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index b0c701b65..b95cc6627 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -4,12 +4,10 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { action, computed, observable, runInAction } from "mobx"; import { observer } from "mobx-react"; import { Doc, DocListCast } from "../../new_fields/Doc"; -import { Id } from '../../new_fields/FieldSymbols'; import { RichTextField } from '../../new_fields/RichTextField'; import { NumCast, StrCast } from "../../new_fields/Types"; import { emptyFunction } from "../../Utils"; import { Pulls, Pushes } from '../apis/google_docs/GoogleApiClientUtils'; -import RichTextMenu from '../util/RichTextMenu'; import { UndoManager } from "../util/UndoManager"; import { CollectionDockingView, DockedFrameRenderer } from './collections/CollectionDockingView'; import { ParentDocSelector } from './collections/ParentDocumentSelector'; @@ -121,10 +119,9 @@ export class DocumentButtonBar extends React.Component<{ views: (DocumentView | const linkDoc = dropEv.linkDragData?.linkDocument as Doc; // equivalent to !dropEve.aborted since linkDocument is only assigned on a completed drop if (this.view0 && linkDoc) { Doc.GetProto(linkDoc).linkRelationship = "hyperlink"; - - const anchor2Title = linkDoc.anchor2 instanceof Doc ? StrCast(linkDoc.anchor2.title) : "-untitled-"; - const anchor2Id = linkDoc.anchor2 instanceof Doc ? linkDoc.anchor2[Id] : ""; - const text = RichTextMenu.Instance.MakeLinkToSelection(linkDoc[Id], anchor2Title, e.ctrlKey ? "onRight" : "inTab", anchor2Id); + dropEv.linkDragData?.linkDropCallback?.(dropEv.linkDragData); + runInAction(() => this.view0!._link = linkDoc); + setTimeout(action(() => this.view0!._link = undefined), 0); } linkDrag?.end(); }, diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index c250da874..da035a6ce 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -58,7 +58,9 @@ export class DocumentContentsView extends React.Component void, layoutKey: string, forceLayout?: string, - forceFieldKey?: string + forceFieldKey?: string, + hideOnLeave?:boolean, + makeLink?: () => Opt; }> { @computed get layout(): string { TraceMobx(); diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 7770a5caf..d8bbd88ce 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -40,7 +40,6 @@ import { ScriptBox } from '../ScriptBox'; import { ScriptingRepl } from '../ScriptingRepl'; import { DocumentContentsView } from "./DocumentContentsView"; import "./DocumentView.scss"; -import { FormattedTextBox } from './FormattedTextBox'; import React = require("react"); import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { SchemaHeaderField } from '../../../new_fields/SchemaHeaderField'; @@ -967,6 +966,7 @@ export class DocumentView extends DocComponent(Docu Document={this.props.Document} DataDoc={this.props.DataDoc} LayoutDoc={this.props.LayoutDoc} + makeLink={this.makeLink} fitToBox={this.props.fitToBox} LibraryPath={this.props.LibraryPath} addDocument={this.props.addDocument} @@ -1002,6 +1002,11 @@ export class DocumentView extends DocComponent(Docu const ept = Doc.AreProtosEqual(this.props.Document, Cast(linkDoc.anchor1, Doc) as Doc) ? linkDoc.anchor1_timecode : linkDoc.anchor2_timecode; return anchor.type === DocumentType.AUDIO && NumCast(ept) ? false : true; } +c + @observable _link:Opt; + makeLink = () => { + return this._link; + } @computed get innards() { TraceMobx(); diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index bc43beab9..241345f3e 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -54,6 +54,7 @@ library.add(faSmile, faTextHeight, faUpload); export interface FormattedTextBoxProps { hideOnLeave?: boolean; + makeLink?: () => Opt; } const richTextSchema = createSchema({ @@ -91,6 +92,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & private _pullReactionDisposer: Opt; private _pushReactionDisposer: Opt; private _buttonBarReactionDisposer: Opt; + private _linkMakerDisposer: Opt; private _scrollDisposer: Opt; private dropDisposer?: DragManager.DragDropDisposer; @@ -282,8 +284,16 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & e.stopPropagation(); // } } // otherwise, fall through to outer collection to handle drop + } else if (de.complete.linkDragData) { + de.complete.linkDragData.linkDropCallback = this.linkDrop; } } + linkDrop = (data: DragManager.LinkDragData) => { + const linkDoc = data.linkDocument!; + const anchor1Title = linkDoc.anchor1 instanceof Doc ? StrCast(linkDoc.anchor1.title) : "-untitled-"; + const anchor1Id = linkDoc.anchor1 instanceof Doc ? linkDoc.anchor1[Id] : ""; + this.makeLinkToSelection(linkDoc[Id], anchor1Title, "onRight", anchor1Id) + } getNodeEndpoints(context: Node, node: Node): { from: number, to: number } | null { let offset = 0; @@ -513,6 +523,13 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & }; } + makeLinkToSelection(linkDocId: string, title: string, location: string, targetDocId: string) { + if (this._editorView) { + const link = this._editorView.state.schema.marks.link.create({ href: Utils.prepend("/doc/" + linkDocId), title: title, location: location, linkId: linkDocId, targetId: targetDocId }); + this._editorView.dispatch(this._editorView.state.tr.removeMark(this._editorView.state.selection.from, this._editorView.state.selection.to, this._editorView.state.schema.marks.link). + addMark(this._editorView.state.selection.from, this._editorView.state.selection.to, link)); + } + } componentDidMount() { this._buttonBarReactionDisposer = reaction( () => DocumentButtonBar.Instance, @@ -523,6 +540,17 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & } } ); + this._linkMakerDisposer = reaction( + () => this.props.makeLink?.(), + (linkDoc: Opt) => { + if (linkDoc) { + const anchor2Title = linkDoc.anchor2 instanceof Doc ? StrCast(linkDoc.anchor2.title) : "-untitled-"; + const anchor2Id = linkDoc.anchor2 instanceof Doc ? linkDoc.anchor2[Id] : ""; + this.makeLinkToSelection(linkDoc[Id], anchor2Title, "onRight", anchor2Id); + } + }, + { fireImmediately: true } + ); this._reactionDisposer = reaction( () => { @@ -858,6 +886,7 @@ export class FormattedTextBox extends DocAnnotatableComponent<(FieldViewProps & this._searchReactionDisposer?.(); this._recordReactionDisposer?.(); this._buttonBarReactionDisposer?.(); + this._linkMakerDisposer?.(); this._editorView?.destroy(); } -- cgit v1.2.3-70-g09d2 From 50552174123eb5622821de5f848e6e70c7346214 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik 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/nodes/FormattedTextBox.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/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/nodes/FormattedTextBox.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