From 61aa3a0a34a647a7f414fbeb72345675a5154433 Mon Sep 17 00:00:00 2001 From: ab Date: Mon, 18 Feb 2019 18:18:53 -0500 Subject: title --- src/client/views/DocumentDecorations.scss | 8 +++++++- src/client/views/DocumentDecorations.tsx | 17 ++++++++++++----- src/client/views/Main.tsx | 2 +- 3 files changed, 20 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index e8b93a18b..5c99c52ea 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -2,7 +2,7 @@ position: absolute; display: grid; z-index: 1000; - grid-template-rows: 20px 1fr 20px; + grid-template-rows: 20px 20px 1fr 20px; grid-template-columns: 20px 1fr 20px; pointer-events: none; #documentDecorations-centerCont { @@ -29,4 +29,10 @@ #documentDecorations-rightResizer { cursor: ew-resize; } + .title{ + background: lightblue; + grid-column-start:1; + grid-column-end: 4; + cursor: ne-resize; + } } \ No newline at end of file diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 7efaa5533..3e674e5ae 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -4,6 +4,7 @@ import { SelectionManager } from "../util/SelectionManager"; import { observer } from "mobx-react"; import './DocumentDecorations.scss' import { CollectionFreeFormView } from "./collections/CollectionFreeFormView"; +import ContentEditable from 'react-contenteditable' @observer export class DocumentDecorations extends React.Component { @@ -14,10 +15,14 @@ export class DocumentDecorations extends React.Component { constructor(props: Readonly<{}>) { super(props) - DocumentDecorations.Instance = this + this.state = { html: "hi" }; } + // handleChange = evt => { + // this.setState({ html: evt.target.value }); + // }; + @computed get Bounds(): { x: number, y: number, b: number, r: number } { return SelectionManager.SelectedDocuments().reduce((bounds, element) => { @@ -47,6 +52,7 @@ export class DocumentDecorations extends React.Component { e.stopPropagation(); if (e.button === 0) { this._isPointerDown = true; + console.log("Pointer down"); this._resizer = e.currentTarget.id; document.removeEventListener("pointermove", this.onPointerMove); document.addEventListener("pointermove", this.onPointerMove); @@ -133,12 +139,14 @@ export class DocumentDecorations extends React.Component { var bounds = this.Bounds; return (
+ {/**/} +
{document.title}
e.preventDefault()}>
e.preventDefault()}>
e.preventDefault()}>
@@ -148,7 +156,6 @@ export class DocumentDecorations extends React.Component {
e.preventDefault()}>
e.preventDefault()}>
e.preventDefault()}>
-
) } diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index ba92cc17e..b9f084b75 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -43,7 +43,7 @@ document.addEventListener("pointerdown", action(function (e: PointerEvent) { let doc1 = Documents.TextDocument({ title: "hello", width: 400, height: 300 }); let doc2 = doc1.MakeDelegate(); doc2.Set(KS.X, new NumberField(150)); - doc2.Set(KS.Y, new NumberField(20)); + doc2.Set(KS.Y, new NumberField(500)); let doc3 = Documents.ImageDocument("https://psmag.com/.image/t_share/MTMyNzc2NzM1MDY1MjgzMDM4/shutterstock_151341212jpg.jpg", { x: 450, y: 100, title: "cat 1", width: 606, height: 386, nativeWidth: 606, nativeHeight: 386 }); -- cgit v1.2.3-70-g09d2 From 2886c2859bfc6ad396fc4bab3e90cf18da5442f1 Mon Sep 17 00:00:00 2001 From: ab Date: Mon, 18 Feb 2019 19:01:17 -0500 Subject: input title --- src/client/views/DocumentDecorations.scss | 2 +- src/client/views/DocumentDecorations.tsx | 15 ++++++++------- 2 files changed, 9 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 5c99c52ea..9bafbda44 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -33,6 +33,6 @@ background: lightblue; grid-column-start:1; grid-column-end: 4; - cursor: ne-resize; + pointer-events: auto; } } \ No newline at end of file diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index dcfedfcd1..b44e32c52 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -8,7 +8,7 @@ import ContentEditable from 'react-contenteditable' import { KeyStore } from '../../fields/Key' @observer -export class DocumentDecorations extends React.Component { +export class DocumentDecorations extends React.Component<{}, { value: string }> { static Instance: DocumentDecorations private _resizer = "" private _isPointerDown = false; @@ -17,12 +17,13 @@ export class DocumentDecorations extends React.Component { constructor(props: Readonly<{}>) { super(props) DocumentDecorations.Instance = this - this.state = { html: "hi" }; + this.state = { value: document.title }; + this.handleChange = this.handleChange.bind(this); } - // handleChange = evt => { - // this.setState({ html: evt.target.value }); - // }; + handleChange(event: any) { + this.setState({ value: event.target.value }); + }; @computed get Bounds(): { x: number, y: number, b: number, r: number } { @@ -146,8 +147,8 @@ export class DocumentDecorations extends React.Component { top: bounds.y - 20 - 20, opacity: this.opacity }}> - {/**/} -
{document.title}
+ + {/*
{document.title}
*/}
e.preventDefault()}>
e.preventDefault()}>
e.preventDefault()}>
-- cgit v1.2.3-70-g09d2 From 12d20ab1b9b843d816bde445d9b67b3aa6abc6ae Mon Sep 17 00:00:00 2001 From: ab Date: Tue, 19 Feb 2019 18:17:17 -0500 Subject: reference created --- src/client/views/DocumentDecorations.tsx | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index b44e32c52..4f16453df 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -13,18 +13,34 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> private _resizer = "" private _isPointerDown = false; @observable private _opacity = 1; + private keyinput: React.RefObject; constructor(props: Readonly<{}>) { super(props) DocumentDecorations.Instance = this this.state = { value: document.title }; this.handleChange = this.handleChange.bind(this); + this.keyinput = React.createRef(); } handleChange(event: any) { this.setState({ value: event.target.value }); + console.log("Input box has changed") }; + enterPressed(e: any) { + var key = e.keyCode || e.which; + // enter pressed + if (key == 13) { + var text = e.target.value; + if (text[0] == '#') { + console.log("hashtag"); + // TODO: Change field with switch statement + } + e.target.blur(); + } + } + @computed get Bounds(): { x: number, y: number, b: number, r: number } { return SelectionManager.SelectedDocuments().reduce((bounds, element) => { @@ -147,7 +163,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> top: bounds.y - 20 - 20, opacity: this.opacity }}> - + {/*
{document.title}
*/}
e.preventDefault()}>
e.preventDefault()}>
-- cgit v1.2.3-70-g09d2 From 381b008c9f860265c0a160104252eee76057bd6b Mon Sep 17 00:00:00 2001 From: ab Date: Sat, 9 Mar 2019 16:09:57 -0500 Subject: stage --- src/client/views/DocumentDecorations.tsx | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 0a126de1f..280fad2e5 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -184,12 +184,8 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> width: (bounds.r - bounds.x + 20 + 20) + "px", height: (bounds.b - bounds.y + 40 + 20) + "px", left: bounds.x - 20, -<<<<<<< HEAD top: bounds.y - 20 - 20, - opacity: this.opacity -======= - top: bounds.y - 20, ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 + opacity: this._opacity }}> {/*
{document.title}
*/} -- cgit v1.2.3-70-g09d2 From 70676c2456f7f330869d6009b52456aba10e7e97 Mon Sep 17 00:00:00 2001 From: ab Date: Sat, 9 Mar 2019 16:17:34 -0500 Subject: idk --- src/client/views/DocumentDecorations.tsx | 9 --------- 1 file changed, 9 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 280fad2e5..7bddc298e 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -3,26 +3,17 @@ import React = require("react"); import { SelectionManager } from "../util/SelectionManager"; import { observer } from "mobx-react"; import './DocumentDecorations.scss' -<<<<<<< HEAD import { CollectionFreeFormView } from "./collections/CollectionFreeFormView"; import ContentEditable from 'react-contenteditable' import { KeyStore } from '../../fields/Key' -======= -import { KeyStore } from '../../fields/KeyStore' -import { NumberField } from "../../fields/NumberField"; ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 @observer export class DocumentDecorations extends React.Component<{}, { value: string }> { static Instance: DocumentDecorations private _resizer = "" private _isPointerDown = false; -<<<<<<< HEAD @observable private _opacity = 1; private keyinput: React.RefObject; -======= - @observable private _hidden = false; ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 constructor(props: Readonly<{}>) { super(props) -- cgit v1.2.3-70-g09d2 From 8d2e07367afd3497cc474d611554eea27d706f0c Mon Sep 17 00:00:00 2001 From: ab Date: Sat, 9 Mar 2019 19:06:41 -0500 Subject: key commands work --- src/client/views/DocumentDecorations.tsx | 40 +++++++++++++++++++++++++------- src/client/views/Main.tsx | 39 ++++--------------------------- 2 files changed, 35 insertions(+), 44 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 7bddc298e..3b2cd2626 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -1,11 +1,14 @@ -import { observable, computed } from "mobx"; +import { observable, computed, action } from "mobx"; import React = require("react"); import { SelectionManager } from "../util/SelectionManager"; import { observer } from "mobx-react"; import './DocumentDecorations.scss' import { CollectionFreeFormView } from "./collections/CollectionFreeFormView"; import ContentEditable from 'react-contenteditable' -import { KeyStore } from '../../fields/Key' +import { KeyStore } from "../../fields/KeyStore"; +import { NumberField } from "../../fields/NumberField"; +import { Document } from "../../fields/Document"; +import { DocumentView } from "./nodes/DocumentView"; @observer export class DocumentDecorations extends React.Component<{}, { value: string }> { @@ -14,6 +17,9 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> private _isPointerDown = false; @observable private _opacity = 1; private keyinput: React.RefObject; + @observable private _documents: DocumentView[] = []; + //@observable private _title: string = this._documents[0].props.Document.Title; + @observable private _title: string = document.title; constructor(props: Readonly<{}>) { super(props) @@ -23,26 +29,42 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> this.keyinput = React.createRef(); } - handleChange(event: any) { - this.setState({ value: event.target.value }); - console.log("Input box has changed") + @action + handleChange = (event: any) => { + //this.setState({ value: event.target.value }); + this._title = event.target.value; + console.log("Input box has changed"); }; - enterPressed(e: any) { + @action + enterPressed = (e: any) => { var key = e.keyCode || e.which; // enter pressed if (key == 13) { var text = e.target.value; if (text[0] == '#') { - console.log("hashtag"); + let command = text.slice(1, text.length); + if (command == "Title" || command == "title") { + this._title = this._documents[0].props.Document.Title; + } + else if (command == "Width" || command == "width") { + this._title = this._documents[0].props.Document.GetNumber(KeyStore.Width, 0).toString(); + } + else { + this._title = "undefined key"; + } // TODO: Change field with switch statement } + else { + this._title = document.title; + } e.target.blur(); } } @computed get Bounds(): { x: number, y: number, b: number, r: number } { + this._documents = SelectionManager.SelectedDocuments(); return SelectionManager.SelectedDocuments().reduce((bounds, documentView) => { if (documentView.props.isTopMost) { return bounds; @@ -61,6 +83,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> @computed public get Hidden() { return this._hidden; } public set Hidden(value: boolean) { this._hidden = value; } + private _hidden: boolean = false; onPointerDown = (e: React.PointerEvent): void => { e.stopPropagation(); @@ -178,8 +201,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> top: bounds.y - 20 - 20, opacity: this._opacity }}> - - {/*
{document.title}
*/} +
e.preventDefault()}>
e.preventDefault()}>
e.preventDefault()}>
diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index 4a3710e74..6e5b84075 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -18,6 +18,9 @@ import { DocumentDecorations } from './DocumentDecorations'; import { DocumentView } from './nodes/DocumentView'; import "./Main.scss"; import { InkingControl } from './InkingControl'; +import { NumberField } from '../../fields/NumberField'; +import { TextField } from '../../fields/TextField'; +import { ListField } from '../../fields/ListField'; configure({ enforceActions: "observed" }); // causes errors to be generated when modifying an observable outside of an action @@ -30,40 +33,6 @@ document.addEventListener("pointerdown", action(function (e: PointerEvent) { }), true) -<<<<<<< HEAD -//runInAction(() => -{ - let doc1 = Documents.TextDocument({ title: "hello", width: 400, height: 300 }); - let doc2 = doc1.MakeDelegate(); - doc2.Set(KS.X, new NumberField(150)); - doc2.Set(KS.Y, new NumberField(500)); - let doc3 = Documents.ImageDocument("https://psmag.com/.image/t_share/MTMyNzc2NzM1MDY1MjgzMDM4/shutterstock_151341212jpg.jpg", { - x: 450, y: 100, title: "dog", width: 606, height: 386, nativeWidth: 606, nativeHeight: 386 - }); - //doc3.Set(KeyStore.Data, new ImageField); - const schemaDocs = Array.from(Array(5).keys()).map(v => Documents.ImageDocument("https://psmag.com/.image/t_share/MTMyNzc2NzM1MDY1MjgzMDM4/shutterstock_151341212jpg.jpg", { - x: 50 + 100 * v, y: 50, width: 100, height: 100, title: "cat" + v, nativeWidth: 606, nativeHeight: 386 - })); - schemaDocs.push(doc3); - schemaDocs[0].SetData(KS.Author, "Tyler", TextField); - schemaDocs[4].SetData(KS.Author, "Bob", TextField); - schemaDocs.push(doc2); - const doc7 = Documents.SchemaDocument(schemaDocs) - const docset = [doc1, doc2, doc3, doc7]; - let doc4 = Documents.CollectionDocument(docset, { - x: 0, y: 400, title: "mini collection" - }); - // let doc5 = Documents.ImageDocument("https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg", { - // x: 650, y: 500, width: 600, height: 600, title: "cat 2" - // }); - let docset2 = [doc3, doc4, doc2]; - let doc6 = Documents.CollectionDocument(docset2, { - x: 350, y: 100, width: 600, height: 600, title: "docking collection" - }); - let mainNodes = null;// mainContainer.GetFieldT(KeyStore.Data, ListField); - if (!mainNodes) { - mainNodes = new ListField(); -======= const mainDocId = "mainDoc"; let mainContainer: Document; let mainfreeform: Document; @@ -83,7 +52,6 @@ Documents.initProtos(mainDocId, (res?: Document) => { mainContainer.SetText(KeyStore.Data, JSON.stringify(dockingLayout)); mainContainer.Set(KeyStore.ActiveFrame, mainfreeform); }, 0); ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } let imgurl = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg"; @@ -141,3 +109,4 @@ Documents.initProtos(mainDocId, (res?: Document) => { ), document.getElementById('root')); }) + -- cgit v1.2.3-70-g09d2 From 43a0768690caa89c606dd5d296d3cc8825c1702b Mon Sep 17 00:00:00 2001 From: ab Date: Mon, 11 Mar 2019 19:59:34 -0400 Subject: title binding works --- package-lock.json | 832 ++++++++++--------------------- package.json | 2 +- src/client/views/DocumentDecorations.tsx | 51 +- 3 files changed, 287 insertions(+), 598 deletions(-) (limited to 'src') diff --git a/package-lock.json b/package-lock.json index 3ebd0a0d0..3422cd9f7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,10 +9,7 @@ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.3.1.tgz", "integrity": "sha512-7jGW8ppV0ant637pIqAcFfQDDH1orEPGJb8aXfUozuCU3QqX7rX4DA8iwrbPrR1hcH0FTTHz47yQnk+bl5xHQA==", "requires": { -<<<<<<< HEAD "regenerator-runtime": "^0.12.0" -======= - "regenerator-runtime": "0.12.1" }, "dependencies": { "regenerator-runtime": { @@ -20,7 +17,6 @@ "resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.12.1.tgz", "integrity": "sha512-odxIc1/vDlo4iZcfXqRYFj0vpXFNoGdKMAUieAlFYO6m/nl5e9KR/beGf41z4a1FI+aQgtjhuaSlDxQ0hmkrHg==" } ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "@fortawesome/fontawesome-common-types": { @@ -33,7 +29,7 @@ "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-free-solid/-/fontawesome-free-solid-5.0.13.tgz", "integrity": "sha512-b+krVnqkdDt52Yfev0x0ZZgtxBQsLw00Zfa3uaVWIDzpNZVtrEXuxldUSUaN/ihgGhSNi8VpvDAdNPVgCKOSxw==", "requires": { - "@fortawesome/fontawesome-common-types": "0.1.7" + "@fortawesome/fontawesome-common-types": "^0.1.7" }, "dependencies": { "@fortawesome/fontawesome-common-types": { @@ -48,11 +44,7 @@ "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-svg-core/-/fontawesome-svg-core-1.2.15.tgz", "integrity": "sha512-M/sHyl4g2VBtKYkay1Z+XImMyTVcaBPmehYtPw4HKD9zg2E7eovB7Yx98aUfZjPbroGqa+IL4/+KhWBMOGlHIQ==", "requires": { -<<<<<<< HEAD - "@fortawesome/fontawesome-common-types": "^0.2.14" -======= - "@fortawesome/fontawesome-common-types": "0.2.15" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 + "@fortawesome/fontawesome-common-types": "^0.2.15" } }, "@fortawesome/free-solid-svg-icons": { @@ -60,7 +52,7 @@ "resolved": "https://registry.npmjs.org/@fortawesome/free-solid-svg-icons/-/free-solid-svg-icons-5.7.2.tgz", "integrity": "sha512-iujcXMyAvIbWM8W3jkOLpvJbR+rPpdN1QyqhZeJaLRdHPH4JmuovIAYP4vx5Sa1csZVXfRD1eDWqVZ/jGM620A==", "requires": { - "@fortawesome/fontawesome-common-types": "0.2.15" + "@fortawesome/fontawesome-common-types": "^0.2.15" } }, "@fortawesome/react-fontawesome": { @@ -68,8 +60,8 @@ "resolved": "https://registry.npmjs.org/@fortawesome/react-fontawesome/-/react-fontawesome-0.1.4.tgz", "integrity": "sha512-GwmxQ+TK7PEdfSwvxtGnMCqrfEm0/HbRHArbUudsYiy9KzVCwndxa2KMcfyTQ8El0vROrq8gOOff09RF1oQe8g==", "requires": { - "humps": "2.0.1", - "prop-types": "15.6.2" + "humps": "^2.0.1", + "prop-types": "^15.5.10" } }, "@icons/material": { @@ -92,7 +84,7 @@ "resolved": "https://registry.npmjs.org/@types/babylon/-/babylon-6.16.5.tgz", "integrity": "sha512-xH2e58elpj1X4ynnKp9qSnWlsRTIs6n3tgLGNfwAGHwePw0mulHQllV34n0T25uYSu1k0hRKkWXF890B1yS47w==", "requires": { - "@types/babel-types": "7.0.6" + "@types/babel-types": "*" } }, "@types/bcrypt-nodejs": { @@ -110,13 +102,8 @@ "resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.17.0.tgz", "integrity": "sha512-a2+YeUjPkztKJu5aIF2yArYFQQp8d51wZ7DavSHjFuY1mqVgidGyzEQ41JIVNy82fXj8yPgy2vJmfIywgESW6w==", "requires": { -<<<<<<< HEAD "@types/connect": "*", "@types/node": "*" -======= - "@types/connect": "3.4.32", - "@types/node": "10.12.29" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "@types/bson": { @@ -124,7 +111,7 @@ "resolved": "https://registry.npmjs.org/@types/bson/-/bson-4.0.0.tgz", "integrity": "sha512-pq/rqJwJWkbS10crsG5bgnrisL8pML79KlMKQMoQwLUjlPAkrUHMvHJ3oGwE7WHR61Lv/nadMwXVAD2b+fpD8Q==", "requires": { - "@types/node": "10.12.29" + "@types/node": "*" } }, "@types/caseless": { @@ -143,10 +130,7 @@ "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.32.tgz", "integrity": "sha512-4r8qa0quOvh7lGD0pre62CAb1oni1OO6ecJLGCezTmhQ8Fz50Arx9RUszryR8KlgK6avuSXvviL6yWyViQABOg==", "requires": { -<<<<<<< HEAD "@types/node": "*" -======= - "@types/node": "10.12.29" } }, "@types/connect-flash": { @@ -154,8 +138,7 @@ "resolved": "https://registry.npmjs.org/@types/connect-flash/-/connect-flash-0.0.34.tgz", "integrity": "sha512-QC93TwnTZ0sk//bfT81o7U4GOedbOZAcgvqi0v1vJqCESC8tqIVnhzB1CHiAUBUWFjoxG5JQF0TYaNa6DMb6Ig==", "requires": { - "@types/express": "4.16.1" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 + "@types/express": "*" } }, "@types/express": { @@ -173,8 +156,8 @@ "resolved": "https://registry.npmjs.org/@types/express-flash/-/express-flash-0.0.0.tgz", "integrity": "sha512-zs1xXRIZOjghUBriJPSnhPmfDpqf/EQxT21ggi/9XZ9/RHYrUi+5vK2jnQrP2pD1abbuZvm7owLICiNCLBQzEQ==", "requires": { - "@types/connect-flash": "0.0.34", - "@types/express": "4.16.1" + "@types/connect-flash": "*", + "@types/express": "*" } }, "@types/express-serve-static-core": { @@ -182,13 +165,8 @@ "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.16.1.tgz", "integrity": "sha512-QgbIMRU1EVRry5cIu1ORCQP4flSYqLM1lS5LYyGWfKnFT3E58f0gKto7BR13clBFVrVZ0G0rbLZ1hUpSkgQQOA==", "requires": { -<<<<<<< HEAD "@types/node": "*", "@types/range-parser": "*" -======= - "@types/node": "10.12.29", - "@types/range-parser": "1.2.3" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "@types/express-session": { @@ -196,8 +174,8 @@ "resolved": "https://registry.npmjs.org/@types/express-session/-/express-session-1.15.12.tgz", "integrity": "sha512-DHZXzWy6Nu5Ng0syXUiVFRpZ6/1DOXoTCWa6RG3itGrub2ioBYvgtDbkT6VHHNo3iOdHRROyWANsMBJVaflblQ==", "requires": { - "@types/express": "4.16.1", - "@types/node": "10.12.29" + "@types/express": "*", + "@types/node": "*" } }, "@types/express-validator": { @@ -205,7 +183,7 @@ "resolved": "https://registry.npmjs.org/@types/express-validator/-/express-validator-3.0.0.tgz", "integrity": "sha512-LusnB0YhTXpBT25PXyGPQlK7leE1e41Vezq1hHEUwjfkopM1Pkv2X2Ppxqh9c+w/HZ6Udzki8AJotKNjDTGdkQ==", "requires": { - "express-validator": "5.3.1" + "express-validator": "*" } }, "@types/form-data": { @@ -213,7 +191,7 @@ "resolved": "https://registry.npmjs.org/@types/form-data/-/form-data-2.2.1.tgz", "integrity": "sha512-JAMFhOaHIciYVh8fb5/83nmuO/AHwmto+Hq7a9y8FzLDcC1KCU344XDOMEmahnrTFlHjgh4L0WJFczNIX2GxnQ==", "requires": { - "@types/node": "10.12.29" + "@types/node": "*" } }, "@types/jquery": { @@ -229,7 +207,7 @@ "resolved": "https://registry.npmjs.org/@types/jsonwebtoken/-/jsonwebtoken-8.3.0.tgz", "integrity": "sha512-YKnUTR4VxwljbPORPrRon9E3uel1aD8nUdvzqArCCdMTWPvo0gnI2UZkwIHN2QATdj6HYXV/Iq3/KcecAO42Ww==", "requires": { - "@types/node": "10.12.29" + "@types/node": "*" } }, "@types/lodash": { @@ -249,11 +227,7 @@ "integrity": "sha512-j5AcZo7dbMxHoOimcHEIh0JZe5e1b8q8AqGSpZJrYc7xOgCIP79cIjTdx5jSDLtySnQDwkDTqwlC7Xw7uXw7qg==", "dev": true, "requires": { -<<<<<<< HEAD "@types/node": "*" -======= - "@types/node": "10.12.29" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "@types/mime": { @@ -272,8 +246,8 @@ "resolved": "https://registry.npmjs.org/@types/mongodb/-/mongodb-3.1.20.tgz", "integrity": "sha512-tl9iKbhM8d9BQjhB/9L4KuyLxfEn9Weq6cBuM8C06fIuUJyyfk+5wlfwzvltvssuxjGY1GiHvZHmSTK8kJ1zwg==", "requires": { - "@types/bson": "4.0.0", - "@types/node": "10.12.29" + "@types/bson": "*", + "@types/node": "*" } }, "@types/mongoose": { @@ -281,8 +255,8 @@ "resolved": "https://registry.npmjs.org/@types/mongoose/-/mongoose-5.3.20.tgz", "integrity": "sha512-KXD/wRaUkxA7NwU+0yp60WEFFmkhzJ4idGawycjUxFMTANIM7ZqlZsoXhHu3p33cg450D8PuwtAorFUwuMXLwA==", "requires": { - "@types/mongodb": "3.1.20", - "@types/node": "10.12.29" + "@types/mongodb": "*", + "@types/node": "*" } }, "@types/node": { @@ -300,7 +274,7 @@ "resolved": "https://registry.npmjs.org/@types/passport/-/passport-1.0.0.tgz", "integrity": "sha512-R2FXqM+AgsMIym0PuKj08Ybx+GR6d2rU3b1/8OcHolJ+4ga2pRPX105wboV6hq1AJvMo2frQzYKdqXS5+4cyMw==", "requires": { - "@types/express": "4.16.1" + "@types/express": "*" } }, "@types/passport-local": { @@ -308,9 +282,9 @@ "resolved": "https://registry.npmjs.org/@types/passport-local/-/passport-local-1.0.33.tgz", "integrity": "sha512-+rn6ZIxje0jZ2+DAiWFI8vGG7ZFKB0hXx2cUdMmudSWsigSq6ES7Emso46r4HJk0qCgrZVfI8sJiM7HIYf4SbA==", "requires": { - "@types/express": "4.16.1", - "@types/passport": "1.0.0", - "@types/passport-strategy": "0.2.35" + "@types/express": "*", + "@types/passport": "*", + "@types/passport-strategy": "*" } }, "@types/passport-strategy": { @@ -318,8 +292,8 @@ "resolved": "https://registry.npmjs.org/@types/passport-strategy/-/passport-strategy-0.2.35.tgz", "integrity": "sha512-o5D19Jy2XPFoX2rKApykY15et3Apgax00RRLf0RUotPDUsYrQa7x4howLYr9El2mlUApHmCMv5CZ1IXqKFQ2+g==", "requires": { - "@types/express": "4.16.1", - "@types/passport": "1.0.0" + "@types/express": "*", + "@types/passport": "*" } }, "@types/prop-types": { @@ -376,9 +350,9 @@ "resolved": "https://registry.npmjs.org/@types/prosemirror-schema-list/-/prosemirror-schema-list-1.0.1.tgz", "integrity": "sha512-+iUYq+pj2wVHSThj0MjNDzkkGwq8aDQ6j0UJK8a0cNCL8v44Ftcx1noGPtBIEUJgitH960VnfBNoTWfQoQZfRA==", "requires": { - "@types/orderedmap": "1.0.0", - "@types/prosemirror-model": "1.7.0", - "@types/prosemirror-state": "1.2.1" + "@types/orderedmap": "*", + "@types/prosemirror-model": "*", + "@types/prosemirror-state": "*" } }, "@types/prosemirror-state": { @@ -433,7 +407,7 @@ "resolved": "https://registry.npmjs.org/@types/react-color/-/react-color-2.14.1.tgz", "integrity": "sha512-mIHKhPpN0tTnfmDXBzMw68ReFkDyzQWRUcDmJD13UA8L7vfjWATIZu1oM1BKW1eJdrUDdXFI6Cu5mJrV5Z/ZPw==", "requires": { - "@types/react": "16.8.1" + "@types/react": "*" } }, "@types/react-dom": { @@ -466,10 +440,10 @@ "resolved": "https://registry.npmjs.org/@types/request/-/request-2.48.1.tgz", "integrity": "sha512-ZgEZ1TiD+KGA9LiAAPPJL68Id2UWfeSO62ijSXZjFJArVV+2pKcsVHmrcu+1oiE3q6eDGiFiSolRc4JHoerBBg==", "requires": { - "@types/caseless": "0.12.1", - "@types/form-data": "2.2.1", - "@types/node": "10.12.29", - "@types/tough-cookie": "2.3.5" + "@types/caseless": "*", + "@types/form-data": "*", + "@types/node": "*", + "@types/tough-cookie": "*" } }, "@types/serve-static": { @@ -491,7 +465,7 @@ "resolved": "https://registry.npmjs.org/@types/socket.io/-/socket.io-2.1.2.tgz", "integrity": "sha512-Ind+4qMNfQ62llyB4IMs1D8znMEBsMKohZBPqfBUIXqLQ9bdtWIbNTBWwtdcBWJKnokMZGcmWOOKslatni5vtA==", "requires": { - "@types/node": "10.12.29" + "@types/node": "*" } }, "@types/socket.io-client": { @@ -537,11 +511,7 @@ "resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-3.4.4.tgz", "integrity": "sha512-tPIgT0GUmdJQNSHxp0X2jnpQfBSTfGxUMc/2CXBU2mnyTFVYVa2ojpoQ74w0U2yn2vw3jnC640+77lkFFpdVDw==", "requires": { -<<<<<<< HEAD "@types/node": "*" -======= - "@types/node": "10.12.29" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "@types/webpack": { @@ -549,19 +519,11 @@ "resolved": "https://registry.npmjs.org/@types/webpack/-/webpack-4.4.24.tgz", "integrity": "sha512-yg99CjvB7xZ/iuHrsZ7dkGKoq/FRDzqLzAxKh2EmTem6FWjzrty4FqCqBYuX5z+MFwSaaQGDAX4Q9HQkLjGLnQ==", "requires": { -<<<<<<< HEAD "@types/anymatch": "*", "@types/node": "*", "@types/tapable": "*", "@types/uglify-js": "*", "source-map": "^0.6.0" -======= - "@types/anymatch": "1.3.1", - "@types/node": "10.12.29", - "@types/tapable": "1.0.4", - "@types/uglify-js": "3.0.4", - "source-map": "0.6.1" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 }, "dependencies": { "source-map": { @@ -807,7 +769,7 @@ "resolved": "https://registry.npmjs.org/acorn-globals/-/acorn-globals-3.1.0.tgz", "integrity": "sha1-/YJw9x+7SZawBPqIDuXUZXOnMb8=", "requires": { - "acorn": "4.0.13" + "acorn": "^4.0.4" }, "dependencies": { "acorn": { @@ -856,9 +818,9 @@ "resolved": "https://registry.npmjs.org/align-text/-/align-text-0.1.4.tgz", "integrity": "sha1-DNkKVhCT810KmSVsIrcGlDP60Rc=", "requires": { - "kind-of": "3.2.2", - "longest": "1.0.1", - "repeat-string": "1.6.1" + "kind-of": "^3.0.2", + "longest": "^1.0.1", + "repeat-string": "^1.5.2" }, "dependencies": { "kind-of": { @@ -866,7 +828,7 @@ "resolved": "https://registry.npmjs.org/kind-of/-/kind-of-3.2.2.tgz", "integrity": "sha1-MeohpzS6ubuw8yRm2JOupR5KPGQ=", "requires": { - "is-buffer": "1.1.6" + "is-buffer": "^1.1.5" } } } @@ -1179,8 +1141,8 @@ "resolved": "https://registry.npmjs.org/babel-runtime/-/babel-runtime-6.26.0.tgz", "integrity": "sha1-llxwWGaOgrVde/4E/yM3vItWR/4=", "requires": { - "core-js": "2.6.4", - "regenerator-runtime": "0.11.1" + "core-js": "^2.4.0", + "regenerator-runtime": "^0.11.0" }, "dependencies": { "regenerator-runtime": { @@ -1195,10 +1157,10 @@ "resolved": "https://registry.npmjs.org/babel-types/-/babel-types-6.26.0.tgz", "integrity": "sha1-o7Bz+Uq0nrb6Vc1lInozQ4BjJJc=", "requires": { - "babel-runtime": "6.26.0", - "esutils": "2.0.2", - "lodash": "4.17.11", - "to-fast-properties": "1.0.3" + "babel-runtime": "^6.26.0", + "esutils": "^2.0.2", + "lodash": "^4.17.4", + "to-fast-properties": "^1.0.3" } }, "babylon": { @@ -1711,8 +1673,8 @@ "resolved": "https://registry.npmjs.org/center-align/-/center-align-0.1.3.tgz", "integrity": "sha1-qg0yYptu6XIgBBHL1EYckHvCt60=", "requires": { - "align-text": "0.1.4", - "lazy-cache": "1.0.4" + "align-text": "^0.1.3", + "lazy-cache": "^1.0.3" } }, "chai": { @@ -1746,7 +1708,7 @@ "resolved": "https://registry.npmjs.org/character-parser/-/character-parser-2.2.0.tgz", "integrity": "sha1-x84o821LzZdE5f/CxfzeHHMmH8A=", "requires": { - "is-regex": "1.0.4" + "is-regex": "^1.0.3" } }, "check-error": { @@ -1837,7 +1799,7 @@ "resolved": "https://registry.npmjs.org/clean-css/-/clean-css-4.2.1.tgz", "integrity": "sha512-4ZxI6dy4lrY6FHzfiy1aEOXgu4LIsW2MhwG0VBKdcoGoH/XLFgaHSdLTGr4O8Be6A8r3MOphEiI8Gc1n0ecf3g==", "requires": { - "source-map": "0.6.1" + "source-map": "~0.6.0" }, "dependencies": { "source-map": { @@ -2035,7 +1997,7 @@ "resolved": "https://registry.npmjs.org/connect-mongo/-/connect-mongo-2.0.3.tgz", "integrity": "sha512-Vs+QZ/6X6gbCrP1Ls7Oh/wlyY6pgpbPSrUKF5yRT+zd+4GZPNbjNquxquZ+Clv2+03HBXE7T4lVM0PUcaBhihg==", "requires": { - "mongodb": "2.2.36" + "mongodb": "^2.0.36" }, "dependencies": { "mongodb": { @@ -2053,8 +2015,8 @@ "resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-2.1.20.tgz", "integrity": "sha512-IN57CX5/Q1bhDq6ShAR6gIv4koFsZP7L8WOK1S0lR0pVDQaScffSMV5jxubLsmZ7J+UdqmykKw4r9hG3XQEGgQ==", "requires": { - "bson": "1.0.9", - "require_optional": "1.0.1" + "bson": "~1.0.4", + "require_optional": "~1.0.0" } }, "process-nextick-args": { @@ -2067,13 +2029,13 @@ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.2.7.tgz", "integrity": "sha1-BwV6y+JGeyIELTb5jFrVBwVOlbE=", "requires": { - "buffer-shims": "1.0.0", - "core-util-is": "1.0.2", - "inherits": "2.0.3", - "isarray": "1.0.0", - "process-nextick-args": "1.0.7", - "string_decoder": "1.0.3", - "util-deprecate": "1.0.2" + "buffer-shims": "~1.0.0", + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "~1.0.0", + "process-nextick-args": "~1.0.6", + "string_decoder": "~1.0.0", + "util-deprecate": "~1.0.1" } }, "string_decoder": { @@ -2081,7 +2043,7 @@ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.0.3.tgz", "integrity": "sha512-4AH6Z5fzNNBcH+6XDMfA/BTt87skxqJlO0lAh3Dker5zThcAxG6mKz+iGu308UKoPPQ8Dcqx/4JhujzltRa+hQ==", "requires": { - "safe-buffer": "5.1.2" + "safe-buffer": "~5.1.0" } } } @@ -2105,10 +2067,10 @@ "resolved": "https://registry.npmjs.org/constantinople/-/constantinople-3.1.2.tgz", "integrity": "sha512-yePcBqEFhLOqSBtwYOGGS1exHo/s1xjekXiinh4itpNQGCu4KA1euPh1fg07N2wMITZXQkBz75Ntdt1ctGZouw==", "requires": { - "@types/babel-types": "7.0.6", - "@types/babylon": "6.16.5", - "babel-types": "6.26.0", - "babylon": "6.18.0" + "@types/babel-types": "^7.0.0", + "@types/babylon": "^6.16.2", + "babel-types": "^6.26.0", + "babylon": "^6.18.0" } }, "constants-browserify": { @@ -2694,7 +2656,7 @@ "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", "requires": { - "safe-buffer": "5.1.2" + "safe-buffer": "^5.0.1" } }, "ee-first": { @@ -2746,12 +2708,12 @@ "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-3.3.2.tgz", "integrity": "sha512-AsaA9KG7cWPXWHp5FvHdDWY3AMWeZ8x+2pUVLcn71qE5AtAzgGbxuclOytygskw8XGmiQafTmnI9Bix3uihu2w==", "requires": { - "accepts": "1.3.5", + "accepts": "~1.3.4", "base64id": "1.0.0", "cookie": "0.3.1", - "debug": "3.1.0", - "engine.io-parser": "2.1.3", - "ws": "6.1.4" + "debug": "~3.1.0", + "engine.io-parser": "~2.1.0", + "ws": "~6.1.0" }, "dependencies": { "debug": { @@ -2771,14 +2733,14 @@ "requires": { "component-emitter": "1.2.1", "component-inherit": "0.0.3", - "debug": "3.1.0", - "engine.io-parser": "2.1.3", + "debug": "~3.1.0", + "engine.io-parser": "~2.1.1", "has-cors": "1.1.0", "indexof": "0.0.1", "parseqs": "0.0.5", "parseuri": "0.0.5", - "ws": "6.1.4", - "xmlhttprequest-ssl": "1.5.5", + "ws": "~6.1.0", + "xmlhttprequest-ssl": "~1.5.4", "yeast": "0.1.2" }, "dependencies": { @@ -2798,10 +2760,10 @@ "integrity": "sha512-6HXPre2O4Houl7c4g7Ic/XzPnHBvaEmN90vtRO9uLmwtRqQmTOw0QMevL1TOfL2Cpu1VzsaTmMotQgMdkzGkVA==", "requires": { "after": "0.8.2", - "arraybuffer.slice": "0.0.7", + "arraybuffer.slice": "~0.0.7", "base64-arraybuffer": "0.1.5", "blob": "0.0.5", - "has-binary2": "1.0.3" + "has-binary2": "~1.0.2" } }, "enhanced-resolve": { @@ -3083,7 +3045,7 @@ "resolved": "https://registry.npmjs.org/express-flash/-/express-flash-0.0.2.tgz", "integrity": "sha1-I9GovPP5DXB5KOSJ+Whp7K0KzaI=", "requires": { - "connect-flash": "0.1.1" + "connect-flash": "0.1.x" } }, "express-session": { @@ -3095,10 +3057,10 @@ "cookie-signature": "1.0.6", "crc": "3.4.4", "debug": "2.6.9", - "depd": "1.1.2", - "on-headers": "1.0.1", - "parseurl": "1.3.2", - "uid-safe": "2.1.5", + "depd": "~1.1.1", + "on-headers": "~1.0.1", + "parseurl": "~1.3.2", + "uid-safe": "~2.1.5", "utils-merge": "1.0.1" } }, @@ -3107,8 +3069,8 @@ "resolved": "https://registry.npmjs.org/express-validator/-/express-validator-5.3.1.tgz", "integrity": "sha512-g8xkipBF6VxHbO1+ksC7nxUU7+pWif0+OZXjZTybKJ/V0aTVhuCoHbyhIPgSYVldwQLocGExPtB2pE0DqK4jsw==", "requires": { - "lodash": "4.17.11", - "validator": "10.11.0" + "lodash": "^4.17.10", + "validator": "^10.4.0" } }, "expressjs": { @@ -3234,18 +3196,11 @@ "resolved": "https://registry.npmjs.org/fbjs/-/fbjs-0.6.1.tgz", "integrity": "sha1-lja3cF9bqWhNRLcveDISVK/IYPc=", "requires": { -<<<<<<< HEAD "core-js": "^1.0.0", "loose-envify": "^1.0.0", "promise": "^7.0.3", "ua-parser-js": "^0.7.9", "whatwg-fetch": "^0.9.0" -======= - "core-js": "1.2.7", - "loose-envify": "1.4.0", - "promise": "7.3.1", - "ua-parser-js": "0.7.19", - "whatwg-fetch": "0.9.0" }, "dependencies": { "core-js": { @@ -3253,7 +3208,6 @@ "resolved": "https://registry.npmjs.org/core-js/-/core-js-1.2.7.tgz", "integrity": "sha1-ZSKUwUZR2yj6k70tX/KYOk8IxjY=" } ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "figgy-pudding": { @@ -3268,8 +3222,8 @@ "integrity": "sha512-4sNIOXgtH/9WZq4NvlfU3Opn5ynUsqBwSLyM+I7UOwdGigTBYfVVQEwe/msZNX/j4pCJTIM14Fsw66Svo1oVrw==", "dev": true, "requires": { - "loader-utils": "1.2.3", - "schema-utils": "1.0.0" + "loader-utils": "^1.0.2", + "schema-utils": "^1.0.0" } }, "fill-range": { @@ -3512,12 +3466,14 @@ "balanced-match": { "version": "1.0.0", "resolved": false, - "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=" + "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", + "optional": true }, "brace-expansion": { "version": "1.1.11", "resolved": false, "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "optional": true, "requires": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" @@ -3537,7 +3493,8 @@ "concat-map": { "version": "0.0.1", "resolved": false, - "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=" + "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", + "optional": true }, "console-control-strings": { "version": "1.1.0", @@ -3685,6 +3642,7 @@ "version": "3.0.4", "resolved": false, "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", + "optional": true, "requires": { "brace-expansion": "^1.1.7" } @@ -4265,7 +4223,7 @@ "resolved": "https://registry.npmjs.org/has/-/has-1.0.3.tgz", "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", "requires": { - "function-bind": "1.1.1" + "function-bind": "^1.1.1" } }, "has-ansi": { @@ -4801,8 +4759,8 @@ "resolved": "https://registry.npmjs.org/is-expression/-/is-expression-3.0.0.tgz", "integrity": "sha1-Oayqa+f9HzRx3ELHQW5hwkMXrJ8=", "requires": { - "acorn": "4.0.13", - "object-assign": "4.1.1" + "acorn": "~4.0.2", + "object-assign": "^4.0.1" }, "dependencies": { "acorn": { @@ -4929,7 +4887,7 @@ "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.0.4.tgz", "integrity": "sha1-VRdIm1RwkbCTDglWVM7SXul+lJE=", "requires": { - "has": "1.0.3" + "has": "^1.0.1" } }, "is-retry-allowed": { @@ -5059,15 +5017,15 @@ "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-8.4.0.tgz", "integrity": "sha512-coyXjRTCy0pw5WYBpMvWOMN+Kjaik2MwTUIq9cna/W7NpO9E+iYbumZONAz3hcr+tXFJECoQVrtmIoC3Oz0gvg==", "requires": { - "jws": "3.2.1", - "lodash.includes": "4.3.0", - "lodash.isboolean": "3.0.3", - "lodash.isinteger": "4.0.4", - "lodash.isnumber": "3.0.3", - "lodash.isplainobject": "4.0.6", - "lodash.isstring": "4.0.1", - "lodash.once": "4.1.1", - "ms": "2.1.1" + "jws": "^3.1.5", + "lodash.includes": "^4.3.0", + "lodash.isboolean": "^3.0.3", + "lodash.isinteger": "^4.0.4", + "lodash.isnumber": "^3.0.3", + "lodash.isplainobject": "^4.0.6", + "lodash.isstring": "^4.0.1", + "lodash.once": "^4.0.0", + "ms": "^2.1.1" }, "dependencies": { "ms": { @@ -5112,8 +5070,8 @@ "resolved": "https://registry.npmjs.org/jstransformer/-/jstransformer-1.0.0.tgz", "integrity": "sha1-7Yvwkh4vPx7U1cGkT2hwntJHIsM=", "requires": { - "is-promise": "2.1.0", - "promise": "7.3.1" + "is-promise": "^2.0.0", + "promise": "^7.0.1" } }, "jsx-to-string": { @@ -5144,7 +5102,7 @@ "requires": { "buffer-equal-constant-time": "1.0.1", "ecdsa-sig-formatter": "1.0.11", - "safe-buffer": "5.1.2" + "safe-buffer": "^5.0.1" } }, "jws": { @@ -5152,8 +5110,8 @@ "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.1.tgz", "integrity": "sha512-bGA2omSrFUkd72dhh05bIAN832znP4wOU3lfuXtRBuGTbsmNmDXMQg28f0Vsxaxgk4myF5YkKQpz6qeRpMgX9g==", "requires": { - "jwa": "1.4.0", - "safe-buffer": "5.1.2" + "jwa": "^1.2.0", + "safe-buffer": "^5.0.1" } }, "kareem": { @@ -5764,7 +5722,7 @@ "integrity": "sha512-sz2dhvBZQWf3LRNDhbd30KHVzdjZx9IKC0L+kSZ/gzYquCF5zPOgGqRz6sSCqYZtKP2ekB4nfLxhGtzGHnIKxA==", "requires": { "mongodb-core": "3.1.11", - "safe-buffer": "5.1.2" + "safe-buffer": "^5.1.2" }, "dependencies": { "bson": { @@ -5777,10 +5735,10 @@ "resolved": "https://registry.npmjs.org/mongodb-core/-/mongodb-core-3.1.11.tgz", "integrity": "sha512-rD2US2s5qk/ckbiiGFHeu+yKYDXdJ1G87F6CG3YdaZpzdOm5zpoAZd/EKbPmFO6cQZ+XVXBXBJ660sSI0gc6qg==", "requires": { - "bson": "1.1.0", - "require_optional": "1.0.1", - "safe-buffer": "5.1.2", - "saslprep": "1.0.2" + "bson": "^1.1.0", + "require_optional": "^1.0.1", + "safe-buffer": "^5.1.2", + "saslprep": "^1.0.0" } } } @@ -5791,7 +5749,7 @@ "integrity": "sha512-9aAg8M0YUmGHQRDYvsKJ02wx/Qaof1Jn2iDH21ZtWGAZpQt9uVLNEOdcBuzi+lPJwGbLYh2dphdKX0sZ+dXAJQ==", "requires": { "async": "2.6.1", - "bson": "1.1.0", + "bson": "~1.1.0", "kareem": "2.3.0", "mongodb": "3.1.13", "mongodb-core": "3.1.11", @@ -5809,7 +5767,7 @@ "resolved": "https://registry.npmjs.org/async/-/async-2.6.1.tgz", "integrity": "sha512-fNEiL2+AZt6AlAw/29Cr0UDe4sRAHCpEHh54WMz+Bb7QfNcFw4h3loofyJpLeQs4Yx7yuqu/2dLgM5hKOs6HlQ==", "requires": { - "lodash": "4.17.11" + "lodash": "^4.17.10" } }, "bson": { @@ -6161,7 +6119,6 @@ "resolved": "https://registry.npmjs.org/npm/-/npm-6.8.0.tgz", "integrity": "sha512-xMH6V0OCSJ5ZET6yWPI3BmJSqMMCuVJSIcLx3LSH/SrratFSt6EDuCuGRFMQYty98Q1l6x/7vKmfURosoyWgrA==", "requires": { -<<<<<<< HEAD "JSONStream": "^1.3.5", "abbrev": "~1.1.1", "ansicolors": "~0.3.2", @@ -6231,22 +6188,22 @@ "move-concurrently": "^1.0.1", "node-gyp": "^3.8.0", "nopt": "~4.0.1", - "normalize-package-data": "~2.4.0", + "normalize-package-data": "^2.5.0", "npm-audit-report": "^1.3.2", "npm-cache-filename": "~1.0.2", "npm-install-checks": "~3.0.0", "npm-lifecycle": "^2.1.0", "npm-package-arg": "^6.1.0", - "npm-packlist": "^1.2.0", + "npm-packlist": "^1.3.0", "npm-pick-manifest": "^2.2.3", "npm-profile": "*", - "npm-registry-fetch": "^3.8.0", + "npm-registry-fetch": "^3.9.0", "npm-user-validate": "~1.0.0", "npmlog": "~4.1.2", "once": "~1.4.0", "opener": "^1.5.1", "osenv": "^0.1.5", - "pacote": "^9.4.0", + "pacote": "^9.4.1", "path-is-inside": "~1.0.2", "promise-inflight": "~1.0.1", "qrcode-terminal": "^0.12.0", @@ -6256,7 +6213,7 @@ "read-cmd-shim": "~1.0.1", "read-installed": "~4.0.3", "read-package-json": "^2.0.13", - "read-package-tree": "^5.2.1", + "read-package-tree": "^5.2.2", "readable-stream": "^3.1.1", "readdir-scoped-modules": "*", "request": "^2.88.0", @@ -6273,119 +6230,6 @@ "tar": "^4.4.8", "text-table": "~0.2.0", "tiny-relative-date": "^1.3.0", -======= - "JSONStream": "1.3.5", - "abbrev": "1.1.1", - "ansicolors": "0.3.2", - "ansistyles": "0.1.3", - "aproba": "2.0.0", - "archy": "1.0.0", - "bin-links": "1.1.2", - "bluebird": "3.5.3", - "byte-size": "5.0.1", - "cacache": "11.3.2", - "call-limit": "1.1.0", - "chownr": "1.1.1", - "ci-info": "2.0.0", - "cli-columns": "3.1.2", - "cli-table3": "0.5.1", - "cmd-shim": "2.0.2", - "columnify": "1.5.4", - "config-chain": "1.1.12", - "debuglog": "1.0.1", - "detect-indent": "5.0.0", - "detect-newline": "2.1.0", - "dezalgo": "1.0.3", - "editor": "1.0.0", - "figgy-pudding": "3.5.1", - "find-npm-prefix": "1.0.2", - "fs-vacuum": "1.2.10", - "fs-write-stream-atomic": "1.0.10", - "gentle-fs": "2.0.1", - "glob": "7.1.3", - "graceful-fs": "4.1.15", - "has-unicode": "2.0.1", - "hosted-git-info": "2.7.1", - "iferr": "1.0.2", - "imurmurhash": "0.1.4", - "inflight": "1.0.6", - "inherits": "2.0.3", - "ini": "1.3.5", - "init-package-json": "1.10.3", - "is-cidr": "3.0.0", - "json-parse-better-errors": "1.0.2", - "lazy-property": "1.0.0", - "libcipm": "3.0.3", - "libnpm": "2.0.1", - "libnpmaccess": "3.0.1", - "libnpmhook": "5.0.2", - "libnpmorg": "1.0.0", - "libnpmsearch": "2.0.0", - "libnpmteam": "1.0.1", - "libnpx": "10.2.0", - "lock-verify": "2.0.2", - "lockfile": "1.0.4", - "lodash._baseindexof": "3.1.0", - "lodash._baseuniq": "4.6.0", - "lodash._bindcallback": "3.0.1", - "lodash._cacheindexof": "3.0.2", - "lodash._createcache": "3.1.2", - "lodash._getnative": "3.9.1", - "lodash.clonedeep": "4.5.0", - "lodash.restparam": "3.6.1", - "lodash.union": "4.6.0", - "lodash.uniq": "4.5.0", - "lodash.without": "4.4.0", - "lru-cache": "4.1.5", - "meant": "1.0.1", - "mississippi": "3.0.0", - "mkdirp": "0.5.1", - "move-concurrently": "1.0.1", - "node-gyp": "3.8.0", - "nopt": "4.0.1", - "normalize-package-data": "2.5.0", - "npm-audit-report": "1.3.2", - "npm-cache-filename": "1.0.2", - "npm-install-checks": "3.0.0", - "npm-lifecycle": "2.1.0", - "npm-package-arg": "6.1.0", - "npm-packlist": "1.3.0", - "npm-pick-manifest": "2.2.3", - "npm-profile": "4.0.1", - "npm-registry-fetch": "3.9.0", - "npm-user-validate": "1.0.0", - "npmlog": "4.1.2", - "once": "1.4.0", - "opener": "1.5.1", - "osenv": "0.1.5", - "pacote": "9.4.1", - "path-is-inside": "1.0.2", - "promise-inflight": "1.0.1", - "qrcode-terminal": "0.12.0", - "query-string": "6.2.0", - "qw": "1.0.1", - "read": "1.0.7", - "read-cmd-shim": "1.0.1", - "read-installed": "4.0.3", - "read-package-json": "2.0.13", - "read-package-tree": "5.2.2", - "readable-stream": "3.1.1", - "readdir-scoped-modules": "1.0.2", - "request": "2.88.0", - "retry": "0.12.0", - "rimraf": "2.6.3", - "safe-buffer": "5.1.2", - "semver": "5.6.0", - "sha": "2.0.1", - "slide": "1.1.6", - "sorted-object": "2.0.1", - "sorted-union-stream": "2.1.3", - "ssri": "6.0.1", - "stringify-package": "1.0.0", - "tar": "4.4.8", - "text-table": "0.2.0", - "tiny-relative-date": "1.3.0", ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 "uid-number": "0.0.6", "umask": "~1.1.0", "unique-filename": "^1.1.1", @@ -7652,19 +7496,8 @@ }, "ip-regex": { "version": "2.1.0", -<<<<<<< HEAD - "bundled": true - }, - "is-builtin-module": { - "version": "1.0.0", - "bundled": true, - "requires": { - "builtin-modules": "^1.0.0" - } -======= "resolved": "https://registry.npmjs.org/ip-regex/-/ip-regex-2.1.0.tgz", "integrity": "sha1-+ni/XS5pE8kRzp+BnuUUa7bYROk=" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 }, "is-ci": { "version": "1.1.0", @@ -7827,23 +7660,6 @@ "resolved": "https://registry.npmjs.org/libcipm/-/libcipm-3.0.3.tgz", "integrity": "sha512-71V5CpTI+zFydTc5IjJ/tx8JHbXEJvmYF2zaSVW1V3X1rRnRjXqh44iuiyry1xgi3ProUQ1vX1uwFiWs00+2og==", "requires": { -<<<<<<< HEAD - "bin-links": "^1.1.2", - "bluebird": "^3.5.1", - "figgy-pudding": "^3.5.1", - "find-npm-prefix": "^1.0.2", - "graceful-fs": "^4.1.11", - "ini": "^1.3.5", - "lock-verify": "^2.0.2", - "mkdirp": "^0.5.1", - "npm-lifecycle": "^2.0.3", - "npm-logical-tree": "^1.2.1", - "npm-package-arg": "^6.1.0", - "pacote": "^9.1.0", - "read-package-json": "^2.0.13", - "rimraf": "^2.6.2", - "worker-farm": "^1.6.0" -======= "bin-links": "1.1.2", "bluebird": "3.5.3", "figgy-pudding": "3.5.1", @@ -7859,7 +7675,6 @@ "read-package-json": "2.0.13", "rimraf": "2.6.3", "worker-farm": "1.6.0" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "libnpm": { @@ -7867,28 +7682,6 @@ "resolved": "https://registry.npmjs.org/libnpm/-/libnpm-2.0.1.tgz", "integrity": "sha512-qTKoxyJvpBxHZQB6k0AhSLajyXq9ZE/lUsZzuHAplr2Bpv9G+k4YuYlExYdUCeVRRGqcJt8hvkPh4tBwKoV98w==", "requires": { -<<<<<<< HEAD - "bin-links": "^1.1.2", - "bluebird": "^3.5.3", - "find-npm-prefix": "^1.0.2", - "libnpmaccess": "^3.0.1", - "libnpmconfig": "^1.2.1", - "libnpmhook": "^5.0.2", - "libnpmorg": "^1.0.0", - "libnpmpublish": "^1.1.0", - "libnpmsearch": "^2.0.0", - "libnpmteam": "^1.0.1", - "lock-verify": "^2.0.2", - "npm-lifecycle": "^2.1.0", - "npm-logical-tree": "^1.2.1", - "npm-package-arg": "^6.1.0", - "npm-profile": "^4.0.1", - "npm-registry-fetch": "^3.8.0", - "npmlog": "^4.1.2", - "pacote": "^9.2.3", - "read-package-json": "^2.0.13", - "stringify-package": "^1.0.0" -======= "bin-links": "1.1.2", "bluebird": "3.5.3", "find-npm-prefix": "1.0.2", @@ -7909,7 +7702,6 @@ "pacote": "9.4.1", "read-package-json": "2.0.13", "stringify-package": "1.0.0" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "libnpmaccess": { @@ -7917,17 +7709,10 @@ "resolved": "https://registry.npmjs.org/libnpmaccess/-/libnpmaccess-3.0.1.tgz", "integrity": "sha512-RlZ7PNarCBt+XbnP7R6PoVgOq9t+kou5rvhaInoNibhPO7eMlRfS0B8yjatgn2yaHIwWNyoJDolC/6Lc5L/IQA==", "requires": { -<<<<<<< HEAD - "aproba": "^2.0.0", - "get-stream": "^4.0.0", - "npm-package-arg": "^6.1.0", - "npm-registry-fetch": "^3.8.0" -======= "aproba": "2.0.0", "get-stream": "4.1.0", "npm-package-arg": "6.1.0", "npm-registry-fetch": "3.9.0" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 }, "dependencies": { "aproba": { @@ -7992,17 +7777,10 @@ "resolved": "https://registry.npmjs.org/libnpmhook/-/libnpmhook-5.0.2.tgz", "integrity": "sha512-vLenmdFWhRfnnZiNFPNMog6CK7Ujofy2TWiM2CrpZUjBRIhHkJeDaAbJdYCT6W4lcHtyrJR8yXW8KFyq6UAp1g==", "requires": { -<<<<<<< HEAD - "aproba": "^2.0.0", - "figgy-pudding": "^3.4.1", - "get-stream": "^4.0.0", - "npm-registry-fetch": "^3.8.0" -======= "aproba": "2.0.0", "figgy-pudding": "3.5.1", "get-stream": "4.1.0", "npm-registry-fetch": "3.9.0" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "libnpmorg": { @@ -8010,17 +7788,10 @@ "resolved": "https://registry.npmjs.org/libnpmorg/-/libnpmorg-1.0.0.tgz", "integrity": "sha512-o+4eVJBoDGMgRwh2lJY0a8pRV2c/tQM/SxlqXezjcAg26Qe9jigYVs+Xk0vvlYDWCDhP0g74J8UwWeAgsB7gGw==", "requires": { -<<<<<<< HEAD - "aproba": "^2.0.0", - "figgy-pudding": "^3.4.1", - "get-stream": "^4.0.0", - "npm-registry-fetch": "^3.8.0" -======= "aproba": "2.0.0", "figgy-pudding": "3.5.1", "get-stream": "4.1.0", "npm-registry-fetch": "3.9.0" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 }, "dependencies": { "aproba": { @@ -8035,17 +7806,6 @@ "resolved": "https://registry.npmjs.org/libnpmpublish/-/libnpmpublish-1.1.1.tgz", "integrity": "sha512-nefbvJd/wY38zdt+b9SHL6171vqBrMtZ56Gsgfd0duEKb/pB8rDT4/ObUQLrHz1tOfht1flt2zM+UGaemzAG5g==", "requires": { -<<<<<<< HEAD - "aproba": "^2.0.0", - "figgy-pudding": "^3.5.1", - "get-stream": "^4.0.0", - "lodash.clonedeep": "^4.5.0", - "normalize-package-data": "^2.4.0", - "npm-package-arg": "^6.1.0", - "npm-registry-fetch": "^3.8.0", - "semver": "^5.5.1", - "ssri": "^6.0.1" -======= "aproba": "2.0.0", "figgy-pudding": "3.5.1", "get-stream": "4.1.0", @@ -8055,7 +7815,6 @@ "npm-registry-fetch": "3.9.0", "semver": "5.6.0", "ssri": "6.0.1" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "libnpmsearch": { @@ -8063,15 +7822,9 @@ "resolved": "https://registry.npmjs.org/libnpmsearch/-/libnpmsearch-2.0.0.tgz", "integrity": "sha512-vd+JWbTGzOSfiOc+72MU6y7WqmBXn49egCCrIXp27iE/88bX8EpG64ST1blWQI1bSMUr9l1AKPMVsqa2tS5KWA==", "requires": { -<<<<<<< HEAD - "figgy-pudding": "^3.5.1", - "get-stream": "^4.0.0", - "npm-registry-fetch": "^3.8.0" -======= "figgy-pudding": "3.5.1", "get-stream": "4.1.0", "npm-registry-fetch": "3.9.0" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "libnpmteam": { @@ -8079,17 +7832,10 @@ "resolved": "https://registry.npmjs.org/libnpmteam/-/libnpmteam-1.0.1.tgz", "integrity": "sha512-gDdrflKFCX7TNwOMX1snWojCoDE5LoRWcfOC0C/fqF7mBq8Uz9zWAX4B2RllYETNO7pBupBaSyBDkTAC15cAMg==", "requires": { -<<<<<<< HEAD - "aproba": "^2.0.0", - "figgy-pudding": "^3.4.1", - "get-stream": "^4.0.0", - "npm-registry-fetch": "^3.8.0" -======= "aproba": "2.0.0", "figgy-pudding": "3.5.1", "get-stream": "4.1.0", "npm-registry-fetch": "3.9.0" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 }, "dependencies": { "aproba": { @@ -8443,12 +8189,6 @@ "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-2.5.0.tgz", "integrity": "sha512-/5CMN3T0R4XTj4DcGaexo+roZSdSFW/0AOOTROrjxzCG1wrWXEsGbRKevjlIL+ZDE4sZlJr5ED4YW0yqmkK+eA==", "requires": { -<<<<<<< HEAD - "hosted-git-info": "^2.1.4", - "is-builtin-module": "^1.0.0", - "semver": "2 || 3 || 4 || 5", - "validate-npm-package-license": "^3.0.1" -======= "hosted-git-info": "2.7.1", "resolve": "1.10.0", "semver": "5.6.0", @@ -8463,7 +8203,6 @@ "path-parse": "1.0.6" } } ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "npm-audit-report": { @@ -8529,13 +8268,8 @@ "resolved": "https://registry.npmjs.org/npm-packlist/-/npm-packlist-1.3.0.tgz", "integrity": "sha512-qPBc6CnxEzpOcc4bjoIBJbYdy0D/LFFPUdxvfwor4/w3vxeE0h6TiOVurCEPpQ6trjN77u/ShyfeJGsbAfB3dA==", "requires": { -<<<<<<< HEAD "ignore-walk": "^3.0.1", "npm-bundled": "^1.0.1" -======= - "ignore-walk": "3.0.1", - "npm-bundled": "1.0.6" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "npm-pick-manifest": { @@ -8553,15 +8287,9 @@ "resolved": "https://registry.npmjs.org/npm-profile/-/npm-profile-4.0.1.tgz", "integrity": "sha512-NQ1I/1Q7YRtHZXkcuU1/IyHeLy6pd+ScKg4+DQHdfsm769TGq6HPrkbuNJVJS4zwE+0mvvmeULzQdWn2L2EsVA==", "requires": { -<<<<<<< HEAD - "aproba": "^1.1.2 || 2", - "figgy-pudding": "^3.4.1", - "npm-registry-fetch": "^3.8.0" -======= "aproba": "2.0.0", "figgy-pudding": "3.5.1", "npm-registry-fetch": "3.9.0" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "npm-registry-fetch": { @@ -8700,7 +8428,6 @@ "resolved": "https://registry.npmjs.org/pacote/-/pacote-9.4.1.tgz", "integrity": "sha512-YKSRsQqmeHxgra0KCdWA2FtVxDPUlBiCdmew+mSe44pzlx5t1ViRMWiQg18T+DREA+vSqYfKzynaToFR4hcKHw==", "requires": { -<<<<<<< HEAD "bluebird": "^3.5.3", "cacache": "^11.3.2", "figgy-pudding": "^3.5.1", @@ -8728,35 +8455,6 @@ "tar": "^4.4.8", "unique-filename": "^1.1.1", "which": "^1.3.1" -======= - "bluebird": "3.5.3", - "cacache": "11.3.2", - "figgy-pudding": "3.5.1", - "get-stream": "4.1.0", - "glob": "7.1.3", - "lru-cache": "5.1.1", - "make-fetch-happen": "4.0.1", - "minimatch": "3.0.4", - "minipass": "2.3.5", - "mississippi": "3.0.0", - "mkdirp": "0.5.1", - "normalize-package-data": "2.5.0", - "npm-package-arg": "6.1.0", - "npm-packlist": "1.3.0", - "npm-pick-manifest": "2.2.3", - "npm-registry-fetch": "3.9.0", - "osenv": "0.1.5", - "promise-inflight": "1.0.1", - "promise-retry": "1.1.1", - "protoduck": "5.0.1", - "rimraf": "2.6.3", - "safe-buffer": "5.1.2", - "semver": "5.6.0", - "ssri": "6.0.1", - "tar": "4.4.8", - "unique-filename": "1.1.1", - "which": "1.3.1" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 }, "dependencies": { "lru-cache": { @@ -9031,19 +8729,11 @@ "resolved": "https://registry.npmjs.org/read-package-json/-/read-package-json-2.0.13.tgz", "integrity": "sha512-/1dZ7TRZvGrYqE0UAfN6qQb5GYBsNcqS1C0tNK601CFOJmtHI7NIGXwetEPU/OtoFHZL3hDxm4rolFFVE9Bnmg==", "requires": { -<<<<<<< HEAD - "glob": "^7.1.1", - "graceful-fs": "^4.1.2", - "json-parse-better-errors": "^1.0.1", - "normalize-package-data": "^2.0.0", - "slash": "^1.0.0" -======= "glob": "7.1.3", "graceful-fs": "4.1.15", "json-parse-better-errors": "1.0.2", "normalize-package-data": "2.5.0", "slash": "1.0.0" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 } }, "read-package-tree": { @@ -10172,7 +9862,7 @@ "resolved": "https://registry.npmjs.org/parseqs/-/parseqs-0.0.5.tgz", "integrity": "sha1-1SCKNzjkZ2bikbouoXNoSSGouJ0=", "requires": { - "better-assert": "1.0.2" + "better-assert": "~1.0.0" } }, "parseuri": { @@ -10180,7 +9870,7 @@ "resolved": "https://registry.npmjs.org/parseuri/-/parseuri-0.0.5.tgz", "integrity": "sha1-gCBKUNTbt3m/3G6+J3jZDkvOMgo=", "requires": { - "better-assert": "1.0.2" + "better-assert": "~1.0.0" } }, "parseurl": { @@ -10198,7 +9888,7 @@ "resolved": "https://registry.npmjs.org/passport/-/passport-0.4.0.tgz", "integrity": "sha1-xQlWkTR71a07XhgCOMORTRbwWBE=", "requires": { - "passport-strategy": "1.0.0", + "passport-strategy": "1.x.x", "pause": "0.0.1" } }, @@ -10207,7 +9897,7 @@ "resolved": "https://registry.npmjs.org/passport-local/-/passport-local-1.0.0.tgz", "integrity": "sha1-H+YyaMkudWBmJkN+O5BmYsFbpu4=", "requires": { - "passport-strategy": "1.0.0" + "passport-strategy": "1.x.x" } }, "passport-strategy": { @@ -10298,8 +9988,8 @@ "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-2.1.266.tgz", "integrity": "sha512-Jy7o1wE3NezPxozexSbq4ltuLT0Z21ew/qrEiAEeUZzHxMHGk4DUV1D7RuCXg5vJDvHmjX1YssN+we9QfRRgXQ==", "requires": { - "node-ensure": "0.0.0", - "worker-loader": "2.0.0" + "node-ensure": "^0.0.0", + "worker-loader": "^2.0.0" } }, "performance-now": { @@ -10525,9 +10215,9 @@ "resolved": "https://registry.npmjs.org/prosemirror-dropcursor/-/prosemirror-dropcursor-1.1.1.tgz", "integrity": "sha512-GeUyMO/tOEf8MXrP7Xb7UIMrfK86OGh0fnyBrHfhav4VjY9cw65mNoqHy87CklE5711AhCP5Qzfp8RL/hVKusg==", "requires": { - "prosemirror-state": "1.2.2", - "prosemirror-transform": "1.1.3", - "prosemirror-view": "1.7.1" + "prosemirror-state": "^1.0.0", + "prosemirror-transform": "^1.1.0", + "prosemirror-view": "^1.1.0" } }, "prosemirror-example-setup": { @@ -10535,15 +10225,15 @@ "resolved": "https://registry.npmjs.org/prosemirror-example-setup/-/prosemirror-example-setup-1.0.1.tgz", "integrity": "sha512-4NKWpdmm75Zzgq/dIrypRnkBNPx+ONKyoGF42a9g3VIVv0TWglf1CBNxt5kzCgli9xdfut/xE5B42F9DR6BLHw==", "requires": { - "prosemirror-commands": "1.0.7", - "prosemirror-dropcursor": "1.1.1", - "prosemirror-gapcursor": "1.0.3", - "prosemirror-history": "1.0.3", - "prosemirror-inputrules": "1.0.1", - "prosemirror-keymap": "1.0.1", - "prosemirror-menu": "1.0.5", - "prosemirror-schema-list": "1.0.2", - "prosemirror-state": "1.2.2" + "prosemirror-commands": "^1.0.0", + "prosemirror-dropcursor": "^1.0.0", + "prosemirror-gapcursor": "^1.0.0", + "prosemirror-history": "^1.0.0", + "prosemirror-inputrules": "^1.0.0", + "prosemirror-keymap": "^1.0.0", + "prosemirror-menu": "^1.0.0", + "prosemirror-schema-list": "^1.0.0", + "prosemirror-state": "^1.0.0" } }, "prosemirror-gapcursor": { @@ -10551,10 +10241,10 @@ "resolved": "https://registry.npmjs.org/prosemirror-gapcursor/-/prosemirror-gapcursor-1.0.3.tgz", "integrity": "sha512-X+hJhr42PcHWiSWL+lI5f/UeOhXCxlBFb8M6O8aG1hssmaRrW7sS2/Fjg5jFV+pTdS1REFkmm1occh01FMdDIQ==", "requires": { - "prosemirror-keymap": "1.0.1", - "prosemirror-model": "1.7.0", - "prosemirror-state": "1.2.2", - "prosemirror-view": "1.7.1" + "prosemirror-keymap": "^1.0.0", + "prosemirror-model": "^1.0.0", + "prosemirror-state": "^1.0.0", + "prosemirror-view": "^1.0.0" } }, "prosemirror-history": { @@ -10572,8 +10262,8 @@ "resolved": "https://registry.npmjs.org/prosemirror-inputrules/-/prosemirror-inputrules-1.0.1.tgz", "integrity": "sha512-UHy22NmwxS5WIMQYkzraDttQAF8mpP82FfbJsmKFfx6jwkR/SZa+ZhbkLY0zKQ5fBdJN7euj36JG/B5iAlrpxA==", "requires": { - "prosemirror-state": "1.2.2", - "prosemirror-transform": "1.1.3" + "prosemirror-state": "^1.0.0", + "prosemirror-transform": "^1.0.0" } }, "prosemirror-keymap": { @@ -10590,10 +10280,10 @@ "resolved": "https://registry.npmjs.org/prosemirror-menu/-/prosemirror-menu-1.0.5.tgz", "integrity": "sha512-9Vrn7CC191v7FA4QrAkL8W1SrR73V3CRIYCDuk94R8oFVk4VxSFdoKVLHuvGzxZ8b5LCu3DMJfh86YW9uL4RkQ==", "requires": { - "crel": "3.1.0", - "prosemirror-commands": "1.0.7", - "prosemirror-history": "1.0.3", - "prosemirror-state": "1.2.2" + "crel": "^3.0.0", + "prosemirror-commands": "^1.0.0", + "prosemirror-history": "^1.0.0", + "prosemirror-state": "^1.0.0" } }, "prosemirror-model": { @@ -10617,8 +10307,8 @@ "resolved": "https://registry.npmjs.org/prosemirror-schema-list/-/prosemirror-schema-list-1.0.2.tgz", "integrity": "sha512-IJ4DEpUEymfO+NNA4DAgCMF39XiQqpmCoPYY3SXa1jYcVgObGpGfJlSjZYVFEpimoLI7/mLoOLDhCtpGCRhTfg==", "requires": { - "prosemirror-model": "1.7.0", - "prosemirror-transform": "1.1.3" + "prosemirror-model": "^1.0.0", + "prosemirror-transform": "^1.0.0" } }, "prosemirror-state": { @@ -10684,12 +10374,12 @@ "integrity": "sha512-zVpa8oKZSz5bTMTFClc1fQOnyyEzpl5ozpi1B5YcvBrdohMjH2rfsBtyXcuNuwjsDIXmBYlF2N5FlJYhR29t8Q==", "dev": true, "requires": { - "bn.js": "4.11.8", - "browserify-rsa": "4.0.1", - "create-hash": "1.2.0", - "parse-asn1": "5.1.3", - "randombytes": "2.0.6", - "safe-buffer": "5.1.2" + "bn.js": "^4.1.0", + "browserify-rsa": "^4.0.0", + "create-hash": "^1.1.0", + "parse-asn1": "^5.0.0", + "randombytes": "^2.0.1", + "safe-buffer": "^5.1.2" } }, "pug": { @@ -10697,14 +10387,14 @@ "resolved": "https://registry.npmjs.org/pug/-/pug-2.0.3.tgz", "integrity": "sha1-ccuoJTfJWl6rftBGluQiH1Oqh44=", "requires": { - "pug-code-gen": "2.0.1", - "pug-filters": "3.1.0", - "pug-lexer": "4.0.0", - "pug-linker": "3.0.5", - "pug-load": "2.0.11", - "pug-parser": "5.0.0", - "pug-runtime": "2.0.4", - "pug-strip-comments": "1.0.3" + "pug-code-gen": "^2.0.1", + "pug-filters": "^3.1.0", + "pug-lexer": "^4.0.0", + "pug-linker": "^3.0.5", + "pug-load": "^2.0.11", + "pug-parser": "^5.0.0", + "pug-runtime": "^2.0.4", + "pug-strip-comments": "^1.0.3" } }, "pug-attrs": { @@ -10712,9 +10402,9 @@ "resolved": "https://registry.npmjs.org/pug-attrs/-/pug-attrs-2.0.3.tgz", "integrity": "sha1-owlflw5kFR972tlX7vVftdeQXRU=", "requires": { - "constantinople": "3.1.2", - "js-stringify": "1.0.2", - "pug-runtime": "2.0.4" + "constantinople": "^3.0.1", + "js-stringify": "^1.0.1", + "pug-runtime": "^2.0.4" } }, "pug-code-gen": { @@ -10722,14 +10412,14 @@ "resolved": "https://registry.npmjs.org/pug-code-gen/-/pug-code-gen-2.0.1.tgz", "integrity": "sha1-CVHsgyJddNjPxHan+Zolm199BQw=", "requires": { - "constantinople": "3.1.2", - "doctypes": "1.1.0", - "js-stringify": "1.0.2", - "pug-attrs": "2.0.3", - "pug-error": "1.3.2", - "pug-runtime": "2.0.4", - "void-elements": "2.0.1", - "with": "5.1.1" + "constantinople": "^3.0.1", + "doctypes": "^1.1.0", + "js-stringify": "^1.0.1", + "pug-attrs": "^2.0.3", + "pug-error": "^1.3.2", + "pug-runtime": "^2.0.4", + "void-elements": "^2.0.1", + "with": "^5.0.0" } }, "pug-error": { @@ -10742,13 +10432,13 @@ "resolved": "https://registry.npmjs.org/pug-filters/-/pug-filters-3.1.0.tgz", "integrity": "sha1-JxZVVbwEwjbkqisDZiRt+gIbYm4=", "requires": { - "clean-css": "4.2.1", - "constantinople": "3.1.2", + "clean-css": "^4.1.11", + "constantinople": "^3.0.1", "jstransformer": "1.0.0", - "pug-error": "1.3.2", - "pug-walk": "1.1.7", - "resolve": "1.10.0", - "uglify-js": "2.8.29" + "pug-error": "^1.3.2", + "pug-walk": "^1.1.7", + "resolve": "^1.1.6", + "uglify-js": "^2.6.1" } }, "pug-lexer": { @@ -10756,9 +10446,9 @@ "resolved": "https://registry.npmjs.org/pug-lexer/-/pug-lexer-4.0.0.tgz", "integrity": "sha1-IQwYRX7y4XYCQnQMXmR715TOwng=", "requires": { - "character-parser": "2.2.0", - "is-expression": "3.0.0", - "pug-error": "1.3.2" + "character-parser": "^2.1.1", + "is-expression": "^3.0.0", + "pug-error": "^1.3.2" } }, "pug-linker": { @@ -10766,8 +10456,8 @@ "resolved": "https://registry.npmjs.org/pug-linker/-/pug-linker-3.0.5.tgz", "integrity": "sha1-npp65ABWgtAn3uuWsAD4juuDoC8=", "requires": { - "pug-error": "1.3.2", - "pug-walk": "1.1.7" + "pug-error": "^1.3.2", + "pug-walk": "^1.1.7" } }, "pug-load": { @@ -10775,8 +10465,8 @@ "resolved": "https://registry.npmjs.org/pug-load/-/pug-load-2.0.11.tgz", "integrity": "sha1-5kjlftET/iwfRdV4WOorrWvAFSc=", "requires": { - "object-assign": "4.1.1", - "pug-walk": "1.1.7" + "object-assign": "^4.1.0", + "pug-walk": "^1.1.7" } }, "pug-parser": { @@ -10784,7 +10474,7 @@ "resolved": "https://registry.npmjs.org/pug-parser/-/pug-parser-5.0.0.tgz", "integrity": "sha1-45Stmz/KkxI5QK/4hcBuRKt+aOQ=", "requires": { - "pug-error": "1.3.2", + "pug-error": "^1.3.2", "token-stream": "0.0.1" } }, @@ -10798,16 +10488,7 @@ "resolved": "https://registry.npmjs.org/pug-strip-comments/-/pug-strip-comments-1.0.3.tgz", "integrity": "sha1-8VWVkiBu3G+FMQ2s9K+0igJa9Z8=", "requires": { -<<<<<<< HEAD - "bn.js": "^4.1.0", - "browserify-rsa": "^4.0.0", - "create-hash": "^1.1.0", - "parse-asn1": "^5.0.0", - "randombytes": "^2.0.1", - "safe-buffer": "^5.1.2" -======= - "pug-error": "1.3.2" ->>>>>>> 96eede5f7d1706a3f7ac6ee02a85bb3da217f467 + "pug-error": "^1.3.2" } }, "pug-walk": { @@ -10914,8 +10595,8 @@ "resolved": "https://registry.npmjs.org/raw-loader/-/raw-loader-1.0.0.tgz", "integrity": "sha512-Uqy5AqELpytJTRxYT4fhltcKPj0TyaEpzJDcGz7DFJi+pQOOi3GjR/DOdxTkTsF+NzhnldIoG6TORaBlInUuqA==", "requires": { - "loader-utils": "1.2.3", - "schema-utils": "1.0.0" + "loader-utils": "^1.1.0", + "schema-utils": "^1.0.0" } }, "rc": { @@ -10945,26 +10626,17 @@ "scheduler": "^0.12.0" } }, - "react-contenteditable": { - "version": "3.2.6", - "resolved": "https://registry.npmjs.org/react-contenteditable/-/react-contenteditable-3.2.6.tgz", - "integrity": "sha512-jmr/wnuaU0teJ7U5ePUtEV4xDqaJS3jAFaXMF/3Dyr0COLV6gegcH0Yj727BdT7DnHWVoXVpR7m1s9hDgmSBTw==", - "requires": { - "@types/prop-types": "^15.5.6", - "fast-deep-equal": "^2.0.1" - } - }, "react-color": { "version": "2.17.0", "resolved": "https://registry.npmjs.org/react-color/-/react-color-2.17.0.tgz", "integrity": "sha512-kJfE5tSaFe6GzalXOHksVjqwCPAsTl+nzS9/BWfP7j3EXbQ4IiLAF9sZGNzk3uq7HfofGYgjmcUgh0JP7xAQ0w==", "requires": { - "@icons/material": "0.2.4", - "lodash": "4.17.11", - "material-colors": "1.2.6", - "prop-types": "15.6.2", - "reactcss": "1.2.3", - "tinycolor2": "1.4.1" + "@icons/material": "^0.2.4", + "lodash": ">4.17.4", + "material-colors": "^1.2.1", + "prop-types": "^15.5.10", + "reactcss": "^1.2.0", + "tinycolor2": "^1.4.1" } }, "react-dimensions": { @@ -10991,8 +10663,8 @@ "resolved": "https://registry.npmjs.org/react-draggable/-/react-draggable-3.2.1.tgz", "integrity": "sha512-r+3Bs9InID2lyIEbR8UIRVtpn4jgu1ArFEZgIy8vibJjijLSdNLX7rH9U68BBVD4RD9v44RXbaK4EHLyKXzNQw==", "requires": { - "classnames": "2.2.6", - "prop-types": "15.6.2" + "classnames": "^2.2.5", + "prop-types": "^15.6.0" } }, "react-golden-layout": { @@ -11069,12 +10741,12 @@ "resolved": "https://registry.npmjs.org/react-pdf/-/react-pdf-4.0.5.tgz", "integrity": "sha512-hoIL08qU5pU1fNEx6NnLl3omD08LAUc+UkmxGXEql/PXiNWjMZHWlu8MSVg9pwSTN6dXtfky0gehrisWvSOrCg==", "requires": { - "@babel/runtime": "7.3.1", - "lodash.once": "4.1.1", - "make-event-props": "1.2.0", - "merge-class-names": "1.1.1", + "@babel/runtime": "^7.0.0", + "lodash.once": "^4.1.1", + "make-event-props": "^1.1.0", + "merge-class-names": "^1.1.1", "pdfjs-dist": "2.1.266", - "prop-types": "15.6.2" + "prop-types": "^15.6.2" } }, "react-pdf-highlighter": { @@ -11082,10 +10754,10 @@ "resolved": "https://registry.npmjs.org/react-pdf-highlighter/-/react-pdf-highlighter-2.1.2.tgz", "integrity": "sha512-aKa/rzpFjOywcRmNyfupvrGdh7mp0VGS9RKCWDbD9p32+P3+DhJvQe/2qCvDAnTXa4LmabNqM+O0RDUcai1C1Q==", "requires": { - "lodash": "4.17.11", + "lodash": "^4.17.10", "pdfjs-dist": "2.0.489", - "react-pointable": "1.1.3", - "react-rnd": "7.4.3" + "react-pointable": "^1.1.1", + "react-rnd": "^7.1.5" }, "dependencies": { "pdfjs-dist": { @@ -11093,8 +10765,8 @@ "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-2.0.489.tgz", "integrity": "sha1-Y+VLKSqGeQpFRpfrRNQ0e4+/rSc=", "requires": { - "node-ensure": "0.0.0", - "worker-loader": "1.1.1" + "node-ensure": "^0.0.0", + "worker-loader": "^1.1.1" } }, "schema-utils": { @@ -11102,8 +10774,8 @@ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-0.4.7.tgz", "integrity": "sha512-v/iwU6wvwGK8HbU9yi3/nhGzP0yGSuhQMzL6ySiec1FSrZZDkhm4noOSWzrNFo/jEc+SJY6jRTwuwbSXJPDUnQ==", "requires": { - "ajv": "6.8.1", - "ajv-keywords": "3.3.0" + "ajv": "^6.1.0", + "ajv-keywords": "^3.1.0" } }, "worker-loader": { @@ -11111,8 +10783,8 @@ "resolved": "https://registry.npmjs.org/worker-loader/-/worker-loader-1.1.1.tgz", "integrity": "sha512-qJZLVS/jMCBITDzPo/RuweYSIG8VJP5P67mP/71alGyTZRe1LYJFdwLjLalY3T5ifx0bMDRD3OB6P2p1escvlg==", "requires": { - "loader-utils": "1.2.3", - "schema-utils": "0.4.7" + "loader-utils": "^1.0.0", + "schema-utils": "^0.4.0" } } } @@ -11130,8 +10802,8 @@ "resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-2.0.943.tgz", "integrity": "sha512-iLhNcm4XceTHRaSU5o22ZGCm4YpuW5+rf4+BJFH/feBhMQLbCGBry+Jet8Q419QDI4qgARaIQzXuiNrsNWS8Yw==", "requires": { - "node-ensure": "0.0.0", - "worker-loader": "2.0.0" + "node-ensure": "^0.0.0", + "worker-loader": "^2.0.0" } } } @@ -11147,7 +10819,7 @@ "integrity": "sha512-TLQ35nqXup7rC63qAETebbO6Znilr20CroTTeAdlYu8nvRSwB7BrmPKZhHB2GgeiSucOoeCyAA9pHPhbMpEd/Q==", "requires": { "re-resizable": "4.5.1", - "react-draggable": "3.2.1" + "react-draggable": "^3.0.5" } }, "react-split-pane": { @@ -11183,7 +10855,7 @@ "resolved": "https://registry.npmjs.org/reactcss/-/reactcss-1.2.3.tgz", "integrity": "sha512-KiwVUcFu1RErkI97ywr8nvx8dNOpT03rbnma0SSalTYjkrPYaEajR4a/MRt6DZ46K6arDRbWMNHF+xH7G7n/8A==", "requires": { - "lodash": "4.17.11" + "lodash": "^4.0.1" } }, "read-pkg": { @@ -11389,8 +11061,8 @@ "resolved": "https://registry.npmjs.org/require_optional/-/require_optional-1.0.1.tgz", "integrity": "sha512-qhM/y57enGWHAe3v/NcwML6a3/vfESLe/sGM2dII+gEO0BpKRUkWZow/tyloNqJyN6kXSl3RyyM8Ll5D/sJP8g==", "requires": { - "resolve-from": "2.0.0", - "semver": "5.6.0" + "resolve-from": "^2.0.0", + "semver": "^5.1.0" }, "dependencies": { "resolve-from": { @@ -11416,7 +11088,7 @@ "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.10.0.tgz", "integrity": "sha512-3sUr9aq5OfSg2S9pNtPA9hL1FVEAjvfOC4leW0SNf/mpnaakz2a9femSd6LqAww2RaFctwyf1lCqnTHuF1rxDg==", "requires": { - "path-parse": "1.0.6" + "path-parse": "^1.0.6" } }, "resolve-cwd": { @@ -11459,7 +11131,7 @@ "resolved": "https://registry.npmjs.org/right-align/-/right-align-0.1.3.tgz", "integrity": "sha1-YTObci/mo1FWiSENJOFMlhSGE+8=", "requires": { - "align-text": "0.1.4" + "align-text": "^0.1.1" } }, "rimraf": { @@ -11518,7 +11190,7 @@ "integrity": "sha512-4cDsYuAjXssUSjxHKRe4DTZC0agDwsCqcMqtJAQPzC74nJ7LfAJflAtC1Zed5hMzEQKj82d3tuzqdGNRsLJ4Gw==", "optional": true, "requires": { - "sparse-bitfield": "3.0.3" + "sparse-bitfield": "^3.0.3" } }, "sass-graph": { @@ -11877,12 +11549,12 @@ "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-2.2.0.tgz", "integrity": "sha512-wxXrIuZ8AILcn+f1B4ez4hJTPG24iNgxBBDaJfT6MsyOhVYiTXWexGoPkd87ktJG8kQEcL/NBvRi64+9k4Kc0w==", "requires": { - "debug": "4.1.1", - "engine.io": "3.3.2", - "has-binary2": "1.0.3", - "socket.io-adapter": "1.1.1", + "debug": "~4.1.0", + "engine.io": "~3.3.1", + "has-binary2": "~1.0.2", + "socket.io-adapter": "~1.1.0", "socket.io-client": "2.2.0", - "socket.io-parser": "3.3.0" + "socket.io-parser": "~3.3.0" }, "dependencies": { "debug": { @@ -11890,7 +11562,7 @@ "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", "requires": { - "ms": "2.1.1" + "ms": "^2.1.1" } }, "ms": { @@ -11914,15 +11586,15 @@ "base64-arraybuffer": "0.1.5", "component-bind": "1.0.0", "component-emitter": "1.2.1", - "debug": "3.1.0", - "engine.io-client": "3.3.2", - "has-binary2": "1.0.3", + "debug": "~3.1.0", + "engine.io-client": "~3.3.1", + "has-binary2": "~1.0.2", "has-cors": "1.1.0", "indexof": "0.0.1", "object-component": "0.0.3", "parseqs": "0.0.5", "parseuri": "0.0.5", - "socket.io-parser": "3.3.0", + "socket.io-parser": "~3.3.0", "to-array": "0.1.4" }, "dependencies": { @@ -11942,7 +11614,7 @@ "integrity": "sha512-hczmV6bDgdaEbVqhAeVMM/jfUfzuEZHsQg6eOmLgJht6G3mPKMxYm75w2+qhAQZ+4X+1+ATZ+QFKeOZD5riHng==", "requires": { "component-emitter": "1.2.1", - "debug": "3.1.0", + "debug": "~3.1.0", "isarray": "2.0.1" }, "dependencies": { @@ -12066,7 +11738,7 @@ "integrity": "sha1-/0rm5oZWBWuks+eSqzM004JzyhE=", "optional": true, "requires": { - "memory-pager": "1.5.0" + "memory-pager": "^1.0.2" } }, "spdx-correct": { @@ -12825,9 +12497,9 @@ "resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-2.8.29.tgz", "integrity": "sha1-KcVzMUgFe7Th913zW3qcty5qWd0=", "requires": { - "source-map": "0.5.7", - "uglify-to-browserify": "1.0.2", - "yargs": "3.10.0" + "source-map": "~0.5.1", + "uglify-to-browserify": "~1.0.0", + "yargs": "~3.10.0" }, "dependencies": { "camelcase": { @@ -12840,8 +12512,8 @@ "resolved": "https://registry.npmjs.org/cliui/-/cliui-2.1.0.tgz", "integrity": "sha1-S0dXYP+AJkx2LDoXGQMukcf+oNE=", "requires": { - "center-align": "0.1.3", - "right-align": "0.1.3", + "center-align": "^0.1.1", + "right-align": "^0.1.1", "wordwrap": "0.0.2" } }, @@ -12855,9 +12527,9 @@ "resolved": "https://registry.npmjs.org/yargs/-/yargs-3.10.0.tgz", "integrity": "sha1-9+572FfdfB0tOMDnTvvWgdFDH9E=", "requires": { - "camelcase": "1.2.1", - "cliui": "2.1.0", - "decamelize": "1.2.0", + "camelcase": "^1.0.2", + "cliui": "^2.1.0", + "decamelize": "^1.0.0", "window-size": "0.1.0" } } @@ -12874,7 +12546,7 @@ "resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz", "integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==", "requires": { - "random-bytes": "1.0.0" + "random-bytes": "~1.0.0" } }, "undefsafe": { @@ -13489,7 +13161,7 @@ "integrity": "sha512-oeXA3m+5gbYbDBGo4SvKpAHJJEGMoekUbHgo1RK7CP1sz7/WOSeu/dWJtSTk+rzDCLkPwQhGocgIq6lQqOyOwg==", "dev": true, "requires": { - "memory-fs": "~0.4.1", + "memory-fs": "^0.4.1", "mime": "^2.3.1", "range-parser": "^1.0.3", "webpack-log": "^2.0.0" @@ -13935,8 +13607,8 @@ "resolved": "https://registry.npmjs.org/with/-/with-5.1.1.tgz", "integrity": "sha1-+k2qktrzLE6pTtRTyB8EaGtXXf4=", "requires": { - "acorn": "3.3.0", - "acorn-globals": "3.1.0" + "acorn": "^3.1.0", + "acorn-globals": "^3.0.0" }, "dependencies": { "acorn": { @@ -13965,8 +13637,8 @@ "resolved": "https://registry.npmjs.org/worker-loader/-/worker-loader-2.0.0.tgz", "integrity": "sha512-tnvNp4K3KQOpfRnD20m8xltE3eWh89Ye+5oj7wXEEHKac1P4oZ6p9oTj8/8ExqoSBnk9nu5Pr4nKfQ1hn2APJw==", "requires": { - "loader-utils": "1.2.3", - "schema-utils": "0.4.7" + "loader-utils": "^1.0.0", + "schema-utils": "^0.4.0" }, "dependencies": { "schema-utils": { @@ -13974,8 +13646,8 @@ "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-0.4.7.tgz", "integrity": "sha512-v/iwU6wvwGK8HbU9yi3/nhGzP0yGSuhQMzL6ySiec1FSrZZDkhm4noOSWzrNFo/jEc+SJY6jRTwuwbSXJPDUnQ==", "requires": { - "ajv": "6.8.1", - "ajv-keywords": "3.3.0" + "ajv": "^6.1.0", + "ajv-keywords": "^3.1.0" } } } @@ -14009,7 +13681,7 @@ "resolved": "https://registry.npmjs.org/ws/-/ws-6.1.4.tgz", "integrity": "sha512-eqZfL+NE/YQc1/ZynhojeV8q+H050oR8AZ2uIev7RU10svA9ZnJUddHcOUZTJLinZ9yEfdA2kSATS2qZK5fhJA==", "requires": { - "async-limiter": "1.0.0" + "async-limiter": "~1.0.0" } }, "xdg-basedir": { diff --git a/package.json b/package.json index e1a9cc6fb..f20f9d427 100644 --- a/package.json +++ b/package.json @@ -131,4 +131,4 @@ "url-loader": "^1.1.2", "uuid": "^3.3.2" } -} \ No newline at end of file +} diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 3b2cd2626..84009907a 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -4,11 +4,15 @@ import { SelectionManager } from "../util/SelectionManager"; import { observer } from "mobx-react"; import './DocumentDecorations.scss' import { CollectionFreeFormView } from "./collections/CollectionFreeFormView"; -import ContentEditable from 'react-contenteditable' +//import ContentEditable from 'react-contenteditable' import { KeyStore } from "../../fields/KeyStore"; import { NumberField } from "../../fields/NumberField"; import { Document } from "../../fields/Document"; import { DocumentView } from "./nodes/DocumentView"; +import { Key } from "../../fields/Key"; +import { TextField } from "../../fields/TextField"; +import { BasicField } from "../../fields/BasicField"; +import { Field, FieldValue } from "../../fields/Field"; @observer export class DocumentDecorations extends React.Component<{}, { value: string }> { @@ -17,23 +21,21 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> private _isPointerDown = false; @observable private _opacity = 1; private keyinput: React.RefObject; - @observable private _documents: DocumentView[] = []; + private _documents: DocumentView[] = SelectionManager.SelectedDocuments(); //@observable private _title: string = this._documents[0].props.Document.Title; - @observable private _title: string = document.title; + @observable private _title: string = this._documents.length > 0 ? this._documents[0].props.Document.Title : ""; + @observable private _fieldKey: Key = KeyStore.Title; constructor(props: Readonly<{}>) { super(props) DocumentDecorations.Instance = this - this.state = { value: document.title }; this.handleChange = this.handleChange.bind(this); this.keyinput = React.createRef(); } @action handleChange = (event: any) => { - //this.setState({ value: event.target.value }); this._title = event.target.value; - console.log("Input box has changed"); }; @action @@ -44,19 +46,18 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> var text = e.target.value; if (text[0] == '#') { let command = text.slice(1, text.length); - if (command == "Title" || command == "title") { - this._title = this._documents[0].props.Document.Title; - } - else if (command == "Width" || command == "width") { - this._title = this._documents[0].props.Document.GetNumber(KeyStore.Width, 0).toString(); - } - else { - this._title = "undefined key"; - } + this._fieldKey = new Key(command) + // if (command == "Title" || command == "title") { + // this._fieldKey = KeyStore.Title; + // } + // else if (command == "Width" || command == "width") { + // this._fieldKey = KeyStore.Width; + // } + this._title = "changed" // TODO: Change field with switch statement } else { - this._title = document.title; + this._title = "changed"; } e.target.blur(); } @@ -184,8 +185,24 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> } } + getValue = (): string => { + console.log("value watched"); + if (this._title === "changed" && this._documents.length > 0) { + let field = this._documents[0].props.Document.Get(this._fieldKey); + if (field instanceof TextField) { + return (field as TextField).GetValue(); + } + else if (field instanceof NumberField) { + return (field as NumberField).GetValue().toString(); + } + } + return this._title; + } + render() { var bounds = this.Bounds; + // console.log(this._documents.length) + // let test = this._documents[0].props.Document.Title; if (this.Hidden) { return (null); } @@ -201,7 +218,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> top: bounds.y - 20 - 20, opacity: this._opacity }}> - +
e.preventDefault()}>
e.preventDefault()}>
e.preventDefault()}>
-- cgit v1.2.3-70-g09d2 From 6473fdcbc01fecfa5bc8dc46cdcd7841c1ef35ae Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Wed, 20 Mar 2019 05:04:01 -0400 Subject: Started adding support for promises --- package.json | 2 ++ src/Utils.ts | 12 +++++++-- src/client/Server.ts | 66 +++++++++++++++++++++++++++--------------------- src/client/SocketStub.ts | 15 ++++++++--- src/fields/Document.ts | 46 +++++++++++++++++++-------------- 5 files changed, 87 insertions(+), 54 deletions(-) (limited to 'src') diff --git a/package.json b/package.json index c87e31bc4..f9761a13f 100644 --- a/package.json +++ b/package.json @@ -78,6 +78,7 @@ "@types/react-measure": "^2.0.4", "@types/react-table": "^6.7.22", "@types/request": "^2.48.1", + "@types/request-promise": "^4.1.42", "@types/socket.io": "^2.1.2", "@types/socket.io-client": "^1.4.32", "@types/typescript": "^2.0.0", @@ -146,6 +147,7 @@ "react-split-pane": "^0.1.85", "react-table": "^6.9.2", "request": "^2.88.0", + "request-promise": "^4.2.4", "socket.io": "^2.2.0", "socket.io-client": "^2.2.0", "socketio": "^1.0.0", diff --git a/src/Utils.ts b/src/Utils.ts index a4db94809..ccd503abe 100644 --- a/src/Utils.ts +++ b/src/Utils.ts @@ -41,8 +41,16 @@ export class Utils { socket.emit(message.Message, args); } - public static EmitCallback(socket: Socket | SocketIOClient.Socket, message: Message, args: T, fn: (args: any) => any) { - socket.emit(message.Message, args, fn); + public static EmitCallback(socket: Socket | SocketIOClient.Socket, message: Message, args: T): Promise; + public static EmitCallback(socket: Socket | SocketIOClient.Socket, message: Message, args: T, fn: (args: any) => any): void; + public static EmitCallback(socket: Socket | SocketIOClient.Socket, message: Message, args: T, fn?: (args: any) => any): void | Promise { + if (fn) { + socket.emit(message.Message, args, fn); + } else { + return new Promise(res => { + socket.emit(message.Message, args, res); + }) + } } public static AddServerHandler(socket: Socket, message: Message, handler: (args: T) => any) { diff --git a/src/client/Server.ts b/src/client/Server.ts index bbdc27397..6a47076fb 100644 --- a/src/client/Server.ts +++ b/src/client/Server.ts @@ -15,37 +15,45 @@ export class Server { // Retrieves the cached value of the field and sends a request to the server for the real value (if it's not cached). // Call this is from within a reaction and test whether the return value is FieldWaiting. - // 'hackTimeout' is here temporarily for simplicity when debugging things. - public static GetField(fieldid: FieldId, callback: (field: Opt) => void): Opt | FIELD_WAITING { - let cached = this.ClientFieldsCached.get(fieldid); - if (!cached) { - this.ClientFieldsCached.set(fieldid, FieldWaiting); - SocketStub.SEND_FIELD_REQUEST(fieldid, action((field: Field | undefined) => { - let cached = this.ClientFieldsCached.get(fieldid); - if (cached != FieldWaiting) - callback(cached); - else { - if (field) { - this.ClientFieldsCached.set(fieldid, field); - } else { - this.ClientFieldsCached.delete(fieldid) + public static GetField(fieldid: FieldId): Promise>; + public static GetField(fieldid: FieldId, callback: (field: Opt) => void): void; + public static GetField(fieldid: FieldId, callback?: (field: Opt) => void): Promise> | void { + let fn = (cb: (field: Opt) => void) => { + + let cached = this.ClientFieldsCached.get(fieldid); + if (!cached) { + this.ClientFieldsCached.set(fieldid, FieldWaiting); + SocketStub.SEND_FIELD_REQUEST(fieldid, action((field: Field | undefined) => { + let cached = this.ClientFieldsCached.get(fieldid); + if (cached != FieldWaiting) + cb(cached); + else { + if (field) { + this.ClientFieldsCached.set(fieldid, field); + } else { + this.ClientFieldsCached.delete(fieldid) + } + cb(field) } - callback(field) - } - })); - } else if (cached != FieldWaiting) { - setTimeout(() => callback(cached as Field), 0); + })); + } else if (cached != FieldWaiting) { + setTimeout(() => cb(cached as Field), 0); + } else { + reaction(() => { + return this.ClientFieldsCached.get(fieldid); + }, (field, reaction) => { + if (field !== "") { + reaction.dispose() + cb(field) + } + }) + } + } + if (callback) { + fn(callback); } else { - reaction(() => { - return this.ClientFieldsCached.get(fieldid); - }, (field, reaction) => { - if (field !== "") { - reaction.dispose() - callback(field) - } - }) + return new Promise>(res => fn(res)); } - return cached; } public static GetFields(fieldIds: FieldId[], callback: (fields: { [id: string]: Field }) => any) { @@ -71,7 +79,7 @@ export class Server { } } reaction(() => { - return waitingFieldIds.map(this.ClientFieldsCached.get); + return waitingFieldIds.map(id => this.ClientFieldsCached.get(id)); }, (cachedFields, reaction) => { if (!cachedFields.some(field => !field || field === FieldWaiting)) { reaction.dispose(); diff --git a/src/client/SocketStub.ts b/src/client/SocketStub.ts index a0b89b7c9..27528c4c3 100644 --- a/src/client/SocketStub.ts +++ b/src/client/SocketStub.ts @@ -35,16 +35,23 @@ export class SocketStub { Utils.Emit(Server.Socket, MessageStore.AddDocument, new DocumentTransfer(document.ToJson())) } - public static SEND_FIELD_REQUEST(fieldid: FieldId, callback: (field: Opt) => void) { - if (fieldid) { + public static SEND_FIELD_REQUEST(fieldid: FieldId): Promise>; + public static SEND_FIELD_REQUEST(fieldid: FieldId, callback: (field: Opt) => void): void; + public static SEND_FIELD_REQUEST(fieldid: FieldId, callback?: (field: Opt) => void): Promise> | void { + let fn = function (cb: (field: Opt) => void) { Utils.EmitCallback(Server.Socket, MessageStore.GetField, fieldid, (field: any) => { if (field) { - ServerUtils.FromJson(field).init(callback); + ServerUtils.FromJson(field).init(cb); } else { - callback(undefined); + cb(undefined); } }) } + if (callback) { + fn(callback); + } else { + return new Promise(res => fn(res)) + } } public static SEND_FIELDS_REQUEST(fieldIds: FieldId[], callback: (fields: { [key: string]: Field }) => any) { diff --git a/src/fields/Document.ts b/src/fields/Document.ts index b6439364a..66d3d3aef 100644 --- a/src/fields/Document.ts +++ b/src/fields/Document.ts @@ -124,22 +124,31 @@ export class Document extends Field { * Note: The callback will not be called if there is no associated field. * @returns `true` if the field exists on the document and `callback` will be called, and `false` otherwise */ - GetAsync(key: Key, callback: (field: Field) => void): boolean { + GetAsync(key: Key, callback: (field: Opt) => void): void { //TODO: This currently doesn't deal with prototypes let field = this.fields.get(key.Id); if (field && field.field) { callback(field.field); } else if (this._proxies.has(key.Id)) { Server.GetDocumentField(this, key, callback); - return true; + } else { + callback(undefined); } - return false; } - GetTAsync(key: Key, ctor: { new(): T }, callback: (field: Opt) => void): boolean { - return this.GetAsync(key, (field) => { - callback(Cast(field, ctor)); - }) + GetTAsync(key: Key, ctor: { new(): T }): Promise>; + GetTAsync(key: Key, ctor: { new(): T }, callback: (field: Opt) => void): void; + GetTAsync(key: Key, ctor: { new(): T }, callback?: (field: Opt) => void): Promise> | void { + let fn = (cb: (field: Opt) => void) => { + return this.GetAsync(key, (field) => { + cb(Cast(field, ctor)); + }); + } + if (callback) { + fn(callback); + } else { + return new Promise(res => fn(res)); + } } /** @@ -214,13 +223,6 @@ export class Document extends Field { return this.GetData>(key, ListField, defaultVal) } - @action - SetOnPrototype(key: Key, field: Field | undefined): void { - this.GetAsync(KeyStore.Prototype, (f: Field) => { - (f as Document).Set(key, field) - }) - } - @action Set(key: Key, field: Field | undefined, setOnPrototype = false): void { let old = this.fields.get(key.Id); @@ -248,16 +250,22 @@ export class Document extends Field { } } + @action + SetOnPrototype(key: Key, field: Field | undefined): void { + this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { + f && f.Set(key, field) + }) + } + @action SetDataOnPrototype(key: Key, value: T, ctor: { new(): U }, replaceWrongType = true) { - this.GetAsync(KeyStore.Prototype, (f: Field) => { - (f as Document).SetData(key, value, ctor) + this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { + f && f.SetData(key, value, ctor) }) } @action SetData(key: Key, value: T, ctor: { new(): U }, replaceWrongType = true) { - let field = this.Get(key, true); if (field instanceof ctor) { field.Data = value; @@ -294,8 +302,8 @@ export class Document extends Field { CreateAlias(id?: string): Document { let alias = new Document(id) - this.GetAsync(KeyStore.Prototype, (f: Field) => { - alias.Set(KeyStore.Prototype, f) + this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { + f && alias.Set(KeyStore.Prototype, f) }) return alias -- cgit v1.2.3-70-g09d2 From bece3110a3d6fa18dd89415a5e636c6792aea4e1 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Wed, 20 Mar 2019 05:07:52 -0400 Subject: Refactored users to have a single user document instead of a list of workspaces --- src/client/views/Main.tsx | 132 ++++++++++++--------- src/fields/KeyStore.ts | 2 + src/mobile/ImageUpload.tsx | 38 +++--- src/server/RouteStore.ts | 5 +- .../authentication/controllers/WorkspacesMenu.tsx | 19 +-- .../authentication/controllers/user_controller.ts | 3 +- .../authentication/models/current_user_utils.ts | 46 +++++-- src/server/authentication/models/user_model.ts | 11 +- src/server/index.ts | 33 +----- 9 files changed, 144 insertions(+), 145 deletions(-) (limited to 'src') diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index ac51a7d87..a1a6cc475 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -8,6 +8,7 @@ import "./Main.scss"; import { MessageStore } from '../../server/Message'; import { Utils } from '../../Utils'; import * as request from 'request' +import * as rp from 'request-promise' import { Documents } from '../documents/Documents'; import { Server } from '../Server'; import { setupDrag } from '../util/DragManager'; @@ -40,7 +41,7 @@ import Measure from 'react-measure'; import { DashUserModel } from '../../server/authentication/models/user_model'; import { ServerUtils } from '../../server/ServerUtil'; import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils'; -import { Field, Opt } from '../../fields/Field'; +import { Field, Opt, FieldWaiting } from '../../fields/Field'; import { ListField } from '../../fields/ListField'; import { map } from 'bluebird'; import { Gateway, Settings } from '../northstar/manager/Gateway'; @@ -49,13 +50,26 @@ import { Catalog } from '../northstar/model/idea/idea'; @observer export class Main extends React.Component { // dummy initializations keep the compiler happy - @observable private mainContainer?: Document; @observable private mainfreeform?: Document; - @observable private userWorkspaces: Document[] = []; @observable public pwidth: number = 0; @observable public pheight: number = 0; @observable private _northstarCatalog: Catalog | undefined = undefined; + @computed private get mainContainer(): Document | undefined { + let doc = this.userDocument.GetT(KeyStore.ActiveWorkspace, Document); + return doc == FieldWaiting ? undefined : doc; + } + + private set mainContainer(doc: Document | undefined) { + if (doc) { + this.userDocument.Set(KeyStore.ActiveWorkspace, doc); + } + } + + private get userDocument(): Document { + return CurrentUserUtils.UserDocument; + } + public mainDocId: string | undefined; private currentUser?: DashUserModel; public static Instance: Main; @@ -67,12 +81,12 @@ export class Main extends React.Component { configure({ enforceActions: "observed" }); if (window.location.pathname !== RouteStore.home) { let pathname = window.location.pathname.split("/"); - this.mainDocId = pathname[pathname.length - 1]; + if (pathname.length > 1 && pathname[pathname.length - 2] == 'doc') { + this.mainDocId = pathname[pathname.length - 1]; + } }; - this.initializeNorthstar(); - - CurrentUserUtils.loadCurrentUser(); + // this.initializeNorthstar(); library.add(faFont); library.add(faImage); @@ -143,63 +157,50 @@ export class Main extends React.Component { initAuthenticationRouters = () => { // Load the user's active workspace, or create a new one if initial session after signup - request.get(ServerUtils.prepend(RouteStore.getActiveWorkspace), (error, response, body) => { - if (this.mainDocId || body) { - Server.GetField(this.mainDocId || body, field => { - if (field instanceof Document) { - this.openWorkspace(field); - this.populateWorkspaces(); - } else { - this.createNewWorkspace(true, this.mainDocId); - } - }); - } else { - this.createNewWorkspace(true, this.mainDocId); - } - }); - } - - @action - createNewWorkspace = (init: boolean, id?: string): void => { - let mainDoc = Documents.DockDocument(JSON.stringify({ content: [{ type: 'row', content: [] }] }), { title: `Main Container ${this.userWorkspaces.length + 1}` }, id); - let newId = mainDoc.Id; - request.post(ServerUtils.prepend(RouteStore.addWorkspace), { - body: { target: newId }, - json: true - }, () => { if (init) this.populateWorkspaces(); }); - - // bcz: strangely, we need a timeout to prevent exceptions/issues initializing GoldenLayout (the rendering engine for Main Container) - setTimeout(() => { - let freeformDoc = Documents.FreeformDocument([], { x: 0, y: 400, title: "mini collection" }); - var dockingLayout = { content: [{ type: 'row', content: [CollectionDockingView.makeDocumentConfig(freeformDoc)] }] }; - mainDoc.SetText(KeyStore.Data, JSON.stringify(dockingLayout)); - mainDoc.Set(KeyStore.ActiveFrame, freeformDoc); - this.openWorkspace(mainDoc); - let pendingDocument = Documents.SchemaDocument([], { title: "New Mobile Uploads" }) - mainDoc.Set(KeyStore.OptionalRightCollection, pendingDocument); - }, 0); - this.userWorkspaces.push(mainDoc); + if (!this.mainDocId) { + this.userDocument.GetTAsync(KeyStore.ActiveWorkspace, Document).then(doc => { + if (doc) { + this.openWorkspace(doc); + } else { + this.createNewWorkspace(); + } + }) + } else { + Server.GetField(this.mainDocId).then(field => { + if (field instanceof Document) { + this.openWorkspace(field) + } else { + this.createNewWorkspace(this.mainDocId); + } + }) + } } @action - populateWorkspaces = () => { - // retrieve all workspace documents from the server - request.get(ServerUtils.prepend(RouteStore.getAllWorkspaces), (error, res, body) => { - let ids = JSON.parse(body) as string[]; - Server.GetFields(ids, action((fields: { [id: string]: Field }) => this.userWorkspaces = ids.map(id => fields[id] as Document))); - }); + createNewWorkspace = (id?: string): void => { + this.userDocument.GetTAsync>(KeyStore.Workspaces, ListField).then(action((list: Opt>) => { + if (list) { + let freeformDoc = Documents.FreeformDocument([], { x: 0, y: 400, title: "mini collection" }); + var dockingLayout = { content: [{ type: 'row', content: [CollectionDockingView.makeDocumentConfig(freeformDoc)] }] }; + let mainDoc = Documents.DockDocument(JSON.stringify(dockingLayout), { title: `Main Container ${list.Data.length + 1}` }, id); + list.Data.push(mainDoc); + // bcz: strangely, we need a timeout to prevent exceptions/issues initializing GoldenLayout (the rendering engine for Main Container) + setTimeout(() => { + mainDoc.Set(KeyStore.ActiveFrame, freeformDoc); + this.openWorkspace(mainDoc); + let pendingDocument = Documents.SchemaDocument([], { title: "New Mobile Uploads" }) + mainDoc.Set(KeyStore.OptionalRightCollection, pendingDocument); + }, 0); + } + })); } @action openWorkspace = (doc: Document, fromHistory = false): void => { - request.post(ServerUtils.prepend(RouteStore.setActiveWorkspace), { - body: { target: doc.Id }, - json: true - }); this.mainContainer = doc; fromHistory || window.history.pushState(null, doc.Title, "/doc/" + doc.Id); this.mainContainer.GetTAsync(KeyStore.ActiveFrame, Document, field => this.mainfreeform = field); - this.mainContainer.GetTAsync(KeyStore.OptionalRightCollection, Document, col => { + this.userDocument.GetTAsync(KeyStore.OptionalRightCollection, Document).then(col => { // if there is a pending doc, and it has new data, show it (syip: we use a timeout to prevent collection docking view from being uninitialized) setTimeout(() => { if (col) { @@ -213,10 +214,15 @@ export class Main extends React.Component { }); } + @observable + workspacesShown: boolean = false; + + areWorkspacesShown = () => { + return this.workspacesShown; + } + @action toggleWorkspaces = () => { - if (WorkspacesMenu.Instance) { - WorkspacesMenu.Instance.toggle() - } + this.workspacesShown = !this.workspacesShown; } screenToLocalTransform = () => Transform.Identity @@ -310,6 +316,12 @@ export class Main extends React.Component { } render() { + let workspaceMenu: any = null; + let workspaces = this.userDocument.GetT>(KeyStore.Workspaces, ListField); + if (workspaces && workspaces !== FieldWaiting) { + workspaceMenu = + } return (
runInAction(() => { @@ -326,11 +338,13 @@ export class Main extends React.Component { {this.nodesMenu} {this.miscButtons} - + {workspaceMenu}
); } } -ReactDOM.render(
, document.getElementById('root')); +CurrentUserUtils.loadCurrentUser().then(() => { + ReactDOM.render(
, document.getElementById('root')); +}); diff --git a/src/fields/KeyStore.ts b/src/fields/KeyStore.ts index 68883d6f1..891caaa81 100644 --- a/src/fields/KeyStore.ts +++ b/src/fields/KeyStore.ts @@ -28,6 +28,7 @@ export namespace KeyStore { export const SchemaSplitPercentage = new Key("SchemaSplitPercentage"); export const Caption = new Key("Caption"); export const ActiveFrame = new Key("ActiveFrame"); + export const ActiveWorkspace = new Key("ActiveWorkspace"); export const DocumentText = new Key("DocumentText"); export const LinkedToDocs = new Key("LinkedToDocs"); export const LinkedFromDocs = new Key("LinkedFromDocs"); @@ -41,4 +42,5 @@ export namespace KeyStore { export const OptionalRightCollection = new Key("OptionalRightCollection"); export const Archives = new Key("Archives"); export const Updated = new Key("Updated"); + export const Workspaces = new Key("Workspaces"); } diff --git a/src/mobile/ImageUpload.tsx b/src/mobile/ImageUpload.tsx index 16808a598..47b9d8f0b 100644 --- a/src/mobile/ImageUpload.tsx +++ b/src/mobile/ImageUpload.tsx @@ -7,7 +7,7 @@ import { Server } from '../client/Server'; import { Documents } from '../client/documents/Documents'; import { ListField } from '../fields/ListField'; import { ImageField } from '../fields/ImageField'; -import request = require('request'); +import * as rp from 'request-promise' import { ServerUtils } from '../server/ServerUtil'; import { RouteStore } from '../server/RouteStore'; @@ -40,28 +40,24 @@ const onFileLoad = (file: any) => { json.map((file: any) => { let path = window.location.origin + file var doc: Document = Documents.ImageDocument(path, { nativeWidth: 200, width: 200 }) - doc.GetTAsync(KeyStore.Data, ImageField, (i) => { - if (i) { - document.getElementById("message")!.innerText = i.Data.href; + + rp.get(ServerUtils.prepend(RouteStore.getUserDocumentId)).then(res => { + if (res) { + return Server.GetField(res); + } + throw new Error("No user id returned"); + }).then(field => { + if (field instanceof Document) { + return field.GetTAsync(KeyStore.OptionalRightCollection, Document) } - }) - request.get(ServerUtils.prepend(RouteStore.getActiveWorkspace), (error, response, body) => { - if (body) { - Server.GetField(body, field => { - if (field instanceof Document) { - field.GetTAsync(KeyStore.OptionalRightCollection, Document, - pending => { - if (pending) { - pending.GetOrCreateAsync(KeyStore.Data, ListField, list => { - list.Data.push(doc); - }) - } - }) - } - } - ); + }).then(pending => { + if (pending) { + pending.GetOrCreateAsync(KeyStore.Data, ListField, list => { + list.Data.push(doc); + }) } - }) + }); + // console.log(window.location.origin + file[0]) //imgPrev.setAttribute("src", window.location.origin + files[0].name) diff --git a/src/server/RouteStore.ts b/src/server/RouteStore.ts index fb06b878b..fdf5b6a5c 100644 --- a/src/server/RouteStore.ts +++ b/src/server/RouteStore.ts @@ -15,10 +15,7 @@ export enum RouteStore { // USER AND WORKSPACES getCurrUser = "/getCurrentUser", - addWorkspace = "/addWorkspaceId", - getAllWorkspaces = "/getAllWorkspaceIds", - getActiveWorkspace = "/getActiveWorkspaceId", - setActiveWorkspace = "/setActiveWorkspaceId", + getUserDocumentId = "/getUserDocumentId", updateCursor = "/updateCursor", openDocumentWithId = "/doc/:docId", diff --git a/src/server/authentication/controllers/WorkspacesMenu.tsx b/src/server/authentication/controllers/WorkspacesMenu.tsx index 1533b1e62..8e14cf98e 100644 --- a/src/server/authentication/controllers/WorkspacesMenu.tsx +++ b/src/server/authentication/controllers/WorkspacesMenu.tsx @@ -9,30 +9,23 @@ import { KeyStore } from '../../../fields/KeyStore'; export interface WorkspaceMenuProps { active: Document | undefined; open: (workspace: Document) => void; - new: (init: boolean) => void; + new: () => void; allWorkspaces: Document[]; + isShown: () => boolean; + toggle: () => void; } @observer export class WorkspacesMenu extends React.Component { - static Instance: WorkspacesMenu; - @observable private workspacesExposed: boolean = false; - constructor(props: WorkspaceMenuProps) { super(props); - WorkspacesMenu.Instance = this; this.addNewWorkspace = this.addNewWorkspace.bind(this); } @action addNewWorkspace() { - this.props.new(false); - this.toggle(); - } - - @action - toggle() { - this.workspacesExposed = !this.workspacesExposed; + this.props.new(); + this.props.toggle(); } render() { @@ -45,7 +38,7 @@ export class WorkspacesMenu extends React.Component { borderRadius: 5, position: "absolute", top: 78, - left: this.workspacesExposed ? 11 : -500, + left: this.props.isShown() ? 11 : -500, background: "white", border: "black solid 2px", transition: "all 1s ease", diff --git a/src/server/authentication/controllers/user_controller.ts b/src/server/authentication/controllers/user_controller.ts index 2cef958e8..e365b8dce 100644 --- a/src/server/authentication/controllers/user_controller.ts +++ b/src/server/authentication/controllers/user_controller.ts @@ -11,6 +11,7 @@ import * as async from 'async'; import * as nodemailer from 'nodemailer'; import c = require("crypto"); import { RouteStore } from "../../RouteStore"; +import { Utils } from "../../../Utils"; /** * GET /signup @@ -54,7 +55,7 @@ export let postSignup = (req: Request, res: Response, next: NextFunction) => { const user = new User({ email, password, - userDoc: "document here" + userDocumentId: Utils.GenerateGuid() }); User.findOne({ email }, (err, existingUser) => { diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index cc433eb73..17a6d493b 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -1,29 +1,61 @@ import { DashUserModel } from "./user_model"; -import * as request from 'request' +import * as rp from 'request-promise'; import { RouteStore } from "../../RouteStore"; import { ServerUtils } from "../../ServerUtil"; +import { Server } from "../../../client/Server"; +import { Document } from "../../../fields/Document"; +import { KeyStore } from "../../../fields/KeyStore"; +import { ListField } from "../../../fields/ListField"; +import { Documents } from "../../../client/documents/Documents"; export class CurrentUserUtils { private static curr_email: string; private static curr_id: string; + private static user_document: Document; - public static get email() { + public static get email(): string { return CurrentUserUtils.curr_email; } - public static get id() { + public static get id(): string { return CurrentUserUtils.curr_id; } - public static loadCurrentUser() { - request.get(ServerUtils.prepend(RouteStore.getCurrUser), (error, response, body) => { - if (body) { - let obj = JSON.parse(body); + public static get UserDocument(): Document { + return CurrentUserUtils.user_document; + } + + private static createUserDocument(id: string): Document { + let doc = new Document(id); + + doc.Set(KeyStore.Workspaces, new ListField()); + doc.Set(KeyStore.OptionalRightCollection, Documents.SchemaDocument([], { title: "Pending documents" })) + return doc; + } + + public static loadCurrentUser(): Promise { + let userPromise = rp.get(ServerUtils.prepend(RouteStore.getCurrUser)).then((response) => { + if (response) { + let obj = JSON.parse(response); CurrentUserUtils.curr_id = obj.id as string; CurrentUserUtils.curr_email = obj.email as string; } else { throw new Error("There should be a user! Why does Dash think there isn't one?") } }); + let userDocPromise = rp.get(ServerUtils.prepend(RouteStore.getUserDocumentId)).then(id => { + if (id) { + return Server.GetField(id).then(field => { + if (field instanceof Document) { + this.user_document = field; + } else { + this.user_document = this.createUserDocument(id); + } + }) + } else { + throw new Error("There should be a user id! Why does Dash think there isn't one?") + } + }); + return Promise.all([userPromise, userDocPromise]); } } \ No newline at end of file diff --git a/src/server/authentication/models/user_model.ts b/src/server/authentication/models/user_model.ts index 3d4ed6896..81580aad5 100644 --- a/src/server/authentication/models/user_model.ts +++ b/src/server/authentication/models/user_model.ts @@ -21,9 +21,7 @@ export type DashUserModel = mongoose.Document & { passwordResetToken: string | undefined, passwordResetExpires: Date | undefined, - allWorkspaceIds: Array, - activeWorkspaceId: String, - activeUsersId: String, + userDocumentId: string; profile: { name: string, @@ -49,12 +47,7 @@ const userSchema = new mongoose.Schema({ passwordResetToken: String, passwordResetExpires: Date, - allWorkspaceIds: { - type: Array, - default: [] - }, - activeWorkspaceId: String, - activeUsersId: String, + userDocumentId: String, facebook: String, twitter: String, diff --git a/src/server/index.ts b/src/server/index.ts index d1eb6847d..16304f1c5 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -156,16 +156,9 @@ addSecureRoute( addSecureRoute( Method.GET, - (user, res) => res.send(user.activeWorkspaceId || ""), + (user, res) => res.send(user.userDocumentId || ""), undefined, - RouteStore.getActiveWorkspace, -); - -addSecureRoute( - Method.GET, - (user, res) => res.send(JSON.stringify(user.allWorkspaceIds)), - undefined, - RouteStore.getAllWorkspaces + RouteStore.getUserDocumentId, ); addSecureRoute( @@ -182,28 +175,6 @@ addSecureRoute( // SETTERS -addSecureRoute( - Method.POST, - (user, res, req) => { - user.update({ $set: { activeWorkspaceId: req.body.target } }, (err, raw) => { - res.sendStatus(err ? 500 : 200); - }); - }, - undefined, - RouteStore.setActiveWorkspace -); - -addSecureRoute( - Method.POST, - (user, res, req) => { - user.update({ $push: { allWorkspaceIds: req.body.target } }, (err, raw) => { - res.sendStatus(err ? 500 : 200); - }); - }, - undefined, - RouteStore.addWorkspace -); - addSecureRoute( Method.POST, (user, res, req) => { -- cgit v1.2.3-70-g09d2 From a80d2e9c72e683c7618d20a83432a3d82feb2a85 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 21 Mar 2019 08:41:18 -0400 Subject: nothing much --- src/Utils.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) (limited to 'src') diff --git a/src/Utils.ts b/src/Utils.ts index ccd503abe..be97dc90b 100644 --- a/src/Utils.ts +++ b/src/Utils.ts @@ -47,9 +47,7 @@ export class Utils { if (fn) { socket.emit(message.Message, args, fn); } else { - return new Promise(res => { - socket.emit(message.Message, args, res); - }) + return new Promise(res => socket.emit(message.Message, args, res)); } } -- cgit v1.2.3-70-g09d2 From 1cf618563838f4ce7d8a98c8a0c8d94670bc4e18 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 21 Mar 2019 21:03:00 -0400 Subject: changes to allow tabs to be dragged into other documents --- src/client/views/collections/CollectionDockingView.tsx | 17 +++++++++++++++++ src/fields/Document.ts | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index fd0810242..950df7261 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -17,6 +17,7 @@ import { COLLECTION_BORDER_WIDTH } from "./CollectionView"; import React = require("react"); import { SubCollectionViewProps } from "./CollectionViewBase"; import { ServerUtils } from "../../../server/ServerUtil"; +import { DragManager } from "../../util/DragManager"; @observer export class CollectionDockingView extends React.Component { @@ -190,6 +191,21 @@ export class CollectionDockingView extends React.Component { var className = (e.target as any).className; + if ((className == "lm_title" || className == "lm_tab lm_active") && e.ctrlKey) { + e.stopPropagation(); + e.preventDefault(); + let docid = (e.target as any).DashDocId; + let tab = (e.target as any).parentElement as HTMLElement; + Server.GetField(docid, action((f: Opt) => + DragManager.StartDocumentDrag(tab, new DragManager.DocumentDragData(f as Document), + { + handlers: { + dragComplete: action(() => { }), + }, + hideSource: true + })) + ); + } if (className == "lm_drag_handle" || className == "lm_close" || className == "lm_maximise" || className == "lm_minimise" || className == "lm_close_tab") { this._flush = true; } @@ -208,6 +224,7 @@ export class CollectionDockingView extends React.Component { + tab.titleElement[0].DashDocId = tab.contentItem.config.props.documentId; tab.closeElement.off('click') //unbind the current click handler .click(function () { tab.contentItem.remove(); diff --git a/src/fields/Document.ts b/src/fields/Document.ts index b6439364a..2403c670c 100644 --- a/src/fields/Document.ts +++ b/src/fields/Document.ts @@ -36,7 +36,7 @@ export class Document extends Field { @computed public get Title() { - return this.GetText(KeyStore.Title, ""); + return this.GetText(KeyStore.Title, "-untitled-"); } @computed -- cgit v1.2.3-70-g09d2 From bc59ea805f32568f0835bd55d39575236c24a066 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 21 Mar 2019 22:22:25 -0400 Subject: added very basic cycle detection when adding to collections --- src/client/util/DragManager.ts | 4 +--- .../views/collections/CollectionDockingView.tsx | 2 +- .../views/collections/CollectionFreeFormView.tsx | 21 ++++++++++++--------- src/client/views/collections/CollectionPDFView.tsx | 2 +- .../views/collections/CollectionVideoView.tsx | 2 +- src/client/views/collections/CollectionView.tsx | 22 ++++++++++++++++++---- .../views/collections/CollectionViewBase.tsx | 12 ++++++++---- src/client/views/collections/MarqueeView.tsx | 2 +- src/client/views/nodes/DocumentView.tsx | 2 +- 9 files changed, 44 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index 753115f76..661fa4dc8 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -197,9 +197,7 @@ export namespace DragManager { document.removeEventListener("pointermove", moveHandler, true); document.removeEventListener("pointerup", upHandler); dragDiv.removeChild(dragElement); - if (hideSource && !wasHidden) { - ele.hidden = false; - } + ele.hidden = false; } const upHandler = (e: PointerEvent) => { abortDrag(); diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 950df7261..39b284d8e 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -202,7 +202,7 @@ export class CollectionDockingView extends React.Component { }), }, - hideSource: true + hideSource: false })) ); } diff --git a/src/client/views/collections/CollectionFreeFormView.tsx b/src/client/views/collections/CollectionFreeFormView.tsx index da9f7b392..8b9d178c9 100644 --- a/src/client/views/collections/CollectionFreeFormView.tsx +++ b/src/client/views/collections/CollectionFreeFormView.tsx @@ -75,16 +75,19 @@ export class CollectionFreeFormView extends CollectionViewBase { @undoBatch @action - drop = (e: Event, de: DragManager.DropEvent) => { - super.drop(e, de); - if (de.data instanceof DragManager.DocumentDragData) { - let screenX = de.x - (de.data.xOffset as number || 0); - let screenY = de.y - (de.data.yOffset as number || 0); - const [x, y] = this.getTransform().transformPoint(screenX, screenY); - de.data.droppedDocument.SetNumber(KeyStore.X, x); - de.data.droppedDocument.SetNumber(KeyStore.Y, y); - this.bringToFront(de.data.droppedDocument); + drop = (e: Event, de: DragManager.DropEvent): boolean => { + if (super.drop(e, de)) { + if (de.data instanceof DragManager.DocumentDragData) { + let screenX = de.x - (de.data.xOffset as number || 0); + let screenY = de.y - (de.data.yOffset as number || 0); + const [x, y] = this.getTransform().transformPoint(screenX, screenY); + de.data.droppedDocument.SetNumber(KeyStore.X, x); + de.data.droppedDocument.SetNumber(KeyStore.Y, y); + this.bringToFront(de.data.droppedDocument); + } + return true; } + return false; } diff --git a/src/client/views/collections/CollectionPDFView.tsx b/src/client/views/collections/CollectionPDFView.tsx index e64b4c945..4d2daf149 100644 --- a/src/client/views/collections/CollectionPDFView.tsx +++ b/src/client/views/collections/CollectionPDFView.tsx @@ -38,7 +38,7 @@ export class CollectionPDFView extends React.Component { public SelectedDocs: FieldId[] = [] public active: () => boolean = () => CollectionView.Active(this); - addDocument = (doc: Document, allowDuplicates: boolean): void => { CollectionView.AddDocument(this.props, doc, allowDuplicates); } + addDocument = (doc: Document, allowDuplicates: boolean): boolean => { return CollectionView.AddDocument(this.props, doc, allowDuplicates); } removeDocument = (doc: Document): boolean => { return CollectionView.RemoveDocument(this.props, doc); } specificContextMenu = (e: React.MouseEvent): void => { diff --git a/src/client/views/collections/CollectionVideoView.tsx b/src/client/views/collections/CollectionVideoView.tsx index 05f759967..a3921696f 100644 --- a/src/client/views/collections/CollectionVideoView.tsx +++ b/src/client/views/collections/CollectionVideoView.tsx @@ -44,7 +44,7 @@ export class CollectionVideoView extends React.Component { public SelectedDocs: FieldId[] = [] public active: () => boolean = () => CollectionView.Active(this); - addDocument = (doc: Document, allowDuplicates: boolean): void => { CollectionView.AddDocument(this.props, doc, allowDuplicates); } + addDocument = (doc: Document, allowDuplicates: boolean): boolean => { return CollectionView.AddDocument(this.props, doc, allowDuplicates); } removeDocument = (doc: Document): boolean => { return CollectionView.RemoveDocument(this.props, doc); } specificContextMenu = (e: React.MouseEvent): void => { diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 7e1d31018..2e93e6bb8 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -37,7 +37,7 @@ export class CollectionView extends React.Component { @observable public SelectedDocs: FieldId[] = []; public active: () => boolean = () => CollectionView.Active(this); - addDocument = (doc: Document, allowDuplicates: boolean): void => { CollectionView.AddDocument(this.props, doc, allowDuplicates); } + addDocument = (doc: Document, allowDuplicates: boolean): boolean => { return CollectionView.AddDocument(this.props, doc, allowDuplicates); } removeDocument = (doc: Document): boolean => { return CollectionView.RemoveDocument(this.props, doc); } get subView() { return CollectionView.SubView(this); } @@ -48,17 +48,31 @@ export class CollectionView extends React.Component { return isSelected || childSelected || topMost; } + static createsCycle(doc: Document, props: CollectionViewProps): boolean { + let ldata = doc.GetList(KeyStore.Data, []); + for (let i = 0; i < ldata.length; i++) { + if (CollectionView.createsCycle(ldata[i], props)) + return true; + } + return doc.Id == props.Document.Id; + } + @action - public static AddDocument(props: CollectionViewProps, doc: Document, allowDuplicates: boolean) { + public static AddDocument(props: CollectionViewProps, doc: Document, allowDuplicates: boolean): boolean { doc.SetNumber(KeyStore.Page, props.Document.GetNumber(KeyStore.CurPage, -1)); if (props.Document.Get(props.fieldKey) instanceof Field) { //TODO This won't create the field if it doesn't already exist const value = props.Document.GetData(props.fieldKey, ListField, new Array()) - if (!value.some(v => v.Id == doc.Id) || allowDuplicates) - value.push(doc); + if (!CollectionView.createsCycle(doc, props)) { + if (!value.some(v => v.Id == doc.Id) || allowDuplicates) + value.push(doc); + } + else + return false; } else { props.Document.SetOnPrototype(props.fieldKey, new ListField([doc])); } + return true; } @action diff --git a/src/client/views/collections/CollectionViewBase.tsx b/src/client/views/collections/CollectionViewBase.tsx index f33007196..535a8a8d2 100644 --- a/src/client/views/collections/CollectionViewBase.tsx +++ b/src/client/views/collections/CollectionViewBase.tsx @@ -17,6 +17,7 @@ import { NumberField } from "../../../fields/NumberField"; import { DocumentManager } from "../../util/DocumentManager"; import request = require("request"); import { ServerUtils } from "../../../server/ServerUtil"; +import { addHiddenFinalProp } from "mobx/lib/internal"; export interface CollectionViewProps { fieldKey: Key; @@ -33,7 +34,7 @@ export interface CollectionViewProps { export interface SubCollectionViewProps extends CollectionViewProps { active: () => boolean; - addDocument: (doc: Document, allowDuplicates: boolean) => void; + addDocument: (doc: Document, allowDuplicates: boolean) => boolean; removeDocument: (doc: Document) => boolean; CollectionView: CollectionView; } @@ -83,17 +84,20 @@ export class CollectionViewBase extends React.Component @undoBatch @action - protected drop(e: Event, de: DragManager.DropEvent) { + protected drop(e: Event, de: DragManager.DropEvent): boolean { if (de.data instanceof DragManager.DocumentDragData) { if (de.data.aliasOnDrop) { [KeyStore.Width, KeyStore.Height, KeyStore.CurPage].map(key => de.data.draggedDocument.GetTAsync(key, NumberField, (f: Opt) => f ? de.data.droppedDocument.SetNumber(key, f.Data) : null)); - } else if (de.data.removeDocument) { + } + let added = this.props.addDocument(de.data.droppedDocument, false); + if (added && de.data.removeDocument && !de.data.aliasOnDrop) { de.data.removeDocument(this.props.CollectionView); } - this.props.addDocument(de.data.droppedDocument, false); e.stopPropagation(); + return added; } + return false; } protected getDocumentFromType(type: string, path: string, options: DocumentOptions): Opt { diff --git a/src/client/views/collections/MarqueeView.tsx b/src/client/views/collections/MarqueeView.tsx index 8c2f3443c..b48ad9c64 100644 --- a/src/client/views/collections/MarqueeView.tsx +++ b/src/client/views/collections/MarqueeView.tsx @@ -17,7 +17,7 @@ interface MarqueeViewProps { getMarqueeTransform: () => Transform; getTransform: () => Transform; container: CollectionFreeFormView; - addDocument: (doc: Document, allowDuplicates: false) => void; + addDocument: (doc: Document, allowDuplicates: false) => boolean; activeDocuments: () => Document[]; selectDocuments: (docs: Document[]) => void; removeDocument: (doc: Document) => boolean; diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index fec451b09..383341e02 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -23,7 +23,7 @@ import React = require("react"); export interface DocumentViewProps { ContainingCollectionView: Opt; Document: Document; - AddDocument?: (doc: Document, allowDuplicates: boolean) => void; + AddDocument?: (doc: Document, allowDuplicates: boolean) => boolean; RemoveDocument?: (doc: Document) => boolean; ScreenToLocalTransform: () => Transform; isTopMost: boolean; -- cgit v1.2.3-70-g09d2 From eb27dd447502ee1f55296b9e496aee998b0259f2 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 21 Mar 2019 23:10:42 -0400 Subject: avoided another cycle --- src/client/views/collections/CollectionView.tsx | 29 +++++++++++++++++++------ 1 file changed, 22 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 2e93e6bb8..be757e22e 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -14,6 +14,7 @@ import { CollectionViewProps } from "./CollectionViewBase"; import { CollectionTreeView } from "./CollectionTreeView"; import { Field, FieldId, FieldWaiting } from "../../../fields/Field"; import { Main } from "../Main"; +import { dropPoint } from "prosemirror-transform"; export enum CollectionViewType { Invalid, @@ -48,13 +49,22 @@ export class CollectionView extends React.Component { return isSelected || childSelected || topMost; } - static createsCycle(doc: Document, props: CollectionViewProps): boolean { - let ldata = doc.GetList(KeyStore.Data, []); - for (let i = 0; i < ldata.length; i++) { - if (CollectionView.createsCycle(ldata[i], props)) + static createsCycle(documentToAdd: Document, containerDocument: Document): boolean { + let data = documentToAdd.GetList(KeyStore.Data, []); + for (let i = 0; i < data.length; i++) { + if (CollectionView.createsCycle(data[i], containerDocument)) return true; } - return doc.Id == props.Document.Id; + let annots = documentToAdd.GetList(KeyStore.Annotations, []); + for (let i = 0; i < annots.length; i++) { + if (CollectionView.createsCycle(annots[i], containerDocument)) + return true; + } + for (let containerProto: any = containerDocument; containerProto && containerProto != FieldWaiting; containerProto = containerProto.GetPrototype()) { + if (containerProto.Id == documentToAdd.Id) + return true; + } + return false; } @action @@ -63,14 +73,19 @@ export class CollectionView extends React.Component { if (props.Document.Get(props.fieldKey) instanceof Field) { //TODO This won't create the field if it doesn't already exist const value = props.Document.GetData(props.fieldKey, ListField, new Array()) - if (!CollectionView.createsCycle(doc, props)) { + if (!CollectionView.createsCycle(doc, props.Document)) { if (!value.some(v => v.Id == doc.Id) || allowDuplicates) value.push(doc); } else return false; } else { - props.Document.SetOnPrototype(props.fieldKey, new ListField([doc])); + let proto = props.Document.GetPrototype(); + if (!proto || proto == FieldWaiting || !CollectionView.createsCycle(proto, doc)) { + props.Document.SetOnPrototype(props.fieldKey, new ListField([doc])); + } + else + return false; } return true; } -- cgit v1.2.3-70-g09d2 From adaba603d22ae28feb2d4d1a5eda43a52f8ad9ba Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 22 Mar 2019 02:53:34 -0400 Subject: Added optional logging for socket.io calls --- src/Utils.ts | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/Utils.ts b/src/Utils.ts index be97dc90b..3849372b0 100644 --- a/src/Utils.ts +++ b/src/Utils.ts @@ -37,26 +37,49 @@ export class Utils { document.body.removeChild(textArea); } + public static loggingEnabled: Boolean = false; + private static log(prefix: string, messageName: string, message: any, receiving: boolean) { + if (!this.loggingEnabled) { + return; + } + !message && console.log(prefix, messageName) + message = message || {}; + let idString = (message._id || message.id || "").padStart(36, ' '); + prefix = prefix.padEnd(16, ' '); + console.log(`${prefix}: ${idString}, ${receiving ? 'receiving' : 'sending'} ${messageName} with data ${JSON.stringify(message)}`); + } + private static loggingCallback(prefix: string, func: (args: any) => any, messageName: string) { + return (args: any) => { + this.log(prefix, messageName, args, true); + func(args); + } + }; + public static Emit(socket: Socket | SocketIOClient.Socket, message: Message, args: T) { + this.log("Emit", message.Name, args, false); socket.emit(message.Message, args); } public static EmitCallback(socket: Socket | SocketIOClient.Socket, message: Message, args: T): Promise; public static EmitCallback(socket: Socket | SocketIOClient.Socket, message: Message, args: T, fn: (args: any) => any): void; public static EmitCallback(socket: Socket | SocketIOClient.Socket, message: Message, args: T, fn?: (args: any) => any): void | Promise { + this.log("Emit", message.Name, args, false); if (fn) { - socket.emit(message.Message, args, fn); + socket.emit(message.Message, args, this.loggingCallback('Receiving', fn, message.Name)); } else { - return new Promise(res => socket.emit(message.Message, args, res)); + return new Promise(res => socket.emit(message.Message, args, this.loggingCallback('Receiving', res, message.Name))); } } - public static AddServerHandler(socket: Socket, message: Message, handler: (args: T) => any) { - socket.on(message.Message, handler); + public static AddServerHandler(socket: Socket | SocketIOClient.Socket, message: Message, handler: (args: T) => any) { + socket.on(message.Message, this.loggingCallback('Incoming', handler, message.Name)); } public static AddServerHandlerCallback(socket: Socket, message: Message, handler: (args: [T, (res: any) => any]) => any) { - socket.on(message.Message, (arg: T, fn: (res: any) => any) => handler([arg, fn])); + socket.on(message.Message, (arg: T, fn: (res: any) => any) => { + this.log('S receiving', message.Name, arg, true); + handler([arg, this.loggingCallback('S sending', fn, message.Name)]) + }); } } -- cgit v1.2.3-70-g09d2 From 618fc97d28686c256bb3b179ada482f142b9bd31 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 22 Mar 2019 02:57:16 -0400 Subject: Added interface for GetFields request Added one more Promise --- src/client/Server.ts | 18 ++++++++++++++---- src/client/SocketStub.ts | 7 ++++++- 2 files changed, 20 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/client/Server.ts b/src/client/Server.ts index 6a47076fb..e2c352b14 100644 --- a/src/client/Server.ts +++ b/src/client/Server.ts @@ -2,7 +2,7 @@ import { Key } from "../fields/Key" import { ObservableMap, action, reaction } from "mobx"; import { Field, FieldWaiting, FIELD_WAITING, Opt, FieldId } from "../fields/Field" import { Document } from "../fields/Document" -import { SocketStub } from "./SocketStub"; +import { SocketStub, FieldMap } from "./SocketStub"; import * as OpenSocket from 'socket.io-client'; import { Utils } from "./../Utils"; import { MessageStore, Types } from "./../server/Message"; @@ -52,11 +52,15 @@ export class Server { if (callback) { fn(callback); } else { - return new Promise>(res => fn(res)); + return new Promise(res => fn(res)); } } - public static GetFields(fieldIds: FieldId[], callback: (fields: { [id: string]: Field }) => any) { + public static GetFields(fieldIds: FieldId[]): Promise<{ [id: string]: Field }>; + public static GetFields(fieldIds: FieldId[], callback: (fields: FieldMap) => any): void; + public static GetFields(fieldIds: FieldId[], callback?: (fields: FieldMap) => any): Promise | void { + let fn = (cb: (fields: FieldMap) => void) => { + let neededFieldIds: FieldId[] = []; let waitingFieldIds: FieldId[] = []; let existingFields: { [id: string]: Field } = {}; @@ -87,10 +91,16 @@ export class Server { let realField = field as Field; existingFields[realField.Id] = realField; } - callback({ ...fields, ...existingFields }) + cb({ ...fields, ...existingFields }) } }, { fireImmediately: true }) }); + }; + if (callback) { + fn(callback); + } else { + return new Promise(res => fn(res)); + } } public static GetDocumentField(doc: Document, key: Key, callback?: (field: Field) => void) { diff --git a/src/client/SocketStub.ts b/src/client/SocketStub.ts index 27528c4c3..5045037c5 100644 --- a/src/client/SocketStub.ts +++ b/src/client/SocketStub.ts @@ -7,6 +7,11 @@ import { Utils } from "../Utils"; import { Server } from "./Server"; import { ServerUtils } from "../server/ServerUtil"; + +export interface FieldMap { + [id: string]: Opt; +} + //TODO tfs: I think it might be cleaner to not have SocketStub deal with turning what the server gives it into Fields (in other words not call ServerUtils.FromJson), and leave that for the Server class. export class SocketStub { @@ -54,7 +59,7 @@ export class SocketStub { } } - public static SEND_FIELDS_REQUEST(fieldIds: FieldId[], callback: (fields: { [key: string]: Field }) => any) { + public static SEND_FIELDS_REQUEST(fieldIds: FieldId[], callback: (fields: FieldMap) => any) { Utils.EmitCallback(Server.Socket, MessageStore.GetFields, fieldIds, (fields: any[]) => { let fieldMap: any = {}; for (let field of fields) { -- cgit v1.2.3-70-g09d2 From b2cfb0061ce74d095b176a830c3bc654dbaa783b Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 22 Mar 2019 02:58:15 -0400 Subject: Better typechecking and more Promises --- src/client/documents/Documents.ts | 5 ++--- src/client/views/Main.tsx | 16 +++++++++------- 2 files changed, 11 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index cf6d7d503..96a7332aa 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -63,15 +63,14 @@ export namespace Documents { const videoProtoId = "videoProto" const audioProtoId = "audioProto"; - export function initProtos(callback: () => void) { - Server.GetFields([collProtoId, textProtoId, imageProtoId], (fields) => { + export function initProtos(): Promise { + return Server.GetFields([textProtoId, histoProtoId, collProtoId, imageProtoId, webProtoId, kvpProtoId]).then(fields => { textProto = fields[textProtoId] as Document; histoProto = fields[histoProtoId] as Document; collProto = fields[collProtoId] as Document; imageProto = fields[imageProtoId] as Document; webProto = fields[webProtoId] as Document; kvpProto = fields[kvpProtoId] as Document; - callback(); }); } function assignOptions(doc: Document, options: DocumentOptions): Document { diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index d2ba6998c..fdbad6ce1 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -23,7 +23,7 @@ import "./Main.scss"; import { observer } from 'mobx-react'; import { InkingControl } from './InkingControl'; import { RouteStore } from '../../server/RouteStore'; -import { library } from '@fortawesome/fontawesome-svg-core'; +import { library, IconName } from '@fortawesome/fontawesome-svg-core'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faFont } from '@fortawesome/free-solid-svg-icons'; import { faImage } from '@fortawesome/free-solid-svg-icons'; @@ -109,7 +109,7 @@ export class Main extends React.Component { library.add(faTree); this.initEventListeners(); - Documents.initProtos(() => this.initAuthenticationRouters()); + this.initAuthenticationRouters(); this.initializeNorthstar(); } @@ -256,7 +256,7 @@ export class Main extends React.Component { let addWebNode = action(() => Documents.WebDocument(weburl, { width: 200, height: 200, title: "a sample web page" })); let addAudioNode = action(() => Documents.AudioDocument(audiourl, { width: 200, height: 200, title: "audio node" })) - let btns = [ + let btns: [React.RefObject, IconName, string, () => Document][] = [ [React.createRef(), "font", "Add Textbox", addTextNode], [React.createRef(), "image", "Add Image", addImageNode], [React.createRef(), "file-pdf", "Add PDF", addPDFNode], @@ -277,9 +277,9 @@ export class Main extends React.Component {
    {btns.map(btn => -
  • }> -
  • )}
@@ -375,6 +375,8 @@ export class Main extends React.Component { } } -CurrentUserUtils.loadCurrentUser().then(() => { +Documents.initProtos().then(() => { + return CurrentUserUtils.loadCurrentUser() +}).then(() => { ReactDOM.render(
, document.getElementById('root')); }); -- cgit v1.2.3-70-g09d2 From 81f81950b771d0cb1974200d25bd2da4bcc52a36 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 22 Mar 2019 02:58:35 -0400 Subject: FieldMap change --- src/fields/ListField.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/fields/ListField.ts b/src/fields/ListField.ts index 4527ee548..c4008bd12 100644 --- a/src/fields/ListField.ts +++ b/src/fields/ListField.ts @@ -4,6 +4,7 @@ import { UndoManager } from "../client/util/UndoManager"; import { Types } from "../server/Message"; import { BasicField } from "./BasicField"; import { Field, FieldId } from "./Field"; +import { FieldMap } from "../client/SocketStub"; export class ListField extends BasicField { private _proxies: string[] = [] @@ -71,7 +72,7 @@ export class ListField extends BasicField { } init(callback: (field: Field) => any) { - Server.GetFields(this._proxies, action((fields: { [index: string]: Field }) => { + Server.GetFields(this._proxies, action((fields: FieldMap) => { if (!this.arraysEqual(this._proxies, this.data.map(field => field.Id))) { var dataids = this.data.map(d => d.Id); var proxies = this._proxies.map(p => p); @@ -111,7 +112,7 @@ export class ListField extends BasicField { ToJson(): { type: Types, data: string[], _id: string } { return { type: Types.List, - data: this._proxies, + data: this._proxies || [], _id: this.Id } } -- cgit v1.2.3-70-g09d2 From 7ffbfd93f6c7c66993e0f447ba10a06386512c75 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 22 Mar 2019 02:59:11 -0400 Subject: Moved LayoutKeys check --- src/client/views/nodes/DocumentContentsView.tsx | 7 ++++++- src/client/views/nodes/DocumentView.tsx | 4 ---- 2 files changed, 6 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index 2f0459f88..12d14eb42 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -47,8 +47,13 @@ export class DocumentContentsView extends React.ComponentError loading layout keys

; + } return { console.log(test) }} diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index fec451b09..cfe67c8fe 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -314,10 +314,6 @@ export class DocumentView extends React.Component { if (!this.props.Document) { return (null); } - let lkeys = this.props.Document.GetT(KeyStore.LayoutKeys, ListField); - if (!lkeys || lkeys === FieldWaiting) { - return

Error loading layout keys

; - } var scaling = this.props.ContentScaling(); var nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 0); var nativeHeight = this.props.Document.GetNumber(KeyStore.NativeHeight, 0); -- cgit v1.2.3-70-g09d2 From 465502a134ec6646d3ce75eae7c0a2d2f7eb5800 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 22 Mar 2019 02:59:46 -0400 Subject: Fixed layout keys bug --- src/client/Server.ts | 79 +++++++++++++++++++++++++++++++--------------------- 1 file changed, 47 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/client/Server.ts b/src/client/Server.ts index e2c352b14..feafe9eb4 100644 --- a/src/client/Server.ts +++ b/src/client/Server.ts @@ -61,40 +61,50 @@ export class Server { public static GetFields(fieldIds: FieldId[], callback?: (fields: FieldMap) => any): Promise | void { let fn = (cb: (fields: FieldMap) => void) => { - let neededFieldIds: FieldId[] = []; - let waitingFieldIds: FieldId[] = []; - let existingFields: { [id: string]: Field } = {}; - for (let id of fieldIds) { - let field = this.ClientFieldsCached.get(id); - if (!field) { - neededFieldIds.push(id); - this.ClientFieldsCached.set(id, FieldWaiting); - } else if (field === FieldWaiting) { - waitingFieldIds.push(id); - } else { - existingFields[id] = field; - } - } - SocketStub.SEND_FIELDS_REQUEST(neededFieldIds, (fields) => { - for (let key in fields) { - let field = fields[key]; - if (!(this.ClientFieldsCached.get(field.Id) instanceof Field)) { - this.ClientFieldsCached.set(field.Id, field) + let neededFieldIds: FieldId[] = []; + let waitingFieldIds: FieldId[] = []; + let existingFields: { [id: string]: Field } = {}; + for (let id of fieldIds) { + let field = this.ClientFieldsCached.get(id); + if (!field) { + neededFieldIds.push(id); + this.ClientFieldsCached.set(id, FieldWaiting); + } else if (field === FieldWaiting) { + waitingFieldIds.push(id); + } else { + existingFields[id] = field; } } - reaction(() => { - return waitingFieldIds.map(id => this.ClientFieldsCached.get(id)); - }, (cachedFields, reaction) => { - if (!cachedFields.some(field => !field || field === FieldWaiting)) { - reaction.dispose(); - for (let field of cachedFields) { - let realField = field as Field; - existingFields[realField.Id] = realField; + SocketStub.SEND_FIELDS_REQUEST(neededFieldIds, (fields) => { + for (let id of neededFieldIds) { + let field = fields[id]; + if (field) { + if (!(this.ClientFieldsCached.get(field.Id) instanceof Field)) { + this.ClientFieldsCached.set(field.Id, field) + } else { + throw new Error("we shouldn't be trying to replace things that are already in the cache") + } + } else { + if (this.ClientFieldsCached.get(id) === FieldWaiting) { + this.ClientFieldsCached.delete(id); + } else { + throw new Error("we shouldn't be trying to replace things that are already in the cache") + } } - cb({ ...fields, ...existingFields }) } - }, { fireImmediately: true }) - }); + reaction(() => { + return waitingFieldIds.map(id => this.ClientFieldsCached.get(id)); + }, (cachedFields, reaction) => { + if (!cachedFields.some(field => !field || field === FieldWaiting)) { + reaction.dispose(); + for (let field of cachedFields) { + let realField = field as Field; + existingFields[realField.Id] = realField; + } + cb({ ...fields, ...existingFields }) + } + }, { fireImmediately: true }) + }); }; if (callback) { fn(callback); @@ -156,12 +166,17 @@ export class Server { if (Server.ClientFieldsCached.has(field._id)) { var f = Server.ClientFieldsCached.get(field._id); if (f && f != FieldWaiting) { + // console.log("Applying : " + field._id); f.UpdateFromServer(field.data); f.init(() => { }); + } else { + // console.log("Not applying wa : " + field._id); } + } else { + // console.log("Not applying mi : " + field._id); } } } -Server.Socket.on(MessageStore.Foo.Message, Server.connected); -Server.Socket.on(MessageStore.SetField.Message, Server.updateField); +Utils.AddServerHandler(Server.Socket, MessageStore.Foo, Server.connected); +Utils.AddServerHandler(Server.Socket, MessageStore.SetField, Server.updateField); -- cgit v1.2.3-70-g09d2 From 8b20d1aa5e980e10f36827c4b9fb2ada29d248b0 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 22 Mar 2019 03:34:20 -0400 Subject: Made delete and deleteAll behave better --- src/server/database.ts | 12 +++++++----- src/server/index.ts | 16 ++++++++-------- 2 files changed, 15 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/server/database.ts b/src/server/database.ts index 99b13805e..73affdb15 100644 --- a/src/server/database.ts +++ b/src/server/database.ts @@ -32,11 +32,13 @@ export class Database { } } - public deleteAll(collectionName: string = 'documents') { - if (this.db) { - let collection = this.db.collection(collectionName); - collection.deleteMany({}); - } + public deleteAll(collectionName: string = 'documents'): Promise { + return new Promise(res => { + if (this.db) { + let collection = this.db.collection(collectionName); + collection.deleteMany({}, res); + } + }) } public insert(kvpairs: any) { diff --git a/src/server/index.ts b/src/server/index.ts index 16304f1c5..17d7432e0 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -223,13 +223,11 @@ app.use(RouteStore.corsProxy, (req, res) => { }); app.get(RouteStore.delete, (req, res) => { - deleteFields(); - res.redirect(RouteStore.home); + deleteFields().then(() => res.redirect(RouteStore.home)); }); app.get(RouteStore.deleteAll, (req, res) => { - deleteAll(); - res.redirect(RouteStore.home); + deleteAll().then(() => res.redirect(RouteStore.home)); }); app.use(wdm(compiler, { @@ -262,13 +260,15 @@ server.on("connection", function (socket: Socket) { }) function deleteFields() { - Database.Instance.deleteAll(); + return Database.Instance.deleteAll(); } function deleteAll() { - Database.Instance.deleteAll(); - Database.Instance.deleteAll('sessions'); - Database.Instance.deleteAll('users'); + return Database.Instance.deleteAll().then(() => { + return Database.Instance.deleteAll('sessions') + }).then(() => { + return Database.Instance.deleteAll('users') + }); } function barReceived(guid: String) { -- cgit v1.2.3-70-g09d2 From 3eefc8c7e901242ac6b7614bf1163858568d53b0 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 22 Mar 2019 05:19:37 -0400 Subject: Moved main doc id --- src/client/views/Main.tsx | 14 ++++++-------- src/client/views/collections/CollectionView.tsx | 4 ++-- src/server/authentication/models/current_user_utils.ts | 16 +++++++++++++--- 3 files changed, 21 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index fdbad6ce1..cb49bc4e6 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -73,8 +73,6 @@ export class Main extends React.Component { return CurrentUserUtils.UserDocument; } - public mainDocId: string | undefined; - private currentUser?: DashUserModel; public static Instance: Main; constructor(props: Readonly<{}>) { @@ -85,7 +83,7 @@ export class Main extends React.Component { if (window.location.pathname !== RouteStore.home) { let pathname = window.location.pathname.split("/"); if (pathname.length > 1 && pathname[pathname.length - 2] == 'doc') { - this.mainDocId = pathname[pathname.length - 1]; + CurrentUserUtils.MainDocId = pathname[pathname.length - 1]; } }; @@ -117,8 +115,8 @@ export class Main extends React.Component { onHistory = () => { if (window.location.pathname !== RouteStore.home) { let pathname = window.location.pathname.split("/"); - this.mainDocId = pathname[pathname.length - 1]; - Server.GetField(this.mainDocId, action((field: Opt) => { + CurrentUserUtils.MainDocId = pathname[pathname.length - 1]; + Server.GetField(CurrentUserUtils.MainDocId, action((field: Opt) => { if (field instanceof Document) { this.openWorkspace(field, true); } @@ -148,7 +146,7 @@ export class Main extends React.Component { initAuthenticationRouters = () => { // Load the user's active workspace, or create a new one if initial session after signup - if (!this.mainDocId) { + if (!CurrentUserUtils.MainDocId) { this.userDocument.GetTAsync(KeyStore.ActiveWorkspace, Document).then(doc => { if (doc) { this.openWorkspace(doc); @@ -157,11 +155,11 @@ export class Main extends React.Component { } }) } else { - Server.GetField(this.mainDocId).then(field => { + Server.GetField(CurrentUserUtils.MainDocId).then(field => { if (field instanceof Document) { this.openWorkspace(field) } else { - this.createNewWorkspace(this.mainDocId); + this.createNewWorkspace(CurrentUserUtils.MainDocId); } }) } diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 7e1d31018..c72633175 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -13,7 +13,7 @@ import { CollectionSchemaView } from "./CollectionSchemaView"; import { CollectionViewProps } from "./CollectionViewBase"; import { CollectionTreeView } from "./CollectionTreeView"; import { Field, FieldId, FieldWaiting } from "../../../fields/Field"; -import { Main } from "../Main"; +import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; export enum CollectionViewType { Invalid, @@ -96,7 +96,7 @@ export class CollectionView extends React.Component { } specificContextMenu = (e: React.MouseEvent): void => { - if (!e.isPropagationStopped() && this.props.Document.Id != Main.Instance.mainDocId) { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7 + if (!e.isPropagationStopped() && this.props.Document.Id != CurrentUserUtils.MainDocId) { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7 ContextMenu.Instance.addItem({ description: "Freeform", event: () => this.props.Document.SetNumber(KeyStore.ViewType, CollectionViewType.Freeform) }) ContextMenu.Instance.addItem({ description: "Schema", event: () => this.props.Document.SetNumber(KeyStore.ViewType, CollectionViewType.Schema) }) ContextMenu.Instance.addItem({ description: "Treeview", event: () => this.props.Document.SetNumber(KeyStore.ViewType, CollectionViewType.Tree) }) diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 17a6d493b..3291c671c 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -12,17 +12,27 @@ export class CurrentUserUtils { private static curr_email: string; private static curr_id: string; private static user_document: Document; + //TODO tfs: this should be temporary... + private static mainDocId: string | undefined; public static get email(): string { - return CurrentUserUtils.curr_email; + return this.curr_email; } public static get id(): string { - return CurrentUserUtils.curr_id; + return this.curr_id; } public static get UserDocument(): Document { - return CurrentUserUtils.user_document; + return this.user_document; + } + + public static get MainDocId(): string | undefined { + return this.mainDocId; + } + + public static set MainDocId(id: string | undefined) { + this.mainDocId = id; } private static createUserDocument(id: string): Document { -- cgit v1.2.3-70-g09d2 From dfe70d4f21a8122a6608e127203de2572a9a25fb Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 22 Mar 2019 05:32:20 -0400 Subject: Moved active schema out of main --- src/client/northstar/model/ModelHelpers.ts | 10 ++++---- .../northstar/operations/HistogramOperation.ts | 4 ++-- src/client/views/Main.tsx | 21 ++--------------- src/client/views/nodes/HistogramBox.tsx | 4 ++-- .../authentication/models/current_user_utils.ts | 27 +++++++++++++++++++++- 5 files changed, 37 insertions(+), 29 deletions(-) (limited to 'src') diff --git a/src/client/northstar/model/ModelHelpers.ts b/src/client/northstar/model/ModelHelpers.ts index e1241b3ef..914e03255 100644 --- a/src/client/northstar/model/ModelHelpers.ts +++ b/src/client/northstar/model/ModelHelpers.ts @@ -9,7 +9,7 @@ import { AlphabeticVisualBinRange } from "./binRanges/AlphabeticVisualBinRange"; import { NominalVisualBinRange } from "./binRanges/NominalVisualBinRange"; import { VisualBinRangeHelper } from "./binRanges/VisualBinRangeHelper"; import { AttributeTransformationModel } from "../core/attribute/AttributeTransformationModel"; -import { Main } from "../../views/Main"; +import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; export class ModelHelpers { @@ -39,19 +39,19 @@ export class ModelHelpers { if (atm.AggregateFunction === AggregateFunction.Avg) { var avg = new AverageAggregateParameters(); avg.attributeParameters = ModelHelpers.GetAttributeParameters(atm.AttributeModel); - avg.distinctAttributeParameters = Main.Instance.ActiveSchema!.distinctAttributeParameters; + avg.distinctAttributeParameters = CurrentUserUtils.ActiveSchema!.distinctAttributeParameters; aggParam = avg; } else if (atm.AggregateFunction === AggregateFunction.Count) { var cnt = new CountAggregateParameters(); cnt.attributeParameters = ModelHelpers.GetAttributeParameters(atm.AttributeModel); - cnt.distinctAttributeParameters = Main.Instance.ActiveSchema!.distinctAttributeParameters; + cnt.distinctAttributeParameters = CurrentUserUtils.ActiveSchema!.distinctAttributeParameters; aggParam = cnt; } else if (atm.AggregateFunction === AggregateFunction.Sum) { var sum = new SumAggregateParameters(); sum.attributeParameters = ModelHelpers.GetAttributeParameters(atm.AttributeModel); - sum.distinctAttributeParameters = Main.Instance.ActiveSchema!.distinctAttributeParameters; + sum.distinctAttributeParameters = CurrentUserUtils.ActiveSchema!.distinctAttributeParameters; aggParam = sum; } return aggParam; @@ -66,7 +66,7 @@ export class ModelHelpers { var margin = new MarginAggregateParameters(); margin.attributeParameters = ModelHelpers.GetAttributeParameters(agg.AttributeModel); - margin.distinctAttributeParameters = Main.Instance.ActiveSchema!.distinctAttributeParameters; + margin.distinctAttributeParameters = CurrentUserUtils.ActiveSchema!.distinctAttributeParameters; margin.aggregateFunction = agg.AggregateFunction; aggregateParameters.push(margin); } diff --git a/src/client/northstar/operations/HistogramOperation.ts b/src/client/northstar/operations/HistogramOperation.ts index a4f5cac70..120a84dad 100644 --- a/src/client/northstar/operations/HistogramOperation.ts +++ b/src/client/northstar/operations/HistogramOperation.ts @@ -5,8 +5,8 @@ import { CalculatedAttributeManager } from "../core/attribute/CalculatedAttribut import { ModelHelpers } from "../model/ModelHelpers"; import { SETTINGS_X_BINS, SETTINGS_Y_BINS, SETTINGS_SAMPLE_SIZE } from "../model/binRanges/VisualBinRangeHelper"; import { AttributeTransformationModel } from "../core/attribute/AttributeTransformationModel"; -import { Main } from "../../views/Main"; import { BaseOperation } from "./BaseOperation"; +import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; export class HistogramOperation extends BaseOperation { @@ -83,7 +83,7 @@ export class HistogramOperation extends BaseOperation { let [perBinAggregateParameters, globalAggregateParameters] = this.GetAggregateParameters(this.X, this.Y, this.V); return new HistogramOperationParameters({ enableBrushComputation: true, - adapterName: Main.Instance.ActiveSchema!.displayName, + adapterName: CurrentUserUtils.ActiveSchema!.displayName, 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), diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index cb49bc4e6..6534cb4f7 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -55,7 +55,6 @@ export class Main extends React.Component { @observable private mainfreeform?: Document; @observable public pwidth: number = 0; @observable public pheight: number = 0; - @observable ActiveSchema: Schema | undefined; private _northstarColumns: Document[] = []; @computed private get mainContainer(): Document | undefined { @@ -339,8 +338,8 @@ export class Main extends React.Component { @action SetNorthstarCatalog(ctlog: Catalog) { if (ctlog && ctlog.schemas) { - this.ActiveSchema = ArrayUtil.FirstOrDefault(ctlog.schemas!, (s: Schema) => s.displayName === "mimic"); - this._northstarColumns = this.GetAllNorthstarColumnAttributes().map(a => Documents.HistogramDocument({ width: 200, height: 200, title: a.displayName! })); + CurrentUserUtils.ActiveSchema = ArrayUtil.FirstOrDefault(ctlog.schemas!, (s: Schema) => s.displayName === "mimic"); + this._northstarColumns = CurrentUserUtils.GetAllNorthstarColumnAttributes().map(a => Documents.HistogramDocument({ width: 200, height: 200, title: a.displayName! })); } } async initializeNorthstar(): Promise { @@ -355,22 +354,6 @@ export class Main extends React.Component { let cat = Gateway.Instance.ClearCatalog(); cat.then(async () => this.SetNorthstarCatalog(await Gateway.Instance.GetCatalog())); } - public GetAllNorthstarColumnAttributes() { - if (!this.ActiveSchema || !this.ActiveSchema.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, this.ActiveSchema.rootAttributeGroup); - return allAttributes; - } } Documents.initProtos().then(() => { diff --git a/src/client/views/nodes/HistogramBox.tsx b/src/client/views/nodes/HistogramBox.tsx index 223fdf0d8..cc43899c1 100644 --- a/src/client/views/nodes/HistogramBox.tsx +++ b/src/client/views/nodes/HistogramBox.tsx @@ -4,11 +4,11 @@ import { FieldView, FieldViewProps } from './FieldView'; import "./VideoBox.scss"; import { observable, reaction } from "mobx"; import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; -import { Main } from "../Main"; import { ColumnAttributeModel } from "../../northstar/core/attribute/AttributeModel"; import { AttributeTransformationModel } from "../../northstar/core/attribute/AttributeTransformationModel"; import { AggregateFunction, HistogramResult, DoubleValueAggregateResult } from "../../northstar/model/idea/idea"; import { ModelHelpers } from "../../northstar/model/ModelHelpers"; +import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; @observer export class HistogramBox extends React.Component { @@ -23,7 +23,7 @@ export class HistogramBox extends React.Component { _histoOp?: HistogramOperation; componentDidMount() { - Main.Instance.GetAllNorthstarColumnAttributes().map(a => { + CurrentUserUtils.GetAllNorthstarColumnAttributes().map(a => { if (a.displayName == this.props.doc.Title) { var atmod = new ColumnAttributeModel(a); this._histoOp = new HistogramOperation(new AttributeTransformationModel(atmod, AggregateFunction.None), diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 3291c671c..055e4cc97 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -7,13 +7,15 @@ import { Document } from "../../../fields/Document"; import { KeyStore } from "../../../fields/KeyStore"; import { ListField } from "../../../fields/ListField"; import { Documents } from "../../../client/documents/Documents"; +import { Schema, Attribute, AttributeGroup } from "../../../client/northstar/model/idea/idea"; export class CurrentUserUtils { private static curr_email: string; private static curr_id: string; private static user_document: Document; - //TODO tfs: this should be temporary... + //TODO tfs: these should be temporary... private static mainDocId: string | undefined; + private static activeSchema: Schema | undefined; public static get email(): string { return this.curr_email; @@ -35,6 +37,29 @@ export class CurrentUserUtils { this.mainDocId = id; } + public static get ActiveSchema(): Schema | undefined { + return this.activeSchema; + } + public static GetAllNorthstarColumnAttributes() { + if (!this.ActiveSchema || !this.ActiveSchema.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, this.ActiveSchema.rootAttributeGroup); + return allAttributes; + } + + public static set ActiveSchema(id: Schema | undefined) { + this.activeSchema = id; + } private static createUserDocument(id: string): Document { let doc = new Document(id); -- cgit v1.2.3-70-g09d2 From 619c01891713b0ceb889ab45659b35f4b9fbc7e3 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 22 Mar 2019 07:15:22 -0400 Subject: Added basic fill down to schema view --- src/client/util/Scripting.ts | 2 +- src/client/util/type_decls.d | 7 ++++ src/client/views/EditableView.tsx | 11 +++++- .../views/collections/CollectionSchemaView.tsx | 43 ++++++++++++++-------- src/fields/Document.ts | 8 +++- 5 files changed, 51 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/client/util/Scripting.ts b/src/client/util/Scripting.ts index 46bd1a206..4cf98472f 100644 --- a/src/client/util/Scripting.ts +++ b/src/client/util/Scripting.ts @@ -110,7 +110,7 @@ export function CompileScript(script: string, scope?: { [name: string]: any }, a let host = new ScriptingCompilerHost; let funcScript = `(function() { ${addReturn ? `return ${script};` : script} - })()` + }).apply(this)` host.writeFile("file.ts", funcScript); host.writeFile('node_modules/typescript/lib/lib.d.ts', typescriptlib); let program = ts.createProgram(["file.ts"], {}, host); diff --git a/src/client/util/type_decls.d b/src/client/util/type_decls.d index 679f73f42..dcf79285d 100644 --- a/src/client/util/type_decls.d +++ b/src/client/util/type_decls.d @@ -213,3 +213,10 @@ declare class Document extends Field { GetAllPrototypes(): Document[]; MakeDelegate(): Document; } + +declare const KeyStore: { + [name: string]: Key; +} + +// @ts-ignore +declare const console: any; diff --git a/src/client/views/EditableView.tsx b/src/client/views/EditableView.tsx index 579d6e6ad..29bf6add7 100644 --- a/src/client/views/EditableView.tsx +++ b/src/client/views/EditableView.tsx @@ -16,6 +16,8 @@ export interface EditableProps { * */ SetValue(value: string): boolean; + OnFillDown?(value: string): void; + /** * The contents to render when not editing */ @@ -36,8 +38,13 @@ export class EditableView extends React.Component { @action onKeyDown = (e: React.KeyboardEvent) => { - if (e.key == "Enter" && !e.ctrlKey) { - if (this.props.SetValue(e.currentTarget.value)) { + if (e.key == "Enter") { + if (!e.ctrlKey) { + if (this.props.SetValue(e.currentTarget.value)) { + this.editing = false; + } + } else if (this.props.OnFillDown) { + this.props.OnFillDown(e.currentTarget.value); this.editing = false; } } else if (e.key == "Escape") { diff --git a/src/client/views/collections/CollectionSchemaView.tsx b/src/client/views/collections/CollectionSchemaView.tsx index 34b019244..8e0a38f05 100644 --- a/src/client/views/collections/CollectionSchemaView.tsx +++ b/src/client/views/collections/CollectionSchemaView.tsx @@ -85,12 +85,31 @@ export class CollectionSchemaView extends CollectionViewBase { ) let reference = React.createRef(); let onItemDown = setupDrag(reference, () => props.doc, (containingCollection: CollectionView) => this.props.removeDocument(props.doc)); + let applyToDoc = (doc: Document, value: string) => { + let script = CompileScript(value, { this: doc }, true); + if (!script.compiled) { + return false; + } + let field = script(); + if (field instanceof Field) { + doc.Set(props.fieldKey, field); + return true; + } else { + let dataField = ToField(field); + if (dataField) { + doc.Set(props.fieldKey, dataField); + return true; + } + } + return false; + } return (
{ + height={36} + GetValue={() => { let field = props.doc.Get(props.fieldKey); if (field && field instanceof Field) { return field.ToScriptString(); @@ -98,22 +117,14 @@ export class CollectionSchemaView extends CollectionViewBase { return field || ""; }} SetValue={(value: string) => { - let script = CompileScript(value); - if (!script.compiled) { - return false; - } - let field = script(); - if (field instanceof Field) { - props.doc.Set(props.fieldKey, field); - return true; - } else { - let dataField = ToField(field); - if (dataField) { - props.doc.Set(props.fieldKey, dataField); - return true; + return applyToDoc(props.doc, value); + }} + OnFillDown={(value: string) => { + this.props.Document.GetTAsync>(this.props.fieldKey, ListField).then((val) => { + if (val) { + val.Data.forEach(doc => applyToDoc(doc, value)); } - } - return false; + }) }}>
diff --git a/src/fields/Document.ts b/src/fields/Document.ts index fc4906d17..d098cc96d 100644 --- a/src/fields/Document.ts +++ b/src/fields/Document.ts @@ -132,7 +132,13 @@ export class Document extends Field { } else if (this._proxies.has(key.Id)) { Server.GetDocumentField(this, key, callback); } else { - callback(undefined); + this.GetTAsync(KeyStore.Prototype, Document, proto => { + if (proto) { + proto.GetAsync(key, callback); + } else { + callback(undefined); + } + }) } } -- cgit v1.2.3-70-g09d2 From 5b92729515e0fb4bbd951425ace945f45c4f93dd Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 22 Mar 2019 07:20:09 -0400 Subject: Added log filtering --- src/Utils.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/Utils.ts b/src/Utils.ts index 3849372b0..a5d9bd0ca 100644 --- a/src/Utils.ts +++ b/src/Utils.ts @@ -38,12 +38,15 @@ export class Utils { } public static loggingEnabled: Boolean = false; + public static logFilter: number | undefined = undefined; private static log(prefix: string, messageName: string, message: any, receiving: boolean) { if (!this.loggingEnabled) { return; } - !message && console.log(prefix, messageName) message = message || {}; + if (this.logFilter !== undefined && this.logFilter !== message.type) { + return; + } let idString = (message._id || message.id || "").padStart(36, ' '); prefix = prefix.padEnd(16, ' '); console.log(`${prefix}: ${idString}, ${receiving ? 'receiving' : 'sending'} ${messageName} with data ${JSON.stringify(message)}`); -- cgit v1.2.3-70-g09d2 From 2086d916c7b4a6fd1795f1613c08fd4c45325c07 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 22 Mar 2019 07:29:24 -0400 Subject: Fixed infinite recursion --- src/fields/Document.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/fields/Document.ts b/src/fields/Document.ts index d098cc96d..c30e8f4db 100644 --- a/src/fields/Document.ts +++ b/src/fields/Document.ts @@ -131,7 +131,7 @@ export class Document extends Field { callback(field.field); } else if (this._proxies.has(key.Id)) { Server.GetDocumentField(this, key, callback); - } else { + } else if (this._proxies.has(KeyStore.Prototype.Id)) { this.GetTAsync(KeyStore.Prototype, Document, proto => { if (proto) { proto.GetAsync(key, callback); @@ -139,6 +139,8 @@ export class Document extends Field { callback(undefined); } }) + } else { + callback(undefined); } } -- cgit v1.2.3-70-g09d2 From 5a353d0339d3b1e7517151ea20bd0cbe98609034 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 22 Mar 2019 07:41:31 -0400 Subject: Added print to DB update --- src/server/database.ts | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/server/database.ts b/src/server/database.ts index 73affdb15..a42d29aac 100644 --- a/src/server/database.ts +++ b/src/server/database.ts @@ -21,7 +21,16 @@ export class Database { let collection = this.db.collection('documents'); collection.updateOne({ _id: id }, { $set: value }, { upsert: true - }, callback); + }, (err, res) => { + if (err) { + console.log(err.message); + console.log(err.errmsg); + } + if (res) { + console.log(JSON.stringify(res.result)); + } + callback() + }); } } -- cgit v1.2.3-70-g09d2 From 1238c172a2ac9fb7dfdee2588f141f2ae0c22b8e Mon Sep 17 00:00:00 2001 From: bob Date: Fri, 22 Mar 2019 08:54:37 -0400 Subject: fixed schema scrolling --- src/client/views/collections/CollectionSchemaView.tsx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/client/views/collections/CollectionSchemaView.tsx b/src/client/views/collections/CollectionSchemaView.tsx index 34b019244..696527049 100644 --- a/src/client/views/collections/CollectionSchemaView.tsx +++ b/src/client/views/collections/CollectionSchemaView.tsx @@ -238,6 +238,11 @@ export class CollectionSchemaView extends CollectionViewBase { } } + onWheel = (e: React.WheelEvent): void => { + if (this.props.active()) + e.stopPropagation(); + } + @observable _optionsActivated: number = 0; @action OptionsMenuDown = (e: React.PointerEvent) => { @@ -293,7 +298,7 @@ export class CollectionSchemaView extends CollectionViewBase { ); return ( -
+
this.onDrop(e, {})} ref={this.createDropTarget}> {({ measureRef }) => -- cgit v1.2.3-70-g09d2 From 6d68c6e5e5f8f8ea8b1bbad10148a691a8c2e23f Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 22 Mar 2019 09:43:13 -0400 Subject: switched setdata to maybe fix mongo issue --- src/fields/Document.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/fields/Document.ts b/src/fields/Document.ts index c30e8f4db..cd393d676 100644 --- a/src/fields/Document.ts +++ b/src/fields/Document.ts @@ -273,13 +273,13 @@ export class Document extends Field { } @action - SetData(key: Key, value: T, ctor: { new(): U }, replaceWrongType = true) { + SetData(key: Key, value: T, ctor: { new(data: T): U }, replaceWrongType = true) { let field = this.Get(key, true); if (field instanceof ctor) { field.Data = value; } else if (!field || replaceWrongType) { - let newField = new ctor(); - newField.Data = value; + let newField = new ctor(value); + // newField.Data = value; this.Set(key, newField); } } -- cgit v1.2.3-70-g09d2 From 356991c6100a44ef45b4574b43c815383d9be751 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Sat, 23 Mar 2019 00:22:52 -0400 Subject: Various fixes for the demo --- src/client/documents/Documents.ts | 17 ++++++--- src/client/util/Scripting.ts | 8 +++-- src/client/util/type_decls.d | 3 ++ .../views/collections/CollectionFreeFormView.tsx | 5 +++ .../views/collections/CollectionSchemaView.tsx | 42 ++++++++++++++++++---- .../views/collections/CollectionViewBase.tsx | 39 ++++++++++++++------ src/client/views/nodes/DocumentView.tsx | 7 ++++ src/client/views/nodes/FieldView.tsx | 18 +++++++++- src/client/views/nodes/FormattedTextBox.tsx | 2 ++ 9 files changed, 117 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 96a7332aa..a2444db06 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -1,6 +1,6 @@ import { AudioField } from "../../fields/AudioField"; import { Document } from "../../fields/Document"; -import { Field } from "../../fields/Field"; +import { Field, FieldWaiting } from "../../fields/Field"; import { HtmlField } from "../../fields/HtmlField"; import { ImageField } from "../../fields/ImageField"; import { InkField, StrokeData } from "../../fields/InkField"; @@ -23,6 +23,7 @@ import { PDFBox } from "../views/nodes/PDFBox"; import { VideoBox } from "../views/nodes/VideoBox"; import { WebBox } from "../views/nodes/WebBox"; import { HistogramBox } from "../views/nodes/HistogramBox"; +import { FieldView } from "../views/nodes/FieldView"; export interface DocumentOptions { x?: number; @@ -112,7 +113,7 @@ export namespace Documents { function GetImagePrototype(): Document { if (!imageProto) { imageProto = setupPrototypeOptions(imageProtoId, "IMAGE_PROTO", CollectionView.LayoutString("AnnotationsKey"), - { x: 0, y: 0, nativeWidth: 300, width: 300, layoutKeys: [KeyStore.Data, KeyStore.Annotations] }); + { x: 0, y: 0, nativeWidth: 300, width: 300, layoutKeys: [KeyStore.Data, KeyStore.Annotations, KeyStore.Caption] }); imageProto.SetText(KeyStore.BackgroundLayout, ImageBox.LayoutString()); } return imageProto; @@ -155,7 +156,7 @@ export namespace Documents { function GetVideoPrototype(): Document { if (!videoProto) { videoProto = setupPrototypeOptions(videoProtoId, "VIDEO_PROTO", CollectionVideoView.LayoutString("AnnotationsKey"), - { x: 0, y: 0, nativeWidth: 600, width: 300, layoutKeys: [KeyStore.Data, KeyStore.Annotations] }); + { x: 0, y: 0, nativeWidth: 600, width: 300, layoutKeys: [KeyStore.Data, KeyStore.Annotations, KeyStore.Caption] }); videoProto.SetNumber(KeyStore.CurPage, 0); videoProto.SetText(KeyStore.BackgroundLayout, VideoBox.LayoutString()); } @@ -218,6 +219,14 @@ export namespace Documents { return assignToDelegate(SetInstanceOptions(GetCollectionPrototype(), { ...options, viewType: CollectionViewType.Docking }, [config, TextField], id), options) } + export function CaptionDocument(doc: Document) { + const captionDoc = doc.CreateAlias(); + captionDoc.SetText(KeyStore.OverlayLayout, FixedCaption()); + captionDoc.SetNumber(KeyStore.Width, doc.GetNumber(KeyStore.Width, 0)); + captionDoc.SetNumber(KeyStore.Height, doc.GetNumber(KeyStore.Height, 0)); + return captionDoc; + } + // example of custom display string for an image that shows a caption. function EmbeddedCaption() { return `
@@ -228,7 +237,7 @@ export namespace Documents { + FormattedTextBox.LayoutString("CaptionKey") + `
` }; - function FixedCaption(fieldName: string = "Caption") { + export function FixedCaption(fieldName: string = "Caption") { return `
` + FormattedTextBox.LayoutString(fieldName + "Key") + diff --git a/src/client/util/Scripting.ts b/src/client/util/Scripting.ts index 4cf98472f..4e97b9401 100644 --- a/src/client/util/Scripting.ts +++ b/src/client/util/Scripting.ts @@ -15,6 +15,8 @@ import { ListField } from "../../fields/ListField"; // @ts-ignore import * as typescriptlib from '!!raw-loader!./type_decls.d' +import { Documents } from "../documents/Documents"; +import { Key } from "../../fields/Key"; export interface ExecutableScript { @@ -28,9 +30,9 @@ function Compile(script: string | undefined, diagnostics: Opt, scope: { [ let func: () => Opt; if (compiled && script) { - let fieldTypes = [Document, NumberField, TextField, ImageField, RichTextField, ListField]; - let paramNames = ["KeyStore", ...fieldTypes.map(fn => fn.name)]; - let params: any[] = [KeyStore, ...fieldTypes] + let fieldTypes = [Document, NumberField, TextField, ImageField, RichTextField, ListField, Key]; + let paramNames = ["KeyStore", "Documents", ...fieldTypes.map(fn => fn.name)]; + let params: any[] = [KeyStore, Documents, ...fieldTypes] for (let prop in scope) { if (prop === "this") { continue; diff --git a/src/client/util/type_decls.d b/src/client/util/type_decls.d index dcf79285d..4f69053b1 100644 --- a/src/client/util/type_decls.d +++ b/src/client/util/type_decls.d @@ -174,6 +174,7 @@ declare class ListField extends BasicField{ Copy(): Field; } declare class Key extends Field { + constructor(name:string); Name: string; TrySetValue(value: any): boolean; GetValue(): any; @@ -220,3 +221,5 @@ declare const KeyStore: { // @ts-ignore declare const console: any; + +declare const Documents: any; diff --git a/src/client/views/collections/CollectionFreeFormView.tsx b/src/client/views/collections/CollectionFreeFormView.tsx index da9f7b392..8f7b4cfe7 100644 --- a/src/client/views/collections/CollectionFreeFormView.tsx +++ b/src/client/views/collections/CollectionFreeFormView.tsx @@ -83,6 +83,10 @@ export class CollectionFreeFormView extends CollectionViewBase { const [x, y] = this.getTransform().transformPoint(screenX, screenY); de.data.droppedDocument.SetNumber(KeyStore.X, x); de.data.droppedDocument.SetNumber(KeyStore.Y, y); + if (!de.data.droppedDocument.GetNumber(KeyStore.Width, 0)) { + de.data.droppedDocument.SetNumber(KeyStore.Width, 300); + de.data.droppedDocument.SetNumber(KeyStore.Height, 300); + } this.bringToFront(de.data.droppedDocument); } } @@ -259,6 +263,7 @@ export class CollectionFreeFormView extends CollectionViewBase { const lvalue = this.props.Document.GetT>(this.props.fieldKey, ListField); if (lvalue && lvalue != FieldWaiting) { return lvalue.Data.map(doc => { + if (!doc) return null; var page = doc.GetNumber(KeyStore.Page, 0); return (page != curPage && page != 0) ? (null) : (); diff --git a/src/client/views/collections/CollectionSchemaView.tsx b/src/client/views/collections/CollectionSchemaView.tsx index 8e0a38f05..7dd364449 100644 --- a/src/client/views/collections/CollectionSchemaView.tsx +++ b/src/client/views/collections/CollectionSchemaView.tsx @@ -1,6 +1,6 @@ import React = require("react") import { library } from '@fortawesome/fontawesome-svg-core'; -import { faCog } from '@fortawesome/free-solid-svg-icons'; +import { faCog, faPlus } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { action, computed, observable, trace, untracked } from "mobx"; import { observer } from "mobx-react"; @@ -8,7 +8,7 @@ import Measure from "react-measure"; import ReactTable, { CellInfo, ComponentPropsGetterR, ReactTableDefaults } from "react-table"; import "react-table/react-table.css"; import { Document } from "../../../fields/Document"; -import { Field, Opt } from "../../../fields/Field"; +import { Field, Opt, FieldWaiting } from "../../../fields/Field"; import { Key } from "../../../fields/Key"; import { KeyStore } from "../../../fields/KeyStore"; import { ListField } from "../../../fields/ListField"; @@ -24,6 +24,7 @@ import { FieldView, FieldViewProps } from "../nodes/FieldView"; import "./CollectionSchemaView.scss"; import { CollectionView, COLLECTION_BORDER_WIDTH } from "./CollectionView"; import { CollectionViewBase } from "./CollectionViewBase"; +import { TextField } from "../../../fields/TextField"; // bcz: need to add drag and drop of rows and columns. This seems like it might work for rows: https://codesandbox.io/s/l94mn1q657 @@ -104,11 +105,11 @@ export class CollectionSchemaView extends CollectionViewBase { return false; } return ( -
+
{ let field = props.doc.Get(props.fieldKey); if (field && field instanceof Field) { @@ -249,23 +250,48 @@ export class CollectionSchemaView extends CollectionViewBase { } } + @action + addColumn = () => { + this.columns.push(new Key(this.newKeyName)); + this.newKeyName = ""; + } + + @observable + newKeyName: string = ""; + + @action + newKeyChange = (e: React.ChangeEvent) => { + this.newKeyName = e.currentTarget.value; + } + @observable _optionsActivated: number = 0; @action OptionsMenuDown = (e: React.PointerEvent) => { this._optionsActivated++; } + + @observable previewScript: string = "this"; + @action + onPreviewScriptChange = (e: React.ChangeEvent) => { + this.previewScript = e.currentTarget.value; + } + render() { library.add(faCog); + library.add(faPlus); const columns = this.columns; const children = this.props.Document.GetList(this.props.fieldKey, []); const selected = children.length > this._selectedIndex ? children[this._selectedIndex] : undefined; //all the keys/columns that will be displayed in the schema const allKeys = this.findAllDocumentKeys; + let doc: any = selected ? selected.Get(new Key(this.previewScript)) : undefined; + + // let doc = CompileScript(this.previewScript, { this: selected }, true)(); let content = this._selectedIndex == -1 || !selected ? (null) : ( {({ measureRef }) =>
- + /> : null} +
}
@@ -297,6 +325,8 @@ export class CollectionSchemaView extends CollectionViewBase { return () })} + +
}> diff --git a/src/client/views/collections/CollectionViewBase.tsx b/src/client/views/collections/CollectionViewBase.tsx index f33007196..7d903899d 100644 --- a/src/client/views/collections/CollectionViewBase.tsx +++ b/src/client/views/collections/CollectionViewBase.tsx @@ -17,6 +17,7 @@ import { NumberField } from "../../../fields/NumberField"; import { DocumentManager } from "../../util/DocumentManager"; import request = require("request"); import { ServerUtils } from "../../../server/ServerUtil"; +import { Server } from "../../Server"; export interface CollectionViewProps { fieldKey: Key; @@ -59,17 +60,20 @@ export class CollectionViewBase extends React.Component let email = CurrentUserUtils.email; if (id && email) { let textInfo: [string, string] = [id, email]; - doc.GetOrCreateAsync>(KeyStore.Cursors, ListField, field => { - let cursors = field.Data; - if (cursors.length > 0 && (ind = cursors.findIndex(entry => entry.Data[0][0] === id)) > -1) { - cursors[ind].Data[1] = position; - } else { - let entry = new TupleField<[string, string], [number, number]>([textInfo, position]); - cursors.push(entry); + doc.GetTAsync(KeyStore.Prototype, Document).then(proto => { + if (!proto) { + return; } + proto.GetOrCreateAsync>(KeyStore.Cursors, ListField, action((field: ListField) => { + let cursors = field.Data; + if (cursors.length > 0 && (ind = cursors.findIndex(entry => entry.Data[0][0] === id)) > -1) { + cursors[ind].Data[1] = position; + } else { + let entry = new TupleField<[string, string], [number, number]>([textInfo, position]); + cursors.push(entry); + } + })) }) - - } } @@ -111,6 +115,21 @@ export class CollectionViewBase extends React.Component ctor = Documents.PdfDocument; } if (type.indexOf("html") !== -1) { + if (path.includes('localhost')) { + let s = path.split('/'); + let id = s[s.length - 1]; + Server.GetField(id).then(field => { + if (field instanceof Document) { + let alias = field.CreateAlias(); + alias.SetNumber(KeyStore.X, options.x || 0); + alias.SetNumber(KeyStore.Y, options.y || 0); + alias.SetNumber(KeyStore.Width, options.width || 300); + alias.SetNumber(KeyStore.Height, options.height || options.width || 300); + this.props.addDocument(alias, false); + } + }) + return undefined; + } ctor = Documents.WebDocument; options = { height: options.width, ...options, }; } @@ -130,7 +149,7 @@ export class CollectionViewBase extends React.Component e.stopPropagation() e.preventDefault() - if (html && html.indexOf(" { ContextMenu.Instance.addItem({ description: "Fields", event: this.fieldsClicked }) ContextMenu.Instance.addItem({ description: "Center", event: () => this.props.focus(this.props.Document) }) ContextMenu.Instance.addItem({ description: "Open Right", event: () => CollectionDockingView.Instance.AddRightSplit(this.props.Document) }) + ContextMenu.Instance.addItem({ + description: "Copy URL", + event: () => { + Utils.CopyText(ServerUtils.prepend("/doc/" + this.props.Document.Id)); + } + }); ContextMenu.Instance.addItem({ description: "Copy ID", event: () => { diff --git a/src/client/views/nodes/FieldView.tsx b/src/client/views/nodes/FieldView.tsx index f6343c631..4e83ec7b9 100644 --- a/src/client/views/nodes/FieldView.tsx +++ b/src/client/views/nodes/FieldView.tsx @@ -16,6 +16,9 @@ import { VideoBox } from "./VideoBox"; import { AudioBox } from "./AudioBox"; import { AudioField } from "../../../fields/AudioField"; import { ListField } from "../../../fields/ListField"; +import { DocumentContentsView } from "./DocumentContentsView"; +import { Transform } from "../../util/Transform"; +import { KeyStore } from "../../../fields/KeyStore"; // @@ -65,7 +68,20 @@ export class FieldView extends React.Component { return } else if (field instanceof Document) { - return
{field.Title}
+ return ( Transform.Identity} + ContentScaling={() => 1} + PanelWidth={() => 100} + PanelHeight={() => 100} + isTopMost={true} + SelectOnLoad={false} + focus={() => { }} + isSelected={() => false} + select={() => false} + layoutKey={KeyStore.Layout} + ContainingCollectionView={undefined} />) } else if (field instanceof ListField) { return (
diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index ba9bd9566..30fa1342e 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -167,6 +167,8 @@ export class FormattedTextBox extends React.Component { onKeyPress={this.onKeyPress} onPointerDown={this.onPointerDown} onContextMenu={this.specificContextMenu} + // tfs: do we need this event handler + onKeyDown={this.onKeyPress} onWheel={this.onPointerWheel} ref={this._ref} />) } -- cgit v1.2.3-70-g09d2 From 60ff3da65fbabd21c29bf1eecace02ebc1f6430c Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 25 Mar 2019 16:00:59 -0400 Subject: histograms render --- .../northstar/operations/HistogramOperation.ts | 11 +- src/client/northstar/utils/LABColor.ts | 90 ++++ src/client/northstar/utils/MathUtil.ts | 13 +- src/client/northstar/utils/SizeConverter.ts | 80 +++ src/client/northstar/utils/StyleContants.ts | 95 ++++ src/client/views/nodes/HistogramBox.scss | 6 + src/client/views/nodes/HistogramBox.tsx | 540 +++++++++++++++++++-- 7 files changed, 788 insertions(+), 47 deletions(-) create mode 100644 src/client/northstar/utils/LABColor.ts create mode 100644 src/client/northstar/utils/SizeConverter.ts create mode 100644 src/client/northstar/utils/StyleContants.ts (limited to 'src') diff --git a/src/client/northstar/operations/HistogramOperation.ts b/src/client/northstar/operations/HistogramOperation.ts index a4f5cac70..5ee1c0795 100644 --- a/src/client/northstar/operations/HistogramOperation.ts +++ b/src/client/northstar/operations/HistogramOperation.ts @@ -1,4 +1,4 @@ -import { reaction, computed, action } from "mobx"; +import { reaction, computed, action, observable } from "mobx"; import { Attribute, DataType, QuantitativeBinRange, HistogramOperationParameters, AggregateParameters, AggregateFunction, AverageAggregateParameters } from "../model/idea/idea"; import { ArrayUtil } from "../utils/ArrayUtil"; import { CalculatedAttributeManager } from "../core/attribute/CalculatedAttributeModel"; @@ -7,12 +7,15 @@ import { SETTINGS_X_BINS, SETTINGS_Y_BINS, SETTINGS_SAMPLE_SIZE } from "../model import { AttributeTransformationModel } from "../core/attribute/AttributeTransformationModel"; import { Main } from "../../views/Main"; import { BaseOperation } from "./BaseOperation"; +import { FilterModel } from "../core/filter/FilterModel"; export class HistogramOperation extends BaseOperation { - public X: AttributeTransformationModel; - public Y: AttributeTransformationModel; - public V: AttributeTransformationModel; + @observable public Normalization: number = -1; + @observable public FilterModels: FilterModel[] = []; + @observable public X: AttributeTransformationModel; + @observable public Y: AttributeTransformationModel; + @observable public V: AttributeTransformationModel; constructor(x: AttributeTransformationModel, y: AttributeTransformationModel, v: AttributeTransformationModel) { super(); this.X = x; diff --git a/src/client/northstar/utils/LABColor.ts b/src/client/northstar/utils/LABColor.ts new file mode 100644 index 000000000..72e46fb7f --- /dev/null +++ b/src/client/northstar/utils/LABColor.ts @@ -0,0 +1,90 @@ + +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 index 3ed8628ee..bb7e73871 100644 --- a/src/client/northstar/utils/MathUtil.ts +++ b/src/client/northstar/utils/MathUtil.ts @@ -1,13 +1,17 @@ export class PIXIPoint { - public x: number; - public y: number; + 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.x = x; - this.y = y; + this.coords[0] = x; + this.coords[1] = y; } } + export class PIXIRectangle { public x: number; public y: number; @@ -17,6 +21,7 @@ export class PIXIRectangle { 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; diff --git a/src/client/northstar/utils/SizeConverter.ts b/src/client/northstar/utils/SizeConverter.ts new file mode 100644 index 000000000..e8973cfd5 --- /dev/null +++ b/src/client/northstar/utils/SizeConverter.ts @@ -0,0 +1,80 @@ +import { PIXIPoint } from "./MathUtil"; +import { NominalVisualBinRange } from "../model/binRanges/NominalVisualBinRange"; +import { VisualBinRange } from "../model/binRanges/VisualBinRange"; + +export class SizeConverter { + public RenderSize: Array = new Array(2); + 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 LeftOffset: number = 40; + public RightOffset: number = 20; + public TopOffset: number = 20; + public BottomOffset: number = 45; + + public IsSmall: boolean = false; + + constructor(size: { x: number, y: number }, visualBinRanges: Array, labelAngle: number) { + this.LeftOffset = 40; + this.RightOffset = 20; + this.TopOffset = 20; + this.BottomOffset = 45; + this.IsSmall = false; + + if (visualBinRanges.length < 1) + return; + + 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: 100 }; // 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); + + if (visualBinRanges[0] instanceof NominalVisualBinRange) { + var lw = this.MaxLabelSizes[0].x + 18; + this.BottomOffset = Math.max(this.BottomOffset, Math.cos(labelAngle) * lw) + 5; + this.RightOffset = Math.max(this.RightOffset, Math.sin(labelAngle) * lw); + } + + this.RenderSize[0] = (size.x - this.LeftOffset - this.RightOffset); + this.RenderSize[1] = (size.y - this.TopOffset - this.BottomOffset); + + //if (this.RenderSize.reduce((agg, cur) => Math.min(agg, cur), Number.MAX_VALUE) < 40) { + if ((this.RenderSize[0] < 40 && this.RenderSize[1] < 40) || + (this.RenderSize[0] < 0 || this.RenderSize[1] < 0)) { + this.LeftOffset = 5; + this.RightOffset = 5; + this.TopOffset = 5; + this.BottomOffset = 25; + this.IsSmall = true; + this.RenderSize[0] = (size.x - this.LeftOffset - this.RightOffset); + this.RenderSize[1] = (size.y - this.TopOffset - this.BottomOffset); + } + + 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 DataToScreenX(x: number): number { + return (((x - this.DataMins[0]) / this.DataRanges[0]) * (this.RenderSize[0]) + (this.LeftOffset)); + } + public DataToScreenY(y: number, flip: boolean = true) { + var retY = ((y - this.DataMins[1]) / this.DataRanges[1]) * (this.RenderSize[1]); + return flip ? (this.RenderSize[1]) - retY + (this.TopOffset) : retY + (this.TopOffset); + } +} \ No newline at end of file diff --git a/src/client/northstar/utils/StyleContants.ts b/src/client/northstar/utils/StyleContants.ts new file mode 100644 index 000000000..ac8617e3b --- /dev/null +++ b/src/client/northstar/utils/StyleContants.ts @@ -0,0 +1,95 @@ +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/views/nodes/HistogramBox.scss b/src/client/views/nodes/HistogramBox.scss index 04bf1d732..f17059f06 100644 --- a/src/client/views/nodes/HistogramBox.scss +++ b/src/client/views/nodes/HistogramBox.scss @@ -5,4 +5,10 @@ width: 100%; height: 100%; } + .histogrambox-xlabel { + position:absolute; + width:100%; + text-align: center; + bottom:0; + } \ No newline at end of file diff --git a/src/client/views/nodes/HistogramBox.tsx b/src/client/views/nodes/HistogramBox.tsx index 223fdf0d8..980719a21 100644 --- a/src/client/views/nodes/HistogramBox.tsx +++ b/src/client/views/nodes/HistogramBox.tsx @@ -1,67 +1,529 @@ import React = require("react") +import { action, computed, observable, reaction } from "mobx"; import { observer } from "mobx-react"; -import { FieldView, FieldViewProps } from './FieldView'; -import "./VideoBox.scss"; -import { observable, reaction } from "mobx"; -import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; -import { Main } from "../Main"; +import Measure from "react-measure"; +import { Dictionary } from "typescript-collections"; +import { Utils as DashUtils } from '../../../Utils'; import { ColumnAttributeModel } from "../../northstar/core/attribute/AttributeModel"; import { AttributeTransformationModel } from "../../northstar/core/attribute/AttributeTransformationModel"; -import { AggregateFunction, HistogramResult, DoubleValueAggregateResult } from "../../northstar/model/idea/idea"; +import { FilterModel } from '../../northstar/core/filter/FilterModel'; +import { DateTimeVisualBinRange } from "../../northstar/model/binRanges/DateTimeVisualBinRange"; +import { NominalVisualBinRange } from "../../northstar/model/binRanges/NominalVisualBinRange"; +import { QuantitativeVisualBinRange } from "../../northstar/model/binRanges/QuantitativeVisualBinRange"; +import { ChartType, VisualBinRange } from '../../northstar/model/binRanges/VisualBinRange'; +import { VisualBinRangeHelper } from "../../northstar/model/binRanges/VisualBinRangeHelper"; +import { AggregateBinRange, AggregateFunction, Bin, Brush, DoubleValueAggregateResult, HistogramResult, MarginAggregateParameters, MarginAggregateResult } from "../../northstar/model/idea/idea"; import { ModelHelpers } from "../../northstar/model/ModelHelpers"; +import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; +import { ArrayUtil } from "../../northstar/utils/ArrayUtil"; +import { LABColor } from '../../northstar/utils/LABcolor'; +import { PIXIRectangle } from "../../northstar/utils/MathUtil"; +import { SizeConverter } from "../../northstar/utils/SizeConverter"; +import { StyleConstants } from "../../northstar/utils/StyleContants"; +import { Main } from "../Main"; +import { FieldView, FieldViewProps } from './FieldView'; +import "./HistogramBox.scss"; + + @observer export class HistogramBox extends React.Component { public static LayoutString(fieldStr: string = "DataKey") { return FieldView.LayoutString(HistogramBox, fieldStr) } + @observable private _renderer = []; + @observable private _visualBinRanges: VisualBinRange[] = []; + @observable private _minValue: number = 0; + @observable private _maxValue: number = 0; + @observable private _panelWidth: number = 100; + @observable private _panelHeight: number = 100; + @observable private _histoOp?: HistogramOperation; + @observable private _sizeConverter?: SizeConverter; + @observable private _chartType: ChartType = ChartType.VerticalBar; + public HitTargets: Dictionary = new Dictionary(); + + + constructor(props: FieldViewProps) { super(props); } - @observable _histoResult?: HistogramResult; - _histoOp?: HistogramOperation; - componentDidMount() { - Main.Instance.GetAllNorthstarColumnAttributes().map(a => { - if (a.displayName == this.props.doc.Title) { - var atmod = new ColumnAttributeModel(a); - this._histoOp = new HistogramOperation(new AttributeTransformationModel(atmod, AggregateFunction.None), - new AttributeTransformationModel(atmod, AggregateFunction.Count), - new AttributeTransformationModel(atmod, AggregateFunction.Count)); - reaction(() => [this._histoOp && this._histoOp.Result], - () => this._histoResult = this._histoOp ? this._histoOp.Result as HistogramResult : undefined - ); - this._histoOp.Update(); - } - }) - } - - twoString() { - let str = ""; - if (this._histoResult && !this._histoResult.isEmpty) { - for (let key in this._histoResult.bins) { - if (this._histoResult.bins.hasOwnProperty(key)) { - let bin = this._histoResult.bins[key]; - str += JSON.stringify(bin.binIndex!.toJSON()) + " = "; - let valueAggregateKey = ModelHelpers.CreateAggregateKey(this._histoOp!.V, this._histoResult, ModelHelpers.AllBrushIndex(this._histoResult)); - let value = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; - if (value && value.hasResult && value.result) { - str += value.result; + reaction(() => [this.props.doc.Title], + () => { + Main.Instance.GetAllNorthstarColumnAttributes().map(a => { + if (a.displayName == this.props.doc.Title) { + var atmod = new ColumnAttributeModel(a); + this._histoOp = new HistogramOperation(new AttributeTransformationModel(atmod, AggregateFunction.None), + new AttributeTransformationModel(atmod, AggregateFunction.Count), + new AttributeTransformationModel(atmod, AggregateFunction.Count)); + this._histoOp.Update(); + } + }); + }, { fireImmediately: true }); + reaction(() => [this._visualBinRanges && this._visualBinRanges.slice(), this._panelHeight, this._panelWidth], + () => this._sizeConverter = new SizeConverter({ x: this._panelWidth, y: this._panelHeight }, this._visualBinRanges, Math.PI / 4)); + reaction(() => [this._histoOp && this._histoOp.Result], + () => { + if (!this._histoOp || !(this._histoOp.Result instanceof HistogramResult) || !this._histoOp.Result.binRanges) + return; + + let binRanges = this._histoOp.Result.binRanges; + this._chartType = binRanges[0] instanceof AggregateBinRange ? (binRanges[1] instanceof AggregateBinRange ? ChartType.SinglePoint : ChartType.HorizontalBar) : + binRanges[1] instanceof AggregateBinRange ? ChartType.VerticalBar : ChartType.HeatMap; + + this._visualBinRanges.length = 0; + this._visualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(this._histoOp.Result.binRanges![0], this._histoOp.Result, this._histoOp.X, this._chartType)); + this._visualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(this._histoOp.Result.binRanges![1], this._histoOp.Result, this._histoOp.Y, this._chartType)); + + if (!this._histoOp.Result.isEmpty) { + this._maxValue = Number.MIN_VALUE; + this._minValue = Number.MAX_VALUE; + for (let key in this._histoOp.Result.bins) { + if (this._histoOp.Result.bins.hasOwnProperty(key)) { + let bin = this._histoOp.Result.bins[key]; + let valueAggregateKey = ModelHelpers.CreateAggregateKey(this._histoOp.V, this._histoOp.Result, ModelHelpers.AllBrushIndex(this._histoOp.Result)); + let value = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; + if (value && value.hasResult) { + this._maxValue = Math.max(this._maxValue, value.result!); + this._minValue = Math.min(this._minValue, value.result!); + } + } } } } + ); + } + + @computed get xaxislines() { return this.renderGridLinesAndLabels(0); } + @computed get yaxislines() { return this.renderGridLinesAndLabels(1); } + + drawLine(xFrom: number, yFrom: number, width: number, height: number) { + return
; + } + + private renderGridLinesAndLabels(axis: number) { + let prims: JSX.Element[] = []; + let sc = this._sizeConverter!; + let labels = this._visualBinRanges[axis].GetLabels(); + + let dim = sc.RenderSize[axis] / sc.MaxLabelSizes[axis].coords[axis] + 5; + let mod = Math.ceil(labels.length / dim); + + if (axis == 0 && this._visualBinRanges[axis] instanceof NominalVisualBinRange) { + mod = Math.ceil( + labels.length / (sc.RenderSize[0] / (12 + 5))); // (FontStyles.AxisLabel.fontSize + 5))); } - return str; + for (let i = 0; i < labels.length; i++) { + let binLabel = labels[i]; + let xFrom = sc.DataToScreenX(axis === 0 ? binLabel.minValue! : sc.DataMins[0]); + let xTo = sc.DataToScreenX(axis === 0 ? binLabel.maxValue! : sc.DataMaxs[0]); + let yFrom = sc.DataToScreenY(axis === 0 ? sc.DataMins[1] : binLabel.minValue!); + let yTo = sc.DataToScreenY(axis === 0 ? sc.DataMaxs[1] : binLabel.maxValue!); + + prims.push(this.drawLine(xFrom, yFrom, axis == 0 ? 1 : xTo - xFrom, axis == 0 ? yTo - yFrom : 1)); + if (i == labels.length - 1) + prims.push(this.drawLine(axis == 0 ? xTo : xFrom, axis == 0 ? yFrom : yTo, axis == 0 ? 1 : xTo - xFrom, axis == 0 ? yTo - yFrom : 1)); + + if (i % mod === 0 && binLabel.label) { + let text = binLabel.label; + if (text.length >= StyleConstants.MAX_CHAR_FOR_HISTOGRAM_LABELS) { + text = text.slice(0, StyleConstants.MAX_CHAR_FOR_HISTOGRAM_LABELS - 3) + "..."; + } + const textHeight = 14; const textWidth = 30; + let xStart = (axis === 0 ? xFrom + (xTo - xFrom) / 2.0 : xFrom - 10 - textWidth); + let yStart = (axis === 1 ? yFrom - textHeight / 2 : yFrom); + let rotation = 0; + + if (axis == 0 && this._visualBinRanges[axis] instanceof NominalVisualBinRange) { + rotation = Math.min(90, Math.max(30, textWidth / (xTo - xFrom) * 90)); + xStart += Math.max(textWidth / 2, (1 - textWidth / (xTo - xFrom)) * textWidth / 2) - textHeight / 2; + } + + prims.push( +
+ {text} +
) + } + } + return prims; + } + + @action + setScaling = (r: any) => { + this._panelWidth = r.entry.width; + this._panelHeight = r.entry.height; + } + + @computed + get binPrimitives() { + if (!this._histoOp || !(this._histoOp.Result instanceof HistogramResult)) + return undefined; + let sizeConverter = new SizeConverter({ x: this._panelWidth, y: this._panelHeight, }, this._visualBinRanges, Math.PI / 4); + let prims: JSX.Element[] = []; + let selectedBinPrimitiveCollections = new Array(); + let allBrushIndex = ModelHelpers.AllBrushIndex(this._histoOp.Result); + for (let key in this._histoOp.Result.bins) { + if (this._histoOp.Result.bins.hasOwnProperty(key)) { + let drawPrims = new HistogramBinPrimitiveCollection(this._histoOp.Result.bins[key], this._histoOp.Result, + this._histoOp!.V, this._histoOp!.X, this._histoOp!.Y, this._chartType, + this._visualBinRanges, this._minValue, this._maxValue, this._histoOp!.Normalization, sizeConverter); + + this.HitTargets.setValue(drawPrims.HitGeom, drawPrims.FilterModel); + + if (ArrayUtil.Contains(this._histoOp!.FilterModels, drawPrims.FilterModel)) { + selectedBinPrimitiveCollections.push(drawPrims); + } + + drawPrims.BinPrimitives.filter(bp => bp.DataValue && bp.BrushIndex !== allBrushIndex).map(binPrimitive => { + prims.push(this.drawRect(binPrimitive.Rect, binPrimitive.Color)); + prims.push(this.drawRect(binPrimitive.MarginRect, StyleConstants.MARGIN_BARS_COLOR)); + }); + } + } + return prims; + } + + drawRect(rect: PIXIRectangle, color: number) { + return
} render() { - if (!this._histoResult) + if (!this.binPrimitives || !this._histoOp || !(this._histoOp.Result instanceof HistogramResult) || !this._visualBinRanges.length) { return (null); + } + return ( -
- `HISTOGRAM RESULT : ${this.twoString()}` -
+ + {({ measureRef }) => +
+ {this.xaxislines} + {this.yaxislines} + {this.binPrimitives} +
{this._histoOp!.X.AttributeModel.DisplayName}
+
+ } +
) } +} + +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; +} + +export class HistogramBinPrimitiveCollection { + private static TOLERANCE: number = 0.0001; + + public BinPrimitives: Array = new Array(); + public FilterModel: FilterModel; + public HitGeom: PIXIRectangle = PIXIRectangle.EMPTY; + + private _y: AttributeTransformationModel; + private _x: AttributeTransformationModel; + private _value: AttributeTransformationModel; + private _chartType: ChartType; + private _histoResult: HistogramResult; + private _visualBinRanges: Array; + + constructor(bin: Bin, histoResult: HistogramResult, + value: AttributeTransformationModel, x: AttributeTransformationModel, y: AttributeTransformationModel, + chartType: ChartType, visualBinRanges: Array, + minValue: number, maxValue: number, normalization: number, sizeConverter: SizeConverter) { + this._histoResult = histoResult; + this._chartType = chartType; + this._value = value; + this._x = x; + this._y = y; + this._visualBinRanges = visualBinRanges; + + var allBrushIndex = ModelHelpers.AllBrushIndex(this._histoResult); + var overlapBrushIndex = ModelHelpers.OverlapBrushIndex(this._histoResult); + this.FilterModel = ModelHelpers.GetBinFilterModel(bin, allBrushIndex, this._histoResult, this._x, this._y); + + var orderedBrushes = new Array(); + orderedBrushes.push(histoResult.brushes![0]); + orderedBrushes.push(histoResult.brushes![overlapBrushIndex]); + for (var b = 0; b < histoResult.brushes!.length; b++) { + var brush = histoResult.brushes![b]; + if (brush.brushIndex != 0 && brush.brushIndex != overlapBrushIndex) { + orderedBrushes.push(brush); + } + } + var binBrushMaxAxis = this.getBinBrushAxisRange(bin, orderedBrushes, normalization); // X= 0, Y = 1 + + var brushFactorSum: number = 0; + for (var b = 0; b < orderedBrushes.length; b++) { + var brush = orderedBrushes[b]; + var valueAggregateKey = ModelHelpers.CreateAggregateKey(value, histoResult, brush.brushIndex!); + var doubleRes = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; + var unNormalizedValue = (doubleRes != null && doubleRes.hasResult) ? doubleRes.result : null; + if (unNormalizedValue == null) { + continue; + } + if (chartType == ChartType.VerticalBar) { + this.createVerticalBarChartBinPrimitives(bin, brush, binBrushMaxAxis, normalization, sizeConverter); // X = 0, Y = 1, NOne = -1 + } + else if (chartType == ChartType.HorizontalBar) { + this.createHorizontalBarChartBinPrimitives(bin, brush, binBrushMaxAxis, normalization, sizeConverter); + } + else if (chartType == ChartType.SinglePoint) { + this.createSinlgePointChartBinPrimitives(bin, brush, unNormalizedValue, sizeConverter); + } + else if (chartType == ChartType.HeatMap) { + var normalizedValue = (unNormalizedValue - minValue) / (Math.abs((maxValue - minValue)) < HistogramBinPrimitiveCollection.TOLERANCE ? + unNormalizedValue : (maxValue - minValue)); + brushFactorSum = this.createHeatmapBinPrimitives(bin, brush, unNormalizedValue, brushFactorSum, normalizedValue, sizeConverter); + } + } + + // adjust brush rects (stacking or not) + var sum: number = 0; + var filtered = this.BinPrimitives.filter(b => b.BrushIndex != allBrushIndex && b.DataValue != 0.0); + var count: number = filtered.length; + for (var i = 0; i < count; i++) { + var bp = filtered[i]; + + if (this._chartType == ChartType.VerticalBar) { + if (this._y.AggregateFunction == AggregateFunction.Count) { + bp.Rect = new PIXIRectangle(bp.Rect.x, bp.Rect.y - sum, bp.Rect.width, bp.Rect.height); + bp.MarginRect = new PIXIRectangle(bp.MarginRect.x, bp.MarginRect.y - sum, bp.MarginRect.width, bp.MarginRect.height); + sum += bp.Rect.height; + } + if (this._y.AggregateFunction == AggregateFunction.Avg) { + var w = bp.Rect.width / 2.0; + bp.Rect = new PIXIRectangle(bp.Rect.x + sum, bp.Rect.y, bp.Rect.width / count, bp.Rect.height); + bp.MarginRect = new PIXIRectangle(bp.MarginRect.x - w + sum + (bp.Rect.width / 2.0), bp.MarginRect.y, bp.MarginRect.width, bp.MarginRect.height); + sum += bp.Rect.width; + } + } + else if (this._chartType == ChartType.HorizontalBar) { + if (this._x.AggregateFunction == AggregateFunction.Count) { + bp.Rect = new PIXIRectangle(bp.Rect.x + sum, bp.Rect.y, bp.Rect.width, bp.Rect.height); + bp.MarginRect = new PIXIRectangle(bp.MarginRect.x + sum, bp.MarginRect.y, bp.MarginRect.width, bp.MarginRect.height); + sum += bp.Rect.width; + } + if (this._x.AggregateFunction == AggregateFunction.Avg) { + var h = bp.Rect.height / 2.0; + bp.Rect = new PIXIRectangle(bp.Rect.x, bp.Rect.y + sum, bp.Rect.width, bp.Rect.height / count); + bp.MarginRect = new PIXIRectangle(bp.MarginRect.x, bp.MarginRect.y - h + sum + (bp.Rect.height / 2.0), bp.MarginRect.width, bp.MarginRect.height); + sum += bp.Rect.height; + } + } + else if (this._chartType == ChartType.HeatMap) { + } + } + 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 getBinBrushAxisRange(bin: Bin, brushes: Array, axis: number): number { + var binBrushMaxAxis = Number.MIN_VALUE; + brushes.forEach((Brush) => { + var maxAggregateKey = ModelHelpers.CreateAggregateKey(axis === 0 ? this._y : this._x, this._histoResult, Brush.brushIndex!); + var aggResult = ModelHelpers.GetAggregateResult(bin, maxAggregateKey) as DoubleValueAggregateResult; + if (aggResult != null) { + if (aggResult.result! > binBrushMaxAxis) + binBrushMaxAxis = aggResult.result!; + } + }); + return binBrushMaxAxis; + } + private createHeatmapBinPrimitives(bin: Bin, brush: Brush, unNormalizedValue: number, brushFactorSum: number, normalizedValue: number, sizeConverter: SizeConverter): number { + var xFrom: number = 0; + var xTo: number = 0; + var yFrom: number = 0; + var yTo: number = 0; + var returnBrushFactorSum = brushFactorSum; + + var valueAggregateKey = ModelHelpers.CreateAggregateKey(this._value, this._histoResult, ModelHelpers.AllBrushIndex(this._histoResult)); + var allUnNormalizedValue = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; + + var tx = this._visualBinRanges[0].GetValueFromIndex(bin.binIndex!.indices![0]); + xFrom = sizeConverter.DataToScreenX(tx); + xTo = sizeConverter.DataToScreenX(this._visualBinRanges[0].AddStep(tx)); + + var ty = this._visualBinRanges[1].GetValueFromIndex(bin.binIndex!.indices![1]); + yFrom = sizeConverter.DataToScreenY(ty); + yTo = sizeConverter.DataToScreenY(this._visualBinRanges[1].AddStep(ty)); + + if (allUnNormalizedValue.hasResult) { + var brushFactor = (unNormalizedValue / allUnNormalizedValue.result!); + 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); + + var marginParams = new MarginAggregateParameters(); + marginParams.aggregateFunction = this._value.AggregateFunction; + var marginAggregateKey = ModelHelpers.CreateAggregateKey(this._value, this._histoResult, + ModelHelpers.AllBrushIndex(this._histoResult), marginParams); + + this.createBinPrimitive(bin, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, dataColor, 1, unNormalizedValue); + return returnBrushFactorSum; + } + + private createSinlgePointChartBinPrimitives(bin: Bin, brush: Brush, unNormalizedValue: number, sizeConverter: SizeConverter): void { + var yAggregateKey = ModelHelpers.CreateAggregateKey(this._y, this._histoResult, brush.brushIndex!); + var marginParams = new MarginAggregateParameters(); + marginParams.aggregateFunction = this._y.AggregateFunction; + + var xAggregateKey = ModelHelpers.CreateAggregateKey(this._x, this._histoResult, brush.brushIndex!); + var marginParams = new MarginAggregateParameters(); + marginParams.aggregateFunction = this._x.AggregateFunction; + + var xValue = ModelHelpers.GetAggregateResult(bin, xAggregateKey) as DoubleValueAggregateResult;; + if (!xValue.hasResult) + return; + var xFrom = sizeConverter.DataToScreenX(xValue.result!) - 5; + var xTo = sizeConverter.DataToScreenX(xValue.result!) + 5; + + var yValue = ModelHelpers.GetAggregateResult(bin, yAggregateKey) as DoubleValueAggregateResult;; + if (!yValue.hasResult) + return; + var yFrom = sizeConverter.DataToScreenY(yValue.result!) + 5; + var yTo = sizeConverter.DataToScreenY(yValue.result!); + + this.createBinPrimitive(bin, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, this.baseColorFromBrush(brush), 1, unNormalizedValue); + } + + private createVerticalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number, sizeConverter: SizeConverter): void { + var yAggregateKey = ModelHelpers.CreateAggregateKey(this._y, this._histoResult, brush.brushIndex!); + var marginParams = new MarginAggregateParameters(); + marginParams.aggregateFunction = this._y.AggregateFunction; + var yMarginAggregateKey = ModelHelpers.CreateAggregateKey(this._y, this._histoResult, + brush.brushIndex!, marginParams); + var dataValue = ModelHelpers.GetAggregateResult(bin, yAggregateKey) as DoubleValueAggregateResult; + + if (dataValue != null && dataValue.hasResult) { + var yValue = normalization != 0 || binBrushMaxAxis == 0 ? dataValue.result! : (dataValue.result! - 0) / (binBrushMaxAxis - 0) * sizeConverter.DataRanges[1]; + + var yFrom = sizeConverter.DataToScreenY(Math.min(0, yValue)); + var yTo = sizeConverter.DataToScreenY(Math.max(0, yValue));; + + var xValue = this._visualBinRanges[0].GetValueFromIndex(bin.binIndex!.indices![0])!; + var xFrom = sizeConverter.DataToScreenX(xValue); + var xTo = sizeConverter.DataToScreenX(this._visualBinRanges[0].AddStep(xValue)); + + var marginResult = ModelHelpers.GetAggregateResult(bin, yMarginAggregateKey)!; + var yMarginAbsolute = marginResult == null ? 0 : (marginResult as MarginAggregateResult).absolutMargin!; + var marginRect = new PIXIRectangle(xFrom + (xTo - xFrom) / 2.0 - 1, + sizeConverter.DataToScreenY(yValue + yMarginAbsolute), 2, + sizeConverter.DataToScreenY(yValue - yMarginAbsolute) - sizeConverter.DataToScreenY(yValue + yMarginAbsolute)); + + this.createBinPrimitive(bin, brush, marginRect, 0, xFrom, xTo, yFrom, yTo, + this.baseColorFromBrush(brush), normalization != 0 ? 1 : 0.6 * binBrushMaxAxis / sizeConverter.DataRanges[1] + 0.4, dataValue.result!); + } + } + + private createHorizontalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number, sizeConverter: SizeConverter): void { + var xAggregateKey = ModelHelpers.CreateAggregateKey(this._x, this._histoResult, brush.brushIndex!); + var marginParams = new MarginAggregateParameters(); + marginParams.aggregateFunction = this._x.AggregateFunction; + var xMarginAggregateKey = ModelHelpers.CreateAggregateKey(this._x, this._histoResult, + brush.brushIndex!, marginParams); + var dataValue = ModelHelpers.GetAggregateResult(bin, xAggregateKey) as DoubleValueAggregateResult; + + if (dataValue != null && dataValue.hasResult) { + var xValue = normalization != 1 || binBrushMaxAxis == 0 ? dataValue.result! : (dataValue.result! - 0) / (binBrushMaxAxis - 0) * sizeConverter.DataRanges[0]; + var xFrom = sizeConverter.DataToScreenX(Math.min(0, xValue)); + var xTo = sizeConverter.DataToScreenX(Math.max(0, xValue)); + + var yValue = this._visualBinRanges[1].GetValueFromIndex(bin.binIndex!.indices![1]); + var yFrom = yValue; + var yTo = this._visualBinRanges[1].AddStep(yValue); + + var marginResult = ModelHelpers.GetAggregateResult(bin, xMarginAggregateKey); + var xMarginAbsolute = sizeConverter.IsSmall || marginResult == null ? 0 : (marginResult as MarginAggregateResult).absolutMargin!; + + var marginRect = new PIXIRectangle(sizeConverter.DataToScreenX(xValue - xMarginAbsolute), + yTo + (yFrom - yTo) / 2.0 - 1, + sizeConverter.DataToScreenX(xValue + xMarginAbsolute) - sizeConverter.DataToScreenX(xValue - xMarginAbsolute), + 2.0); + + this.createBinPrimitive(bin, brush, marginRect, 0, xFrom, xTo, yFrom, yTo, + this.baseColorFromBrush(brush), normalization != 1 ? 1 : 0.6 * binBrushMaxAxis / sizeConverter.DataRanges[0] + 0.4, dataValue.result!); + } + } + + private createBinPrimitive(bin: Bin, brush: Brush, marginRect: PIXIRectangle, + marginPercentage: number, xFrom: number, xTo: number, yFrom: number, yTo: number, color: number, opacity: number, dataValue: number) { + // hitgeom todo + + 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 + }); + this.BinPrimitives.push(binPrimitive); + } + + private baseColorFromBrush(brush: Brush): number { + var baseColor: number = StyleConstants.HIGHLIGHT_COLOR; + if (brush.brushIndex == ModelHelpers.RestBrushIndex(this._histoResult)) { + baseColor = StyleConstants.HIGHLIGHT_COLOR; + } + else if (brush.brushIndex == ModelHelpers.OverlapBrushIndex(this._histoResult)) { + baseColor = StyleConstants.OVERLAP_COLOR; + } + else if (brush.brushIndex == ModelHelpers.AllBrushIndex(this._histoResult)) { + baseColor = 0x00ff00; + } + else { + // if (this._histogramOperationViewModel.BrushColors.length > 0) { + // baseColor = this._histogramOperationViewModel.BrushColors[brush.brushIndex! % this._histogramOperationViewModel.BrushColors.length]; + // } + // else { + baseColor = StyleConstants.HIGHLIGHT_COLOR; + // } + } + return baseColor; + } } \ No newline at end of file -- cgit v1.2.3-70-g09d2 From a000ca8dccbaa2028acef3d5c1d1666b5e928a31 Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 25 Mar 2019 17:55:41 -0400 Subject: restructured. --- src/client/documents/Documents.ts | 10 +- src/client/views/nodes/HistogramBox.scss | 8 +- src/client/views/nodes/HistogramBox.tsx | 336 +++++++++++++------------------ 3 files changed, 158 insertions(+), 196 deletions(-) (limited to 'src') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index a2444db06..bc0a18d50 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -119,9 +119,13 @@ export namespace Documents { return imageProto; } function GetHistogramPrototype(): Document { - return histoProto ? histoProto : - histoProto = setupPrototypeOptions(textProtoId, "HISTO PROTOTYPE", HistogramBox.LayoutString(), - { x: 0, y: 0, width: 300, height: 300, layoutKeys: [KeyStore.Data] }); + if (!histoProto) { + + histoProto = setupPrototypeOptions(histoProtoId, "HISTO PROTO", CollectionView.LayoutString("AnnotationsKey"), + { x: 0, y: 0, width: 300, height: 300, layoutKeys: [KeyStore.Data, KeyStore.Annotations, KeyStore.Caption] }); + histoProto.SetText(KeyStore.BackgroundLayout, HistogramBox.LayoutString()); + } + return histoProto; } function GetTextPrototype(): Document { return textProto ? textProto : diff --git a/src/client/views/nodes/HistogramBox.scss b/src/client/views/nodes/HistogramBox.scss index f17059f06..00ad099ac 100644 --- a/src/client/views/nodes/HistogramBox.scss +++ b/src/client/views/nodes/HistogramBox.scss @@ -1,11 +1,15 @@ .histogrambox-container { padding: 0vw; - position: relative; + position: absolute; text-align: center; width: 100%; height: 100%; } - .histogrambox-xlabel { + .histogrambox-gridlabel { + position:absolute; + transform-origin: left top; + } + .histogrambox-xaxislabel { position:absolute; width:100%; text-align: center; diff --git a/src/client/views/nodes/HistogramBox.tsx b/src/client/views/nodes/HistogramBox.tsx index 1508b201b..ea54ed29a 100644 --- a/src/client/views/nodes/HistogramBox.tsx +++ b/src/client/views/nodes/HistogramBox.tsx @@ -1,5 +1,5 @@ import React = require("react") -import { action, computed, observable, reaction } from "mobx"; +import { computed, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; import Measure from "react-measure"; import { Dictionary } from "typescript-collections"; @@ -21,70 +21,66 @@ import { SizeConverter } from "../../northstar/utils/SizeConverter"; import { StyleConstants } from "../../northstar/utils/StyleContants"; import { FieldView, FieldViewProps } from './FieldView'; import "./HistogramBox.scss"; - - +import { KeyStore } from "../../../fields/KeyStore"; @observer export class HistogramBox extends React.Component { public static LayoutString(fieldStr: string = "DataKey") { return FieldView.LayoutString(HistogramBox, fieldStr) } - @observable private _renderer = []; - @observable private _visualBinRanges: VisualBinRange[] = []; - @observable private _minValue: number = 0; - @observable private _maxValue: number = 0; @observable private _panelWidth: number = 100; @observable private _panelHeight: number = 100; - @observable private _histoOp?: HistogramOperation; - @observable private _sizeConverter?: SizeConverter; - @observable private _chartType: ChartType = ChartType.VerticalBar; + @observable public HistoOp?: HistogramOperation; + @observable public VisualBinRanges: VisualBinRange[] = []; + @observable public MinValue: number = 0; + @observable public MaxValue: number = 0; + @observable public SizeConverter?: SizeConverter; + @observable public ChartType: ChartType = ChartType.VerticalBar; public HitTargets: Dictionary = new Dictionary(); - - constructor(props: FieldViewProps) { super(props); } + @computed get xaxislines() { return this.renderGridLinesAndLabels(0); } + @computed get yaxislines() { return this.renderGridLinesAndLabels(1); } + componentDidMount() { - reaction(() => [this.props.doc.Title], + reaction(() => CurrentUserUtils.GetAllNorthstarColumnAttributes().filter(a => a.displayName == this.props.doc.Title), + (columnAttrs) => columnAttrs.map(a => { + var atmod = new ColumnAttributeModel(a); + this.HistoOp = new HistogramOperation(new AttributeTransformationModel(atmod, AggregateFunction.None), + new AttributeTransformationModel(atmod, AggregateFunction.Count), + new AttributeTransformationModel(atmod, AggregateFunction.Count)); + this.HistoOp.Update(); + }) + , { fireImmediately: true }); + reaction(() => [this.VisualBinRanges && this.VisualBinRanges.slice(), this._panelHeight, this._panelWidth], + () => this.SizeConverter = new SizeConverter({ x: this._panelWidth, y: this._panelHeight }, this.VisualBinRanges, Math.PI / 4)); + reaction(() => [this.HistoOp && this.HistoOp.Result], () => { - CurrentUserUtils.GetAllNorthstarColumnAttributes().map(a => { - if (a.displayName == this.props.doc.Title) { - var atmod = new ColumnAttributeModel(a); - this._histoOp = new HistogramOperation(new AttributeTransformationModel(atmod, AggregateFunction.None), - new AttributeTransformationModel(atmod, AggregateFunction.Count), - new AttributeTransformationModel(atmod, AggregateFunction.Count)); - this._histoOp.Update(); - } - }); - }, { fireImmediately: true }); - reaction(() => [this._visualBinRanges && this._visualBinRanges.slice(), this._panelHeight, this._panelWidth], - () => this._sizeConverter = new SizeConverter({ x: this._panelWidth, y: this._panelHeight }, this._visualBinRanges, Math.PI / 4)); - reaction(() => [this._histoOp && this._histoOp.Result], - () => { - if (!this._histoOp || !(this._histoOp.Result instanceof HistogramResult) || !this._histoOp.Result.binRanges) + if (!this.HistoOp || !(this.HistoOp.Result instanceof HistogramResult) || !this.HistoOp.Result.binRanges) return; - let binRanges = this._histoOp.Result.binRanges; - this._chartType = binRanges[0] instanceof AggregateBinRange ? (binRanges[1] instanceof AggregateBinRange ? ChartType.SinglePoint : ChartType.HorizontalBar) : + let binRanges = this.HistoOp.Result.binRanges; + this.ChartType = binRanges[0] instanceof AggregateBinRange ? (binRanges[1] instanceof AggregateBinRange ? ChartType.SinglePoint : ChartType.HorizontalBar) : binRanges[1] instanceof AggregateBinRange ? ChartType.VerticalBar : ChartType.HeatMap; - this._visualBinRanges.length = 0; - this._visualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(this._histoOp.Result.binRanges![0], this._histoOp.Result, this._histoOp.X, this._chartType)); - this._visualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(this._histoOp.Result.binRanges![1], this._histoOp.Result, this._histoOp.Y, this._chartType)); - - if (!this._histoOp.Result.isEmpty) { - this._maxValue = Number.MIN_VALUE; - this._minValue = Number.MAX_VALUE; - for (let key in this._histoOp.Result.bins) { - if (this._histoOp.Result.bins.hasOwnProperty(key)) { - let bin = this._histoOp.Result.bins[key]; - let valueAggregateKey = ModelHelpers.CreateAggregateKey(this._histoOp.V, this._histoOp.Result, ModelHelpers.AllBrushIndex(this._histoOp.Result)); + this.VisualBinRanges.length = 0; + this.VisualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(this.HistoOp.Result.binRanges[0], this.HistoOp.Result, this.HistoOp.X, this.ChartType)); + this.VisualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(this.HistoOp.Result.binRanges[1], this.HistoOp.Result, this.HistoOp.Y, this.ChartType)); + + if (!this.HistoOp.Result.isEmpty) { + this.MaxValue = Number.MIN_VALUE; + this.MinValue = Number.MAX_VALUE; + for (let key in this.HistoOp.Result.bins) { + if (this.HistoOp.Result.bins.hasOwnProperty(key)) { + let bin = this.HistoOp.Result.bins[key]; + let valueAggregateKey = ModelHelpers.CreateAggregateKey(this.HistoOp.V, this.HistoOp.Result, ModelHelpers.AllBrushIndex(this.HistoOp.Result)); let value = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; if (value && value.hasResult) { - this._maxValue = Math.max(this._maxValue, value.result!); - this._minValue = Math.min(this._minValue, value.result!); + this.MaxValue = Math.max(this.MaxValue, value.result!); + this.MinValue = Math.min(this.MinValue, value.result!); } } } @@ -93,34 +89,27 @@ export class HistogramBox extends React.Component { ); } - @computed get xaxislines() { return this.renderGridLinesAndLabels(0); } - @computed get yaxislines() { return this.renderGridLinesAndLabels(1); } - drawLine(xFrom: number, yFrom: number, width: number, height: number) { - return
; + return
; + } + + drawRect(r: PIXIRectangle, color: number) { + return
} private renderGridLinesAndLabels(axis: number) { - let prims: JSX.Element[] = []; - let sc = this._sizeConverter!; - let labels = this._visualBinRanges[axis].GetLabels(); + let sc = this.SizeConverter!; + let labels = this.VisualBinRanges[axis].GetLabels(); let dim = sc.RenderSize[axis] / sc.MaxLabelSizes[axis].coords[axis] + 5; let mod = Math.ceil(labels.length / dim); - if (axis == 0 && this._visualBinRanges[axis] instanceof NominalVisualBinRange) { + if (axis == 0 && this.VisualBinRanges[axis] instanceof NominalVisualBinRange) { mod = Math.ceil( labels.length / (sc.RenderSize[0] / (12 + 5))); // (FontStyles.AxisLabel.fontSize + 5))); } - for (let i = 0; i < labels.length; i++) { - let binLabel = labels[i]; + let prims: JSX.Element[] = []; + labels.map((binLabel, i) => { let xFrom = sc.DataToScreenX(axis === 0 ? binLabel.minValue! : sc.DataMins[0]); let xTo = sc.DataToScreenX(axis === 0 ? binLabel.maxValue! : sc.DataMaxs[0]); let yFrom = sc.DataToScreenY(axis === 0 ? sc.DataMins[1] : binLabel.minValue!); @@ -140,43 +129,34 @@ export class HistogramBox extends React.Component { let yStart = (axis === 1 ? yFrom - textHeight / 2 : yFrom); let rotation = 0; - if (axis == 0 && this._visualBinRanges[axis] instanceof NominalVisualBinRange) { + if (axis == 0 && this.VisualBinRanges[axis] instanceof NominalVisualBinRange) { rotation = Math.min(90, Math.max(30, textWidth / (xTo - xFrom) * 90)); xStart += Math.max(textWidth / 2, (1 - textWidth / (xTo - xFrom)) * textWidth / 2) - textHeight / 2; } prims.push( -
+
{text}
) } - } + }); return prims; } - @action - setScaling = (r: any) => { - this._panelWidth = r.entry.width; - this._panelHeight = r.entry.height; - } - @computed get binPrimitives() { - if (!this._histoOp || !(this._histoOp.Result instanceof HistogramResult)) + if (!this.HistoOp || !(this.HistoOp.Result instanceof HistogramResult) || !this.SizeConverter) return undefined; - let sizeConverter = new SizeConverter({ x: this._panelWidth, y: this._panelHeight, }, this._visualBinRanges, Math.PI / 4); let prims: JSX.Element[] = []; let selectedBinPrimitiveCollections = new Array(); - let allBrushIndex = ModelHelpers.AllBrushIndex(this._histoOp.Result); - for (let key in this._histoOp.Result.bins) { - if (this._histoOp.Result.bins.hasOwnProperty(key)) { - let drawPrims = new HistogramBinPrimitiveCollection(this._histoOp.Result.bins[key], this._histoOp.Result, - this._histoOp!.V, this._histoOp!.X, this._histoOp!.Y, this._chartType, - this._visualBinRanges, this._minValue, this._maxValue, this._histoOp!.Normalization, sizeConverter); + let allBrushIndex = ModelHelpers.AllBrushIndex(this.HistoOp.Result); + for (let key in this.HistoOp.Result.bins) { + if (this.HistoOp.Result.bins.hasOwnProperty(key)) { + let drawPrims = new HistogramBinPrimitiveCollection(key, this); this.HitTargets.setValue(drawPrims.HitGeom, drawPrims.FilterModel); - if (ArrayUtil.Contains(this._histoOp!.FilterModels, drawPrims.FilterModel)) { + if (ArrayUtil.Contains(this.HistoOp.FilterModels, drawPrims.FilterModel)) { selectedBinPrimitiveCollections.push(drawPrims); } @@ -189,29 +169,19 @@ export class HistogramBox extends React.Component { return prims; } - drawRect(rect: PIXIRectangle, color: number) { - return
- } - render() { - if (!this.binPrimitives || !this._histoOp || !(this._histoOp.Result instanceof HistogramResult) || !this._visualBinRanges.length) { + if (!this.binPrimitives || !this.VisualBinRanges.length) { return (null); } return ( - + runInAction(() => { this._panelWidth = r.entry.width; this._panelHeight = r.entry.height })}> {({ measureRef }) => -
+
{this.xaxislines} {this.yaxislines} {this.binPrimitives} -
{this._histoOp!.X.AttributeModel.DisplayName}
+
{this.HistoOp!.X.AttributeModel.DisplayName}
} @@ -238,101 +208,85 @@ export class HistogramBinPrimitiveCollection { public BinPrimitives: Array = new Array(); public FilterModel: FilterModel; public HitGeom: PIXIRectangle = PIXIRectangle.EMPTY; + private _histoBox: HistogramBox; + private get histoOp() { return this._histoBox.HistoOp!; } + private get histoResult() { return this.histoOp.Result as HistogramResult; } - private _y: AttributeTransformationModel; - private _x: AttributeTransformationModel; - private _value: AttributeTransformationModel; - private _chartType: ChartType; - private _histoResult: HistogramResult; - private _visualBinRanges: Array; - - constructor(bin: Bin, histoResult: HistogramResult, - value: AttributeTransformationModel, x: AttributeTransformationModel, y: AttributeTransformationModel, - chartType: ChartType, visualBinRanges: Array, - minValue: number, maxValue: number, normalization: number, sizeConverter: SizeConverter) { - this._histoResult = histoResult; - this._chartType = chartType; - this._value = value; - this._x = x; - this._y = y; - this._visualBinRanges = visualBinRanges; - - var allBrushIndex = ModelHelpers.AllBrushIndex(this._histoResult); - var overlapBrushIndex = ModelHelpers.OverlapBrushIndex(this._histoResult); - this.FilterModel = ModelHelpers.GetBinFilterModel(bin, allBrushIndex, this._histoResult, this._x, this._y); + constructor(key: string, histoBox: HistogramBox) { + this._histoBox = histoBox; + let bin = this.histoResult.bins![key]; + + var allBrushIndex = ModelHelpers.AllBrushIndex(this.histoResult); + var overlapBrushIndex = ModelHelpers.OverlapBrushIndex(this.histoResult); + this.FilterModel = ModelHelpers.GetBinFilterModel(bin, allBrushIndex, this.histoResult, this.histoOp.X, this.histoOp.Y); var orderedBrushes = new Array(); - orderedBrushes.push(histoResult.brushes![0]); - orderedBrushes.push(histoResult.brushes![overlapBrushIndex]); - for (var b = 0; b < histoResult.brushes!.length; b++) { - var brush = histoResult.brushes![b]; + orderedBrushes.push(this.histoResult.brushes![0]); + orderedBrushes.push(this.histoResult.brushes![overlapBrushIndex]); + for (var b = 0; b < this.histoResult.brushes!.length; b++) { + var brush = this.histoResult.brushes![b]; if (brush.brushIndex != 0 && brush.brushIndex != overlapBrushIndex) { orderedBrushes.push(brush); } } - var binBrushMaxAxis = this.getBinBrushAxisRange(bin, orderedBrushes, normalization); // X= 0, Y = 1 + var binBrushMaxAxis = this.getBinBrushAxisRange(bin, orderedBrushes, this.histoOp.Normalization); // X= 0, Y = 1 var brushFactorSum: number = 0; for (var b = 0; b < orderedBrushes.length; b++) { var brush = orderedBrushes[b]; - var valueAggregateKey = ModelHelpers.CreateAggregateKey(value, histoResult, brush.brushIndex!); + var valueAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.V, this.histoResult, brush.brushIndex!); var doubleRes = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; var unNormalizedValue = (doubleRes != null && doubleRes.hasResult) ? doubleRes.result : null; - if (unNormalizedValue == null) { - continue; - } - if (chartType == ChartType.VerticalBar) { - this.createVerticalBarChartBinPrimitives(bin, brush, binBrushMaxAxis, normalization, sizeConverter); // X = 0, Y = 1, NOne = -1 - } - else if (chartType == ChartType.HorizontalBar) { - this.createHorizontalBarChartBinPrimitives(bin, brush, binBrushMaxAxis, normalization, sizeConverter); - } - else if (chartType == ChartType.SinglePoint) { - this.createSinlgePointChartBinPrimitives(bin, brush, unNormalizedValue, sizeConverter); - } - else if (chartType == ChartType.HeatMap) { - var normalizedValue = (unNormalizedValue - minValue) / (Math.abs((maxValue - minValue)) < HistogramBinPrimitiveCollection.TOLERANCE ? - unNormalizedValue : (maxValue - minValue)); - brushFactorSum = this.createHeatmapBinPrimitives(bin, brush, unNormalizedValue, brushFactorSum, normalizedValue, sizeConverter); - } + if (unNormalizedValue) + switch (histoBox.ChartType) { + case ChartType.VerticalBar: + this.createVerticalBarChartBinPrimitives(bin, brush, binBrushMaxAxis, this.histoOp.Normalization, histoBox.SizeConverter!); // X = 0, Y = 1, NOne = -1 + break; + case ChartType.HorizontalBar: + this.createHorizontalBarChartBinPrimitives(bin, brush, binBrushMaxAxis, this.histoOp.Normalization, histoBox.SizeConverter!); + break; + case ChartType.SinglePoint: + this.createSinlgePointChartBinPrimitives(bin, brush, unNormalizedValue, histoBox.SizeConverter!); + break; + case ChartType.HeatMap: + var normalizedValue = (unNormalizedValue - histoBox.MinValue) / (Math.abs((histoBox.MaxValue - histoBox.MinValue)) < HistogramBinPrimitiveCollection.TOLERANCE ? + unNormalizedValue : histoBox.MaxValue - histoBox.MinValue); + brushFactorSum = this.createHeatmapBinPrimitives(bin, brush, unNormalizedValue, brushFactorSum, normalizedValue, histoBox.SizeConverter!); + } } // adjust brush rects (stacking or not) var sum: number = 0; - var filtered = this.BinPrimitives.filter(b => b.BrushIndex != allBrushIndex && b.DataValue != 0.0); - var count: number = filtered.length; - for (var i = 0; i < count; i++) { - var bp = filtered[i]; - - if (this._chartType == ChartType.VerticalBar) { - if (this._y.AggregateFunction == AggregateFunction.Count) { - bp.Rect = new PIXIRectangle(bp.Rect.x, bp.Rect.y - sum, bp.Rect.width, bp.Rect.height); - bp.MarginRect = new PIXIRectangle(bp.MarginRect.x, bp.MarginRect.y - sum, bp.MarginRect.width, bp.MarginRect.height); - sum += bp.Rect.height; + var filteredBinPrims = this.BinPrimitives.filter(b => b.BrushIndex != allBrushIndex && b.DataValue != 0.0); + var count: number = filteredBinPrims.length; + filteredBinPrims.map(fbp => { + if (histoBox.ChartType == ChartType.VerticalBar) { + if (this.histoOp.X.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); + sum += fbp.Rect.height; } - if (this._y.AggregateFunction == AggregateFunction.Avg) { - var w = bp.Rect.width / 2.0; - bp.Rect = new PIXIRectangle(bp.Rect.x + sum, bp.Rect.y, bp.Rect.width / count, bp.Rect.height); - bp.MarginRect = new PIXIRectangle(bp.MarginRect.x - w + sum + (bp.Rect.width / 2.0), bp.MarginRect.y, bp.MarginRect.width, bp.MarginRect.height); - sum += bp.Rect.width; + 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 / count, 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); + sum += fbp.Rect.width; } } - else if (this._chartType == ChartType.HorizontalBar) { - if (this._x.AggregateFunction == AggregateFunction.Count) { - bp.Rect = new PIXIRectangle(bp.Rect.x + sum, bp.Rect.y, bp.Rect.width, bp.Rect.height); - bp.MarginRect = new PIXIRectangle(bp.MarginRect.x + sum, bp.MarginRect.y, bp.MarginRect.width, bp.MarginRect.height); - sum += bp.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); + sum += fbp.Rect.width; } - if (this._x.AggregateFunction == AggregateFunction.Avg) { - var h = bp.Rect.height / 2.0; - bp.Rect = new PIXIRectangle(bp.Rect.x, bp.Rect.y + sum, bp.Rect.width, bp.Rect.height / count); - bp.MarginRect = new PIXIRectangle(bp.MarginRect.x, bp.MarginRect.y - h + sum + (bp.Rect.height / 2.0), bp.MarginRect.width, bp.MarginRect.height); - sum += bp.Rect.height; + 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 / count); + fbp.MarginRect = new PIXIRectangle(fbp.MarginRect.x, fbp.MarginRect.y - h + sum + (fbp.Rect.height / 2.0), fbp.MarginRect.width, fbp.MarginRect.height); + sum += fbp.Rect.height; } } - else if (this._chartType == ChartType.HeatMap) { - } - } + }); this.BinPrimitives = this.BinPrimitives.reverse(); var f = this.BinPrimitives.filter(b => b.BrushIndex == allBrushIndex); this.HitGeom = f.length > 0 ? f[0].Rect : PIXIRectangle.EMPTY; @@ -340,7 +294,7 @@ export class HistogramBinPrimitiveCollection { private getBinBrushAxisRange(bin: Bin, brushes: Array, axis: number): number { var binBrushMaxAxis = Number.MIN_VALUE; brushes.forEach((Brush) => { - var maxAggregateKey = ModelHelpers.CreateAggregateKey(axis === 0 ? this._y : this._x, this._histoResult, Brush.brushIndex!); + var maxAggregateKey = ModelHelpers.CreateAggregateKey(axis === 0 ? this.histoOp.Y : this.histoOp.X, this.histoResult, Brush.brushIndex!); var aggResult = ModelHelpers.GetAggregateResult(bin, maxAggregateKey) as DoubleValueAggregateResult; if (aggResult != null) { if (aggResult.result! > binBrushMaxAxis) @@ -356,16 +310,16 @@ export class HistogramBinPrimitiveCollection { var yTo: number = 0; var returnBrushFactorSum = brushFactorSum; - var valueAggregateKey = ModelHelpers.CreateAggregateKey(this._value, this._histoResult, ModelHelpers.AllBrushIndex(this._histoResult)); + var valueAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.V, this.histoResult, ModelHelpers.AllBrushIndex(this.histoResult)); var allUnNormalizedValue = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; - var tx = this._visualBinRanges[0].GetValueFromIndex(bin.binIndex!.indices![0]); + var tx = this._histoBox.VisualBinRanges[0].GetValueFromIndex(bin.binIndex!.indices![0]); xFrom = sizeConverter.DataToScreenX(tx); - xTo = sizeConverter.DataToScreenX(this._visualBinRanges[0].AddStep(tx)); + xTo = sizeConverter.DataToScreenX(this._histoBox.VisualBinRanges[0].AddStep(tx)); - var ty = this._visualBinRanges[1].GetValueFromIndex(bin.binIndex!.indices![1]); + var ty = this._histoBox.VisualBinRanges[1].GetValueFromIndex(bin.binIndex!.indices![1]); yFrom = sizeConverter.DataToScreenY(ty); - yTo = sizeConverter.DataToScreenY(this._visualBinRanges[1].AddStep(ty)); + yTo = sizeConverter.DataToScreenY(this._histoBox.VisualBinRanges[1].AddStep(ty)); if (allUnNormalizedValue.hasResult) { var brushFactor = (unNormalizedValue / allUnNormalizedValue.result!); @@ -391,24 +345,24 @@ export class HistogramBinPrimitiveCollection { var dataColor = LABColor.ToColor(lerpColor); var marginParams = new MarginAggregateParameters(); - marginParams.aggregateFunction = this._value.AggregateFunction; - var marginAggregateKey = ModelHelpers.CreateAggregateKey(this._value, this._histoResult, - ModelHelpers.AllBrushIndex(this._histoResult), marginParams); + marginParams.aggregateFunction = this.histoOp.V.AggregateFunction; + var marginAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.V, this.histoResult, + ModelHelpers.AllBrushIndex(this.histoResult), marginParams); this.createBinPrimitive(bin, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, dataColor, 1, unNormalizedValue); return returnBrushFactorSum; } private createSinlgePointChartBinPrimitives(bin: Bin, brush: Brush, unNormalizedValue: number, sizeConverter: SizeConverter): void { - var yAggregateKey = ModelHelpers.CreateAggregateKey(this._y, this._histoResult, brush.brushIndex!); + var yAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, brush.brushIndex!); var marginParams = new MarginAggregateParameters(); - marginParams.aggregateFunction = this._y.AggregateFunction; + marginParams.aggregateFunction = this.histoOp.Y.AggregateFunction; - var xAggregateKey = ModelHelpers.CreateAggregateKey(this._x, this._histoResult, brush.brushIndex!); + var xAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, brush.brushIndex!); var marginParams = new MarginAggregateParameters(); - marginParams.aggregateFunction = this._x.AggregateFunction; + marginParams.aggregateFunction = this.histoOp.X.AggregateFunction; - var xValue = ModelHelpers.GetAggregateResult(bin, xAggregateKey) as DoubleValueAggregateResult;; + var xValue = ModelHelpers.GetAggregateResult(bin, xAggregateKey) as DoubleValueAggregateResult; if (!xValue.hasResult) return; var xFrom = sizeConverter.DataToScreenX(xValue.result!) - 5; @@ -424,10 +378,10 @@ export class HistogramBinPrimitiveCollection { } private createVerticalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number, sizeConverter: SizeConverter): void { - var yAggregateKey = ModelHelpers.CreateAggregateKey(this._y, this._histoResult, brush.brushIndex!); + var yAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, brush.brushIndex!); var marginParams = new MarginAggregateParameters(); - marginParams.aggregateFunction = this._y.AggregateFunction; - var yMarginAggregateKey = ModelHelpers.CreateAggregateKey(this._y, this._histoResult, + marginParams.aggregateFunction = this.histoOp.Y.AggregateFunction; + var yMarginAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, brush.brushIndex!, marginParams); var dataValue = ModelHelpers.GetAggregateResult(bin, yAggregateKey) as DoubleValueAggregateResult; @@ -437,9 +391,9 @@ export class HistogramBinPrimitiveCollection { var yFrom = sizeConverter.DataToScreenY(Math.min(0, yValue)); var yTo = sizeConverter.DataToScreenY(Math.max(0, yValue));; - var xValue = this._visualBinRanges[0].GetValueFromIndex(bin.binIndex!.indices![0])!; + var xValue = this._histoBox.VisualBinRanges[0].GetValueFromIndex(bin.binIndex!.indices![0])!; var xFrom = sizeConverter.DataToScreenX(xValue); - var xTo = sizeConverter.DataToScreenX(this._visualBinRanges[0].AddStep(xValue)); + var xTo = sizeConverter.DataToScreenX(this._histoBox.VisualBinRanges[0].AddStep(xValue)); var marginResult = ModelHelpers.GetAggregateResult(bin, yMarginAggregateKey)!; var yMarginAbsolute = marginResult == null ? 0 : (marginResult as MarginAggregateResult).absolutMargin!; @@ -453,10 +407,10 @@ export class HistogramBinPrimitiveCollection { } private createHorizontalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number, sizeConverter: SizeConverter): void { - var xAggregateKey = ModelHelpers.CreateAggregateKey(this._x, this._histoResult, brush.brushIndex!); + var xAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, brush.brushIndex!); var marginParams = new MarginAggregateParameters(); - marginParams.aggregateFunction = this._x.AggregateFunction; - var xMarginAggregateKey = ModelHelpers.CreateAggregateKey(this._x, this._histoResult, + marginParams.aggregateFunction = this.histoOp.X.AggregateFunction; + var xMarginAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, brush.brushIndex!, marginParams); var dataValue = ModelHelpers.GetAggregateResult(bin, xAggregateKey) as DoubleValueAggregateResult; @@ -465,9 +419,9 @@ export class HistogramBinPrimitiveCollection { var xFrom = sizeConverter.DataToScreenX(Math.min(0, xValue)); var xTo = sizeConverter.DataToScreenX(Math.max(0, xValue)); - var yValue = this._visualBinRanges[1].GetValueFromIndex(bin.binIndex!.indices![1]); + var yValue = this._histoBox.VisualBinRanges[1].GetValueFromIndex(bin.binIndex!.indices![1]); var yFrom = yValue; - var yTo = this._visualBinRanges[1].AddStep(yValue); + var yTo = this._histoBox.VisualBinRanges[1].AddStep(yValue); var marginResult = ModelHelpers.GetAggregateResult(bin, xMarginAggregateKey); var xMarginAbsolute = sizeConverter.IsSmall || marginResult == null ? 0 : (marginResult as MarginAggregateResult).absolutMargin!; @@ -505,13 +459,13 @@ export class HistogramBinPrimitiveCollection { private baseColorFromBrush(brush: Brush): number { var baseColor: number = StyleConstants.HIGHLIGHT_COLOR; - if (brush.brushIndex == ModelHelpers.RestBrushIndex(this._histoResult)) { + if (brush.brushIndex == ModelHelpers.RestBrushIndex(this.histoResult)) { baseColor = StyleConstants.HIGHLIGHT_COLOR; } - else if (brush.brushIndex == ModelHelpers.OverlapBrushIndex(this._histoResult)) { + else if (brush.brushIndex == ModelHelpers.OverlapBrushIndex(this.histoResult)) { baseColor = StyleConstants.OVERLAP_COLOR; } - else if (brush.brushIndex == ModelHelpers.AllBrushIndex(this._histoResult)) { + else if (brush.brushIndex == ModelHelpers.AllBrushIndex(this.histoResult)) { baseColor = 0x00ff00; } else { -- cgit v1.2.3-70-g09d2 From 31049374ef26d33e9d5304e1975e550d9046a50a Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 25 Mar 2019 18:00:38 -0400 Subject: from last --- src/client/views/nodes/HistogramBox.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/client/views/nodes/HistogramBox.tsx b/src/client/views/nodes/HistogramBox.tsx index ea54ed29a..c6903d397 100644 --- a/src/client/views/nodes/HistogramBox.tsx +++ b/src/client/views/nodes/HistogramBox.tsx @@ -93,8 +93,8 @@ export class HistogramBox extends React.Component { return
; } - drawRect(r: PIXIRectangle, color: number) { - return
+ drawRect(r: PIXIRectangle, color: number, tapHandler: () => void) { + return
} private renderGridLinesAndLabels(axis: number) { @@ -161,8 +161,8 @@ export class HistogramBox extends React.Component { } drawPrims.BinPrimitives.filter(bp => bp.DataValue && bp.BrushIndex !== allBrushIndex).map(binPrimitive => { - prims.push(this.drawRect(binPrimitive.Rect, binPrimitive.Color)); - prims.push(this.drawRect(binPrimitive.MarginRect, StyleConstants.MARGIN_BARS_COLOR)); + prims.push(this.drawRect(binPrimitive.Rect, binPrimitive.Color, () => { console.log("FM = " + drawPrims.FilterModel.ToPythonString()) })); + prims.push(this.drawRect(binPrimitive.MarginRect, StyleConstants.MARGIN_BARS_COLOR, () => { console.log("FM = " + drawPrims.FilterModel.ToPythonString()) })); }); } } -- cgit v1.2.3-70-g09d2 From 2264fb874a09ee01540141986325c76650f32c21 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Mon, 25 Mar 2019 23:20:22 -0400 Subject: added 1-level navigation to region annotations --- .../views/collections/CollectionDockingView.tsx | 2 +- .../views/collections/CollectionVideoView.tsx | 108 ++++++++++++--------- src/client/views/collections/CollectionView.tsx | 6 +- src/client/views/nodes/LinkBox.tsx | 21 +++- src/client/views/nodes/PDFBox.tsx | 21 ++-- src/client/views/nodes/VideoBox.tsx | 29 ++++-- src/fields/KeyStore.ts | 2 + 7 files changed, 120 insertions(+), 69 deletions(-) (limited to 'src') diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 39b284d8e..d4f510f5d 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -191,7 +191,7 @@ export class CollectionDockingView extends React.Component { var className = (e.target as any).className; - if ((className == "lm_title" || className == "lm_tab lm_active") && e.ctrlKey) { + if ((className == "lm_title" || className == "lm_tab lm_active") && (e.ctrlKey || e.altKey)) { e.stopPropagation(); e.preventDefault(); let docid = (e.target as any).DashDocId; diff --git a/src/client/views/collections/CollectionVideoView.tsx b/src/client/views/collections/CollectionVideoView.tsx index a3921696f..470a853e3 100644 --- a/src/client/views/collections/CollectionVideoView.tsx +++ b/src/client/views/collections/CollectionVideoView.tsx @@ -1,4 +1,4 @@ -import { action, computed, observable } from "mobx"; +import { action, computed, observable, trace } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../../fields/Document"; import { KeyStore } from "../../../fields/KeyStore"; @@ -12,24 +12,26 @@ import "./CollectionVideoView.scss" @observer export class CollectionVideoView extends React.Component { + private _intervalTimer: any = undefined; + private _player: HTMLVideoElement | undefined = undefined; + + @observable _currentTimecode: number = 0; + @observable _isPlaying: boolean = false; public static LayoutString(fieldKey: string = "DataKey") { return `<${CollectionVideoView.name} Document={Document} ScreenToLocalTransform={ScreenToLocalTransform} fieldKey={${fieldKey}} panelWidth={PanelWidth} panelHeight={PanelHeight} isSelected={isSelected} select={select} bindings={bindings} isTopMost={isTopMost} SelectOnLoad={selectOnLoad} BackgroundView={BackgroundView} focus={focus}/>`; } - - private _mainCont = React.createRef(); - private get uIButtons() { let scaling = Math.min(1.8, this.props.ScreenToLocalTransform().transformDirection(1, 1)[0]); return ([
- {"" + Math.round(this.ctime)} - {" " + Math.round((this.ctime - Math.trunc(this.ctime)) * 100)} + {"" + Math.round(this._currentTimecode)} + {" " + Math.round((this._currentTimecode - Math.trunc(this._currentTimecode)) * 100)}
,
- {this.playing ? "\"" : ">"} + {this._isPlaying ? "\"" : ">"}
,
F @@ -37,64 +39,54 @@ export class CollectionVideoView extends React.Component { ]); } - - // "inherited" CollectionView API starts here... - - @observable - public SelectedDocs: FieldId[] = [] - public active: () => boolean = () => CollectionView.Active(this); - - addDocument = (doc: Document, allowDuplicates: boolean): boolean => { return CollectionView.AddDocument(this.props, doc, allowDuplicates); } - removeDocument = (doc: Document): boolean => { return CollectionView.RemoveDocument(this.props, doc); } - - specificContextMenu = (e: React.MouseEvent): void => { - if (!e.isPropagationStopped() && this.props.Document.Id != "mainDoc") { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7 - ContextMenu.Instance.addItem({ description: "VideoOptions", event: () => { } }); + @action + mainCont = (ele: HTMLDivElement | null) => { + if (ele) { + this._player = ele!.getElementsByTagName("video")[0]; + if (this.props.Document.GetNumber(KeyStore.CurPage, -1) >= 0) { + this._currentTimecode = this.props.Document.GetNumber(KeyStore.CurPage, -1); + } } } - get collectionViewType(): CollectionViewType { return CollectionViewType.Freeform; } - get subView(): any { return CollectionView.SubView(this); } - componentDidMount() { - this.updateTimecode(); + this._intervalTimer = setInterval(this.updateTimecode, 1000); } - get player(): HTMLVideoElement | undefined { - return this._mainCont.current ? this._mainCont.current.getElementsByTagName("video")[0] : undefined; + componentWillUnmount() { + clearInterval(this._intervalTimer); } @action updateTimecode = () => { - if (this.player) { - this.ctime = this.player.currentTime; - this.props.Document.SetNumber(KeyStore.CurPage, Math.round(this.ctime)); + if (this._player) { + if ((this._player as any).AHackBecauseSomethingResetsTheVideoToZero != -1) { + this._player.currentTime = (this._player as any).AHackBecauseSomethingResetsTheVideoToZero; + (this._player as any).AHackBecauseSomethingResetsTheVideoToZero = -1; + } else { + this._currentTimecode = this._player.currentTime; + this.props.Document.SetNumber(KeyStore.CurPage, Math.round(this._currentTimecode)); + } } - setTimeout(() => this.updateTimecode(), 100) } - - @observable - ctime: number = 0 - @observable - playing: boolean = false; - @action onPlayDown = () => { - if (this.player) { - if (this.player.paused) { - this.player.play(); - this.playing = true; + if (this._player) { + if (this._player.paused) { + this._player.play(); + this._isPlaying = true; } else { - this.player.pause(); - this.playing = false; + this._player.pause(); + this._isPlaying = false; } } } + @action onFullDown = (e: React.PointerEvent) => { - if (this.player) { - this.player.requestFullscreen(); + if (this._player) { + this._player.requestFullscreen(); e.stopPropagation(); e.preventDefault(); } @@ -102,15 +94,35 @@ export class CollectionVideoView extends React.Component { @action onResetDown = () => { - if (this.player) { - this.player.pause(); - this.player.currentTime = 0; + if (this._player) { + this._player.pause(); + this._player.currentTime = 0; } } + // "inherited" CollectionView API starts here... + + @observable + public SelectedDocs: FieldId[] = [] + public active: () => boolean = () => CollectionView.Active(this); + + addDocument = (doc: Document, allowDuplicates: boolean): boolean => { return CollectionView.AddDocument(this.props, doc, allowDuplicates); } + removeDocument = (doc: Document): boolean => { return CollectionView.RemoveDocument(this.props, doc); } + + specificContextMenu = (e: React.MouseEvent): void => { + if (!e.isPropagationStopped() && this.props.Document.Id != "mainDoc") { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7 + ContextMenu.Instance.addItem({ description: "VideoOptions", event: () => { } }); + } + } + + get collectionViewType(): CollectionViewType { return CollectionViewType.Freeform; } + get subView(): any { return CollectionView.SubView(this); } + + render() { - return (
+ trace(); + return (
{this.subView} {this.props.isSelected() ? this.uIButtons : (null)}
) diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index a740865ad..2fa2c9086 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -68,7 +68,11 @@ export class CollectionView extends React.Component { @action public static AddDocument(props: CollectionViewProps, doc: Document, allowDuplicates: boolean): boolean { - doc.SetNumber(KeyStore.Page, props.Document.GetNumber(KeyStore.CurPage, -1)); + var curPage = props.Document.GetNumber(KeyStore.CurPage, -1); + doc.SetNumber(KeyStore.Page, curPage); + if (curPage > 0) { + doc.Set(KeyStore.AnnotationOn, props.Document); + } if (props.Document.Get(props.fieldKey) instanceof Field) { //TODO This won't create the field if it doesn't already exist const value = props.Document.GetData(props.fieldKey, ListField, new Array()) diff --git a/src/client/views/nodes/LinkBox.tsx b/src/client/views/nodes/LinkBox.tsx index dd2f71b59..638d3b5a7 100644 --- a/src/client/views/nodes/LinkBox.tsx +++ b/src/client/views/nodes/LinkBox.tsx @@ -17,6 +17,8 @@ import { faEye } from '@fortawesome/free-solid-svg-icons'; import { faEdit } from '@fortawesome/free-solid-svg-icons'; import { faTimes } from '@fortawesome/free-solid-svg-icons'; import { undoBatch } from "../../util/UndoManager"; +import { FieldWaiting } from "../../../fields/Field"; +import { NumberField } from "../../../fields/NumberField"; library.add(faEye); @@ -41,7 +43,24 @@ export class LinkBox extends React.Component { if (docView) { docView.props.focus(this.props.pairedDoc); } else { - CollectionDockingView.Instance.AddRightSplit(this.props.pairedDoc) + this.props.pairedDoc.GetAsync(KeyStore.AnnotationOn, (contextDoc: any) => { + if (!contextDoc) { + CollectionDockingView.Instance.AddRightSplit(this.props.pairedDoc); + } else if (contextDoc instanceof Document) { + this.props.pairedDoc.GetTAsync(KeyStore.Page, NumberField).then((pfield: any) => { + contextDoc.GetTAsync(KeyStore.CurPage, NumberField).then((cfield: any) => { + if (pfield != cfield) + contextDoc.SetNumber(KeyStore.CurPage, pfield.Data); + let contextView = DocumentManager.Instance.getDocumentView(contextDoc); + if (contextView) { + contextView.props.focus(contextDoc); + } else { + CollectionDockingView.Instance.AddRightSplit(contextDoc); + } + }) + }); + } + }); } } diff --git a/src/client/views/nodes/PDFBox.tsx b/src/client/views/nodes/PDFBox.tsx index 3a0ef2d32..e273b0b4f 100644 --- a/src/client/views/nodes/PDFBox.tsx +++ b/src/client/views/nodes/PDFBox.tsx @@ -1,5 +1,5 @@ import * as htmlToImage from "html-to-image"; -import { action, computed, observable, reaction, IReactionDisposer, trace } from 'mobx'; +import { action, computed, observable, reaction, IReactionDisposer, trace, keys } from 'mobx'; import { observer } from "mobx-react"; import 'react-image-lightbox/style.css'; import Measure from "react-measure"; @@ -18,6 +18,7 @@ import "./PDFBox.scss"; import { Sticky } from './Sticky'; //you should look at sticky and annotation, because they are used here import React = require("react") import { RouteStore } from "../../../server/RouteStore"; +import { NumberField } from "../../../fields/NumberField"; /** ALSO LOOK AT: Annotation.tsx, Sticky.tsx * This method renders PDF and puts all kinds of functionalities such as annotation, highlighting, @@ -60,7 +61,6 @@ export class PDFBox extends React.Component { //very useful for keeping track of X and y position throughout the PDF Canvas private initX: number = 0; private initY: number = 0; - private initPage: boolean = false; //checks if tool is on private _toolOn: boolean = false; //checks if tool is on @@ -88,17 +88,15 @@ export class PDFBox extends React.Component { @observable private _loaded: boolean = false; @computed private get curPage() { return this.props.doc.GetNumber(KeyStore.CurPage, -1); } + @computed private get thumbnailPage() { return this.props.doc.GetNumber(KeyStore.ThumbnailPage, -1); } componentDidMount() { this._reactionDisposer = reaction( - () => this.curPage, + () => [this.curPage, this.thumbnailPage], () => { - if (this.curPage && this.initPage) { + if (this.curPage > 0 && this.thumbnailPage > 0 && this.curPage != this.thumbnailPage) { this.saveThumbnail(); this._interactive = true; - } else { - if (this.curPage > 0) - this.initPage = true; } }, { fireImmediately: true }); @@ -384,6 +382,7 @@ export class PDFBox extends React.Component { { width: me.props.doc.GetNumber(KeyStore.NativeWidth, 0), height: me.props.doc.GetNumber(KeyStore.NativeHeight, 0), quality: 0.5 }) .then(function (dataUrl: string) { me.props.doc.SetData(KeyStore.Thumbnail, new URL(dataUrl), ImageField); + me.props.doc.SetNumber(KeyStore.ThumbnailPage, me.props.doc.GetNumber(KeyStore.CurPage, -1)); }) .catch(function (error: any) { console.error('oops, something went wrong!', error); @@ -473,10 +472,10 @@ export class PDFBox extends React.Component { @computed get imageProxyRenderer() { - let field = this.props.doc.Get(KeyStore.Thumbnail); - if (field) { - let path = field == FieldWaiting ? "https://image.flaticon.com/icons/svg/66/66163.svg" : - field instanceof ImageField ? field.Data.href : "http://cs.brown.edu/people/bcz/prairie.jpg"; + let thumbField = this.props.doc.Get(KeyStore.Thumbnail); + if (thumbField) { + let path = thumbField == FieldWaiting || this.thumbnailPage != this.curPage ? "https://image.flaticon.com/icons/svg/66/66163.svg" : + thumbField instanceof ImageField ? thumbField.Data.href : "http://cs.brown.edu/people/bcz/prairie.jpg"; return ; } return (null); diff --git a/src/client/views/nodes/VideoBox.tsx b/src/client/views/nodes/VideoBox.tsx index 09ae95183..7c0db83a8 100644 --- a/src/client/views/nodes/VideoBox.tsx +++ b/src/client/views/nodes/VideoBox.tsx @@ -1,23 +1,27 @@ import React = require("react") import { observer } from "mobx-react"; -import { FieldWaiting } from '../../../fields/Field'; +import { FieldWaiting, Opt } from '../../../fields/Field'; import { VideoField } from '../../../fields/VideoField'; import { FieldView, FieldViewProps } from './FieldView'; import "./VideoBox.scss"; import Measure from "react-measure"; -import { action, trace, observable } from "mobx"; +import { action, trace, observable, IReactionDisposer, computed, reaction } from "mobx"; import { KeyStore } from "../../../fields/KeyStore"; import { number } from "prop-types"; @observer export class VideoBox extends React.Component { + private _reactionDisposer: Opt; + private _videoRef = React.createRef() public static LayoutString() { return FieldView.LayoutString(VideoBox) } constructor(props: FieldViewProps) { super(props); } + @computed private get curPage() { return this.props.doc.GetNumber(KeyStore.CurPage, -1); } + _loaded: boolean = false; @@ -39,7 +43,17 @@ export class VideoBox extends React.Component { } } + get player(): HTMLVideoElement | undefined { + return this._videoRef.current ? this._videoRef.current.getElementsByTagName("video")[0] : undefined; + } + @action + setVideoRef = (vref: HTMLVideoElement | null) => { + if (this.curPage >= 0 && vref) { + vref!.currentTime = this.curPage; + (vref! as any).AHackBecauseSomethingResetsTheVideoToZero = this.curPage; + } + } render() { let field = this.props.doc.GetT(this.props.fieldKey, VideoField); @@ -47,15 +61,16 @@ export class VideoBox extends React.Component { return
Loading
} let path = field.Data.href; - - //setTimeout(action(() => this._loaded = true), 500); + trace(); return ( {({ measureRef }) => - ) diff --git a/src/fields/KeyStore.ts b/src/fields/KeyStore.ts index 611e2951b..f9684b212 100644 --- a/src/fields/KeyStore.ts +++ b/src/fields/KeyStore.ts @@ -36,7 +36,9 @@ export namespace KeyStore { export const LinkDescription = new Key("LinkDescription"); export const LinkTags = new Key("LinkTag"); export const Thumbnail = new Key("Thumbnail"); + export const ThumbnailPage = new Key("ThumbnailPage"); export const CurPage = new Key("CurPage"); + export const AnnotationOn = new Key("AnnotationOn"); export const NumPages = new Key("NumPages"); export const Ink = new Key("Ink"); export const Cursors = new Key("Cursors"); -- cgit v1.2.3-70-g09d2 From 970ecdb7158340cec2ea9e9a381d86afa8a59430 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 26 Mar 2019 00:02:30 -0400 Subject: tried to fix keyboard event issue when editing a text note in an embedded free form collection. --- src/client/views/collections/PreviewCursor.tsx | 9 ++++++--- src/client/views/nodes/FormattedTextBox.tsx | 6 ++++-- 2 files changed, 10 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/client/views/collections/PreviewCursor.tsx b/src/client/views/collections/PreviewCursor.tsx index cbf36cf9e..5d621f321 100644 --- a/src/client/views/collections/PreviewCursor.tsx +++ b/src/client/views/collections/PreviewCursor.tsx @@ -37,13 +37,13 @@ export class PreviewCursor extends React.Component { @action cleanupInteractions = () => { - document.removeEventListener("keypress", this.onKeyPress, true); + document.removeEventListener("keypress", this.onKeyPress, false); } @action onCursorPlaced = (visible: boolean, downX: number, downY: number): void => { if (visible) { - document.addEventListener("keypress", this.onKeyPress, true); + document.addEventListener("keypress", this.onKeyPress, false); this._lastX = downX; this._lastY = downY; } else @@ -52,8 +52,11 @@ export class PreviewCursor extends React.Component { @action onKeyPress = (e: KeyboardEvent) => { + // Mixing events between React and Native is finicky. In FormattedTextBox, we set the + // DASHFormattedTextBoxHandled flag when a text box consumes a key press so that we can ignore + // the keyPress here. //if not these keys, make a textbox if preview cursor is active! - if (!e.ctrlKey && !e.altKey && !e.defaultPrevented) { + if (!e.ctrlKey && !e.altKey && !e.defaultPrevented && !(e as any).DASHFormattedTextBoxHandled) { //make textbox and add it to this collection let [x, y] = this.props.getTransform().transformPoint(this._lastX, this._lastY); let newBox = Documents.TextDocument({ width: 200, height: 100, x: x, y: y, title: "new" }); diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 30fa1342e..512ad7d70 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -158,17 +158,19 @@ export class FormattedTextBox extends React.Component { } }) } - onKeyPress(e: React.KeyboardEvent) { e.stopPropagation(); + // stop propagation doesn't seem to stop propagation of native keyboard events. + // so we set a flag on the native event that marks that the event's been handled. + // (e.nativeEvent as any).DASHFormattedTextBoxHandled = true; } render() { return (
) } -- cgit v1.2.3-70-g09d2 From 731cab330389b1730d9700b5452ac75975b79b3c Mon Sep 17 00:00:00 2001 From: bob Date: Tue, 26 Mar 2019 09:28:35 -0400 Subject: minor restructure --- src/client/northstar/model/ModelHelpers.ts | 4 +- .../northstar/operations/HistogramOperation.ts | 7 ++- src/client/views/nodes/HistogramBox.tsx | 64 +++++++++------------- 3 files changed, 33 insertions(+), 42 deletions(-) (limited to 'src') diff --git a/src/client/northstar/model/ModelHelpers.ts b/src/client/northstar/model/ModelHelpers.ts index 914e03255..8de0bd260 100644 --- a/src/client/northstar/model/ModelHelpers.ts +++ b/src/client/northstar/model/ModelHelpers.ts @@ -64,10 +64,10 @@ export class ModelHelpers { if (aggParams) { aggregateParameters.push(aggParams); - var margin = new MarginAggregateParameters(); + var margin = new MarginAggregateParameters() + margin.aggregateFunction = agg.AggregateFunction; margin.attributeParameters = ModelHelpers.GetAttributeParameters(agg.AttributeModel); margin.distinctAttributeParameters = CurrentUserUtils.ActiveSchema!.distinctAttributeParameters; - margin.aggregateFunction = agg.AggregateFunction; aggregateParameters.push(margin); } }); diff --git a/src/client/northstar/operations/HistogramOperation.ts b/src/client/northstar/operations/HistogramOperation.ts index 8367cc725..cf2571285 100644 --- a/src/client/northstar/operations/HistogramOperation.ts +++ b/src/client/northstar/operations/HistogramOperation.ts @@ -8,14 +8,19 @@ import { AttributeTransformationModel } from "../core/attribute/AttributeTransfo import { BaseOperation } from "./BaseOperation"; import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; import { FilterModel } from "../core/filter/FilterModel"; +import { BrushLinkModel } from "../core/brusher/BrushLinkModel"; export class HistogramOperation extends BaseOperation { + @observable public BrushColors: number[] = []; @observable public Normalization: number = -1; @observable public FilterModels: FilterModel[] = []; @observable public X: AttributeTransformationModel; @observable public Y: AttributeTransformationModel; @observable public V: AttributeTransformationModel; + @observable public BrusherModels: BrushLinkModel[] = []; + @observable public BrushableModels: BrushLinkModel[] = []; + constructor(x: AttributeTransformationModel, y: AttributeTransformationModel, v: AttributeTransformationModel) { super(); this.X = x; @@ -106,7 +111,7 @@ export class HistogramOperation extends BaseOperation { @action public async Update(): Promise { - // this.TypedViewModel.BrushColors = this.TypedViewModel.BrusherModels.map(e => e.Color); + this.BrushColors = this.BrusherModels.map(e => e.Color); return super.Update(); } } diff --git a/src/client/views/nodes/HistogramBox.tsx b/src/client/views/nodes/HistogramBox.tsx index c6903d397..675bf30b2 100644 --- a/src/client/views/nodes/HistogramBox.tsx +++ b/src/client/views/nodes/HistogramBox.tsx @@ -154,15 +154,18 @@ export class HistogramBox extends React.Component { if (this.HistoOp.Result.bins.hasOwnProperty(key)) { let drawPrims = new HistogramBinPrimitiveCollection(key, this); - this.HitTargets.setValue(drawPrims.HitGeom, drawPrims.FilterModel); + let filterModel = ModelHelpers.GetBinFilterModel(this.HistoOp.Result.bins![key], allBrushIndex, this.HistoOp.Result, this.HistoOp.X, this.HistoOp.Y); - if (ArrayUtil.Contains(this.HistoOp.FilterModels, drawPrims.FilterModel)) { + + this.HitTargets.setValue(drawPrims.HitGeom, filterModel); + + if (ArrayUtil.Contains(this.HistoOp.FilterModels, filterModel)) { selectedBinPrimitiveCollections.push(drawPrims); } drawPrims.BinPrimitives.filter(bp => bp.DataValue && bp.BrushIndex !== allBrushIndex).map(binPrimitive => { - prims.push(this.drawRect(binPrimitive.Rect, binPrimitive.Color, () => { console.log("FM = " + drawPrims.FilterModel.ToPythonString()) })); - prims.push(this.drawRect(binPrimitive.MarginRect, StyleConstants.MARGIN_BARS_COLOR, () => { console.log("FM = " + drawPrims.FilterModel.ToPythonString()) })); + prims.push(this.drawRect(binPrimitive.Rect, binPrimitive.Color, () => { console.log("FM = " + filterModel.ToPythonString()) })); + prims.push(this.drawRect(binPrimitive.MarginRect, StyleConstants.MARGIN_BARS_COLOR, () => { console.log("FM = " + filterModel.ToPythonString()) })); }); } } @@ -205,21 +208,17 @@ export class HistogramBinPrimitive { export class HistogramBinPrimitiveCollection { private static TOLERANCE: number = 0.0001; - public BinPrimitives: Array = new Array(); - public FilterModel: FilterModel; - public HitGeom: PIXIRectangle = PIXIRectangle.EMPTY; private _histoBox: HistogramBox; private get histoOp() { return this._histoBox.HistoOp!; } private get histoResult() { return this.histoOp.Result as HistogramResult; } + public BinPrimitives: Array = new Array(); + public HitGeom: PIXIRectangle = PIXIRectangle.EMPTY; constructor(key: string, histoBox: HistogramBox) { this._histoBox = histoBox; let bin = this.histoResult.bins![key]; - var allBrushIndex = ModelHelpers.AllBrushIndex(this.histoResult); var overlapBrushIndex = ModelHelpers.OverlapBrushIndex(this.histoResult); - this.FilterModel = ModelHelpers.GetBinFilterModel(bin, allBrushIndex, this.histoResult, this.histoOp.X, this.histoOp.Y); - var orderedBrushes = new Array(); orderedBrushes.push(this.histoResult.brushes![0]); orderedBrushes.push(this.histoResult.brushes![overlapBrushIndex]); @@ -257,6 +256,7 @@ export class HistogramBinPrimitiveCollection { // adjust brush rects (stacking or not) var sum: number = 0; + var allBrushIndex = ModelHelpers.AllBrushIndex(this.histoResult); var filteredBinPrims = this.BinPrimitives.filter(b => b.BrushIndex != allBrushIndex && b.DataValue != 0.0); var count: number = filteredBinPrims.length; filteredBinPrims.map(fbp => { @@ -304,23 +304,19 @@ export class HistogramBinPrimitiveCollection { return binBrushMaxAxis; } private createHeatmapBinPrimitives(bin: Bin, brush: Brush, unNormalizedValue: number, brushFactorSum: number, normalizedValue: number, sizeConverter: SizeConverter): number { - var xFrom: number = 0; - var xTo: number = 0; - var yFrom: number = 0; - var yTo: number = 0; - var returnBrushFactorSum = brushFactorSum; var valueAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.V, this.histoResult, ModelHelpers.AllBrushIndex(this.histoResult)); var allUnNormalizedValue = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; var tx = this._histoBox.VisualBinRanges[0].GetValueFromIndex(bin.binIndex!.indices![0]); - xFrom = sizeConverter.DataToScreenX(tx); - xTo = sizeConverter.DataToScreenX(this._histoBox.VisualBinRanges[0].AddStep(tx)); + var xFrom = sizeConverter.DataToScreenX(tx); + var xTo = sizeConverter.DataToScreenX(this._histoBox.VisualBinRanges[0].AddStep(tx)); var ty = this._histoBox.VisualBinRanges[1].GetValueFromIndex(bin.binIndex!.indices![1]); - yFrom = sizeConverter.DataToScreenY(ty); - yTo = sizeConverter.DataToScreenY(this._histoBox.VisualBinRanges[1].AddStep(ty)); + var yFrom = sizeConverter.DataToScreenY(ty); + var yTo = sizeConverter.DataToScreenY(this._histoBox.VisualBinRanges[1].AddStep(ty)); + var returnBrushFactorSum = brushFactorSum; if (allUnNormalizedValue.hasResult) { var brushFactor = (unNormalizedValue / allUnNormalizedValue.result!); returnBrushFactorSum += brushFactor; @@ -344,23 +340,13 @@ export class HistogramBinPrimitiveCollection { (alpha + Math.pow(normalizedValue, 1.0 / 3.0) * (1.0 - alpha))); var dataColor = LABColor.ToColor(lerpColor); - var marginParams = new MarginAggregateParameters(); - marginParams.aggregateFunction = this.histoOp.V.AggregateFunction; - var marginAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.V, this.histoResult, - ModelHelpers.AllBrushIndex(this.histoResult), marginParams); - this.createBinPrimitive(bin, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, dataColor, 1, unNormalizedValue); return returnBrushFactorSum; } private createSinlgePointChartBinPrimitives(bin: Bin, brush: Brush, unNormalizedValue: number, sizeConverter: SizeConverter): void { var yAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, brush.brushIndex!); - var marginParams = new MarginAggregateParameters(); - marginParams.aggregateFunction = this.histoOp.Y.AggregateFunction; - var xAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, brush.brushIndex!); - var marginParams = new MarginAggregateParameters(); - marginParams.aggregateFunction = this.histoOp.X.AggregateFunction; var xValue = ModelHelpers.GetAggregateResult(bin, xAggregateKey) as DoubleValueAggregateResult; if (!xValue.hasResult) @@ -395,8 +381,8 @@ export class HistogramBinPrimitiveCollection { var xFrom = sizeConverter.DataToScreenX(xValue); var xTo = sizeConverter.DataToScreenX(this._histoBox.VisualBinRanges[0].AddStep(xValue)); - var marginResult = ModelHelpers.GetAggregateResult(bin, yMarginAggregateKey)!; - var yMarginAbsolute = marginResult == null ? 0 : (marginResult as MarginAggregateResult).absolutMargin!; + var marginResult = ModelHelpers.GetAggregateResult(bin, yMarginAggregateKey) as MarginAggregateResult; + var yMarginAbsolute = !marginResult ? 0 : marginResult.absolutMargin!; var marginRect = new PIXIRectangle(xFrom + (xTo - xFrom) / 2.0 - 1, sizeConverter.DataToScreenY(yValue + yMarginAbsolute), 2, sizeConverter.DataToScreenY(yValue - yMarginAbsolute) - sizeConverter.DataToScreenY(yValue + yMarginAbsolute)); @@ -423,8 +409,8 @@ export class HistogramBinPrimitiveCollection { var yFrom = yValue; var yTo = this._histoBox.VisualBinRanges[1].AddStep(yValue); - var marginResult = ModelHelpers.GetAggregateResult(bin, xMarginAggregateKey); - var xMarginAbsolute = sizeConverter.IsSmall || marginResult == null ? 0 : (marginResult as MarginAggregateResult).absolutMargin!; + var marginResult = ModelHelpers.GetAggregateResult(bin, xMarginAggregateKey) as MarginAggregateResult; + var xMarginAbsolute = sizeConverter.IsSmall || !marginResult ? 0 : marginResult.absolutMargin!; var marginRect = new PIXIRectangle(sizeConverter.DataToScreenX(xValue - xMarginAbsolute), yTo + (yFrom - yTo) / 2.0 - 1, @@ -469,12 +455,12 @@ export class HistogramBinPrimitiveCollection { baseColor = 0x00ff00; } else { - // if (this._histogramOperationViewModel.BrushColors.length > 0) { - // baseColor = this._histogramOperationViewModel.BrushColors[brush.brushIndex! % this._histogramOperationViewModel.BrushColors.length]; - // } - // else { - baseColor = StyleConstants.HIGHLIGHT_COLOR; - // } + if (this._histoBox.HistoOp!.BrushColors.length > 0) { + baseColor = this._histoBox.HistoOp!.BrushColors[brush.brushIndex! % this._histoBox.HistoOp!.BrushColors.length]; + } + else { + baseColor = StyleConstants.HIGHLIGHT_COLOR; + } } return baseColor; } -- cgit v1.2.3-70-g09d2 From 8335f0ba0b780a0ed0619e52076f051f122e4865 Mon Sep 17 00:00:00 2001 From: bob Date: Tue, 26 Mar 2019 12:37:26 -0400 Subject: added HistogramField --- package.json | 1 + src/client/documents/Documents.ts | 9 ++-- src/client/northstar/core/filter/FilterModel.ts | 21 ++++---- .../northstar/core/filter/IBaseFilterConsumer.ts | 2 + .../northstar/operations/HistogramOperation.ts | 42 ++++++++------- src/client/views/Main.tsx | 22 +++++++- src/client/views/nodes/HistogramBox.tsx | 60 ++++++++++++++-------- src/fields/HistogramField.ts | 59 +++++++++++++++++++++ src/fields/KeyStore.ts | 2 +- src/server/Message.ts | 2 +- src/server/ServerUtil.ts | 3 ++ .../authentication/models/current_user_utils.ts | 3 ++ 12 files changed, 166 insertions(+), 60 deletions(-) create mode 100644 src/fields/HistogramField.ts (limited to 'src') diff --git a/package.json b/package.json index 4f75d139d..27b3eead1 100644 --- a/package.json +++ b/package.json @@ -92,6 +92,7 @@ "bluebird": "^3.5.3", "body-parser": "^1.18.3", "bootstrap": "^4.3.1", + "class-transformer": "^0.2.0", "connect-flash": "^0.1.1", "connect-mongo": "^2.0.3", "cookie-parser": "^1.4.4", diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index bc0a18d50..1d23b8c2c 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -24,6 +24,8 @@ import { VideoBox } from "../views/nodes/VideoBox"; import { WebBox } from "../views/nodes/WebBox"; import { HistogramBox } from "../views/nodes/HistogramBox"; import { FieldView } from "../views/nodes/FieldView"; +import { HistogramField } from "../../fields/HistogramField"; +import { HistogramOperation } from "../northstar/operations/HistogramOperation"; export interface DocumentOptions { x?: number; @@ -42,6 +44,7 @@ export interface DocumentOptions { layoutKeys?: Key[]; viewType?: number; backgroundColor?: string; + northstarSchema?: string; } export namespace Documents { @@ -85,6 +88,7 @@ export namespace Documents { if (options.ink !== undefined) { doc.Set(KeyStore.Ink, new InkField(options.ink)); } if (options.layout !== undefined) { doc.SetText(KeyStore.Layout, options.layout); } if (options.layoutKeys !== undefined) { doc.Set(KeyStore.LayoutKeys, new ListField(options.layoutKeys)); } + if (options.northstarSchema !== undefined) { doc.SetText(KeyStore.NorthstarSchema, options.northstarSchema); } return doc; } @@ -120,7 +124,6 @@ export namespace Documents { } function GetHistogramPrototype(): Document { if (!histoProto) { - histoProto = setupPrototypeOptions(histoProtoId, "HISTO PROTO", CollectionView.LayoutString("AnnotationsKey"), { x: 0, y: 0, width: 300, height: 300, layoutKeys: [KeyStore.Data, KeyStore.Annotations, KeyStore.Caption] }); histoProto.SetText(KeyStore.BackgroundLayout, HistogramBox.LayoutString()); @@ -189,8 +192,8 @@ export namespace Documents { return assignToDelegate(SetInstanceOptions(GetAudioPrototype(), options, [new URL(url), AudioField]), options); } - export function HistogramDocument(options: DocumentOptions = {}) { - return assignToDelegate(SetInstanceOptions(GetHistogramPrototype(), options, ["", TextField]).MakeDelegate(), options); + export function HistogramDocument(histoOp: HistogramOperation, options: DocumentOptions = {}, id?: string) { + return assignToDelegate(SetInstanceOptions(GetHistogramPrototype(), options, [histoOp, HistogramField], id).MakeDelegate(), options); } export function TextDocument(options: DocumentOptions = {}) { return assignToDelegate(SetInstanceOptions(GetTextPrototype(), options, ["", TextField]).MakeDelegate(), options); diff --git a/src/client/northstar/core/filter/FilterModel.ts b/src/client/northstar/core/filter/FilterModel.ts index 3c4cfc4a7..01bf2a809 100644 --- a/src/client/northstar/core/filter/FilterModel.ts +++ b/src/client/northstar/core/filter/FilterModel.ts @@ -1,5 +1,8 @@ import { ValueComparison } from "./ValueComparision"; import { Utils } from "../../utils/Utils"; +import { IBaseFilterProvider } from "./IBaseFilterProvider"; +import { BaseOperation } from "../../operations/BaseOperation"; +import { FilterOperand } from "./FilterOperand"; export class FilterModel { public ValueComparisons: ValueComparison[]; @@ -36,20 +39,20 @@ export class FilterModel { return ret; } - // public static GetFilterModelsRecursive(filterGraphNode: GraphNode, - // visitedFilterProviders: Set>, filterModels: FilterModel[], isFirst: boolean): string { + // public static GetFilterModelsRecursive(baseOperation: BaseOperation, + // visitedFilterProviders: Set, filterModels: FilterModel[], isFirst: boolean): string { // let ret = ""; - // if (Utils.isBaseFilterProvider(filterGraphNode.Data)) { - // visitedFilterProviders.add(filterGraphNode); - // let filtered = filterGraphNode.Data.FilterModels.filter(fm => fm && fm.ValueComparisons.length > 0); + // if (Utils.isBaseFilterProvider(baseOperation)) { + // visitedFilterProviders.add(baseOperation); + // let filtered = baseOperation.FilterModels.filter(fm => fm && fm.ValueComparisons.length > 0); // if (!isFirst && filtered.length > 0) { // filterModels.push(...filtered); - // ret = "(" + filterGraphNode.Data.FilterModels.filter(fm => fm != null).map(fm => fm.ToPythonString()).join(" || ") + ")"; + // ret = "(" + baseOperation.FilterModels.filter(fm => fm != null).map(fm => fm.ToPythonString()).join(" || ") + ")"; // } // } - // if (Utils.isBaseFilterConsumer(filterGraphNode.Data) && filterGraphNode.Links != null) { + // if (Utils.isBaseFilterConsumer(baseOperation) && baseOperation.Links) { // let children = new Array(); - // let linkedGraphNodes = filterGraphNode.Links.get(LinkType.Filter); + // let linkedGraphNodes = baseOperation.Links.get(LinkType.Filter); // if (linkedGraphNodes != null) { // for (let i = 0; i < linkedGraphNodes.length; i++) { // let linkVm = linkedGraphNodes[i].Data; @@ -66,7 +69,7 @@ export class FilterModel { // } // } - // let childrenJoined = children.join(filterGraphNode.Data.FilterOperand === FilterOperand.AND ? " && " : " || "); + // let childrenJoined = children.join(baseOperation.FilterOperand === FilterOperand.AND ? " && " : " || "); // if (children.length > 0) { // if (ret !== "") { // ret = "(" + ret + " && (" + childrenJoined + "))"; diff --git a/src/client/northstar/core/filter/IBaseFilterConsumer.ts b/src/client/northstar/core/filter/IBaseFilterConsumer.ts index e687acb8a..3eb32b6db 100644 --- a/src/client/northstar/core/filter/IBaseFilterConsumer.ts +++ b/src/client/northstar/core/filter/IBaseFilterConsumer.ts @@ -1,8 +1,10 @@ import { FilterOperand } from '../filter/FilterOperand' import { IEquatable } from '../../utils/IEquatable' +import { IBaseFilterProvider } from './IBaseFilterProvider'; export interface IBaseFilterConsumer extends IEquatable { FilterOperand: FilterOperand; + Links: IBaseFilterProvider[]; } export function instanceOfIBaseFilterConsumer(object: any): object is IBaseFilterConsumer { diff --git a/src/client/northstar/operations/HistogramOperation.ts b/src/client/northstar/operations/HistogramOperation.ts index cf2571285..0c38679e5 100644 --- a/src/client/northstar/operations/HistogramOperation.ts +++ b/src/client/northstar/operations/HistogramOperation.ts @@ -9,9 +9,15 @@ import { BaseOperation } from "./BaseOperation"; import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; import { FilterModel } from "../core/filter/FilterModel"; import { BrushLinkModel } from "../core/brusher/BrushLinkModel"; +import { IBaseFilterConsumer } from "../core/filter/IBaseFilterConsumer"; +import { FilterOperand } from "../core/filter/FilterOperand"; +import { IBaseFilterProvider } from "../core/filter/IBaseFilterProvider"; +import { AttributeModel, ColumnAttributeModel } from "../core/attribute/AttributeModel"; -export class HistogramOperation extends BaseOperation { +export class HistogramOperation extends BaseOperation implements IBaseFilterConsumer, IBaseFilterProvider { + @observable public FilterOperand: FilterOperand = FilterOperand.AND; + @observable public Links: IBaseFilterProvider[] = []; @observable public BrushColors: number[] = []; @observable public Normalization: number = -1; @observable public FilterModels: FilterModel[] = []; @@ -21,12 +27,18 @@ export class HistogramOperation extends BaseOperation { @observable public BrusherModels: BrushLinkModel[] = []; @observable public BrushableModels: BrushLinkModel[] = []; - constructor(x: AttributeTransformationModel, y: AttributeTransformationModel, v: AttributeTransformationModel) { + public static Empty = new HistogramOperation(new AttributeTransformationModel(new ColumnAttributeModel(new Attribute())), new AttributeTransformationModel(new ColumnAttributeModel(new Attribute())), new AttributeTransformationModel(new ColumnAttributeModel(new Attribute()))); + + Equals(other: Object): boolean { + throw new Error("Method not implemented."); + } + + constructor(x: AttributeTransformationModel, y: AttributeTransformationModel, v: AttributeTransformationModel, normalized?: number) { super(); this.X = x; this.Y = y; this.V = v; - reaction(() => this.createOperationParamsCache, () => this.Update()); + this.Normalization = normalized ? normalized : -1; } @computed.struct @@ -47,20 +59,11 @@ export class HistogramOperation extends BaseOperation { } - @computed.struct - public get SelectionString() { - return ""; - // let filterModels = new Array(); - // let rdg = MainManager.Instance.MainViewModel.FilterReverseDependencyGraph; - // let graphNode: GraphNode; - // if (rdg.has(this.TypedViewModel)) { - // graphNode = MainManager.Instance.MainViewModel.FilterReverseDependencyGraph.get(this.TypedViewModel); - // } - // else { - // graphNode = new GraphNode(this.TypedViewModel); - // } - // return FilterModel.GetFilterModelsRecursive(graphNode, new Set>(), filterModels, false); - } + // @computed.struct + // public get SelectionString() { + // let filterModels = new Array(); + // return FilterModel.GetFilterModelsRecursive(this, new Set>(), filterModels, false); + // } GetAggregateParameters(histoX: AttributeTransformationModel, histoY: AttributeTransformationModel, histoValue: AttributeTransformationModel) { let allAttributes = new Array(histoX, histoY, histoValue); @@ -79,11 +82,6 @@ export class HistogramOperation extends BaseOperation { return [perBinAggregateParameters, globalAggregateParameters]; } - @computed - get createOperationParamsCache() { - return this.CreateOperationParameters(); - } - public QRange: QuantitativeBinRange | undefined; public CreateOperationParameters(): HistogramOperationParameters | undefined { diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index 6534cb4f7..3e0e02f42 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -44,10 +44,13 @@ import { CurrentUserUtils } from '../../server/authentication/models/current_use import { Field, Opt, FieldWaiting } from '../../fields/Field'; import { ListField } from '../../fields/ListField'; import { Gateway, Settings } from '../northstar/manager/Gateway'; -import { Catalog, Schema, Attribute, AttributeGroup } from '../northstar/model/idea/idea'; +import { Catalog, Schema, Attribute, AttributeGroup, AggregateFunction } from '../northstar/model/idea/idea'; import { ArrayUtil } from '../northstar/utils/ArrayUtil'; import '../northstar/model/ModelExtensions' import '../northstar/utils/Extensions' +import { HistogramOperation } from '../northstar/operations/HistogramOperation'; +import { AttributeTransformationModel } from '../northstar/core/attribute/AttributeTransformationModel'; +import { ColumnAttributeModel } from '../northstar/core/attribute/AttributeModel'; @observer export class Main extends React.Component { @@ -339,7 +342,22 @@ export class Main extends React.Component { @action SetNorthstarCatalog(ctlog: Catalog) { if (ctlog && ctlog.schemas) { CurrentUserUtils.ActiveSchema = ArrayUtil.FirstOrDefault(ctlog.schemas!, (s: Schema) => s.displayName === "mimic"); - this._northstarColumns = CurrentUserUtils.GetAllNorthstarColumnAttributes().map(a => Documents.HistogramDocument({ width: 200, height: 200, title: a.displayName! })); + CurrentUserUtils.GetAllNorthstarColumnAttributes().map(attr => { + Server.GetField(attr.displayName!, action((field: Opt) => { + if (field instanceof Document) { + this._northstarColumns.push(field); + } else { + var atmod = new ColumnAttributeModel(attr); + let histoOp = new HistogramOperation( + new AttributeTransformationModel(atmod, AggregateFunction.None), + new AttributeTransformationModel(atmod, AggregateFunction.Count), + new AttributeTransformationModel(atmod, AggregateFunction.Count)); + this._northstarColumns.push(Documents.HistogramDocument(histoOp, { width: 200, height: 200, title: attr.displayName!, northstarSchema: CurrentUserUtils.ActiveSchema!.displayName! }, attr.displayName!)); + } + })); + }) + console.log("Activating schema " + CurrentUserUtils.ActiveSchema!.displayName!) + CurrentUserUtils.ActiveSchemaName = CurrentUserUtils.ActiveSchema!.displayName!; } } async initializeNorthstar(): Promise { diff --git a/src/client/views/nodes/HistogramBox.tsx b/src/client/views/nodes/HistogramBox.tsx index 675bf30b2..73d3f3bc3 100644 --- a/src/client/views/nodes/HistogramBox.tsx +++ b/src/client/views/nodes/HistogramBox.tsx @@ -1,17 +1,17 @@ import React = require("react") -import { computed, observable, reaction, runInAction } from "mobx"; +import { computed, observable, reaction, runInAction, action, observe } from "mobx"; import { observer } from "mobx-react"; import Measure from "react-measure"; import { Dictionary } from "typescript-collections"; import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; import { Utils as DashUtils } from '../../../Utils'; -import { ColumnAttributeModel } from "../../northstar/core/attribute/AttributeModel"; +import { ColumnAttributeModel, AttributeModel } from "../../northstar/core/attribute/AttributeModel"; import { AttributeTransformationModel } from "../../northstar/core/attribute/AttributeTransformationModel"; import { FilterModel } from '../../northstar/core/filter/FilterModel'; import { NominalVisualBinRange } from "../../northstar/model/binRanges/NominalVisualBinRange"; import { ChartType, VisualBinRange } from '../../northstar/model/binRanges/VisualBinRange'; import { VisualBinRangeHelper } from "../../northstar/model/binRanges/VisualBinRangeHelper"; -import { AggregateBinRange, AggregateFunction, Bin, Brush, DoubleValueAggregateResult, HistogramResult, MarginAggregateParameters, MarginAggregateResult } from "../../northstar/model/idea/idea"; +import { AggregateBinRange, AggregateFunction, Bin, Brush, DoubleValueAggregateResult, HistogramResult, MarginAggregateParameters, MarginAggregateResult, Attribute, BinRange } from "../../northstar/model/idea/idea"; import { ModelHelpers } from "../../northstar/model/ModelHelpers"; import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; import { ArrayUtil } from "../../northstar/utils/ArrayUtil"; @@ -22,6 +22,10 @@ import { StyleConstants } from "../../northstar/utils/StyleContants"; import { FieldView, FieldViewProps } from './FieldView'; import "./HistogramBox.scss"; import { KeyStore } from "../../../fields/KeyStore"; +import { ListField } from "../../../fields/ListField"; +import { Document } from "../../../fields/Document" +import { HistogramField } from "../../../fields/HistogramField"; +import { FieldWaiting, Opt } from "../../../fields/Field"; @observer export class HistogramBox extends React.Component { @@ -38,37 +42,26 @@ export class HistogramBox extends React.Component { @observable public ChartType: ChartType = ChartType.VerticalBar; public HitTargets: Dictionary = new Dictionary(); - constructor(props: FieldViewProps) { - super(props); - } - @computed get xaxislines() { return this.renderGridLinesAndLabels(0); } @computed get yaxislines() { return this.renderGridLinesAndLabels(1); } componentDidMount() { - reaction(() => CurrentUserUtils.GetAllNorthstarColumnAttributes().filter(a => a.displayName == this.props.doc.Title), - (columnAttrs) => columnAttrs.map(a => { - var atmod = new ColumnAttributeModel(a); - this.HistoOp = new HistogramOperation(new AttributeTransformationModel(atmod, AggregateFunction.None), - new AttributeTransformationModel(atmod, AggregateFunction.Count), - new AttributeTransformationModel(atmod, AggregateFunction.Count)); - this.HistoOp.Update(); - }) - , { fireImmediately: true }); + reaction(() => [CurrentUserUtils.ActiveSchemaName, this.props.doc.GetText(KeyStore.NorthstarSchema, "?")], + () => CurrentUserUtils.ActiveSchemaName == this.props.doc.GetText(KeyStore.NorthstarSchema, "?") && this.activateHistogramOperation(), + { fireImmediately: true }); reaction(() => [this.VisualBinRanges && this.VisualBinRanges.slice(), this._panelHeight, this._panelWidth], () => this.SizeConverter = new SizeConverter({ x: this._panelWidth, y: this._panelHeight }, this.VisualBinRanges, Math.PI / 4)); - reaction(() => [this.HistoOp && this.HistoOp.Result], - () => { - if (!this.HistoOp || !(this.HistoOp.Result instanceof HistogramResult) || !this.HistoOp.Result.binRanges) + reaction(() => this.HistoOp && this.HistoOp.Result instanceof HistogramResult ? this.HistoOp.Result.binRanges : undefined, + (binRanges: BinRange[] | undefined) => { + if (!binRanges || !this.HistoOp || !(this.HistoOp!.Result instanceof HistogramResult)) return; - let binRanges = this.HistoOp.Result.binRanges; this.ChartType = binRanges[0] instanceof AggregateBinRange ? (binRanges[1] instanceof AggregateBinRange ? ChartType.SinglePoint : ChartType.HorizontalBar) : binRanges[1] instanceof AggregateBinRange ? ChartType.VerticalBar : ChartType.HeatMap; this.VisualBinRanges.length = 0; - this.VisualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(this.HistoOp.Result.binRanges[0], this.HistoOp.Result, this.HistoOp.X, this.ChartType)); - this.VisualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(this.HistoOp.Result.binRanges[1], this.HistoOp.Result, this.HistoOp.Y, this.ChartType)); + this.VisualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(binRanges[0], this.HistoOp.Result, this.HistoOp.X, this.ChartType)); + this.VisualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(binRanges[1], this.HistoOp.Result, this.HistoOp.Y, this.ChartType)); if (!this.HistoOp.Result.isEmpty) { this.MaxValue = Number.MIN_VALUE; @@ -89,6 +82,29 @@ export class HistogramBox extends React.Component { ); } + @computed + get createOperationParamsCache() { + return this.HistoOp!.CreateOperationParameters(); + } + + activateHistogramOperation() { + this.props.doc.GetTAsync(this.props.fieldKey, HistogramField).then((histoOp: Opt) => { + if (histoOp) { + runInAction(() => this.HistoOp = histoOp.Data); + this.HistoOp!.Update(); + reaction(() => this.createOperationParamsCache, () => this.HistoOp!.Update()); + reaction(() => this.props.doc.GetList(KeyStore.LinkedFromDocs, []), + () => { + let linkFrom: Document[] = this.props.doc.GetData(KeyStore.LinkedFromDocs, ListField, []); + this.HistoOp!.Links.length = 0; + linkFrom.map(l => this.HistoOp!.Links.push(l.GetData(KeyStore.Data, HistogramField, HistogramOperation.Empty))); + }, + { fireImmediately: true } + ); + } + }) + } + drawLine(xFrom: number, yFrom: number, width: number, height: number) { return
; } diff --git a/src/fields/HistogramField.ts b/src/fields/HistogramField.ts new file mode 100644 index 000000000..bb0014ab3 --- /dev/null +++ b/src/fields/HistogramField.ts @@ -0,0 +1,59 @@ +import { BasicField } from "./BasicField"; +import { Field, FieldId } from "./Field"; +import { Types } from "../server/Message"; +import { HistogramOperation } from "../client/northstar/operations/HistogramOperation"; +import { action } from "mobx"; +import { AttributeTransformationModel } from "../client/northstar/core/attribute/AttributeTransformationModel"; +import { ColumnAttributeModel } from "../client/northstar/core/attribute/AttributeModel"; +import { CurrentUserUtils } from "../server/authentication/models/current_user_utils"; + + +export class HistogramField extends BasicField { + constructor(data?: HistogramOperation, id?: FieldId, save: boolean = true) { + super(data ? data : HistogramOperation.Empty, save, id); + } + + toString(): string { + return JSON.stringify(this.Data); + } + + Copy(): Field { + return new HistogramField(this.Data); + } + + ToScriptString(): string { + return `new HistogramField("${this.Data}")`; + } + + ToJson(): { type: Types, data: string, _id: string } { + return { + type: Types.HistogramOp, + data: JSON.stringify(this.Data), + _id: this.Id + } + } + + @action + static FromJson(id: string, data: any): HistogramField { + let jp = JSON.parse(data); + let X: AttributeTransformationModel | undefined; + let Y: AttributeTransformationModel | undefined; + let V: AttributeTransformationModel | undefined; + + CurrentUserUtils.GetAllNorthstarColumnAttributes().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 HistogramField(new HistogramOperation(X, Y, V, jp.Normalization), id, false); + } + return new HistogramField(HistogramOperation.Empty, id, false); + } +} \ No newline at end of file diff --git a/src/fields/KeyStore.ts b/src/fields/KeyStore.ts index f9684b212..20e8cd930 100644 --- a/src/fields/KeyStore.ts +++ b/src/fields/KeyStore.ts @@ -29,7 +29,6 @@ export namespace KeyStore { export const Caption = new Key("Caption"); export const ActiveFrame = new Key("ActiveFrame"); export const ActiveWorkspace = new Key("ActiveWorkspace"); - export const ActiveDB = new Key("ActiveDB"); export const DocumentText = new Key("DocumentText"); export const LinkedToDocs = new Key("LinkedToDocs"); export const LinkedFromDocs = new Key("LinkedFromDocs"); @@ -46,4 +45,5 @@ export namespace KeyStore { export const Archives = new Key("Archives"); export const Updated = new Key("Updated"); export const Workspaces = new Key("Workspaces"); + export const NorthstarSchema = new Key("NorthstarSchema"); } diff --git a/src/server/Message.ts b/src/server/Message.ts index a2d1ab829..05ae0f19a 100644 --- a/src/server/Message.ts +++ b/src/server/Message.ts @@ -45,7 +45,7 @@ export class GetFieldArgs { } export enum Types { - Number, List, Key, Image, Web, Document, Text, RichText, DocumentReference, Html, Video, Audio, Ink, PDF, Tuple + Number, List, Key, Image, Web, Document, Text, RichText, DocumentReference, Html, Video, Audio, Ink, PDF, Tuple, HistogramOp } export class DocumentTransfer implements Transferable { diff --git a/src/server/ServerUtil.ts b/src/server/ServerUtil.ts index f10f82deb..f958df04b 100644 --- a/src/server/ServerUtil.ts +++ b/src/server/ServerUtil.ts @@ -17,6 +17,7 @@ import { VideoField } from '../fields/VideoField'; import { InkField } from '../fields/InkField'; import { PDFField } from '../fields/PDFField'; import { TupleField } from '../fields/TupleField'; +import { HistogramField } from '../fields/HistogramField'; @@ -50,6 +51,8 @@ export class ServerUtils { return new Key(data, id, false) case Types.Image: return new ImageField(new URL(data), id, false) + case Types.HistogramOp: + return HistogramField.FromJson(id, data); case Types.PDF: return new PDFField(new URL(data), id, false) case Types.List: diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 055e4cc97..4b42e40b6 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -8,6 +8,7 @@ import { KeyStore } from "../../../fields/KeyStore"; import { ListField } from "../../../fields/ListField"; import { Documents } from "../../../client/documents/Documents"; import { Schema, Attribute, AttributeGroup } from "../../../client/northstar/model/idea/idea"; +import { observable, computed, action } from "mobx"; export class CurrentUserUtils { private static curr_email: string; @@ -16,6 +17,7 @@ export class CurrentUserUtils { //TODO tfs: these should be temporary... private static mainDocId: string | undefined; private static activeSchema: Schema | undefined; + @observable public static ActiveSchemaName: string = ""; public static get email(): string { return this.curr_email; @@ -37,6 +39,7 @@ export class CurrentUserUtils { this.mainDocId = id; } + public static get ActiveSchema(): Schema | undefined { return this.activeSchema; } -- cgit v1.2.3-70-g09d2 From b9d23e5adde2da01708cc8501ca375726d232d06 Mon Sep 17 00:00:00 2001 From: bob Date: Tue, 26 Mar 2019 13:56:50 -0400 Subject: some filtering --- src/client/northstar/core/filter/FilterModel.ts | 48 +++++++++++++++++- .../northstar/core/filter/IBaseFilterConsumer.ts | 4 +- src/client/northstar/operations/BaseOperation.ts | 2 + .../northstar/operations/HistogramOperation.ts | 57 +++++++++++++++------- src/client/views/nodes/HistogramBox.tsx | 35 +++++++------ 5 files changed, 110 insertions(+), 36 deletions(-) (limited to 'src') diff --git a/src/client/northstar/core/filter/FilterModel.ts b/src/client/northstar/core/filter/FilterModel.ts index 01bf2a809..a9c79d245 100644 --- a/src/client/northstar/core/filter/FilterModel.ts +++ b/src/client/northstar/core/filter/FilterModel.ts @@ -1,8 +1,13 @@ import { ValueComparison } from "./ValueComparision"; import { Utils } from "../../utils/Utils"; -import { IBaseFilterProvider } from "./IBaseFilterProvider"; +import { IBaseFilterProvider, instanceOfIBaseFilterProvider } from "./IBaseFilterProvider"; import { BaseOperation } from "../../operations/BaseOperation"; import { FilterOperand } from "./FilterOperand"; +import { HistogramField } from "../../../../fields/HistogramField"; +import { KeyStore } from "../../../../fields/KeyStore"; +import { filter } from "bluebird"; +import { FieldWaiting } from "../../../../fields/Field"; +import { Document } from "../../../../fields/Document"; export class FilterModel { public ValueComparisons: ValueComparison[]; @@ -38,6 +43,47 @@ export class FilterModel { 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 = linkVm.Get(KeyStore.LinkedFromDocs); + if (filterDoc && filterDoc != FieldWaiting && filterDoc instanceof Document) { + let filterHistogram = filterDoc.GetT(KeyStore.Data, HistogramField); + if (filterHistogram && filterHistogram != FieldWaiting) { + if (!visitedFilterProviders.has(filterHistogram.Data)) { + let child = FilterModel.GetFilterModelsRecursive(filterHistogram.Data, 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; + } // public static GetFilterModelsRecursive(baseOperation: BaseOperation, // visitedFilterProviders: Set, filterModels: FilterModel[], isFirst: boolean): string { diff --git a/src/client/northstar/core/filter/IBaseFilterConsumer.ts b/src/client/northstar/core/filter/IBaseFilterConsumer.ts index 3eb32b6db..93f66a154 100644 --- a/src/client/northstar/core/filter/IBaseFilterConsumer.ts +++ b/src/client/northstar/core/filter/IBaseFilterConsumer.ts @@ -1,10 +1,10 @@ import { FilterOperand } from '../filter/FilterOperand' import { IEquatable } from '../../utils/IEquatable' -import { IBaseFilterProvider } from './IBaseFilterProvider'; +import { Document } from "../../../../fields/Document"; export interface IBaseFilterConsumer extends IEquatable { FilterOperand: FilterOperand; - Links: IBaseFilterProvider[]; + Links: Document[]; } export function instanceOfIBaseFilterConsumer(object: any): object is IBaseFilterConsumer { diff --git a/src/client/northstar/operations/BaseOperation.ts b/src/client/northstar/operations/BaseOperation.ts index 4c0303a48..4bc8873d5 100644 --- a/src/client/northstar/operations/BaseOperation.ts +++ b/src/client/northstar/operations/BaseOperation.ts @@ -25,6 +25,8 @@ export abstract class BaseOperation { @computed public get FilterString(): string { + // let filterModels: FilterModel[] = []; + // return FilterModel.GetFilterModelsRecursive(this, new Set>(), filterModels, true) // if (this.OverridingFilters.length > 0) { // return "(" + this.OverridingFilters.filter(fm => fm != null).map(fm => fm.ToPythonString()).join(" || ") + ")"; // } diff --git a/src/client/northstar/operations/HistogramOperation.ts b/src/client/northstar/operations/HistogramOperation.ts index 0c38679e5..93946b296 100644 --- a/src/client/northstar/operations/HistogramOperation.ts +++ b/src/client/northstar/operations/HistogramOperation.ts @@ -1,23 +1,24 @@ -import { reaction, computed, action, observable } from "mobx"; -import { Attribute, DataType, QuantitativeBinRange, HistogramOperationParameters, AggregateParameters, AggregateFunction, AverageAggregateParameters } from "../model/idea/idea"; -import { ArrayUtil } from "../utils/ArrayUtil"; -import { CalculatedAttributeManager } from "../core/attribute/CalculatedAttributeModel"; -import { ModelHelpers } from "../model/ModelHelpers"; -import { SETTINGS_X_BINS, SETTINGS_Y_BINS, SETTINGS_SAMPLE_SIZE } from "../model/binRanges/VisualBinRangeHelper"; -import { AttributeTransformationModel } from "../core/attribute/AttributeTransformationModel"; -import { BaseOperation } from "./BaseOperation"; +import { action, computed, observable } from "mobx"; +import { Document } from "../../../fields/Document"; import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; -import { FilterModel } from "../core/filter/FilterModel"; +import { ColumnAttributeModel } from "../core/attribute/AttributeModel"; +import { AttributeTransformationModel } from "../core/attribute/AttributeTransformationModel"; +import { CalculatedAttributeManager } from "../core/attribute/CalculatedAttributeModel"; import { BrushLinkModel } from "../core/brusher/BrushLinkModel"; -import { IBaseFilterConsumer } from "../core/filter/IBaseFilterConsumer"; +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 { AttributeModel, ColumnAttributeModel } from "../core/attribute/AttributeModel"; +import { SETTINGS_SAMPLE_SIZE, SETTINGS_X_BINS, SETTINGS_Y_BINS } from "../model/binRanges/VisualBinRangeHelper"; +import { AggregateFunction, AggregateParameters, Attribute, AverageAggregateParameters, DataType, HistogramOperationParameters, QuantitativeBinRange } from "../model/idea/idea"; +import { ModelHelpers } from "../model/ModelHelpers"; +import { ArrayUtil } from "../utils/ArrayUtil"; +import { BaseOperation } from "./BaseOperation"; export class HistogramOperation extends BaseOperation implements IBaseFilterConsumer, IBaseFilterProvider { @observable public FilterOperand: FilterOperand = FilterOperand.AND; - @observable public Links: IBaseFilterProvider[] = []; + @observable public Links: Document[] = []; @observable public BrushColors: number[] = []; @observable public Normalization: number = -1; @observable public FilterModels: FilterModel[] = []; @@ -27,6 +28,15 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons @observable public BrusherModels: BrushLinkModel[] = []; @observable public BrushableModels: BrushLinkModel[] = []; + @action + public AddFilterModels(filterModels: FilterModel[]): void { + filterModels.filter(f => f !== null).forEach(fm => this.FilterModels.push(fm)); + } + @action + public RemoveFilterModels(filterModels: FilterModel[]): void { + ArrayUtil.RemoveMany(this.FilterModels, filterModels); + } + public static Empty = new HistogramOperation(new AttributeTransformationModel(new ColumnAttributeModel(new Attribute())), new AttributeTransformationModel(new ColumnAttributeModel(new Attribute())), new AttributeTransformationModel(new ColumnAttributeModel(new Attribute()))); Equals(other: Object): boolean { @@ -41,6 +51,19 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons this.Normalization = normalized ? normalized : -1; } + @computed + public get FilterString(): string { + let filterModels: FilterModel[] = []; + let fstring = FilterModel.GetFilterModelsRecursive(this, new Set(), filterModels, true) + console.log("Filter string " + this.X.AttributeModel.DisplayName + " = " + fstring); + return fstring; + } + @computed + public get OutputFilterString(): string { + let filterModels: FilterModel[] = []; + return FilterModel.GetFilterModelsRecursive(this, new Set(), filterModels, false) + } + @computed.struct public get BrushString() { return []; @@ -59,11 +82,11 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons } - // @computed.struct - // public get SelectionString() { - // let filterModels = new Array(); - // return FilterModel.GetFilterModelsRecursive(this, new Set>(), filterModels, false); - // } + @computed.struct + public get SelectionString() { + let filterModels = new Array(); + return FilterModel.GetFilterModelsRecursive(this, new Set(), filterModels, false); + } GetAggregateParameters(histoX: AttributeTransformationModel, histoY: AttributeTransformationModel, histoValue: AttributeTransformationModel) { let allAttributes = new Array(histoX, histoY, histoValue); diff --git a/src/client/views/nodes/HistogramBox.tsx b/src/client/views/nodes/HistogramBox.tsx index 73d3f3bc3..e21054e15 100644 --- a/src/client/views/nodes/HistogramBox.tsx +++ b/src/client/views/nodes/HistogramBox.tsx @@ -1,17 +1,19 @@ import React = require("react") -import { computed, observable, reaction, runInAction, action, observe } from "mobx"; +import { computed, observable, reaction, runInAction, trace } from "mobx"; import { observer } from "mobx-react"; import Measure from "react-measure"; import { Dictionary } from "typescript-collections"; +import { Document } from "../../../fields/Document"; +import { Opt } from "../../../fields/Field"; +import { HistogramField } from "../../../fields/HistogramField"; +import { KeyStore } from "../../../fields/KeyStore"; import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; import { Utils as DashUtils } from '../../../Utils'; -import { ColumnAttributeModel, AttributeModel } from "../../northstar/core/attribute/AttributeModel"; -import { AttributeTransformationModel } from "../../northstar/core/attribute/AttributeTransformationModel"; import { FilterModel } from '../../northstar/core/filter/FilterModel'; import { NominalVisualBinRange } from "../../northstar/model/binRanges/NominalVisualBinRange"; import { ChartType, VisualBinRange } from '../../northstar/model/binRanges/VisualBinRange'; import { VisualBinRangeHelper } from "../../northstar/model/binRanges/VisualBinRangeHelper"; -import { AggregateBinRange, AggregateFunction, Bin, Brush, DoubleValueAggregateResult, HistogramResult, MarginAggregateParameters, MarginAggregateResult, Attribute, BinRange } from "../../northstar/model/idea/idea"; +import { AggregateBinRange, AggregateFunction, Bin, BinRange, Brush, DoubleValueAggregateResult, HistogramResult, MarginAggregateParameters, MarginAggregateResult } from "../../northstar/model/idea/idea"; import { ModelHelpers } from "../../northstar/model/ModelHelpers"; import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; import { ArrayUtil } from "../../northstar/utils/ArrayUtil"; @@ -21,11 +23,6 @@ import { SizeConverter } from "../../northstar/utils/SizeConverter"; import { StyleConstants } from "../../northstar/utils/StyleContants"; import { FieldView, FieldViewProps } from './FieldView'; import "./HistogramBox.scss"; -import { KeyStore } from "../../../fields/KeyStore"; -import { ListField } from "../../../fields/ListField"; -import { Document } from "../../../fields/Document" -import { HistogramField } from "../../../fields/HistogramField"; -import { FieldWaiting, Opt } from "../../../fields/Field"; @observer export class HistogramBox extends React.Component { @@ -92,12 +89,13 @@ export class HistogramBox extends React.Component { if (histoOp) { runInAction(() => this.HistoOp = histoOp.Data); this.HistoOp!.Update(); - reaction(() => this.createOperationParamsCache, () => this.HistoOp!.Update()); + reaction( + () => this.createOperationParamsCache, + () => this.HistoOp!.Update(); reaction(() => this.props.doc.GetList(KeyStore.LinkedFromDocs, []), - () => { - let linkFrom: Document[] = this.props.doc.GetData(KeyStore.LinkedFromDocs, ListField, []); + (docs: Document[]) => { this.HistoOp!.Links.length = 0; - linkFrom.map(l => this.HistoOp!.Links.push(l.GetData(KeyStore.Data, HistogramField, HistogramOperation.Empty))); + this.HistoOp!.Links.push(...docs); }, { fireImmediately: true } ); @@ -172,7 +170,6 @@ export class HistogramBox extends React.Component { let filterModel = ModelHelpers.GetBinFilterModel(this.HistoOp.Result.bins![key], allBrushIndex, this.HistoOp.Result, this.HistoOp.X, this.HistoOp.Y); - this.HitTargets.setValue(drawPrims.HitGeom, filterModel); if (ArrayUtil.Contains(this.HistoOp.FilterModels, filterModel)) { @@ -180,8 +177,13 @@ export class HistogramBox extends React.Component { } drawPrims.BinPrimitives.filter(bp => bp.DataValue && bp.BrushIndex !== allBrushIndex).map(binPrimitive => { - prims.push(this.drawRect(binPrimitive.Rect, binPrimitive.Color, () => { console.log("FM = " + filterModel.ToPythonString()) })); - prims.push(this.drawRect(binPrimitive.MarginRect, StyleConstants.MARGIN_BARS_COLOR, () => { console.log("FM = " + filterModel.ToPythonString()) })); + let toggleFilter = () => { + if ([filterModel].filter(h => ArrayUtil.Contains(this.HistoOp!.FilterModels, h)).length > 0) + this.HistoOp!.RemoveFilterModels([filterModel]); + else this.HistoOp!.AddFilterModels([filterModel]); + } + prims.push(this.drawRect(binPrimitive.Rect, binPrimitive.Color, () => runInAction(toggleFilter))); + prims.push(this.drawRect(binPrimitive.MarginRect, StyleConstants.MARGIN_BARS_COLOR, () => runInAction(toggleFilter))); }); } } @@ -189,6 +191,7 @@ export class HistogramBox extends React.Component { } render() { + trace(); if (!this.binPrimitives || !this.VisualBinRanges.length) { return (null); } -- cgit v1.2.3-70-g09d2 From e9826e0ac334bac28d173f67b4f0db0800b40680 Mon Sep 17 00:00:00 2001 From: bob Date: Tue, 26 Mar 2019 16:06:06 -0400 Subject: cleaned up a bit. got rid of blinking when histos change. --- src/client/northstar/core/filter/FilterModel.ts | 50 +-- src/client/northstar/operations/BaseOperation.ts | 3 +- .../northstar/operations/HistogramOperation.ts | 1 - src/client/views/nodes/DocumentContentsView.tsx | 3 +- src/client/views/nodes/HistogramBox.tsx | 360 ++------------------ src/client/views/nodes/HistogramBoxPrimitives.tsx | 373 +++++++++++++++++++++ 6 files changed, 399 insertions(+), 391 deletions(-) create mode 100644 src/client/views/nodes/HistogramBoxPrimitives.tsx (limited to 'src') diff --git a/src/client/northstar/core/filter/FilterModel.ts b/src/client/northstar/core/filter/FilterModel.ts index a9c79d245..bc7938947 100644 --- a/src/client/northstar/core/filter/FilterModel.ts +++ b/src/client/northstar/core/filter/FilterModel.ts @@ -1,11 +1,9 @@ import { ValueComparison } from "./ValueComparision"; import { Utils } from "../../utils/Utils"; -import { IBaseFilterProvider, instanceOfIBaseFilterProvider } from "./IBaseFilterProvider"; -import { BaseOperation } from "../../operations/BaseOperation"; +import { IBaseFilterProvider } from "./IBaseFilterProvider"; import { FilterOperand } from "./FilterOperand"; import { HistogramField } from "../../../../fields/HistogramField"; import { KeyStore } from "../../../../fields/KeyStore"; -import { filter } from "bluebird"; import { FieldWaiting } from "../../../../fields/Field"; import { Document } from "../../../../fields/Document"; @@ -35,8 +33,7 @@ export class FilterModel { } public ToPythonString(): string { - let ret = "(" + this.ValueComparisons.map(vc => vc.ToPythonString()).join("&&") + ")"; - return ret; + return "(" + this.ValueComparisons.map(vc => vc.ToPythonString()).join("&&") + ")"; } public static And(filters: string[]): string { @@ -84,47 +81,4 @@ export class FilterModel { } return ret; } - - // public static GetFilterModelsRecursive(baseOperation: BaseOperation, - // visitedFilterProviders: Set, filterModels: FilterModel[], isFirst: boolean): string { - // let ret = ""; - // if (Utils.isBaseFilterProvider(baseOperation)) { - // 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.get(LinkType.Filter); - // if (linkedGraphNodes != null) { - // for (let i = 0; i < linkedGraphNodes.length; i++) { - // let linkVm = linkedGraphNodes[i].Data; - // let linkedGraphNode = linkedGraphNodes[i].Target; - // if (!visitedFilterProviders.has(linkedGraphNode)) { - // let child = FilterModel.GetFilterModelsRecursive(linkedGraphNode, 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/operations/BaseOperation.ts b/src/client/northstar/operations/BaseOperation.ts index 4bc8873d5..7db6fcb91 100644 --- a/src/client/northstar/operations/BaseOperation.ts +++ b/src/client/northstar/operations/BaseOperation.ts @@ -61,7 +61,8 @@ export abstract class BaseOperation { } let operationParameters = this.CreateOperationParameters(); - this.Result = undefined; + if (this.Result) + this.Result.progress = 0; // bcz: used to set Result to undefined, but that causes the display to blink this.Error = ""; let salt = Math.random().toString(); this.RequestSalt = salt; diff --git a/src/client/northstar/operations/HistogramOperation.ts b/src/client/northstar/operations/HistogramOperation.ts index 93946b296..bceadb961 100644 --- a/src/client/northstar/operations/HistogramOperation.ts +++ b/src/client/northstar/operations/HistogramOperation.ts @@ -55,7 +55,6 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons public get FilterString(): string { let filterModels: FilterModel[] = []; let fstring = FilterModel.GetFilterModelsRecursive(this, new Set(), filterModels, true) - console.log("Filter string " + this.X.AttributeModel.DisplayName + " = " + fstring); return fstring; } @computed diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index 12d14eb42..40990b76a 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -20,6 +20,7 @@ import { PDFBox } from "./PDFBox"; import { VideoBox } from "./VideoBox"; import { WebBox } from "./WebBox"; import { HistogramBox } from "./HistogramBox"; +import { HistogramBoxPrimitives } from "./HistogramBoxPrimitives"; import React = require("react"); const JsxParser = require('react-jsx-parser').default; //TODO Why does this need to be imported like this? @@ -52,7 +53,7 @@ export class DocumentContentsView extends React.ComponentError loading layout keys

; } return { @@ -41,6 +40,7 @@ export class HistogramBox extends React.Component { @computed get xaxislines() { return this.renderGridLinesAndLabels(0); } @computed get yaxislines() { return this.renderGridLinesAndLabels(1); } + @computed get createOperationParamsCache() { return this.HistoOp!.CreateOperationParameters(); } componentDidMount() { reaction(() => [CurrentUserUtils.ActiveSchemaName, this.props.doc.GetText(KeyStore.NorthstarSchema, "?")], @@ -57,8 +57,8 @@ export class HistogramBox extends React.Component { binRanges[1] instanceof AggregateBinRange ? ChartType.VerticalBar : ChartType.HeatMap; this.VisualBinRanges.length = 0; - this.VisualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(binRanges[0], this.HistoOp.Result, this.HistoOp.X, this.ChartType)); - this.VisualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(binRanges[1], this.HistoOp.Result, this.HistoOp.Y, this.ChartType)); + this.VisualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(binRanges[0], this.HistoOp!.Result!, this.HistoOp!.X, this.ChartType)); + this.VisualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(binRanges[1], this.HistoOp!.Result!, this.HistoOp!.Y, this.ChartType)); if (!this.HistoOp.Result.isEmpty) { this.MaxValue = Number.MIN_VALUE; @@ -79,11 +79,6 @@ export class HistogramBox extends React.Component { ); } - @computed - get createOperationParamsCache() { - return this.HistoOp!.CreateOperationParameters(); - } - activateHistogramOperation() { this.props.doc.GetTAsync(this.props.fieldKey, HistogramField).then((histoOp: Opt) => { if (histoOp) { @@ -91,7 +86,7 @@ export class HistogramBox extends React.Component { this.HistoOp!.Update(); reaction( () => this.createOperationParamsCache, - () => this.HistoOp!.Update(); + () => this.HistoOp!.Update()); reaction(() => this.props.doc.GetList(KeyStore.LinkedFromDocs, []), (docs: Document[]) => { this.HistoOp!.Links.length = 0; @@ -107,22 +102,16 @@ export class HistogramBox extends React.Component { return
; } - drawRect(r: PIXIRectangle, color: number, tapHandler: () => void) { - return
- } - private renderGridLinesAndLabels(axis: number) { let sc = this.SizeConverter!; - let labels = this.VisualBinRanges[axis].GetLabels(); - - let dim = sc.RenderSize[axis] / sc.MaxLabelSizes[axis].coords[axis] + 5; - let mod = Math.ceil(labels.length / dim); + if (!sc || !this.VisualBinRanges.length) + return (null); + let dim = sc.RenderSize[axis] / ((axis == 0 && this.VisualBinRanges[axis] instanceof NominalVisualBinRange) ? + (12 + 5) : // (FontStyles.AxisLabel.fontSize + 5))); + sc.MaxLabelSizes[axis].coords[axis] + 5); - if (axis == 0 && this.VisualBinRanges[axis] instanceof NominalVisualBinRange) { - mod = Math.ceil( - labels.length / (sc.RenderSize[0] / (12 + 5))); // (FontStyles.AxisLabel.fontSize + 5))); - } let prims: JSX.Element[] = []; + let labels = this.VisualBinRanges[axis].GetLabels(); labels.map((binLabel, i) => { let xFrom = sc.DataToScreenX(axis === 0 ? binLabel.minValue! : sc.DataMins[0]); let xTo = sc.DataToScreenX(axis === 0 ? binLabel.maxValue! : sc.DataMaxs[0]); @@ -133,7 +122,7 @@ export class HistogramBox extends React.Component { if (i == labels.length - 1) prims.push(this.drawLine(axis == 0 ? xTo : xFrom, axis == 0 ? yFrom : yTo, axis == 0 ? 1 : xTo - xFrom, axis == 0 ? yTo - yFrom : 1)); - if (i % mod === 0 && binLabel.label) { + if (i % Math.ceil(labels.length / dim) === 0 && binLabel.label) { let text = binLabel.label; if (text.length >= StyleConstants.MAX_CHAR_FOR_HISTOGRAM_LABELS) { text = text.slice(0, StyleConstants.MAX_CHAR_FOR_HISTOGRAM_LABELS - 3) + "..."; @@ -157,330 +146,21 @@ export class HistogramBox extends React.Component { return prims; } - @computed - get binPrimitives() { - if (!this.HistoOp || !(this.HistoOp.Result instanceof HistogramResult) || !this.SizeConverter) - return undefined; - let prims: JSX.Element[] = []; - let selectedBinPrimitiveCollections = new Array(); - let allBrushIndex = ModelHelpers.AllBrushIndex(this.HistoOp.Result); - for (let key in this.HistoOp.Result.bins) { - if (this.HistoOp.Result.bins.hasOwnProperty(key)) { - let drawPrims = new HistogramBinPrimitiveCollection(key, this); - - let filterModel = ModelHelpers.GetBinFilterModel(this.HistoOp.Result.bins![key], allBrushIndex, this.HistoOp.Result, this.HistoOp.X, this.HistoOp.Y); - - this.HitTargets.setValue(drawPrims.HitGeom, filterModel); - - if (ArrayUtil.Contains(this.HistoOp.FilterModels, filterModel)) { - selectedBinPrimitiveCollections.push(drawPrims); - } - - drawPrims.BinPrimitives.filter(bp => bp.DataValue && bp.BrushIndex !== allBrushIndex).map(binPrimitive => { - let toggleFilter = () => { - if ([filterModel].filter(h => ArrayUtil.Contains(this.HistoOp!.FilterModels, h)).length > 0) - this.HistoOp!.RemoveFilterModels([filterModel]); - else this.HistoOp!.AddFilterModels([filterModel]); - } - prims.push(this.drawRect(binPrimitive.Rect, binPrimitive.Color, () => runInAction(toggleFilter))); - prims.push(this.drawRect(binPrimitive.MarginRect, StyleConstants.MARGIN_BARS_COLOR, () => runInAction(toggleFilter))); - }); - } - } - return prims; - } - render() { - trace(); - if (!this.binPrimitives || !this.VisualBinRanges.length) { - return (null); - } - + let label = this.HistoOp && this.HistoOp.X ? this.HistoOp.X.AttributeModel.DisplayName : "<...>"; + let xaxislines = this.xaxislines; + let yaxislines = this.yaxislines; return ( runInAction(() => { this._panelWidth = r.entry.width; this._panelHeight = r.entry.height })}> {({ measureRef }) =>
- {this.xaxislines} - {this.yaxislines} - {this.binPrimitives} -
{this.HistoOp!.X.AttributeModel.DisplayName}
+ {xaxislines} + {yaxislines} + +
{label}
}
) } -} - -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; -} - -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; } - public BinPrimitives: Array = new Array(); - public HitGeom: PIXIRectangle = PIXIRectangle.EMPTY; - - constructor(key: string, histoBox: HistogramBox) { - this._histoBox = histoBox; - let bin = this.histoResult.bins![key]; - - var overlapBrushIndex = ModelHelpers.OverlapBrushIndex(this.histoResult); - var orderedBrushes = new Array(); - orderedBrushes.push(this.histoResult.brushes![0]); - orderedBrushes.push(this.histoResult.brushes![overlapBrushIndex]); - for (var b = 0; b < this.histoResult.brushes!.length; b++) { - var brush = this.histoResult.brushes![b]; - if (brush.brushIndex != 0 && brush.brushIndex != overlapBrushIndex) { - orderedBrushes.push(brush); - } - } - var binBrushMaxAxis = this.getBinBrushAxisRange(bin, orderedBrushes, this.histoOp.Normalization); // X= 0, Y = 1 - - var brushFactorSum: number = 0; - for (var b = 0; b < orderedBrushes.length; b++) { - var brush = orderedBrushes[b]; - var valueAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.V, this.histoResult, brush.brushIndex!); - var doubleRes = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; - var unNormalizedValue = (doubleRes != null && doubleRes.hasResult) ? doubleRes.result : null; - if (unNormalizedValue) - switch (histoBox.ChartType) { - case ChartType.VerticalBar: - this.createVerticalBarChartBinPrimitives(bin, brush, binBrushMaxAxis, this.histoOp.Normalization, histoBox.SizeConverter!); // X = 0, Y = 1, NOne = -1 - break; - case ChartType.HorizontalBar: - this.createHorizontalBarChartBinPrimitives(bin, brush, binBrushMaxAxis, this.histoOp.Normalization, histoBox.SizeConverter!); - break; - case ChartType.SinglePoint: - this.createSinlgePointChartBinPrimitives(bin, brush, unNormalizedValue, histoBox.SizeConverter!); - break; - case ChartType.HeatMap: - var normalizedValue = (unNormalizedValue - histoBox.MinValue) / (Math.abs((histoBox.MaxValue - histoBox.MinValue)) < HistogramBinPrimitiveCollection.TOLERANCE ? - unNormalizedValue : histoBox.MaxValue - histoBox.MinValue); - brushFactorSum = this.createHeatmapBinPrimitives(bin, brush, unNormalizedValue, brushFactorSum, normalizedValue, histoBox.SizeConverter!); - } - } - - // adjust brush rects (stacking or not) - var sum: number = 0; - var allBrushIndex = ModelHelpers.AllBrushIndex(this.histoResult); - var filteredBinPrims = this.BinPrimitives.filter(b => b.BrushIndex != allBrushIndex && b.DataValue != 0.0); - var count: number = filteredBinPrims.length; - filteredBinPrims.map(fbp => { - if (histoBox.ChartType == ChartType.VerticalBar) { - if (this.histoOp.X.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); - 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 / count, 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); - 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); - 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 / count); - fbp.MarginRect = new PIXIRectangle(fbp.MarginRect.x, fbp.MarginRect.y - h + sum + (fbp.Rect.height / 2.0), fbp.MarginRect.width, fbp.MarginRect.height); - sum += fbp.Rect.height; - } - } - }); - 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 getBinBrushAxisRange(bin: Bin, brushes: Array, axis: number): number { - var binBrushMaxAxis = Number.MIN_VALUE; - brushes.forEach((Brush) => { - var maxAggregateKey = ModelHelpers.CreateAggregateKey(axis === 0 ? this.histoOp.Y : this.histoOp.X, this.histoResult, Brush.brushIndex!); - var aggResult = ModelHelpers.GetAggregateResult(bin, maxAggregateKey) as DoubleValueAggregateResult; - if (aggResult != null) { - if (aggResult.result! > binBrushMaxAxis) - binBrushMaxAxis = aggResult.result!; - } - }); - return binBrushMaxAxis; - } - private createHeatmapBinPrimitives(bin: Bin, brush: Brush, unNormalizedValue: number, brushFactorSum: number, normalizedValue: number, sizeConverter: SizeConverter): number { - - var valueAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.V, this.histoResult, ModelHelpers.AllBrushIndex(this.histoResult)); - var allUnNormalizedValue = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; - - var tx = this._histoBox.VisualBinRanges[0].GetValueFromIndex(bin.binIndex!.indices![0]); - var xFrom = sizeConverter.DataToScreenX(tx); - var xTo = sizeConverter.DataToScreenX(this._histoBox.VisualBinRanges[0].AddStep(tx)); - - var ty = this._histoBox.VisualBinRanges[1].GetValueFromIndex(bin.binIndex!.indices![1]); - var yFrom = sizeConverter.DataToScreenY(ty); - var yTo = sizeConverter.DataToScreenY(this._histoBox.VisualBinRanges[1].AddStep(ty)); - - var returnBrushFactorSum = brushFactorSum; - if (allUnNormalizedValue.hasResult) { - var brushFactor = (unNormalizedValue / allUnNormalizedValue.result!); - 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(bin, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, dataColor, 1, unNormalizedValue); - return returnBrushFactorSum; - } - - private createSinlgePointChartBinPrimitives(bin: Bin, brush: Brush, unNormalizedValue: number, sizeConverter: SizeConverter): void { - var yAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, brush.brushIndex!); - var xAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, brush.brushIndex!); - - var xValue = ModelHelpers.GetAggregateResult(bin, xAggregateKey) as DoubleValueAggregateResult; - if (!xValue.hasResult) - return; - var xFrom = sizeConverter.DataToScreenX(xValue.result!) - 5; - var xTo = sizeConverter.DataToScreenX(xValue.result!) + 5; - - var yValue = ModelHelpers.GetAggregateResult(bin, yAggregateKey) as DoubleValueAggregateResult;; - if (!yValue.hasResult) - return; - var yFrom = sizeConverter.DataToScreenY(yValue.result!) + 5; - var yTo = sizeConverter.DataToScreenY(yValue.result!); - - this.createBinPrimitive(bin, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, this.baseColorFromBrush(brush), 1, unNormalizedValue); - } - - private createVerticalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number, sizeConverter: SizeConverter): void { - var yAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, brush.brushIndex!); - var marginParams = new MarginAggregateParameters(); - marginParams.aggregateFunction = this.histoOp.Y.AggregateFunction; - var yMarginAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, - brush.brushIndex!, marginParams); - var dataValue = ModelHelpers.GetAggregateResult(bin, yAggregateKey) as DoubleValueAggregateResult; - - if (dataValue != null && dataValue.hasResult) { - var yValue = normalization != 0 || binBrushMaxAxis == 0 ? dataValue.result! : (dataValue.result! - 0) / (binBrushMaxAxis - 0) * sizeConverter.DataRanges[1]; - - var yFrom = sizeConverter.DataToScreenY(Math.min(0, yValue)); - var yTo = sizeConverter.DataToScreenY(Math.max(0, yValue));; - - var xValue = this._histoBox.VisualBinRanges[0].GetValueFromIndex(bin.binIndex!.indices![0])!; - var xFrom = sizeConverter.DataToScreenX(xValue); - var xTo = sizeConverter.DataToScreenX(this._histoBox.VisualBinRanges[0].AddStep(xValue)); - - var marginResult = ModelHelpers.GetAggregateResult(bin, yMarginAggregateKey) as MarginAggregateResult; - var yMarginAbsolute = !marginResult ? 0 : marginResult.absolutMargin!; - var marginRect = new PIXIRectangle(xFrom + (xTo - xFrom) / 2.0 - 1, - sizeConverter.DataToScreenY(yValue + yMarginAbsolute), 2, - sizeConverter.DataToScreenY(yValue - yMarginAbsolute) - sizeConverter.DataToScreenY(yValue + yMarginAbsolute)); - - this.createBinPrimitive(bin, brush, marginRect, 0, xFrom, xTo, yFrom, yTo, - this.baseColorFromBrush(brush), normalization != 0 ? 1 : 0.6 * binBrushMaxAxis / sizeConverter.DataRanges[1] + 0.4, dataValue.result!); - } - } - - private createHorizontalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number, sizeConverter: SizeConverter): void { - var xAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, brush.brushIndex!); - var marginParams = new MarginAggregateParameters(); - marginParams.aggregateFunction = this.histoOp.X.AggregateFunction; - var xMarginAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, - brush.brushIndex!, marginParams); - var dataValue = ModelHelpers.GetAggregateResult(bin, xAggregateKey) as DoubleValueAggregateResult; - - if (dataValue != null && dataValue.hasResult) { - var xValue = normalization != 1 || binBrushMaxAxis == 0 ? dataValue.result! : (dataValue.result! - 0) / (binBrushMaxAxis - 0) * sizeConverter.DataRanges[0]; - var xFrom = sizeConverter.DataToScreenX(Math.min(0, xValue)); - var xTo = sizeConverter.DataToScreenX(Math.max(0, xValue)); - - var yValue = this._histoBox.VisualBinRanges[1].GetValueFromIndex(bin.binIndex!.indices![1]); - var yFrom = yValue; - var yTo = this._histoBox.VisualBinRanges[1].AddStep(yValue); - - var marginResult = ModelHelpers.GetAggregateResult(bin, xMarginAggregateKey) as MarginAggregateResult; - var xMarginAbsolute = sizeConverter.IsSmall || !marginResult ? 0 : marginResult.absolutMargin!; - - var marginRect = new PIXIRectangle(sizeConverter.DataToScreenX(xValue - xMarginAbsolute), - yTo + (yFrom - yTo) / 2.0 - 1, - sizeConverter.DataToScreenX(xValue + xMarginAbsolute) - sizeConverter.DataToScreenX(xValue - xMarginAbsolute), - 2.0); - - this.createBinPrimitive(bin, brush, marginRect, 0, xFrom, xTo, yFrom, yTo, - this.baseColorFromBrush(brush), normalization != 1 ? 1 : 0.6 * binBrushMaxAxis / sizeConverter.DataRanges[0] + 0.4, dataValue.result!); - } - } - - private createBinPrimitive(bin: Bin, brush: Brush, marginRect: PIXIRectangle, - marginPercentage: number, xFrom: number, xTo: number, yFrom: number, yTo: number, color: number, opacity: number, dataValue: number) { - // hitgeom todo - - 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 - }); - this.BinPrimitives.push(binPrimitive); - } - - private baseColorFromBrush(brush: Brush): number { - var baseColor: number = StyleConstants.HIGHLIGHT_COLOR; - if (brush.brushIndex == ModelHelpers.RestBrushIndex(this.histoResult)) { - baseColor = StyleConstants.HIGHLIGHT_COLOR; - } - else if (brush.brushIndex == ModelHelpers.OverlapBrushIndex(this.histoResult)) { - baseColor = StyleConstants.OVERLAP_COLOR; - } - else if (brush.brushIndex == ModelHelpers.AllBrushIndex(this.histoResult)) { - baseColor = 0x00ff00; - } - else { - if (this._histoBox.HistoOp!.BrushColors.length > 0) { - baseColor = this._histoBox.HistoOp!.BrushColors[brush.brushIndex! % this._histoBox.HistoOp!.BrushColors.length]; - } - else { - baseColor = StyleConstants.HIGHLIGHT_COLOR; - } - } - return baseColor; - } } \ No newline at end of file diff --git a/src/client/views/nodes/HistogramBoxPrimitives.tsx b/src/client/views/nodes/HistogramBoxPrimitives.tsx new file mode 100644 index 000000000..2f4a553b7 --- /dev/null +++ b/src/client/views/nodes/HistogramBoxPrimitives.tsx @@ -0,0 +1,373 @@ +import React = require("react") +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 { SizeConverter } from "../../northstar/utils/SizeConverter"; +import { StyleConstants } from "../../northstar/utils/StyleContants"; +import "./HistogramBox.scss"; +import { HistogramBox } from "./HistogramBox"; +import { computed, runInAction, observable, trace } from "mobx"; +import { ArrayUtil } from "../../northstar/utils/ArrayUtil"; +import { Utils as DashUtils } from '../../../Utils'; +import { observer } from "mobx-react"; + + +export interface HistogramBoxPrimitivesProps { + HistoBox: HistogramBox; +} + +@observer +export class HistogramBoxPrimitives extends React.Component { + @observable _selectedPrims: HistogramBinPrimitive[] = []; + + @computed + get selectedPrimitives() { + return this._selectedPrims.map((bp) => this.drawBorder(bp.Rect, StyleConstants.OPERATOR_BACKGROUND_COLOR)); + } + @computed + get binPrimitives() { + if (!this.props.HistoBox.HistoOp || !(this.props.HistoBox.HistoOp.Result instanceof HistogramResult) || !this.props.HistoBox.SizeConverter) + return (null); + let prims: JSX.Element[] = []; + let allBrushIndex = ModelHelpers.AllBrushIndex(this.props.HistoBox.HistoOp.Result); + for (let key in this.props.HistoBox.HistoOp.Result.bins) { + if (this.props.HistoBox.HistoOp.Result.bins.hasOwnProperty(key)) { + let drawPrims = new HistogramBinPrimitiveCollection(key, this.props.HistoBox); + let filterModel = ModelHelpers.GetBinFilterModel(this.props.HistoBox.HistoOp.Result.bins![key], allBrushIndex, this.props.HistoBox.HistoOp.Result, this.props.HistoBox.HistoOp.X, this.props.HistoBox.HistoOp.Y); + + this.props.HistoBox.HitTargets.setValue(drawPrims.HitGeom, filterModel); + + drawPrims.BinPrimitives.filter(bp => bp.DataValue && bp.BrushIndex !== allBrushIndex).map(binPrimitive => { + let toggleFilter = () => { + if ([filterModel].filter(h => ArrayUtil.Contains(this.props.HistoBox.HistoOp!.FilterModels, h)).length > 0) { + let bp = ArrayUtil.FirstOrDefault(drawPrims.BinPrimitives, (bp: HistogramBinPrimitive) => bp.BrushIndex == allBrushIndex); + if (bp && bp.DataValue) { + this._selectedPrims.splice(this._selectedPrims.indexOf(bp), 1); + } + this.props.HistoBox.HistoOp!.RemoveFilterModels([filterModel]); + } + else { + let bp = ArrayUtil.FirstOrDefault(drawPrims.BinPrimitives, (bp: HistogramBinPrimitive) => bp.BrushIndex == allBrushIndex); + if (bp && bp.DataValue) { + this._selectedPrims.push(bp!); + } + this.props.HistoBox.HistoOp!.AddFilterModels([filterModel]); + } + } + prims.push(this.drawRect(binPrimitive.Rect, binPrimitive.Color, () => runInAction(toggleFilter))); + prims.push(this.drawRect(binPrimitive.MarginRect, StyleConstants.MARGIN_BARS_COLOR, () => runInAction(toggleFilter))); + }); + } + } + return prims; + } + drawBorder(r: PIXIRectangle, color: number) { + return
+ } + + drawRect(r: PIXIRectangle, color: number, tapHandler: () => void) { + return
+ } + render() { + return
+ {this.binPrimitives} + {this.selectedPrimitives} +
+ } +} + + +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; +} + +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; } + public BinPrimitives: Array = new Array(); + public HitGeom: PIXIRectangle = PIXIRectangle.EMPTY; + + constructor(key: string, histoBox: HistogramBox) { + this._histoBox = histoBox; + let bin = this.histoResult.bins![key]; + + var overlapBrushIndex = ModelHelpers.OverlapBrushIndex(this.histoResult); + var orderedBrushes = new Array(); + orderedBrushes.push(this.histoResult.brushes![0]); + orderedBrushes.push(this.histoResult.brushes![overlapBrushIndex]); + for (var b = 0; b < this.histoResult.brushes!.length; b++) { + var brush = this.histoResult.brushes![b]; + if (brush.brushIndex != 0 && brush.brushIndex != overlapBrushIndex) { + orderedBrushes.push(brush); + } + } + var binBrushMaxAxis = this.getBinBrushAxisRange(bin, orderedBrushes, this.histoOp.Normalization); // X= 0, Y = 1 + + var brushFactorSum: number = 0; + for (var b = 0; b < orderedBrushes.length; b++) { + var brush = orderedBrushes[b]; + var valueAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.V, this.histoResult, brush.brushIndex!); + var doubleRes = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; + var unNormalizedValue = (doubleRes != null && doubleRes.hasResult) ? doubleRes.result : null; + if (unNormalizedValue) + switch (histoBox.ChartType) { + case ChartType.VerticalBar: + this.createVerticalBarChartBinPrimitives(bin, brush, binBrushMaxAxis, this.histoOp.Normalization, histoBox.SizeConverter!); // X = 0, Y = 1, NOne = -1 + break; + case ChartType.HorizontalBar: + this.createHorizontalBarChartBinPrimitives(bin, brush, binBrushMaxAxis, this.histoOp.Normalization, histoBox.SizeConverter!); + break; + case ChartType.SinglePoint: + this.createSinlgePointChartBinPrimitives(bin, brush, unNormalizedValue, histoBox.SizeConverter!); + break; + case ChartType.HeatMap: + var normalizedValue = (unNormalizedValue - histoBox.MinValue) / (Math.abs((histoBox.MaxValue - histoBox.MinValue)) < HistogramBinPrimitiveCollection.TOLERANCE ? + unNormalizedValue : histoBox.MaxValue - histoBox.MinValue); + brushFactorSum = this.createHeatmapBinPrimitives(bin, brush, unNormalizedValue, brushFactorSum, normalizedValue, histoBox.SizeConverter!); + } + } + + // adjust brush rects (stacking or not) + var sum: number = 0; + var allBrushIndex = ModelHelpers.AllBrushIndex(this.histoResult); + var filteredBinPrims = this.BinPrimitives.filter(b => b.BrushIndex != allBrushIndex && b.DataValue != 0.0); + var count: number = filteredBinPrims.length; + filteredBinPrims.map(fbp => { + if (histoBox.ChartType == ChartType.VerticalBar) { + if (this.histoOp.X.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); + 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 / count, 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); + 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); + 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 / count); + fbp.MarginRect = new PIXIRectangle(fbp.MarginRect.x, fbp.MarginRect.y - h + sum + (fbp.Rect.height / 2.0), fbp.MarginRect.width, fbp.MarginRect.height); + sum += fbp.Rect.height; + } + } + }); + 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 getBinBrushAxisRange(bin: Bin, brushes: Array, axis: number): number { + var binBrushMaxAxis = Number.MIN_VALUE; + brushes.forEach((Brush) => { + var maxAggregateKey = ModelHelpers.CreateAggregateKey(axis === 0 ? this.histoOp.Y : this.histoOp.X, this.histoResult, Brush.brushIndex!); + var aggResult = ModelHelpers.GetAggregateResult(bin, maxAggregateKey) as DoubleValueAggregateResult; + if (aggResult != null) { + if (aggResult.result! > binBrushMaxAxis) + binBrushMaxAxis = aggResult.result!; + } + }); + return binBrushMaxAxis; + } + private createHeatmapBinPrimitives(bin: Bin, brush: Brush, unNormalizedValue: number, brushFactorSum: number, normalizedValue: number, sizeConverter: SizeConverter): number { + + var valueAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.V, this.histoResult, ModelHelpers.AllBrushIndex(this.histoResult)); + var allUnNormalizedValue = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; + + var tx = this._histoBox.VisualBinRanges[0].GetValueFromIndex(bin.binIndex!.indices![0]); + var xFrom = sizeConverter.DataToScreenX(tx); + var xTo = sizeConverter.DataToScreenX(this._histoBox.VisualBinRanges[0].AddStep(tx)); + + var ty = this._histoBox.VisualBinRanges[1].GetValueFromIndex(bin.binIndex!.indices![1]); + var yFrom = sizeConverter.DataToScreenY(ty); + var yTo = sizeConverter.DataToScreenY(this._histoBox.VisualBinRanges[1].AddStep(ty)); + + var returnBrushFactorSum = brushFactorSum; + if (allUnNormalizedValue.hasResult) { + var brushFactor = (unNormalizedValue / allUnNormalizedValue.result!); + 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(bin, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, dataColor, 1, unNormalizedValue); + return returnBrushFactorSum; + } + + private createSinlgePointChartBinPrimitives(bin: Bin, brush: Brush, unNormalizedValue: number, sizeConverter: SizeConverter): void { + var yAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, brush.brushIndex!); + var xAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, brush.brushIndex!); + + var xValue = ModelHelpers.GetAggregateResult(bin, xAggregateKey) as DoubleValueAggregateResult; + if (!xValue.hasResult) + return; + var xFrom = sizeConverter.DataToScreenX(xValue.result!) - 5; + var xTo = sizeConverter.DataToScreenX(xValue.result!) + 5; + + var yValue = ModelHelpers.GetAggregateResult(bin, yAggregateKey) as DoubleValueAggregateResult;; + if (!yValue.hasResult) + return; + var yFrom = sizeConverter.DataToScreenY(yValue.result!) + 5; + var yTo = sizeConverter.DataToScreenY(yValue.result!); + + this.createBinPrimitive(bin, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, this.baseColorFromBrush(brush), 1, unNormalizedValue); + } + + private createVerticalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number, sizeConverter: SizeConverter): void { + var yAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, brush.brushIndex!); + var marginParams = new MarginAggregateParameters(); + marginParams.aggregateFunction = this.histoOp.Y.AggregateFunction; + var yMarginAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, + brush.brushIndex!, marginParams); + var dataValue = ModelHelpers.GetAggregateResult(bin, yAggregateKey) as DoubleValueAggregateResult; + + if (dataValue != null && dataValue.hasResult) { + var yValue = normalization != 0 || binBrushMaxAxis == 0 ? dataValue.result! : (dataValue.result! - 0) / (binBrushMaxAxis - 0) * sizeConverter.DataRanges[1]; + + var yFrom = sizeConverter.DataToScreenY(Math.min(0, yValue)); + var yTo = sizeConverter.DataToScreenY(Math.max(0, yValue));; + + var xValue = this._histoBox.VisualBinRanges[0].GetValueFromIndex(bin.binIndex!.indices![0])!; + var xFrom = sizeConverter.DataToScreenX(xValue); + var xTo = sizeConverter.DataToScreenX(this._histoBox.VisualBinRanges[0].AddStep(xValue)); + + var marginResult = ModelHelpers.GetAggregateResult(bin, yMarginAggregateKey) as MarginAggregateResult; + var yMarginAbsolute = !marginResult ? 0 : marginResult.absolutMargin!; + var marginRect = new PIXIRectangle(xFrom + (xTo - xFrom) / 2.0 - 1, + sizeConverter.DataToScreenY(yValue + yMarginAbsolute), 2, + sizeConverter.DataToScreenY(yValue - yMarginAbsolute) - sizeConverter.DataToScreenY(yValue + yMarginAbsolute)); + + this.createBinPrimitive(bin, brush, marginRect, 0, xFrom, xTo, yFrom, yTo, + this.baseColorFromBrush(brush), normalization != 0 ? 1 : 0.6 * binBrushMaxAxis / sizeConverter.DataRanges[1] + 0.4, dataValue.result!); + } + } + + private createHorizontalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number, sizeConverter: SizeConverter): void { + var xAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, brush.brushIndex!); + var marginParams = new MarginAggregateParameters(); + marginParams.aggregateFunction = this.histoOp.X.AggregateFunction; + var xMarginAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, + brush.brushIndex!, marginParams); + var dataValue = ModelHelpers.GetAggregateResult(bin, xAggregateKey) as DoubleValueAggregateResult; + + if (dataValue != null && dataValue.hasResult) { + var xValue = normalization != 1 || binBrushMaxAxis == 0 ? dataValue.result! : (dataValue.result! - 0) / (binBrushMaxAxis - 0) * sizeConverter.DataRanges[0]; + var xFrom = sizeConverter.DataToScreenX(Math.min(0, xValue)); + var xTo = sizeConverter.DataToScreenX(Math.max(0, xValue)); + + var yValue = this._histoBox.VisualBinRanges[1].GetValueFromIndex(bin.binIndex!.indices![1]); + var yFrom = yValue; + var yTo = this._histoBox.VisualBinRanges[1].AddStep(yValue); + + var marginResult = ModelHelpers.GetAggregateResult(bin, xMarginAggregateKey) as MarginAggregateResult; + var xMarginAbsolute = sizeConverter.IsSmall || !marginResult ? 0 : marginResult.absolutMargin!; + + var marginRect = new PIXIRectangle(sizeConverter.DataToScreenX(xValue - xMarginAbsolute), + yTo + (yFrom - yTo) / 2.0 - 1, + sizeConverter.DataToScreenX(xValue + xMarginAbsolute) - sizeConverter.DataToScreenX(xValue - xMarginAbsolute), + 2.0); + + this.createBinPrimitive(bin, brush, marginRect, 0, xFrom, xTo, yFrom, yTo, + this.baseColorFromBrush(brush), normalization != 1 ? 1 : 0.6 * binBrushMaxAxis / sizeConverter.DataRanges[0] + 0.4, dataValue.result!); + } + } + + private createBinPrimitive(bin: Bin, brush: Brush, marginRect: PIXIRectangle, + marginPercentage: number, xFrom: number, xTo: number, yFrom: number, yTo: number, color: number, opacity: number, dataValue: number) { + // hitgeom todo + + 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 + }); + this.BinPrimitives.push(binPrimitive); + } + + private baseColorFromBrush(brush: Brush): number { + var baseColor: number = StyleConstants.HIGHLIGHT_COLOR; + if (brush.brushIndex == ModelHelpers.RestBrushIndex(this.histoResult)) { + baseColor = StyleConstants.HIGHLIGHT_COLOR; + } + else if (brush.brushIndex == ModelHelpers.OverlapBrushIndex(this.histoResult)) { + baseColor = StyleConstants.OVERLAP_COLOR; + } + else if (brush.brushIndex == ModelHelpers.AllBrushIndex(this.histoResult)) { + baseColor = 0x00ff00; + } + else { + if (this._histoBox.HistoOp!.BrushColors.length > 0) { + baseColor = this._histoBox.HistoOp!.BrushColors[brush.brushIndex! % this._histoBox.HistoOp!.BrushColors.length]; + } + else { + baseColor = StyleConstants.HIGHLIGHT_COLOR; + } + } + return baseColor; + } +} \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 9f585c4f0a8287951f142f99dcc54861cb348728 Mon Sep 17 00:00:00 2001 From: bob Date: Tue, 26 Mar 2019 16:09:27 -0400 Subject: treeview scrolling. --- src/client/views/collections/CollectionTreeView.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index 6cc14ebcb..70790af18 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -125,7 +125,7 @@ export class CollectionTreeView extends CollectionViewBase { ) return ( -
this.onDrop(e, {})} ref={this.createDropTarget} style={{ borderWidth: `${COLLECTION_BORDER_WIDTH}px` }}> +
e.stopPropagation()} onDrop={(e: React.DragEvent) => this.onDrop(e, {})} ref={this.createDropTarget} style={{ borderWidth: `${COLLECTION_BORDER_WIDTH}px` }}>
Date: Tue, 26 Mar 2019 16:44:53 -0400 Subject: fixed histos in docking pane and not selecting bars when dragging. --- src/client/views/collections/CollectionFreeFormView.tsx | 4 ++-- src/client/views/nodes/DocumentContentsView.tsx | 1 + src/client/views/nodes/HistogramBox.tsx | 4 +++- src/client/views/nodes/HistogramBoxPrimitives.tsx | 2 +- 4 files changed, 7 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/client/views/collections/CollectionFreeFormView.tsx b/src/client/views/collections/CollectionFreeFormView.tsx index 53fe969fe..1eab3e475 100644 --- a/src/client/views/collections/CollectionFreeFormView.tsx +++ b/src/client/views/collections/CollectionFreeFormView.tsx @@ -279,13 +279,13 @@ export class CollectionFreeFormView extends CollectionViewBase { get backgroundView() { return !this.backgroundLayout ? (null) : ( false} select={() => { }} />); + layoutKey={KeyStore.BackgroundLayout} isTopMost={this.props.isTopMost} isSelected={() => false} select={() => { }} />); } @computed get overlayView() { return !this.overlayLayout ? (null) : ( false} select={() => { }} />); + layoutKey={KeyStore.OverlayLayout} isTopMost={this.props.isTopMost} isSelected={() => false} select={() => { }} />); } getTransform = (): Transform => this.props.ScreenToLocalTransform().translate(-COLLECTION_BORDER_WIDTH, -COLLECTION_BORDER_WIDTH).translate(-this.centeringShiftX, -this.centeringShiftY).transform(this.getLocalTransform()) diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index 40990b76a..f48be2047 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -35,6 +35,7 @@ export class DocumentContentsView extends React.Component()); } @computed get layoutFields(): Key[] { return this.props.Document.GetData(KeyStore.LayoutFields, ListField, new Array()); } + CreateBindings(): JsxBindings { let bindings: JsxBindings = { ...this.props, }; for (const key of this.layoutKeys) { diff --git a/src/client/views/nodes/HistogramBox.tsx b/src/client/views/nodes/HistogramBox.tsx index 20a022227..4d7922c1b 100644 --- a/src/client/views/nodes/HistogramBox.tsx +++ b/src/client/views/nodes/HistogramBox.tsx @@ -150,10 +150,12 @@ export class HistogramBox extends React.Component { let label = this.HistoOp && this.HistoOp.X ? this.HistoOp.X.AttributeModel.DisplayName : "<...>"; let xaxislines = this.xaxislines; let yaxislines = this.yaxislines; + var h = this.props.isTopMost ? this._panelHeight : this.props.doc.GetNumber(KeyStore.Height, 0); + var w = this.props.isTopMost ? this._panelWidth : this.props.doc.GetNumber(KeyStore.Width, 0); return ( runInAction(() => { this._panelWidth = r.entry.width; this._panelHeight = r.entry.height })}> {({ measureRef }) => -
+
{xaxislines} {yaxislines} diff --git a/src/client/views/nodes/HistogramBoxPrimitives.tsx b/src/client/views/nodes/HistogramBoxPrimitives.tsx index 2f4a553b7..a8ada99a4 100644 --- a/src/client/views/nodes/HistogramBoxPrimitives.tsx +++ b/src/client/views/nodes/HistogramBoxPrimitives.tsx @@ -79,7 +79,7 @@ export class HistogramBoxPrimitives extends React.Component void) { - return
{ if (e.button == 0) tapHandler() }} style={{ position: "absolute", transform: `translate(${r.x}px,${r.y}px)`, -- cgit v1.2.3-70-g09d2 From f51ca77dcea14bafe4126b5cf7b092db6d3c2c5b Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 26 Mar 2019 22:37:24 -0400 Subject: a bunch more cleanup --- .../northstar/operations/HistogramOperation.ts | 13 +- src/client/northstar/utils/Extensions.ts | 9 + src/client/northstar/utils/SizeConverter.ts | 35 +++ src/client/views/Main.tsx | 4 - src/client/views/nodes/HistogramBox.tsx | 94 ++---- src/client/views/nodes/HistogramBoxPrimitives.scss | 10 + src/client/views/nodes/HistogramBoxPrimitives.tsx | 333 ++++++++------------- 7 files changed, 222 insertions(+), 276 deletions(-) create mode 100644 src/client/views/nodes/HistogramBoxPrimitives.scss (limited to 'src') diff --git a/src/client/northstar/operations/HistogramOperation.ts b/src/client/northstar/operations/HistogramOperation.ts index bceadb961..6c7288d42 100644 --- a/src/client/northstar/operations/HistogramOperation.ts +++ b/src/client/northstar/operations/HistogramOperation.ts @@ -10,7 +10,7 @@ import { FilterOperand } from "../core/filter/FilterOperand"; import { IBaseFilterConsumer } from "../core/filter/IBaseFilterConsumer"; import { IBaseFilterProvider } from "../core/filter/IBaseFilterProvider"; import { SETTINGS_SAMPLE_SIZE, SETTINGS_X_BINS, SETTINGS_Y_BINS } from "../model/binRanges/VisualBinRangeHelper"; -import { AggregateFunction, AggregateParameters, Attribute, AverageAggregateParameters, DataType, HistogramOperationParameters, QuantitativeBinRange } from "../model/idea/idea"; +import { AggregateFunction, AggregateParameters, Attribute, AverageAggregateParameters, DataType, HistogramOperationParameters, QuantitativeBinRange, HistogramResult, Brush, DoubleValueAggregateResult, Bin } from "../model/idea/idea"; import { ModelHelpers } from "../model/ModelHelpers"; import { ArrayUtil } from "../utils/ArrayUtil"; import { BaseOperation } from "./BaseOperation"; @@ -37,6 +37,12 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons ArrayUtil.RemoveMany(this.FilterModels, filterModels); } + public getValue(axis: number, bin: Bin, result: HistogramResult, brushIndex: number) { + var aggregateKey = ModelHelpers.CreateAggregateKey(axis == 0 ? this.X : axis == 1 ? this.Y : this.V, result, brushIndex); + let dataValue = ModelHelpers.GetAggregateResult(bin, aggregateKey) as DoubleValueAggregateResult; + return dataValue != null && dataValue.hasResult ? dataValue.result : undefined; + } + public static Empty = new HistogramOperation(new AttributeTransformationModel(new ColumnAttributeModel(new Attribute())), new AttributeTransformationModel(new ColumnAttributeModel(new Attribute())), new AttributeTransformationModel(new ColumnAttributeModel(new Attribute()))); Equals(other: Object): boolean { @@ -57,11 +63,6 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons let fstring = FilterModel.GetFilterModelsRecursive(this, new Set(), filterModels, true) return fstring; } - @computed - public get OutputFilterString(): string { - let filterModels: FilterModel[] = []; - return FilterModel.GetFilterModelsRecursive(this, new Set(), filterModels, false) - } @computed.struct public get BrushString() { diff --git a/src/client/northstar/utils/Extensions.ts b/src/client/northstar/utils/Extensions.ts index 71bcadf89..7c2b7fc9d 100644 --- a/src/client/northstar/utils/Extensions.ts +++ b/src/client/northstar/utils/Extensions.ts @@ -1,5 +1,6 @@ interface String { ReplaceAll(toReplace: string, replacement: string): string; + Truncate(length: number, replacement: string): String; } String.prototype.ReplaceAll = function (toReplace: string, replacement: string): string { @@ -7,6 +8,14 @@ String.prototype.ReplaceAll = function (toReplace: string, replacement: string): 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; } diff --git a/src/client/northstar/utils/SizeConverter.ts b/src/client/northstar/utils/SizeConverter.ts index e8973cfd5..2dc2a7557 100644 --- a/src/client/northstar/utils/SizeConverter.ts +++ b/src/client/northstar/utils/SizeConverter.ts @@ -1,6 +1,9 @@ import { PIXIPoint } from "./MathUtil"; import { NominalVisualBinRange } from "../model/binRanges/NominalVisualBinRange"; import { VisualBinRange } from "../model/binRanges/VisualBinRange"; +import { Bin, DoubleValueAggregateResult, AggregateKey } from "../model/idea/idea"; +import { AttributeTransformationModel } from "../core/attribute/AttributeTransformationModel"; +import { ModelHelpers } from "../model/ModelHelpers"; export class SizeConverter { public RenderSize: Array = new Array(2); @@ -70,6 +73,26 @@ export class SizeConverter { 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.hasResult) + return [this.DataToScreenCoord(value.result!, axis) - 5, + this.DataToScreenCoord(value.result!, axis) + 5]; + return [undefined, undefined]; + } + + public DataToScreenAxisRange(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 DataToScreenX(x: number): number { return (((x - this.DataMins[0]) / this.DataRanges[0]) * (this.RenderSize[0]) + (this.LeftOffset)); } @@ -77,4 +100,16 @@ export class SizeConverter { var retY = ((y - this.DataMins[1]) / this.DataRanges[1]) * (this.RenderSize[1]); return flip ? (this.RenderSize[1]) - retY + (this.TopOffset) : retY + (this.TopOffset); } + 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/views/Main.tsx b/src/client/views/Main.tsx index 3e0e02f42..87d8eb648 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -89,10 +89,6 @@ export class Main extends React.Component { } }; - // this.initializeNorthstar(); - let y = ""; - y.ReplaceAll("a", "B"); - CurrentUserUtils.loadCurrentUser(); library.add(faFont); diff --git a/src/client/views/nodes/HistogramBox.tsx b/src/client/views/nodes/HistogramBox.tsx index 4d7922c1b..c9537bcf8 100644 --- a/src/client/views/nodes/HistogramBox.tsx +++ b/src/client/views/nodes/HistogramBox.tsx @@ -1,9 +1,8 @@ import React = require("react") -import { computed, observable, reaction, runInAction, trace } from "mobx"; +import { computed, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; import Measure from "react-measure"; import { Dictionary } from "typescript-collections"; -import { Document } from "../../../fields/Document"; import { Opt } from "../../../fields/Field"; import { HistogramField } from "../../../fields/HistogramField"; import { KeyStore } from "../../../fields/KeyStore"; @@ -19,81 +18,60 @@ import { HistogramOperation } from "../../northstar/operations/HistogramOperatio import { PIXIRectangle } from "../../northstar/utils/MathUtil"; import { SizeConverter } from "../../northstar/utils/SizeConverter"; import { StyleConstants } from "../../northstar/utils/StyleContants"; +import "./../../northstar/utils/Extensions"; import { FieldView, FieldViewProps } from './FieldView'; import "./HistogramBox.scss"; import { HistogramBoxPrimitives } from './HistogramBoxPrimitives'; @observer export class HistogramBox extends React.Component { - public static LayoutString(fieldStr: string = "DataKey") { return FieldView.LayoutString(HistogramBox, fieldStr) } @observable private _panelWidth: number = 100; @observable private _panelHeight: number = 100; @observable public HistoOp?: HistogramOperation; @observable public VisualBinRanges: VisualBinRange[] = []; - @observable public MinValue: number = 0; - @observable public MaxValue: number = 0; + @observable public ValueRange: number[] = []; @observable public SizeConverter?: SizeConverter; - @observable public ChartType: ChartType = ChartType.VerticalBar; public HitTargets: Dictionary = new Dictionary(); @computed get xaxislines() { return this.renderGridLinesAndLabels(0); } @computed get yaxislines() { return this.renderGridLinesAndLabels(1); } @computed get createOperationParamsCache() { return this.HistoOp!.CreateOperationParameters(); } + @computed get HistogramResult() { return this.HistoOp ? this.HistoOp.Result as HistogramResult : undefined; } + @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; + } componentDidMount() { reaction(() => [CurrentUserUtils.ActiveSchemaName, this.props.doc.GetText(KeyStore.NorthstarSchema, "?")], - () => CurrentUserUtils.ActiveSchemaName == this.props.doc.GetText(KeyStore.NorthstarSchema, "?") && this.activateHistogramOperation(), - { fireImmediately: true }); + (params: string[]) => params[0] == params[1] && this.activateHistogramOperation(), { fireImmediately: true }); reaction(() => [this.VisualBinRanges && this.VisualBinRanges.slice(), this._panelHeight, this._panelWidth], () => this.SizeConverter = new SizeConverter({ x: this._panelWidth, y: this._panelHeight }, this.VisualBinRanges, Math.PI / 4)); - reaction(() => this.HistoOp && this.HistoOp.Result instanceof HistogramResult ? this.HistoOp.Result.binRanges : undefined, - (binRanges: BinRange[] | undefined) => { - if (!binRanges || !this.HistoOp || !(this.HistoOp!.Result instanceof HistogramResult)) - return; - - this.ChartType = binRanges[0] instanceof AggregateBinRange ? (binRanges[1] instanceof AggregateBinRange ? ChartType.SinglePoint : ChartType.HorizontalBar) : - binRanges[1] instanceof AggregateBinRange ? ChartType.VerticalBar : ChartType.HeatMap; - - this.VisualBinRanges.length = 0; - this.VisualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(binRanges[0], this.HistoOp!.Result!, this.HistoOp!.X, this.ChartType)); - this.VisualBinRanges.push(VisualBinRangeHelper.GetVisualBinRange(binRanges[1], this.HistoOp!.Result!, this.HistoOp!.Y, this.ChartType)); - - if (!this.HistoOp.Result.isEmpty) { - this.MaxValue = Number.MIN_VALUE; - this.MinValue = Number.MAX_VALUE; - for (let key in this.HistoOp.Result.bins) { - if (this.HistoOp.Result.bins.hasOwnProperty(key)) { - let bin = this.HistoOp.Result.bins[key]; - let valueAggregateKey = ModelHelpers.CreateAggregateKey(this.HistoOp.V, this.HistoOp.Result, ModelHelpers.AllBrushIndex(this.HistoOp.Result)); - let value = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; - if (value && value.hasResult) { - this.MaxValue = Math.max(this.MaxValue, value.result!); - this.MinValue = Math.min(this.MinValue, value.result!); - } - } - } - } + reaction(() => this.BinRanges, (binRanges: BinRange[] | undefined) => { + if (binRanges && this.HistogramResult && !this.HistogramResult!.isEmpty && this.HistogramResult!.bins) { + this.VisualBinRanges.splice(0, this.VisualBinRanges.length, ...binRanges.map(br => + VisualBinRangeHelper.GetVisualBinRange(br, this.HistogramResult!, this.HistoOp!.X, this.ChartType))); + + let valueAggregateKey = ModelHelpers.CreateAggregateKey(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.MIN_VALUE, Number.MAX_VALUE]); } - ); + }); } activateHistogramOperation() { this.props.doc.GetTAsync(this.props.fieldKey, HistogramField).then((histoOp: Opt) => { if (histoOp) { runInAction(() => this.HistoOp = histoOp.Data); - this.HistoOp!.Update(); - reaction( - () => this.createOperationParamsCache, - () => this.HistoOp!.Update()); reaction(() => this.props.doc.GetList(KeyStore.LinkedFromDocs, []), - (docs: Document[]) => { - this.HistoOp!.Links.length = 0; - this.HistoOp!.Links.push(...docs); - }, - { fireImmediately: true } - ); + docs => this.HistoOp!.Links.splice(0, this.HistoOp!.Links.length, ...docs), { fireImmediately: true }); + reaction(() => this.createOperationParamsCache, () => this.HistoOp!.Update(), { fireImmediately: true }); } }) } @@ -113,33 +91,27 @@ export class HistogramBox extends React.Component { let prims: JSX.Element[] = []; let labels = this.VisualBinRanges[axis].GetLabels(); labels.map((binLabel, i) => { - let xFrom = sc.DataToScreenX(axis === 0 ? binLabel.minValue! : sc.DataMins[0]); - let xTo = sc.DataToScreenX(axis === 0 ? binLabel.maxValue! : sc.DataMaxs[0]); - let yFrom = sc.DataToScreenY(axis === 0 ? sc.DataMins[1] : binLabel.minValue!); - let yTo = sc.DataToScreenY(axis === 0 ? sc.DataMaxs[1] : binLabel.maxValue!); + let r = sc.DataToScreenRange(binLabel.minValue!, binLabel.maxValue!, axis); - prims.push(this.drawLine(xFrom, yFrom, axis == 0 ? 1 : xTo - xFrom, axis == 0 ? yTo - yFrom : 1)); + prims.push(this.drawLine(r.xFrom, r.yFrom, axis == 0 ? 1 : r.xTo - r.xFrom, axis == 0 ? r.yTo - r.yFrom : 1)); if (i == labels.length - 1) - prims.push(this.drawLine(axis == 0 ? xTo : xFrom, axis == 0 ? yFrom : yTo, axis == 0 ? 1 : xTo - xFrom, axis == 0 ? yTo - yFrom : 1)); + prims.push(this.drawLine(axis == 0 ? r.xTo : r.xFrom, axis == 0 ? r.yFrom : r.yTo, axis == 0 ? 1 : r.xTo - r.xFrom, axis == 0 ? r.yTo - r.yFrom : 1)); if (i % Math.ceil(labels.length / dim) === 0 && binLabel.label) { - let text = binLabel.label; - if (text.length >= StyleConstants.MAX_CHAR_FOR_HISTOGRAM_LABELS) { - text = text.slice(0, StyleConstants.MAX_CHAR_FOR_HISTOGRAM_LABELS - 3) + "..."; - } + const label = binLabel.label.Truncate(StyleConstants.MAX_CHAR_FOR_HISTOGRAM_LABELS, "..."); const textHeight = 14; const textWidth = 30; - let xStart = (axis === 0 ? xFrom + (xTo - xFrom) / 2.0 : xFrom - 10 - textWidth); - let yStart = (axis === 1 ? yFrom - textHeight / 2 : yFrom); + 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); let rotation = 0; if (axis == 0 && this.VisualBinRanges[axis] instanceof NominalVisualBinRange) { - rotation = Math.min(90, Math.max(30, textWidth / (xTo - xFrom) * 90)); - xStart += Math.max(textWidth / 2, (1 - textWidth / (xTo - xFrom)) * textWidth / 2) - textHeight / 2; + rotation = Math.min(90, Math.max(30, textWidth / (r.xTo - r.xFrom) * 90)); + xStart += Math.max(textWidth / 2, (1 - textWidth / (r.xTo - r.xFrom)) * textWidth / 2) - textHeight / 2; } prims.push(
- {text} + {label}
) } }); diff --git a/src/client/views/nodes/HistogramBoxPrimitives.scss b/src/client/views/nodes/HistogramBoxPrimitives.scss new file mode 100644 index 000000000..c88d3a227 --- /dev/null +++ b/src/client/views/nodes/HistogramBoxPrimitives.scss @@ -0,0 +1,10 @@ +.histogramboxprimitives-border { + border: 1px; + border-style: solid; + pointer-events: none; + position: absolute; + border-color: #282828; +} +.histogramboxprimitives-bar { + position: absolute; +} \ No newline at end of file diff --git a/src/client/views/nodes/HistogramBoxPrimitives.tsx b/src/client/views/nodes/HistogramBoxPrimitives.tsx index a8ada99a4..8c5969938 100644 --- a/src/client/views/nodes/HistogramBoxPrimitives.tsx +++ b/src/client/views/nodes/HistogramBoxPrimitives.tsx @@ -1,18 +1,17 @@ import React = require("react") +import { computed, observable, runInAction } from "mobx"; +import { observer } from "mobx-react"; +import { Utils as DashUtils } from '../../../Utils'; +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 { AggregateFunction, Bin, Brush, HistogramResult, MarginAggregateParameters, MarginAggregateResult } from "../../northstar/model/idea/idea"; 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 { SizeConverter } from "../../northstar/utils/SizeConverter"; import { StyleConstants } from "../../northstar/utils/StyleContants"; -import "./HistogramBox.scss"; import { HistogramBox } from "./HistogramBox"; -import { computed, runInAction, observable, trace } from "mobx"; -import { ArrayUtil } from "../../northstar/utils/ArrayUtil"; -import { Utils as DashUtils } from '../../../Utils'; -import { observer } from "mobx-react"; - +import "./HistogramBox.scss"; export interface HistogramBoxPrimitivesProps { HistoBox: HistogramBox; @@ -24,80 +23,63 @@ export class HistogramBoxPrimitives extends React.Component this.drawBorder(bp.Rect, StyleConstants.OPERATOR_BACKGROUND_COLOR)); + return this._selectedPrims.map((bp) => this.drawRect(bp.Rect, undefined, () => { }, "border")); } @computed get binPrimitives() { - if (!this.props.HistoBox.HistoOp || !(this.props.HistoBox.HistoOp.Result instanceof HistogramResult) || !this.props.HistoBox.SizeConverter) + let histoOp = this.props.HistoBox.HistoOp; + let histoResult = this.props.HistoBox.HistogramResult; + if (!histoOp || !histoResult || !this.props.HistoBox.SizeConverter || !histoResult.bins) return (null); + let prims: JSX.Element[] = []; - let allBrushIndex = ModelHelpers.AllBrushIndex(this.props.HistoBox.HistoOp.Result); - for (let key in this.props.HistoBox.HistoOp.Result.bins) { - if (this.props.HistoBox.HistoOp.Result.bins.hasOwnProperty(key)) { - let drawPrims = new HistogramBinPrimitiveCollection(key, this.props.HistoBox); - let filterModel = ModelHelpers.GetBinFilterModel(this.props.HistoBox.HistoOp.Result.bins![key], allBrushIndex, this.props.HistoBox.HistoOp.Result, this.props.HistoBox.HistoOp.X, this.props.HistoBox.HistoOp.Y); - - this.props.HistoBox.HitTargets.setValue(drawPrims.HitGeom, filterModel); - - drawPrims.BinPrimitives.filter(bp => bp.DataValue && bp.BrushIndex !== allBrushIndex).map(binPrimitive => { - let toggleFilter = () => { - if ([filterModel].filter(h => ArrayUtil.Contains(this.props.HistoBox.HistoOp!.FilterModels, h)).length > 0) { - let bp = ArrayUtil.FirstOrDefault(drawPrims.BinPrimitives, (bp: HistogramBinPrimitive) => bp.BrushIndex == allBrushIndex); - if (bp && bp.DataValue) { - this._selectedPrims.splice(this._selectedPrims.indexOf(bp), 1); - } - this.props.HistoBox.HistoOp!.RemoveFilterModels([filterModel]); - } - else { - let bp = ArrayUtil.FirstOrDefault(drawPrims.BinPrimitives, (bp: HistogramBinPrimitive) => bp.BrushIndex == allBrushIndex); - if (bp && bp.DataValue) { - this._selectedPrims.push(bp!); - } - this.props.HistoBox.HistoOp!.AddFilterModels([filterModel]); - } + let allBrushIndex = ModelHelpers.AllBrushIndex(histoResult); + for (let key in Object.keys(histoResult.bins)) { + let drawPrims = new HistogramBinPrimitiveCollection(histoResult.bins![key], this.props.HistoBox); + let filterModel = ModelHelpers.GetBinFilterModel(histoResult.bins[key], allBrushIndex, histoResult, histoOp.X, histoOp.Y); + + this.props.HistoBox.HitTargets.setValue(drawPrims.HitGeom, filterModel); + + let allBrushPrim = ArrayUtil.FirstOrDefault(drawPrims.BinPrimitives, (bp: HistogramBinPrimitive) => bp.BrushIndex == allBrushIndex); + if (allBrushPrim && allBrushPrim.DataValue) { + let toggleFilter = () => { + if (ArrayUtil.Contains(histoOp!.FilterModels, filterModel)) { + this._selectedPrims.splice(this._selectedPrims.indexOf(allBrushPrim!), 1); + histoOp!.RemoveFilterModels([filterModel]); + } + else { + this._selectedPrims.push(allBrushPrim!); + histoOp!.AddFilterModels([filterModel]); } - prims.push(this.drawRect(binPrimitive.Rect, binPrimitive.Color, () => runInAction(toggleFilter))); - prims.push(this.drawRect(binPrimitive.MarginRect, StyleConstants.MARGIN_BARS_COLOR, () => runInAction(toggleFilter))); - }); + } + drawPrims.BinPrimitives.filter(bp => bp.DataValue && bp.BrushIndex !== allBrushIndex).map(bp => + prims.push( + this.drawRect(bp.Rect, bp.Color, () => runInAction(toggleFilter), "bar"), + this.drawRect(bp.MarginRect, StyleConstants.MARGIN_BARS_COLOR, () => runInAction(toggleFilter), "bar"))); } } + return prims; } - drawBorder(r: PIXIRectangle, color: number) { - return
- } - drawRect(r: PIXIRectangle, color: number, tapHandler: () => void) { - return
{ if (e.button == 0) tapHandler() }} + drawRect(r: PIXIRectangle, color: number | undefined, tapHandler: () => void, classExt: string) { + return
{ if (e.button == 0) tapHandler() }} style={{ - position: "absolute", transform: `translate(${r.x}px,${r.y}px)`, width: `${r.width - 1}`, height: `${r.height}`, - background: `${LABColor.RGBtoHexString(color)}` + background: color ? `${LABColor.RGBtoHexString(color)}` : "" }} /> } render() { - return
+ return
{this.binPrimitives} {this.selectedPrimitives}
} } - class HistogramBinPrimitive { constructor(init?: Partial) { Object.assign(this, init); @@ -117,114 +99,89 @@ export class HistogramBinPrimitiveCollection { 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(key: string, histoBox: HistogramBox) { + constructor(bin: Bin, histoBox: HistogramBox) { this._histoBox = histoBox; - let bin = this.histoResult.bins![key]; - - var overlapBrushIndex = ModelHelpers.OverlapBrushIndex(this.histoResult); - var orderedBrushes = new Array(); - orderedBrushes.push(this.histoResult.brushes![0]); - orderedBrushes.push(this.histoResult.brushes![overlapBrushIndex]); - for (var b = 0; b < this.histoResult.brushes!.length; b++) { - var brush = this.histoResult.brushes![b]; - if (brush.brushIndex != 0 && brush.brushIndex != overlapBrushIndex) { - orderedBrushes.push(brush); + 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); } - } - var binBrushMaxAxis = this.getBinBrushAxisRange(bin, orderedBrushes, this.histoOp.Normalization); // X= 0, Y = 1 - - var brushFactorSum: number = 0; - for (var b = 0; b < orderedBrushes.length; b++) { - var brush = orderedBrushes[b]; - var valueAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.V, this.histoResult, brush.brushIndex!); - var doubleRes = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; - var unNormalizedValue = (doubleRes != null && doubleRes.hasResult) ? doubleRes.result : null; - if (unNormalizedValue) - switch (histoBox.ChartType) { - case ChartType.VerticalBar: - this.createVerticalBarChartBinPrimitives(bin, brush, binBrushMaxAxis, this.histoOp.Normalization, histoBox.SizeConverter!); // X = 0, Y = 1, NOne = -1 - break; - case ChartType.HorizontalBar: - this.createHorizontalBarChartBinPrimitives(bin, brush, binBrushMaxAxis, this.histoOp.Normalization, histoBox.SizeConverter!); - break; - case ChartType.SinglePoint: - this.createSinlgePointChartBinPrimitives(bin, brush, unNormalizedValue, histoBox.SizeConverter!); - break; - case ChartType.HeatMap: - var normalizedValue = (unNormalizedValue - histoBox.MinValue) / (Math.abs((histoBox.MaxValue - histoBox.MinValue)) < HistogramBinPrimitiveCollection.TOLERANCE ? - unNormalizedValue : histoBox.MaxValue - histoBox.MinValue); - brushFactorSum = this.createHeatmapBinPrimitives(bin, brush, unNormalizedValue, brushFactorSum, normalizedValue, histoBox.SizeConverter!); - } - } + }, 0); // adjust brush rects (stacking or not) - var sum: number = 0; var allBrushIndex = ModelHelpers.AllBrushIndex(this.histoResult); var filteredBinPrims = this.BinPrimitives.filter(b => b.BrushIndex != allBrushIndex && b.DataValue != 0.0); - var count: number = filteredBinPrims.length; - filteredBinPrims.map(fbp => { + filteredBinPrims.reduce((sum, fbp) => { if (histoBox.ChartType == ChartType.VerticalBar) { if (this.histoOp.X.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); - sum += fbp.Rect.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 / count, fbp.Rect.height); + 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); - sum += fbp.Rect.width; + 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); - sum += fbp.Rect.width; + 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 / count); + 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); - sum += fbp.Rect.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 getBinBrushAxisRange(bin: Bin, brushes: Array, axis: number): number { - var binBrushMaxAxis = Number.MIN_VALUE; - brushes.forEach((Brush) => { - var maxAggregateKey = ModelHelpers.CreateAggregateKey(axis === 0 ? this.histoOp.Y : this.histoOp.X, this.histoResult, Brush.brushIndex!); - var aggResult = ModelHelpers.GetAggregateResult(bin, maxAggregateKey) as DoubleValueAggregateResult; - if (aggResult != null) { - if (aggResult.result! > binBrushMaxAxis) - binBrushMaxAxis = aggResult.result!; - } - }); - return binBrushMaxAxis; + 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.histoOp.getValue(normalization, bin, this.histoResult, Brush.brushIndex!); + return aggResult != undefined && aggResult > prev ? aggResult : prev; + }, Number.MIN_VALUE) + }; } - private createHeatmapBinPrimitives(bin: Bin, brush: Brush, unNormalizedValue: number, brushFactorSum: number, normalizedValue: number, sizeConverter: SizeConverter): number { + private createHeatmapBinPrimitives(bin: Bin, brush: Brush, brushFactorSum: number): number { + + let unNormalizedValue = this.histoOp!.getValue(2, bin, this.histoResult, brush.brushIndex!); + if (unNormalizedValue == undefined) + return brushFactorSum; - var valueAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.V, this.histoResult, ModelHelpers.AllBrushIndex(this.histoResult)); - var allUnNormalizedValue = ModelHelpers.GetAggregateResult(bin, valueAggregateKey) as DoubleValueAggregateResult; + 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]); - var tx = this._histoBox.VisualBinRanges[0].GetValueFromIndex(bin.binIndex!.indices![0]); - var xFrom = sizeConverter.DataToScreenX(tx); - var xTo = sizeConverter.DataToScreenX(this._histoBox.VisualBinRanges[0].AddStep(tx)); + let allUnNormalizedValue = this.histoOp.getValue(2, bin, this.histoResult, ModelHelpers.AllBrushIndex(this.histoResult)) - var ty = this._histoBox.VisualBinRanges[1].GetValueFromIndex(bin.binIndex!.indices![1]); - var yFrom = sizeConverter.DataToScreenY(ty); - var yTo = sizeConverter.DataToScreenY(this._histoBox.VisualBinRanges[1].AddStep(ty)); + // bcz: are these calls needed? + let [xFrom, xTo] = this.sizeConverter.DataToScreenAxisRange(this._histoBox.VisualBinRanges, 0, bin); + let [yFrom, yTo] = this.sizeConverter.DataToScreenAxisRange(this._histoBox.VisualBinRanges, 1, bin); var returnBrushFactorSum = brushFactorSum; - if (allUnNormalizedValue.hasResult) { - var brushFactor = (unNormalizedValue / allUnNormalizedValue.result!); + if (allUnNormalizedValue != undefined) { + var brushFactor = (unNormalizedValue / allUnNormalizedValue); returnBrushFactorSum += brushFactor; returnBrushFactorSum = Math.min(returnBrushFactorSum, 1.0); @@ -250,95 +207,67 @@ export class HistogramBinPrimitiveCollection { return returnBrushFactorSum; } - private createSinlgePointChartBinPrimitives(bin: Bin, brush: Brush, unNormalizedValue: number, sizeConverter: SizeConverter): void { - var yAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, brush.brushIndex!); - var xAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, brush.brushIndex!); - - var xValue = ModelHelpers.GetAggregateResult(bin, xAggregateKey) as DoubleValueAggregateResult; - if (!xValue.hasResult) - return; - var xFrom = sizeConverter.DataToScreenX(xValue.result!) - 5; - var xTo = sizeConverter.DataToScreenX(xValue.result!) + 5; + private createSinglePointChartBinPrimitives(bin: Bin, brush: Brush): number { + let unNormalizedValue = this._histoBox.HistoOp!.getValue(2, bin, this.histoResult, brush.brushIndex!); + if (unNormalizedValue != undefined) { + let [xFrom, xTo] = this.sizeConverter.DataToScreenPointRange(0, bin, ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, brush.brushIndex!)); + let [yFrom, yTo] = this.sizeConverter.DataToScreenPointRange(1, bin, ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, brush.brushIndex!)); - var yValue = ModelHelpers.GetAggregateResult(bin, yAggregateKey) as DoubleValueAggregateResult;; - if (!yValue.hasResult) - return; - var yFrom = sizeConverter.DataToScreenY(yValue.result!) + 5; - var yTo = sizeConverter.DataToScreenY(yValue.result!); - - this.createBinPrimitive(bin, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, this.baseColorFromBrush(brush), 1, unNormalizedValue); + if (xFrom != undefined && yFrom != undefined && xTo != undefined && yTo != undefined) + this.createBinPrimitive(bin, 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, sizeConverter: SizeConverter): void { - var yAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, brush.brushIndex!); - var marginParams = new MarginAggregateParameters(); - marginParams.aggregateFunction = this.histoOp.Y.AggregateFunction; - var yMarginAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, - brush.brushIndex!, marginParams); - var dataValue = ModelHelpers.GetAggregateResult(bin, yAggregateKey) as DoubleValueAggregateResult; - - if (dataValue != null && dataValue.hasResult) { - var yValue = normalization != 0 || binBrushMaxAxis == 0 ? dataValue.result! : (dataValue.result! - 0) / (binBrushMaxAxis - 0) * sizeConverter.DataRanges[1]; - - var yFrom = sizeConverter.DataToScreenY(Math.min(0, yValue)); - var yTo = sizeConverter.DataToScreenY(Math.max(0, yValue));; - - var xValue = this._histoBox.VisualBinRanges[0].GetValueFromIndex(bin.binIndex!.indices![0])!; - var xFrom = sizeConverter.DataToScreenX(xValue); - var xTo = sizeConverter.DataToScreenX(this._histoBox.VisualBinRanges[0].AddStep(xValue)); + private createVerticalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number): number { + let dataValue = this.histoOp.getValue(1, bin, this.histoResult, brush.brushIndex!); + if (dataValue != undefined) { + let [yFrom, yValue, yTo] = this.sizeConverter.DataToScreenNormalizedRange(dataValue, normalization, 1, binBrushMaxAxis); + let [xFrom, xTo] = this.sizeConverter.DataToScreenAxisRange(this._histoBox.VisualBinRanges, 0, bin); - var marginResult = ModelHelpers.GetAggregateResult(bin, yMarginAggregateKey) as MarginAggregateResult; - var yMarginAbsolute = !marginResult ? 0 : marginResult.absolutMargin!; + var yMarginAbsolute = this.getMargin(bin, brush, this.histoOp.Y); var marginRect = new PIXIRectangle(xFrom + (xTo - xFrom) / 2.0 - 1, - sizeConverter.DataToScreenY(yValue + yMarginAbsolute), 2, - sizeConverter.DataToScreenY(yValue - yMarginAbsolute) - sizeConverter.DataToScreenY(yValue + yMarginAbsolute)); + this.sizeConverter.DataToScreenY(yValue + yMarginAbsolute), 2, + this.sizeConverter.DataToScreenY(yValue - yMarginAbsolute) - this.sizeConverter.DataToScreenY(yValue + yMarginAbsolute)); this.createBinPrimitive(bin, brush, marginRect, 0, xFrom, xTo, yFrom, yTo, - this.baseColorFromBrush(brush), normalization != 0 ? 1 : 0.6 * binBrushMaxAxis / sizeConverter.DataRanges[1] + 0.4, dataValue.result!); + 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, sizeConverter: SizeConverter): void { - var xAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, brush.brushIndex!); - var marginParams = new MarginAggregateParameters(); - marginParams.aggregateFunction = this.histoOp.X.AggregateFunction; - var xMarginAggregateKey = ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, - brush.brushIndex!, marginParams); - var dataValue = ModelHelpers.GetAggregateResult(bin, xAggregateKey) as DoubleValueAggregateResult; - - if (dataValue != null && dataValue.hasResult) { - var xValue = normalization != 1 || binBrushMaxAxis == 0 ? dataValue.result! : (dataValue.result! - 0) / (binBrushMaxAxis - 0) * sizeConverter.DataRanges[0]; - var xFrom = sizeConverter.DataToScreenX(Math.min(0, xValue)); - var xTo = sizeConverter.DataToScreenX(Math.max(0, xValue)); - - var yValue = this._histoBox.VisualBinRanges[1].GetValueFromIndex(bin.binIndex!.indices![1]); - var yFrom = yValue; - var yTo = this._histoBox.VisualBinRanges[1].AddStep(yValue); + private createHorizontalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number): number { + let dataValue = this.histoOp.getValue(0, bin, this.histoResult, brush.brushIndex!); + if (dataValue != undefined) { + let [xFrom, xValue, xTo] = this.sizeConverter.DataToScreenNormalizedRange(dataValue, normalization, 0, binBrushMaxAxis); + let [yFrom, yTo] = this.sizeConverter.DataToScreenAxisRange(this._histoBox.VisualBinRanges, 1, bin); - var marginResult = ModelHelpers.GetAggregateResult(bin, xMarginAggregateKey) as MarginAggregateResult; - var xMarginAbsolute = sizeConverter.IsSmall || !marginResult ? 0 : marginResult.absolutMargin!; - - var marginRect = new PIXIRectangle(sizeConverter.DataToScreenX(xValue - xMarginAbsolute), + 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, - sizeConverter.DataToScreenX(xValue + xMarginAbsolute) - sizeConverter.DataToScreenX(xValue - xMarginAbsolute), + this.sizeConverter.DataToScreenX(xValue + xMarginAbsolute) - this.sizeConverter.DataToScreenX(xValue - xMarginAbsolute), 2.0); this.createBinPrimitive(bin, brush, marginRect, 0, xFrom, xTo, yFrom, yTo, - this.baseColorFromBrush(brush), normalization != 1 ? 1 : 0.6 * binBrushMaxAxis / sizeConverter.DataRanges[0] + 0.4, dataValue.result!); + this.baseColorFromBrush(brush), normalization != 1 ? 1 : 0.6 * binBrushMaxAxis / this.sizeConverter.DataRanges[0] + 0.4, dataValue); } + return 0; + } + + + private getMargin(bin: Bin, brush: Brush, axis: AttributeTransformationModel) { + var marginParams = new MarginAggregateParameters(); + marginParams.aggregateFunction = axis.AggregateFunction; + var marginAggregateKey = ModelHelpers.CreateAggregateKey(axis, this.histoResult, brush.brushIndex!, marginParams); + var marginResult = ModelHelpers.GetAggregateResult(bin, marginAggregateKey) as MarginAggregateResult; + return !marginResult ? 0 : marginResult.absolutMargin!; } private createBinPrimitive(bin: Bin, brush: Brush, marginRect: PIXIRectangle, marginPercentage: number, xFrom: number, xTo: number, yFrom: number, yTo: number, color: number, opacity: number, dataValue: number) { - // hitgeom todo - var binPrimitive = new HistogramBinPrimitive( { - Rect: new PIXIRectangle( - xFrom, - yTo, - xTo - xFrom, - yFrom - yTo), + Rect: new PIXIRectangle(xFrom, yTo, xTo - xFrom, yFrom - yTo), MarginRect: marginRect, MarginPercentage: marginPercentage, BrushIndex: brush.brushIndex, @@ -350,24 +279,18 @@ export class HistogramBinPrimitiveCollection { } private baseColorFromBrush(brush: Brush): number { - var baseColor: number = StyleConstants.HIGHLIGHT_COLOR; if (brush.brushIndex == ModelHelpers.RestBrushIndex(this.histoResult)) { - baseColor = StyleConstants.HIGHLIGHT_COLOR; + return StyleConstants.HIGHLIGHT_COLOR; } else if (brush.brushIndex == ModelHelpers.OverlapBrushIndex(this.histoResult)) { - baseColor = StyleConstants.OVERLAP_COLOR; + return StyleConstants.OVERLAP_COLOR; } else if (brush.brushIndex == ModelHelpers.AllBrushIndex(this.histoResult)) { - baseColor = 0x00ff00; + return 0x00ff00; } - else { - if (this._histoBox.HistoOp!.BrushColors.length > 0) { - baseColor = this._histoBox.HistoOp!.BrushColors[brush.brushIndex! % this._histoBox.HistoOp!.BrushColors.length]; - } - else { - baseColor = StyleConstants.HIGHLIGHT_COLOR; - } + else if (this.histoOp.BrushColors.length > 0) { + return this.histoOp.BrushColors[brush.brushIndex! % this.histoOp.BrushColors.length]; } - return baseColor; + return StyleConstants.HIGHLIGHT_COLOR; } } \ No newline at end of file -- cgit v1.2.3-70-g09d2 From e3ec05fbe6f3057fa33cb4d66025ff4c94f23f83 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 26 Mar 2019 23:28:12 -0400 Subject: from last --- src/client/views/nodes/HistogramBoxPrimitives.tsx | 49 +++++++++++------------ 1 file changed, 24 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/src/client/views/nodes/HistogramBoxPrimitives.tsx b/src/client/views/nodes/HistogramBoxPrimitives.tsx index 8c5969938..10f6515cf 100644 --- a/src/client/views/nodes/HistogramBoxPrimitives.tsx +++ b/src/client/views/nodes/HistogramBoxPrimitives.tsx @@ -12,6 +12,9 @@ import { PIXIRectangle } from "../../northstar/utils/MathUtil"; import { StyleConstants } from "../../northstar/utils/StyleContants"; import { HistogramBox } from "./HistogramBox"; import "./HistogramBox.scss"; +import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; +import { FilterModel } from "../../northstar/core/filter/FilterModel"; +import { jSXElement } from "babel-types"; export interface HistogramBoxPrimitivesProps { HistoBox: HistogramBox; @@ -25,41 +28,37 @@ export class HistogramBoxPrimitives extends React.Component this.drawRect(bp.Rect, undefined, () => { }, "border")); } + private getSelectionToggle(histoOp: HistogramOperation, binPrimitives: HistogramBinPrimitive[], allBrushIndex: number, filterModel: FilterModel) { + let allBrushPrim = ArrayUtil.FirstOrDefault(binPrimitives, bp => bp.BrushIndex == allBrushIndex); + return !allBrushPrim ? () => { } : () => runInAction(() => { + if (ArrayUtil.Contains(histoOp!.FilterModels, filterModel)) { + this._selectedPrims.splice(this._selectedPrims.indexOf(allBrushPrim!), 1); + histoOp!.RemoveFilterModels([filterModel]); + } + else { + this._selectedPrims.push(allBrushPrim!); + histoOp!.AddFilterModels([filterModel]); + } + }) + } @computed get binPrimitives() { let histoOp = this.props.HistoBox.HistoOp; let histoResult = this.props.HistoBox.HistogramResult; if (!histoOp || !histoResult || !this.props.HistoBox.SizeConverter || !histoResult.bins) return (null); - - let prims: JSX.Element[] = []; let allBrushIndex = ModelHelpers.AllBrushIndex(histoResult); - for (let key in Object.keys(histoResult.bins)) { - let drawPrims = new HistogramBinPrimitiveCollection(histoResult.bins![key], this.props.HistoBox); - let filterModel = ModelHelpers.GetBinFilterModel(histoResult.bins[key], allBrushIndex, histoResult, histoOp.X, histoOp.Y); + return Object.keys(histoResult.bins).reduce((prims, key) => { + let drawPrims = new HistogramBinPrimitiveCollection(histoResult!.bins![key], this.props.HistoBox); + let filterModel = ModelHelpers.GetBinFilterModel(histoResult!.bins![key], allBrushIndex, histoResult!, histoOp!.X, histoOp!.Y); this.props.HistoBox.HitTargets.setValue(drawPrims.HitGeom, filterModel); - let allBrushPrim = ArrayUtil.FirstOrDefault(drawPrims.BinPrimitives, (bp: HistogramBinPrimitive) => bp.BrushIndex == allBrushIndex); - if (allBrushPrim && allBrushPrim.DataValue) { - let toggleFilter = () => { - if (ArrayUtil.Contains(histoOp!.FilterModels, filterModel)) { - this._selectedPrims.splice(this._selectedPrims.indexOf(allBrushPrim!), 1); - histoOp!.RemoveFilterModels([filterModel]); - } - else { - this._selectedPrims.push(allBrushPrim!); - histoOp!.AddFilterModels([filterModel]); - } - } - drawPrims.BinPrimitives.filter(bp => bp.DataValue && bp.BrushIndex !== allBrushIndex).map(bp => - prims.push( - this.drawRect(bp.Rect, bp.Color, () => runInAction(toggleFilter), "bar"), - this.drawRect(bp.MarginRect, StyleConstants.MARGIN_BARS_COLOR, () => runInAction(toggleFilter), "bar"))); - } - } - - return prims; + let toggle = this.getSelectionToggle(histoOp!, drawPrims.BinPrimitives, allBrushIndex, filterModel); + 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, pair.c, toggle, "bar")))); + return prims; + }, [] as JSX.Element[]); } drawRect(r: PIXIRectangle, color: number | undefined, tapHandler: () => void, classExt: string) { -- cgit v1.2.3-70-g09d2 From ab78b1514ac16154d443d1d4a117a5fcaf891794 Mon Sep 17 00:00:00 2001 From: bob Date: Wed, 27 Mar 2019 16:12:36 -0400 Subject: converted histograms to % coords to avoid re-rendering. --- src/client/northstar/utils/SizeConverter.ts | 82 +++++------- src/client/views/nodes/HistogramBox.scss | 22 +++- src/client/views/nodes/HistogramBox.tsx | 146 +++++++++++++-------- src/client/views/nodes/HistogramBoxPrimitives.scss | 19 ++- src/client/views/nodes/HistogramBoxPrimitives.tsx | 106 +++++++++++---- 5 files changed, 237 insertions(+), 138 deletions(-) (limited to 'src') diff --git a/src/client/northstar/utils/SizeConverter.ts b/src/client/northstar/utils/SizeConverter.ts index 2dc2a7557..ffd162a83 100644 --- a/src/client/northstar/utils/SizeConverter.ts +++ b/src/client/northstar/utils/SizeConverter.ts @@ -1,68 +1,48 @@ import { PIXIPoint } from "./MathUtil"; -import { NominalVisualBinRange } from "../model/binRanges/NominalVisualBinRange"; import { VisualBinRange } from "../model/binRanges/VisualBinRange"; import { Bin, DoubleValueAggregateResult, AggregateKey } from "../model/idea/idea"; -import { AttributeTransformationModel } from "../core/attribute/AttributeTransformationModel"; import { ModelHelpers } from "../model/ModelHelpers"; +import { observable, action, computed } from "mobx"; export class SizeConverter { - public RenderSize: Array = new Array(2); - 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 LeftOffset: number = 40; - public RightOffset: number = 20; - public TopOffset: number = 20; - public BottomOffset: number = 45; - - public IsSmall: boolean = false; - - constructor(size: { x: number, y: number }, visualBinRanges: Array, labelAngle: number) { - this.LeftOffset = 40; - this.RightOffset = 20; - this.TopOffset = 20; - this.BottomOffset = 45; - this.IsSmall = false; - - if (visualBinRanges.length < 1) - return; - + 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: 100 }; // RenderUtils.MeasureText(FontStyles.Default.fontFamily.toString(), 12, // FontStyles.AxisLabel.fontSize as number, + 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); - - if (visualBinRanges[0] instanceof NominalVisualBinRange) { - var lw = this.MaxLabelSizes[0].x + 18; - this.BottomOffset = Math.max(this.BottomOffset, Math.cos(labelAngle) * lw) + 5; - this.RightOffset = Math.max(this.RightOffset, Math.sin(labelAngle) * lw); - } - - this.RenderSize[0] = (size.x - this.LeftOffset - this.RightOffset); - this.RenderSize[1] = (size.y - this.TopOffset - this.BottomOffset); - - //if (this.RenderSize.reduce((agg, cur) => Math.min(agg, cur), Number.MAX_VALUE) < 40) { - if ((this.RenderSize[0] < 40 && this.RenderSize[1] < 40) || - (this.RenderSize[0] < 0 || this.RenderSize[1] < 0)) { - this.LeftOffset = 5; - this.RightOffset = 5; - this.TopOffset = 5; - this.BottomOffset = 25; - this.IsSmall = true; - this.RenderSize[0] = (size.x - this.LeftOffset - this.RightOffset); - this.RenderSize[1] = (size.y - this.TopOffset - this.BottomOffset); - } + 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); @@ -94,11 +74,11 @@ export class SizeConverter { } public DataToScreenX(x: number): number { - return (((x - this.DataMins[0]) / this.DataRanges[0]) * (this.RenderSize[0]) + (this.LeftOffset)); + 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.RenderSize[1]); - return flip ? (this.RenderSize[1]) - retY + (this.TopOffset) : retY + (this.TopOffset); + 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) diff --git a/src/client/views/nodes/HistogramBox.scss b/src/client/views/nodes/HistogramBox.scss index 00ad099ac..7c28fc99e 100644 --- a/src/client/views/nodes/HistogramBox.scss +++ b/src/client/views/nodes/HistogramBox.scss @@ -5,14 +5,28 @@ width: 100%; height: 100%; } - .histogrambox-gridlabel { - position:absolute; - transform-origin: left top; - } .histogrambox-xaxislabel { position:absolute; width:100%; text-align: center; bottom:0; + font-size: 12; + } + + .histogrambox-container { + position:absolute; + width:100%; + height: 100%; + } + .histogramLabelPrimitives-gridlabel { + position:absolute; + transform-origin: left top; + font-size: 12; + } + .histogramLabelPrimitives-placer { + position:absolute; + width:100%; + height:100%; + pointer-events: none; } \ No newline at end of file diff --git a/src/client/views/nodes/HistogramBox.tsx b/src/client/views/nodes/HistogramBox.tsx index c9537bcf8..2291d1418 100644 --- a/src/client/views/nodes/HistogramBox.tsx +++ b/src/client/views/nodes/HistogramBox.tsx @@ -1,5 +1,5 @@ import React = require("react") -import { computed, observable, reaction, runInAction } from "mobx"; +import { computed, observable, reaction, runInAction, trace, action } from "mobx"; import { observer } from "mobx-react"; import Measure from "react-measure"; import { Dictionary } from "typescript-collections"; @@ -21,22 +21,20 @@ import { StyleConstants } from "../../northstar/utils/StyleContants"; import "./../../northstar/utils/Extensions"; import { FieldView, FieldViewProps } from './FieldView'; import "./HistogramBox.scss"; -import { HistogramBoxPrimitives } from './HistogramBoxPrimitives'; +import { HistogramBoxPrimitives, HistogramBoxPrimitivesProps } from './HistogramBoxPrimitives'; @observer export class HistogramBox extends React.Component { public static LayoutString(fieldStr: string = "DataKey") { return FieldView.LayoutString(HistogramBox, fieldStr) } + public HitTargets: Dictionary = new Dictionary(); - @observable private _panelWidth: number = 100; - @observable private _panelHeight: number = 100; + @observable public PanelWidth: number = 100; + @observable public PanelHeight: number = 100; @observable public HistoOp?: HistogramOperation; @observable public VisualBinRanges: VisualBinRange[] = []; @observable public ValueRange: number[] = []; - @observable public SizeConverter?: SizeConverter; - public HitTargets: Dictionary = new Dictionary(); + @observable public SizeConverter: SizeConverter = new SizeConverter(); - @computed get xaxislines() { return this.renderGridLinesAndLabels(0); } - @computed get yaxislines() { return this.renderGridLinesAndLabels(1); } @computed get createOperationParamsCache() { return this.HistoOp!.CreateOperationParameters(); } @computed get HistogramResult() { return this.HistoOp ? this.HistoOp.Result as HistogramResult : undefined; } @computed get BinRanges() { return this.HistogramResult ? this.HistogramResult.binRanges : undefined; } @@ -48,93 +46,127 @@ export class HistogramBox extends React.Component { componentDidMount() { reaction(() => [CurrentUserUtils.ActiveSchemaName, this.props.doc.GetText(KeyStore.NorthstarSchema, "?")], - (params: string[]) => params[0] == params[1] && this.activateHistogramOperation(), { fireImmediately: true }); - reaction(() => [this.VisualBinRanges && this.VisualBinRanges.slice(), this._panelHeight, this._panelWidth], - () => this.SizeConverter = new SizeConverter({ x: this._panelWidth, y: this._panelHeight }, this.VisualBinRanges, Math.PI / 4)); - reaction(() => this.BinRanges, (binRanges: BinRange[] | undefined) => { - if (binRanges && this.HistogramResult && !this.HistogramResult!.isEmpty && this.HistogramResult!.bins) { - this.VisualBinRanges.splice(0, this.VisualBinRanges.length, ...binRanges.map(br => - VisualBinRangeHelper.GetVisualBinRange(br, this.HistogramResult!, this.HistoOp!.X, this.ChartType))); + (params: string[]) => params[0] === params[1] && this.activateHistogramOperation(), { fireImmediately: true }); + reaction(() => [this.VisualBinRanges && this.VisualBinRanges.slice()], () => this.SizeConverter.SetVisualBinRanges(this.VisualBinRanges)); + reaction(() => [this.PanelHeight, this.PanelWidth], () => this.SizeConverter.SetIsSmall(this.PanelWidth < 40 && this.PanelHeight < 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(br, this.HistogramResult!, ind ? this.HistoOp!.Y : this.HistoOp!.X, this.ChartType))); - let valueAggregateKey = ModelHelpers.CreateAggregateKey(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.MIN_VALUE, Number.MAX_VALUE]); - } - }); + let valueAggregateKey = ModelHelpers.CreateAggregateKey(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.MIN_VALUE, Number.MAX_VALUE]); + } + }); } activateHistogramOperation() { this.props.doc.GetTAsync(this.props.fieldKey, HistogramField).then((histoOp: Opt) => { if (histoOp) { runInAction(() => this.HistoOp = histoOp.Data); - reaction(() => this.props.doc.GetList(KeyStore.LinkedFromDocs, []), - docs => this.HistoOp!.Links.splice(0, this.HistoOp!.Links.length, ...docs), { fireImmediately: true }); + reaction(() => this.props.doc.GetList(KeyStore.LinkedFromDocs, []), docs => this.HistoOp!.Links.splice(0, this.HistoOp!.Links.length, ...docs), { fireImmediately: true }); reaction(() => this.createOperationParamsCache, () => this.HistoOp!.Update(), { fireImmediately: true }); } }) } + render() { + let label = this.HistoOp && this.HistoOp.X ? this.HistoOp.X.AttributeModel.DisplayName : "<...>"; + var h = this.props.isTopMost ? this.PanelHeight : this.props.doc.GetNumber(KeyStore.Height, 0); + var w = this.props.isTopMost ? this.PanelWidth : this.props.doc.GetNumber(KeyStore.Width, 0); + let loff = this.SizeConverter.LeftOffset; + let toff = this.SizeConverter.TopOffset; + let roff = this.SizeConverter.RightOffset; + let boff = this.SizeConverter.BottomOffset; + return ( + runInAction(() => { this.PanelWidth = r.entry.width; this.PanelHeight = r.entry.height })}> + {({ measureRef }) => +
+
+ + +
+
{label}
+
+ } +
+ ) + } +} + +@observer +export class HistogramLabelPrimitives extends React.Component { + componentDidMount() { + reaction(() => [this.props.HistoBox.PanelWidth, this.props.HistoBox.SizeConverter.LeftOffset, this.props.HistoBox.VisualBinRanges.length], + (fields) => HistogramLabelPrimitives.computeLabelAngle(fields[0] as number, fields[1] as number, this.props.HistoBox), { fireImmediately: true }); + } - drawLine(xFrom: number, yFrom: number, width: number, height: number) { - return
; + @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.SizeConverter!; - if (!sc || !this.VisualBinRanges.length) + let sc = this.props.HistoBox.SizeConverter; + let vb = this.props.HistoBox.VisualBinRanges; + if (!vb.length || !sc.Initialized) return (null); - let dim = sc.RenderSize[axis] / ((axis == 0 && this.VisualBinRanges[axis] instanceof NominalVisualBinRange) ? + let dim = (axis == 0 ? this.props.HistoBox.PanelWidth : this.props.HistoBox.PanelHeight) / ((axis == 0 && vb[axis] instanceof NominalVisualBinRange) ? (12 + 5) : // (FontStyles.AxisLabel.fontSize + 5))); sc.MaxLabelSizes[axis].coords[axis] + 5); let prims: JSX.Element[] = []; - let labels = this.VisualBinRanges[axis].GetLabels(); + let labels = vb[axis].GetLabels(); labels.map((binLabel, i) => { let r = sc.DataToScreenRange(binLabel.minValue!, binLabel.maxValue!, axis); - - prims.push(this.drawLine(r.xFrom, r.yFrom, axis == 0 ? 1 : r.xTo - r.xFrom, axis == 0 ? r.yTo - r.yFrom : 1)); - if (i == labels.length - 1) - prims.push(this.drawLine(axis == 0 ? r.xTo : r.xFrom, axis == 0 ? r.yFrom : r.yTo, axis == 0 ? 1 : r.xTo - r.xFrom, axis == 0 ? r.yTo - r.yFrom : 1)); - 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); - let rotation = 0; - if (axis == 0 && this.VisualBinRanges[axis] instanceof NominalVisualBinRange) { - rotation = Math.min(90, Math.max(30, textWidth / (r.xTo - r.xFrom) * 90)); - xStart += Math.max(textWidth / 2, (1 - textWidth / (r.xTo - r.xFrom)) * textWidth / 2) - textHeight / 2; + if (axis == 0 && vb[axis] instanceof NominalVisualBinRange) { + let space = (r.xTo - r.xFrom) / sc.RenderDimension * this.props.HistoBox.PanelWidth; + xStart += Math.max(textWidth / 2, (1 - textWidth / space) * textWidth / 2) - textHeight / 2; } + let xPercent = axis == 1 ? `${xStart}px` : `${xStart / sc.RenderDimension * 100}%` + let yPercent = axis == 0 ? `${this.props.HistoBox.PanelHeight - sc.BottomOffset - textHeight}px` : `${yStart / sc.RenderDimension * 100}%` + prims.push( -
- {label} -
) +
+
+ {label} +
+
+ ) } }); return prims; } render() { - let label = this.HistoOp && this.HistoOp.X ? this.HistoOp.X.AttributeModel.DisplayName : "<...>"; let xaxislines = this.xaxislines; let yaxislines = this.yaxislines; - var h = this.props.isTopMost ? this._panelHeight : this.props.doc.GetNumber(KeyStore.Height, 0); - var w = this.props.isTopMost ? this._panelWidth : this.props.doc.GetNumber(KeyStore.Width, 0); - return ( - runInAction(() => { this._panelWidth = r.entry.width; this._panelHeight = r.entry.height })}> - {({ measureRef }) => -
- {xaxislines} - {yaxislines} - -
{label}
-
- } -
- ) + return
+ {xaxislines} + {yaxislines} +
} + } \ No newline at end of file diff --git a/src/client/views/nodes/HistogramBoxPrimitives.scss b/src/client/views/nodes/HistogramBoxPrimitives.scss index c88d3a227..85f2c092d 100644 --- a/src/client/views/nodes/HistogramBoxPrimitives.scss +++ b/src/client/views/nodes/HistogramBoxPrimitives.scss @@ -1,10 +1,25 @@ .histogramboxprimitives-border { - border: 1px; + border: 3px; border-style: solid; + border-color: #282828; pointer-events: none; position: absolute; - border-color: #282828; } .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-line { + position: absolute; + background: lightgray; } \ No newline at end of file diff --git a/src/client/views/nodes/HistogramBoxPrimitives.tsx b/src/client/views/nodes/HistogramBoxPrimitives.tsx index 10f6515cf..06b318750 100644 --- a/src/client/views/nodes/HistogramBoxPrimitives.tsx +++ b/src/client/views/nodes/HistogramBoxPrimitives.tsx @@ -1,5 +1,5 @@ import React = require("react") -import { computed, observable, runInAction } from "mobx"; +import { computed, observable, runInAction, trace } from "mobx"; import { observer } from "mobx-react"; import { Utils as DashUtils } from '../../../Utils'; import { AttributeTransformationModel } from "../../northstar/core/attribute/AttributeTransformationModel"; @@ -11,10 +11,9 @@ import { LABColor } from '../../northstar/utils/LABcolor'; import { PIXIRectangle } from "../../northstar/utils/MathUtil"; import { StyleConstants } from "../../northstar/utils/StyleContants"; import { HistogramBox } from "./HistogramBox"; -import "./HistogramBox.scss"; +import "./HistogramBoxPrimitives.scss"; import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; import { FilterModel } from "../../northstar/core/filter/FilterModel"; -import { jSXElement } from "babel-types"; export interface HistogramBoxPrimitivesProps { HistoBox: HistogramBox; @@ -24,9 +23,10 @@ export interface HistogramBoxPrimitivesProps { export class HistogramBoxPrimitives extends React.Component { @observable _selectedPrims: HistogramBinPrimitive[] = []; - @computed - get selectedPrimitives() { - return this._selectedPrims.map((bp) => this.drawRect(bp.Rect, undefined, () => { }, "border")); + @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")); } private getSelectionToggle(histoOp: HistogramOperation, binPrimitives: HistogramBinPrimitive[], allBrushIndex: number, filterModel: FilterModel) { let allBrushPrim = ArrayUtil.FirstOrDefault(binPrimitives, bp => bp.BrushIndex == allBrushIndex); @@ -45,7 +45,7 @@ export class HistogramBoxPrimitives extends React.Component { @@ -56,23 +56,79 @@ export class HistogramBoxPrimitives extends React.Component 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, pair.c, toggle, "bar")))); + 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, toggle, "bar")))); return prims; }, [] as JSX.Element[]); } - drawRect(r: PIXIRectangle, color: number | undefined, tapHandler: () => void, classExt: string) { - return
{ if (e.button == 0) tapHandler() }} - style={{ - transform: `translate(${r.x}px,${r.y}px)`, - width: `${r.width - 1}`, - height: `${r.height}`, - background: color ? `${LABColor.RGBtoHexString(color)}` : "" - }} - /> + + private renderGridLinesAndLabels(axis: number) { + let sc = this.props.HistoBox.SizeConverter; + let vb = this.props.HistoBox.VisualBinRanges; + if (!vb.length || !sc.Initialized) + return (null); + + let prims: JSX.Element[] = []; + let labels = vb[axis].GetLabels(); + labels.map((binLabel, i) => { + let r = sc.DataToScreenRange(binLabel.minValue!, binLabel.maxValue!, axis); + + prims.push(this.drawLine(r.xFrom, r.yFrom, axis == 0 ? 1 : r.xTo - r.xFrom, axis == 0 ? r.yTo - r.yFrom : 1)); + if (i == labels.length - 1) + prims.push(this.drawLine(axis == 0 ? r.xTo : r.xFrom, axis == 0 ? r.yFrom : r.yTo, axis == 0 ? 1 : r.xTo - r.xFrom, axis == 0 ? r.yTo - r.yFrom : 1)); + }); + return prims; + } + + drawLine(xFrom: number, yFrom: number, width: number, height: number) { + if (height < 0) { + yFrom += height; + height = -height; + } + if (width < 0) { + xFrom += width; + width = -width; + } + let transXpercent = (xFrom) / this.props.HistoBox.SizeConverter.RenderDimension; + let transYpercent = (yFrom) / this.props.HistoBox.SizeConverter.RenderDimension; + let trans2Xpercent = width == 1 ? "1px" : `${(xFrom + width) / this.props.HistoBox.SizeConverter.RenderDimension * 100}%`; + let trans2Ypercent = height == 1 ? "1px" : `${(yFrom + height) / this.props.HistoBox.SizeConverter.RenderDimension * 100}%`; + return
+
; + } + + drawRect(r: PIXIRectangle, barAxis: number, color: number | undefined, tapHandler: () => void, classExt: string) { + let widthPercent = (r.width - 0) / this.props.HistoBox.SizeConverter.RenderDimension; + let heightPercent = r.height / this.props.HistoBox.SizeConverter.RenderDimension; + let transXpercent = (r.x) / this.props.HistoBox.SizeConverter.RenderDimension; + let transYpercent = (r.y) / this.props.HistoBox.SizeConverter.RenderDimension; + return (
+
{ if (e.button == 0) tapHandler() }} + style={{ + borderBottomStyle: barAxis == 1 ? "none" : "solid", + borderLeftStyle: barAxis == 0 ? "none" : "solid", + width: `${widthPercent * 100}%`, + height: `${heightPercent * 100}%`, + background: color ? `${LABColor.RGBtoHexString(color)}` : "" + }} + />
); } render() { - return
+ if (!this.props.HistoBox.SizeConverter.Initialized) + return (null); + let xaxislines = this.xaxislines; + let yaxislines = this.yaxislines; + return
+ {xaxislines} + {yaxislines} {this.binPrimitives} {this.selectedPrimitives}
@@ -90,6 +146,7 @@ class HistogramBinPrimitive { public Color: number = StyleConstants.WARNING_COLOR; public Opacity: number = 1; public BrushIndex: number = 0; + public BarAxis: number = -1; } export class HistogramBinPrimitiveCollection { @@ -202,7 +259,7 @@ export class HistogramBinPrimitiveCollection { (alpha + Math.pow(normalizedValue, 1.0 / 3.0) * (1.0 - alpha))); var dataColor = LABColor.ToColor(lerpColor); - this.createBinPrimitive(bin, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, dataColor, 1, unNormalizedValue); + this.createBinPrimitive(-1, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, dataColor, 1, unNormalizedValue); return returnBrushFactorSum; } @@ -213,7 +270,7 @@ export class HistogramBinPrimitiveCollection { let [yFrom, yTo] = this.sizeConverter.DataToScreenPointRange(1, bin, ModelHelpers.CreateAggregateKey(this.histoOp.Y, this.histoResult, brush.brushIndex!)); if (xFrom != undefined && yFrom != undefined && xTo != undefined && yTo != undefined) - this.createBinPrimitive(bin, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, this.baseColorFromBrush(brush), 1, unNormalizedValue); + this.createBinPrimitive(-1, brush, PIXIRectangle.EMPTY, 0, xFrom, xTo, yFrom, yTo, this.baseColorFromBrush(brush), 1, unNormalizedValue); } return 0; } @@ -229,7 +286,7 @@ export class HistogramBinPrimitiveCollection { this.sizeConverter.DataToScreenY(yValue + yMarginAbsolute), 2, this.sizeConverter.DataToScreenY(yValue - yMarginAbsolute) - this.sizeConverter.DataToScreenY(yValue + yMarginAbsolute)); - this.createBinPrimitive(bin, brush, marginRect, 0, xFrom, xTo, yFrom, yTo, + 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; @@ -247,7 +304,7 @@ export class HistogramBinPrimitiveCollection { this.sizeConverter.DataToScreenX(xValue + xMarginAbsolute) - this.sizeConverter.DataToScreenX(xValue - xMarginAbsolute), 2.0); - this.createBinPrimitive(bin, brush, marginRect, 0, xFrom, xTo, yFrom, yTo, + 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; @@ -262,7 +319,7 @@ export class HistogramBinPrimitiveCollection { return !marginResult ? 0 : marginResult.absolutMargin!; } - private createBinPrimitive(bin: Bin, brush: Brush, marginRect: PIXIRectangle, + 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( { @@ -272,7 +329,8 @@ export class HistogramBinPrimitiveCollection { BrushIndex: brush.brushIndex, Color: color, Opacity: opacity, - DataValue: dataValue + DataValue: dataValue, + BarAxis: barAxis }); this.BinPrimitives.push(binPrimitive); } -- cgit v1.2.3-70-g09d2 From fde267b5f11e7218216bc5a9de41208a0a74fad5 Mon Sep 17 00:00:00 2001 From: bob Date: Wed, 27 Mar 2019 17:00:57 -0400 Subject: final layout tweaks. --- src/client/views/nodes/HistogramBox.scss | 14 +-- src/client/views/nodes/HistogramBox.tsx | 81 ++----------- src/client/views/nodes/HistogramBoxPrimitives.tsx | 133 +++++++++------------ .../views/nodes/HistogramLabelPrimitives.scss | 12 ++ .../views/nodes/HistogramLabelPrimitives.tsx | 78 ++++++++++++ 5 files changed, 157 insertions(+), 161 deletions(-) create mode 100644 src/client/views/nodes/HistogramLabelPrimitives.scss create mode 100644 src/client/views/nodes/HistogramLabelPrimitives.tsx (limited to 'src') diff --git a/src/client/views/nodes/HistogramBox.scss b/src/client/views/nodes/HistogramBox.scss index 7c28fc99e..2660b1b75 100644 --- a/src/client/views/nodes/HistogramBox.scss +++ b/src/client/views/nodes/HistogramBox.scss @@ -10,7 +10,8 @@ width:100%; text-align: center; bottom:0; - font-size: 12; + font-size: 14; + font-weight: bold; } .histogrambox-container { @@ -18,15 +19,4 @@ width:100%; height: 100%; } - .histogramLabelPrimitives-gridlabel { - position:absolute; - transform-origin: left top; - font-size: 12; - } - .histogramLabelPrimitives-placer { - position:absolute; - width:100%; - height:100%; - pointer-events: none; - } \ No newline at end of file diff --git a/src/client/views/nodes/HistogramBox.tsx b/src/client/views/nodes/HistogramBox.tsx index 2291d1418..3307925a2 100644 --- a/src/client/views/nodes/HistogramBox.tsx +++ b/src/client/views/nodes/HistogramBox.tsx @@ -1,5 +1,5 @@ import React = require("react") -import { computed, observable, reaction, runInAction, trace, action } from "mobx"; +import { computed, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; import Measure from "react-measure"; import { Dictionary } from "typescript-collections"; @@ -7,9 +7,7 @@ import { Opt } from "../../../fields/Field"; import { HistogramField } from "../../../fields/HistogramField"; import { KeyStore } from "../../../fields/KeyStore"; import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; -import { Utils as DashUtils } from '../../../Utils'; import { FilterModel } from '../../northstar/core/filter/FilterModel'; -import { NominalVisualBinRange } from "../../northstar/model/binRanges/NominalVisualBinRange"; import { ChartType, VisualBinRange } from '../../northstar/model/binRanges/VisualBinRange'; import { VisualBinRangeHelper } from "../../northstar/model/binRanges/VisualBinRangeHelper"; import { AggregateBinRange, BinRange, DoubleValueAggregateResult, HistogramResult } from "../../northstar/model/idea/idea"; @@ -17,11 +15,15 @@ import { ModelHelpers } from "../../northstar/model/ModelHelpers"; import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; import { PIXIRectangle } from "../../northstar/utils/MathUtil"; import { SizeConverter } from "../../northstar/utils/SizeConverter"; -import { StyleConstants } from "../../northstar/utils/StyleContants"; import "./../../northstar/utils/Extensions"; import { FieldView, FieldViewProps } from './FieldView'; import "./HistogramBox.scss"; -import { HistogramBoxPrimitives, HistogramBoxPrimitivesProps } from './HistogramBoxPrimitives'; +import { HistogramBoxPrimitives } from './HistogramBoxPrimitives'; +import { HistogramLabelPrimitives } from "./HistogramLabelPrimitives"; + +export interface HistogramPrimitivesProps { + HistoBox: HistogramBox; +} @observer export class HistogramBox extends React.Component { @@ -101,72 +103,3 @@ export class HistogramBox extends React.Component { } } -@observer -export class HistogramLabelPrimitives extends React.Component { - componentDidMount() { - reaction(() => [this.props.HistoBox.PanelWidth, this.props.HistoBox.SizeConverter.LeftOffset, this.props.HistoBox.VisualBinRanges.length], - (fields) => HistogramLabelPrimitives.computeLabelAngle(fields[0] as number, fields[1] as number, 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.PanelWidth : this.props.HistoBox.PanelHeight) / ((axis == 0 && vb[axis] instanceof NominalVisualBinRange) ? - (12 + 5) : // (FontStyles.AxisLabel.fontSize + 5))); - sc.MaxLabelSizes[axis].coords[axis] + 5); - - let prims: JSX.Element[] = []; - let labels = vb[axis].GetLabels(); - labels.map((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.PanelWidth; - xStart += Math.max(textWidth / 2, (1 - textWidth / space) * textWidth / 2) - textHeight / 2; - } - - let xPercent = axis == 1 ? `${xStart}px` : `${xStart / sc.RenderDimension * 100}%` - let yPercent = axis == 0 ? `${this.props.HistoBox.PanelHeight - sc.BottomOffset - textHeight}px` : `${yStart / sc.RenderDimension * 100}%` - - prims.push( -
-
- {label} -
-
- ) - } - }); - return prims; - } - - render() { - let xaxislines = this.xaxislines; - let yaxislines = this.yaxislines; - return
- {xaxislines} - {yaxislines} -
- } - -} \ No newline at end of file diff --git a/src/client/views/nodes/HistogramBoxPrimitives.tsx b/src/client/views/nodes/HistogramBoxPrimitives.tsx index 06b318750..f15cb5689 100644 --- a/src/client/views/nodes/HistogramBoxPrimitives.tsx +++ b/src/client/views/nodes/HistogramBoxPrimitives.tsx @@ -4,82 +4,78 @@ import { observer } from "mobx-react"; import { Utils as DashUtils } from '../../../Utils'; import { AttributeTransformationModel } from "../../northstar/core/attribute/AttributeTransformationModel"; import { ChartType } from '../../northstar/model/binRanges/VisualBinRange'; -import { AggregateFunction, Bin, Brush, HistogramResult, MarginAggregateParameters, MarginAggregateResult } from "../../northstar/model/idea/idea"; +import { AggregateFunction, Bin, Brush, HistogramResult, MarginAggregateParameters, MarginAggregateResult, BinLabel } from "../../northstar/model/idea/idea"; 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 { HistogramBox } from "./HistogramBox"; +import { HistogramBox, HistogramPrimitivesProps } from "./HistogramBox"; import "./HistogramBoxPrimitives.scss"; import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; import { FilterModel } from "../../northstar/core/filter/FilterModel"; -export interface HistogramBoxPrimitivesProps { - HistoBox: HistogramBox; -} @observer -export class HistogramBoxPrimitives extends React.Component { +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")); - } - private getSelectionToggle(histoOp: HistogramOperation, binPrimitives: HistogramBinPrimitive[], allBrushIndex: number, filterModel: FilterModel) { - let allBrushPrim = ArrayUtil.FirstOrDefault(binPrimitives, bp => bp.BrushIndex == allBrushIndex); - return !allBrushPrim ? () => { } : () => runInAction(() => { - if (ArrayUtil.Contains(histoOp!.FilterModels, filterModel)) { - this._selectedPrims.splice(this._selectedPrims.indexOf(allBrushPrim!), 1); - histoOp!.RemoveFilterModels([filterModel]); - } - else { - this._selectedPrims.push(allBrushPrim!); - histoOp!.AddFilterModels([filterModel]); - } - }) - } - @computed - get binPrimitives() { - let histoOp = this.props.HistoBox.HistoOp; + @computed get selectedPrimitives() { return this._selectedPrims.map(bp => this.drawRect(bp.Rect, bp.BarAxis, undefined, "border")); } + @computed get binPrimitives() { let histoResult = this.props.HistoBox.HistogramResult; - if (!histoOp || !histoResult || !histoResult.bins || !this.props.HistoBox.VisualBinRanges.length) + if (!histoResult || !histoResult.bins || !this.props.HistoBox.VisualBinRanges.length) return (null); let allBrushIndex = ModelHelpers.AllBrushIndex(histoResult); return Object.keys(histoResult.bins).reduce((prims, key) => { let drawPrims = new HistogramBinPrimitiveCollection(histoResult!.bins![key], this.props.HistoBox); - let filterModel = ModelHelpers.GetBinFilterModel(histoResult!.bins![key], allBrushIndex, histoResult!, histoOp!.X, histoOp!.Y); + let filterModel = ModelHelpers.GetBinFilterModel(histoResult!.bins![key], allBrushIndex, histoResult!, this.histoOp!.X, this.histoOp!.Y); this.props.HistoBox.HitTargets.setValue(drawPrims.HitGeom, filterModel); - let toggle = this.getSelectionToggle(histoOp!, drawPrims.BinPrimitives, allBrushIndex, filterModel); + let toggle = this.getSelectionToggle(drawPrims.BinPrimitives, allBrushIndex, filterModel); 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, toggle, "bar")))); + 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[]); } + private getSelectionToggle(binPrimitives: HistogramBinPrimitive[], allBrushIndex: number, filterModel: FilterModel) { + let allBrushPrim = ArrayUtil.FirstOrDefault(binPrimitives, bp => bp.BrushIndex == allBrushIndex); + return !allBrushPrim ? () => { } : () => 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) { - let sc = this.props.HistoBox.SizeConverter; - let vb = this.props.HistoBox.VisualBinRanges; - if (!vb.length || !sc.Initialized) + if (!this.props.HistoBox.SizeConverter.Initialized) return (null); - - let prims: JSX.Element[] = []; - let labels = vb[axis].GetLabels(); - labels.map((binLabel, i) => { - let r = sc.DataToScreenRange(binLabel.minValue!, binLabel.maxValue!, axis); - - prims.push(this.drawLine(r.xFrom, r.yFrom, axis == 0 ? 1 : r.xTo - r.xFrom, axis == 0 ? r.yTo - r.yFrom : 1)); + 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 ? 1 : r.xTo - r.xFrom, axis == 0 ? r.yTo - r.yFrom : 1)); - }); - return prims; + 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[]); } + drawEntity(xFrom: number, yFrom: number, entity: JSX.Element) { + let transXpercent = xFrom / this.renderDimension * 100; + let transYpercent = yFrom / this.renderDimension * 100; + return (
+ {entity} +
); + } drawLine(xFrom: number, yFrom: number, width: number, height: number) { if (height < 0) { yFrom += height; @@ -89,46 +85,33 @@ export class HistogramBoxPrimitives extends React.Component -
; + let trans2Xpercent = width == 0 ? `1px` : `${(xFrom + width) / this.renderDimension * 100}%`; + let trans2Ypercent = height == 0 ? `1px` : `${(yFrom + height) / this.renderDimension * 100}%`; + let line = (
); + return this.drawEntity(xFrom, yFrom, line); } - drawRect(r: PIXIRectangle, barAxis: number, color: number | undefined, tapHandler: () => void, classExt: string) { - let widthPercent = (r.width - 0) / this.props.HistoBox.SizeConverter.RenderDimension; - let heightPercent = r.height / this.props.HistoBox.SizeConverter.RenderDimension; - let transXpercent = (r.x) / this.props.HistoBox.SizeConverter.RenderDimension; - let transYpercent = (r.y) / this.props.HistoBox.SizeConverter.RenderDimension; - return (
-
{ if (e.button == 0) tapHandler() }} - style={{ - borderBottomStyle: barAxis == 1 ? "none" : "solid", - borderLeftStyle: barAxis == 0 ? "none" : "solid", - width: `${widthPercent * 100}%`, - height: `${heightPercent * 100}%`, - background: color ? `${LABColor.RGBtoHexString(color)}` : "" - }} - />
); + drawRect(r: PIXIRectangle, barAxis: number, color: number | undefined, classExt: string, tapHandler: () => void = () => { }) { + let widthPercent = r.width / this.renderDimension * 100; + let heightPercent = r.height / this.renderDimension * 100; + let rect = (
{ if (e.button == 0) tapHandler() }} + style={{ + borderBottomStyle: barAxis == 1 ? "none" : "solid", + borderLeftStyle: barAxis == 0 ? "none" : "solid", + width: `${widthPercent}%`, + height: `${heightPercent}%`, + background: color ? `${LABColor.RGBtoHexString(color)}` : "" + }} + />); + return this.drawEntity(r.x, r.y, rect); } render() { - if (!this.props.HistoBox.SizeConverter.Initialized) - return (null); - let xaxislines = this.xaxislines; - let yaxislines = this.yaxislines; return
- {xaxislines} - {yaxislines} + {this.xaxislines} + {this.yaxislines} {this.binPrimitives} {this.selectedPrimitives}
diff --git a/src/client/views/nodes/HistogramLabelPrimitives.scss b/src/client/views/nodes/HistogramLabelPrimitives.scss new file mode 100644 index 000000000..d8ee88d72 --- /dev/null +++ b/src/client/views/nodes/HistogramLabelPrimitives.scss @@ -0,0 +1,12 @@ + + .histogramLabelPrimitives-gridlabel { + position:absolute; + transform-origin: left top; + font-size: 11; + } + .histogramLabelPrimitives-placer { + position:absolute; + width:100%; + height:100%; + pointer-events: none; + } \ No newline at end of file diff --git a/src/client/views/nodes/HistogramLabelPrimitives.tsx b/src/client/views/nodes/HistogramLabelPrimitives.tsx new file mode 100644 index 000000000..7f365e45b --- /dev/null +++ b/src/client/views/nodes/HistogramLabelPrimitives.tsx @@ -0,0 +1,78 @@ +import React = require("react") +import { action, computed, reaction } from "mobx"; +import { observer } from "mobx-react"; +import { Utils as DashUtils } from '../../../Utils'; +import { NominalVisualBinRange } from "../../northstar/model/binRanges/NominalVisualBinRange"; +import { StyleConstants } from "../../northstar/utils/StyleContants"; +import "./../../northstar/utils/Extensions"; +import "./HistogramLabelPrimitives.scss"; +import { HistogramBox, HistogramPrimitivesProps } from "./HistogramBox"; + +@observer +export class HistogramLabelPrimitives extends React.Component { + componentDidMount() { + reaction(() => [this.props.HistoBox.PanelWidth, this.props.HistoBox.SizeConverter.LeftOffset, this.props.HistoBox.VisualBinRanges.length], + (fields) => HistogramLabelPrimitives.computeLabelAngle(fields[0] as number, fields[1] as number, 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.PanelWidth : this.props.HistoBox.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.PanelWidth; + xStart += Math.max(textWidth / 2, (1 - textWidth / space) * textWidth / 2) - textHeight / 2; + } + + let xPercent = axis == 1 ? `${xStart}px` : `${xStart / sc.RenderDimension * 100}%` + let yPercent = axis == 0 ? `${this.props.HistoBox.PanelHeight - sc.BottomOffset - textHeight}px` : `${yStart / sc.RenderDimension * 100}%` + + 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 -- cgit v1.2.3-70-g09d2 From 4704f088af92a8c04a148861c547afa54a276761 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Wed, 27 Mar 2019 19:33:56 -0400 Subject: fixed linking to work with delegates. fixed full screen option and tab dragging bugs. --- src/client/util/DocumentManager.ts | 8 +++++++- .../views/collections/CollectionDockingView.tsx | 22 ++++++++++++---------- .../views/collections/CollectionViewBase.tsx | 2 +- src/client/views/collections/PreviewCursor.tsx | 2 +- src/client/views/nodes/DocumentView.tsx | 21 +++++++++++++-------- src/client/views/nodes/LinkBox.tsx | 2 +- src/fields/Document.ts | 14 ++++++++++++-- 7 files changed, 47 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts index 5b99b4ef8..03df11ad7 100644 --- a/src/client/util/DocumentManager.ts +++ b/src/client/util/DocumentManager.ts @@ -3,6 +3,8 @@ import { observer } from 'mobx-react'; import { observable, action } from 'mobx'; import { Document } from "../../fields/Document" import { DocumentView } from '../views/nodes/DocumentView'; +import { KeyStore } from '../../fields/KeyStore'; +import { FieldWaiting } from '../../fields/Field'; export class DocumentManager { @@ -39,11 +41,15 @@ export class DocumentManager { // } // } + if (Object.is(doc, toFind)) { toReturn = view; return; } - + let docSrc = doc.GetT(KeyStore.Prototype, Document); + if (docSrc && docSrc != FieldWaiting && Object.is(docSrc, toFind)) { + toReturn = view; + } }) return (toReturn); diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index d4f510f5d..b77af8cd6 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -196,15 +196,16 @@ export class CollectionDockingView extends React.Component) => - DragManager.StartDocumentDrag(tab, new DragManager.DocumentDragData(f as Document), - { - handlers: { - dragComplete: action(() => { }), - }, - hideSource: false - })) - ); + Server.GetField(docid, action((f: Opt) => { + if (f instanceof Document) + DragManager.StartDocumentDrag(tab, new DragManager.DocumentDragData(f as Document), + { + handlers: { + dragComplete: action(() => { }), + }, + hideSource: false + }) + })); } if (className == "lm_drag_handle" || className == "lm_close" || className == "lm_maximise" || className == "lm_minimise" || className == "lm_close_tab") { this._flush = true; @@ -224,7 +225,8 @@ export class CollectionDockingView extends React.Component { - tab.titleElement[0].DashDocId = tab.contentItem.config.props.documentId; + if (tab.hasOwnProperty("contentItem") && tab.contentItem.config.type != "stack") + tab.titleElement[0].DashDocId = tab.contentItem.config.props.documentId; tab.closeElement.off('click') //unbind the current click handler .click(function () { tab.contentItem.remove(); diff --git a/src/client/views/collections/CollectionViewBase.tsx b/src/client/views/collections/CollectionViewBase.tsx index adaf810ea..48adce4d8 100644 --- a/src/client/views/collections/CollectionViewBase.tsx +++ b/src/client/views/collections/CollectionViewBase.tsx @@ -133,7 +133,7 @@ export class CollectionViewBase extends React.Component return undefined; } ctor = Documents.WebDocument; - options = { height: options.width, ...options, }; + options = { height: options.width, ...options, title: path }; } return ctor ? ctor(path, options) : undefined; } diff --git a/src/client/views/collections/PreviewCursor.tsx b/src/client/views/collections/PreviewCursor.tsx index 5d621f321..8ae59a83a 100644 --- a/src/client/views/collections/PreviewCursor.tsx +++ b/src/client/views/collections/PreviewCursor.tsx @@ -59,7 +59,7 @@ export class PreviewCursor extends React.Component { if (!e.ctrlKey && !e.altKey && !e.defaultPrevented && !(e as any).DASHFormattedTextBoxHandled) { //make textbox and add it to this collection let [x, y] = this.props.getTransform().transformPoint(this._lastX, this._lastY); - let newBox = Documents.TextDocument({ width: 200, height: 100, x: x, y: y, title: "new" }); + let newBox = Documents.TextDocument({ width: 200, height: 100, x: x, y: y, title: "typed text" }); this.props.addLiveTextDocument(newBox); e.stopPropagation(); } diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 3873a6f89..c31e8b8c4 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -243,15 +243,20 @@ export class DocumentView extends React.Component { } let linkDoc: Document = new Document(); - linkDoc.Set(KeyStore.Title, new TextField("New Link")); - linkDoc.Set(KeyStore.LinkDescription, new TextField("")); - linkDoc.Set(KeyStore.LinkTags, new TextField("Default")); - - sourceDoc.GetOrCreateAsync(KeyStore.LinkedToDocs, ListField, field => { (field as ListField).Data.push(linkDoc) }); - linkDoc.Set(KeyStore.LinkedToDocs, destDoc); - destDoc.GetOrCreateAsync(KeyStore.LinkedFromDocs, ListField, field => { (field as ListField).Data.push(linkDoc) }); - linkDoc.Set(KeyStore.LinkedFromDocs, sourceDoc); + destDoc.GetTAsync(KeyStore.Prototype, Document).then((protoDest) => + sourceDoc.GetTAsync(KeyStore.Prototype, Document).then((protoSrc) => runInAction(() => { + let dstTarg = (protoDest ? protoDest : destDoc); + let srcTarg = (protoSrc ? protoSrc : sourceDoc); + linkDoc.Set(KeyStore.Title, new TextField("New Link")); + linkDoc.Set(KeyStore.LinkDescription, new TextField("")); + linkDoc.Set(KeyStore.LinkTags, new TextField("Default")); + linkDoc.Set(KeyStore.LinkedToDocs, dstTarg); + linkDoc.Set(KeyStore.LinkedFromDocs, srcTarg); + dstTarg.GetOrCreateAsync(KeyStore.LinkedFromDocs, ListField, field => { (field as ListField).Data.push(linkDoc) }) + srcTarg.GetOrCreateAsync(KeyStore.LinkedToDocs, ListField, field => { (field as ListField).Data.push(linkDoc) }) + })) + ) e.stopPropagation(); } } diff --git a/src/client/views/nodes/LinkBox.tsx b/src/client/views/nodes/LinkBox.tsx index 638d3b5a7..457fecee3 100644 --- a/src/client/views/nodes/LinkBox.tsx +++ b/src/client/views/nodes/LinkBox.tsx @@ -41,7 +41,7 @@ export class LinkBox extends React.Component { e.stopPropagation(); let docView = DocumentManager.Instance.getDocumentView(this.props.pairedDoc); if (docView) { - docView.props.focus(this.props.pairedDoc); + docView.props.focus(docView.props.Document); } else { this.props.pairedDoc.GetAsync(KeyStore.AnnotationOn, (contextDoc: any) => { if (!contextDoc) { diff --git a/src/fields/Document.ts b/src/fields/Document.ts index cd393d676..e9192f267 100644 --- a/src/fields/Document.ts +++ b/src/fields/Document.ts @@ -35,8 +35,18 @@ export class Document extends Field { public Scale = () => { return this.GetNumber(KeyStore.Scale, 1) } @computed - public get Title() { - return this.GetText(KeyStore.Title, "-untitled-"); + public get Title(): string { + let title = this.Get(KeyStore.Title, true); + if (title) + if (title != FieldWaiting && title instanceof TextField) + return title.Data; + else return ""; + let parTitle = this.GetT(KeyStore.Title, TextField); + if (parTitle) + if (parTitle != FieldWaiting) + return parTitle.Data + ".alias"; + else return ".alias"; + return "-untitled-"; } @computed -- cgit v1.2.3-70-g09d2 From 5e53c5953d8550dcf4aa6ad87cd0f68fd835bd14 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Wed, 27 Mar 2019 19:52:49 -0400 Subject: fixed tab titles of docking view --- src/client/views/collections/CollectionDockingView.tsx | 16 +++++++++++++++- src/fields/Document.ts | 4 ++-- 2 files changed, 17 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index b77af8cd6..f123149dd 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -18,6 +18,7 @@ import React = require("react"); import { SubCollectionViewProps } from "./CollectionViewBase"; import { ServerUtils } from "../../../server/ServerUtil"; import { DragManager } from "../../util/DragManager"; +import { TextField } from "../../../fields/TextField"; @observer export class CollectionDockingView extends React.Component { @@ -225,8 +226,21 @@ export class CollectionDockingView extends React.Component { - if (tab.hasOwnProperty("contentItem") && tab.contentItem.config.type != "stack") + if (tab.hasOwnProperty("contentItem") && tab.contentItem.config.type != "stack") { + if (tab.titleElement[0].textContent.indexOf("-waiting") != -1) { + Server.GetField(tab.contentItem.config.props.documentId, action((f: Opt) => { + if (f != undefined && f instanceof Document) { + f.GetTAsync(KeyStore.Title, TextField, (tfield) => { + if (tfield != undefined) { + tab.titleElement[0].textContent = f.Title; + } + }) + } + })); + tab.titleElement[0].DashDocId = tab.contentItem.config.props.documentId; + } tab.titleElement[0].DashDocId = tab.contentItem.config.props.documentId; + } tab.closeElement.off('click') //unbind the current click handler .click(function () { tab.contentItem.remove(); diff --git a/src/fields/Document.ts b/src/fields/Document.ts index e9192f267..85ff6ddcb 100644 --- a/src/fields/Document.ts +++ b/src/fields/Document.ts @@ -40,12 +40,12 @@ export class Document extends Field { if (title) if (title != FieldWaiting && title instanceof TextField) return title.Data; - else return ""; + else return "-waiting-"; let parTitle = this.GetT(KeyStore.Title, TextField); if (parTitle) if (parTitle != FieldWaiting) return parTitle.Data + ".alias"; - else return ".alias"; + else return "-waiting-.alias"; return "-untitled-"; } -- cgit v1.2.3-70-g09d2 From 510c26bb46cb8b70cc3fad756396f39a8b7fd687 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Wed, 27 Mar 2019 20:14:37 -0400 Subject: addressed contextmenu issues (partially off screen and duplicate entries) and got rid of KeyStore.ActiveFrame --- src/client/views/ContextMenu.tsx | 9 +++------ src/client/views/Main.tsx | 8 +++----- src/fields/KeyStore.ts | 1 - 3 files changed, 6 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/client/views/ContextMenu.tsx b/src/client/views/ContextMenu.tsx index 9109b56bb..cfa8ea7b7 100644 --- a/src/client/views/ContextMenu.tsx +++ b/src/client/views/ContextMenu.tsx @@ -49,7 +49,7 @@ export class ContextMenu extends React.Component { //maxX and maxY will change if the UI/font size changes, but will work for any amount //of items added to the menu let maxX = window.innerWidth - 150; - let maxY = window.innerHeight - (this._items.length * 34 + 30); + let maxY = window.innerHeight - ((this._items.length + 1/*for search box*/) * 34 + 30); this._pageX = x > maxX ? maxX : x; this._pageY = y > maxY ? maxY : y; @@ -83,11 +83,8 @@ export class ContextMenu extends React.Component { return (
- {this._items.filter(prop => { - return prop.description.toLowerCase().indexOf(this._searchString.toLowerCase()) !== -1; - }).map(prop => { - return - })} + {this._items.filter(prop => prop.description.toLowerCase().indexOf(this._searchString.toLowerCase()) !== -1). + map(prop => )}
) } diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index 87d8eb648..09778ac77 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -147,6 +147,7 @@ export class Main extends React.Component { if (!CurrentUserUtils.MainDocId) { this.userDocument.GetTAsync(KeyStore.ActiveWorkspace, Document).then(doc => { if (doc) { + CurrentUserUtils.MainDocId = doc.Id; this.openWorkspace(doc); } else { this.createNewWorkspace(); @@ -171,9 +172,9 @@ export class Main extends React.Component { var dockingLayout = { content: [{ type: 'row', content: [CollectionDockingView.makeDocumentConfig(freeformDoc)] }] }; let mainDoc = Documents.DockDocument(JSON.stringify(dockingLayout), { title: `Main Container ${list.Data.length + 1}` }, id); list.Data.push(mainDoc); + CurrentUserUtils.MainDocId = mainDoc.Id; // bcz: strangely, we need a timeout to prevent exceptions/issues initializing GoldenLayout (the rendering engine for Main Container) setTimeout(() => { - mainDoc.Set(KeyStore.ActiveFrame, freeformDoc); this.openWorkspace(mainDoc); let pendingDocument = Documents.SchemaDocument([], { title: "New Mobile Uploads" }) mainDoc.Set(KeyStore.OptionalRightCollection, pendingDocument); @@ -186,7 +187,6 @@ export class Main extends React.Component { openWorkspace = (doc: Document, fromHistory = false): void => { this.mainContainer = doc; fromHistory || window.history.pushState(null, doc.Title, "/doc/" + doc.Id); - this.mainContainer.GetTAsync(KeyStore.ActiveFrame, Document, field => this.mainfreeform = field); this.userDocument.GetTAsync(KeyStore.OptionalRightCollection, Document).then(col => { // if there is a pending doc, and it has new data, show it (syip: we use a timeout to prevent collection docking view from being uninitialized) setTimeout(() => { @@ -264,8 +264,6 @@ export class Main extends React.Component { [React.createRef(), "table", "Add Schema", addSchemaNode], ] - let addClick = (creator: () => Document) => action(() => this.mainfreeform!.GetList(KeyStore.Data, []).push(creator())); - return < div id="add-nodes-menu" > @@ -274,7 +272,7 @@ export class Main extends React.Component {
    {btns.map(btn =>
  • -
  • )} diff --git a/src/fields/KeyStore.ts b/src/fields/KeyStore.ts index 20e8cd930..09dddf962 100644 --- a/src/fields/KeyStore.ts +++ b/src/fields/KeyStore.ts @@ -27,7 +27,6 @@ export namespace KeyStore { export const ColumnsKey = new Key("SchemaColumns"); export const SchemaSplitPercentage = new Key("SchemaSplitPercentage"); export const Caption = new Key("Caption"); - export const ActiveFrame = new Key("ActiveFrame"); export const ActiveWorkspace = new Key("ActiveWorkspace"); export const DocumentText = new Key("DocumentText"); export const LinkedToDocs = new Key("LinkedToDocs"); -- cgit v1.2.3-70-g09d2 From f6c6220d92b8556615f3c17463ca5b0c7452b439 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 28 Mar 2019 00:27:36 -0400 Subject: placeholder for drawing links. --- .../views/nodes/CollectionFreeFormDocumentView.tsx | 42 +++++++++++++++++++++- src/client/views/nodes/DocumentView.tsx | 6 ++-- 2 files changed, 45 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx index 50dc5a619..ed3468400 100644 --- a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx +++ b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx @@ -1,4 +1,4 @@ -import { computed, trace } from "mobx"; +import { computed, trace, reaction, runInAction, observable } from "mobx"; import { observer } from "mobx-react"; import { KeyStore } from "../../../fields/KeyStore"; import { NumberField } from "../../../fields/NumberField"; @@ -6,6 +6,8 @@ import { Transform } from "../../util/Transform"; import { DocumentView, DocumentViewProps } from "./DocumentView"; import "./DocumentView.scss"; import React = require("react"); +import { Document } from "../../../fields/Document"; +import { DocumentManager } from "../../util/DocumentManager"; @observer @@ -67,8 +69,46 @@ export class CollectionFreeFormDocumentView extends React.Component } + @observable _docView1: DocumentView | null = null; + @observable _docView2: DocumentView | null = null; + + componentDidMount() { + reaction(() => { + let linkFrom = this.props.Document.GetT(KeyStore.LinkedFromDocs, Document); + let linkTo = this.props.Document.GetT(KeyStore.LinkedToDocs, Document); + let docView1: DocumentView | null = null; + let docView2: DocumentView | null = null; + if (linkFrom instanceof Document && linkTo instanceof Document) { + docView1 = DocumentManager.Instance.getDocumentView(linkFrom); + docView2 = DocumentManager.Instance.getDocumentView(linkTo); + } + return [docView1, docView2]; + }, (vals) => runInAction(() => { + this._docView1 = vals[0]; + this._docView2 = vals[1]; + }), { fireImmediately: true }); + } render() { + if (this._docView1 != null && this._docView2 != null) { + let doc1 = this._docView1.props.Document; + let doc2 = this._docView2.props.Document; + let x1 = doc1.GetNumber(KeyStore.X, 0) + doc1.GetNumber(KeyStore.Width, 0) / 2; + let y1 = doc1.GetNumber(KeyStore.Y, 0) + doc1.GetNumber(KeyStore.Height, 0) / 2; + let x2 = doc2.GetNumber(KeyStore.X, 0) + doc2.GetNumber(KeyStore.Width, 0) / 2; + let y2 = doc2.GetNumber(KeyStore.Y, 0) + doc2.GetNumber(KeyStore.Height, 0) / 2; + let lx = Math.min(x1, x2); + let ly = Math.min(y1, y2); + let w = Math.max(x1, x2) - lx; + let h = Math.max(y1, y2) - ly; + let unflipped = (x1 == lx && y1 == ly) || (x2 == lx && y2 == ly); + return ( +
    + + + +
    ); + } return (
    { destDoc.GetTAsync(KeyStore.Prototype, Document).then((protoDest) => sourceDoc.GetTAsync(KeyStore.Prototype, Document).then((protoSrc) => runInAction(() => { - let dstTarg = (protoDest ? protoDest : destDoc); - let srcTarg = (protoSrc ? protoSrc : sourceDoc); linkDoc.Set(KeyStore.Title, new TextField("New Link")); linkDoc.Set(KeyStore.LinkDescription, new TextField("")); linkDoc.Set(KeyStore.LinkTags, new TextField("Default")); + let dstTarg = (protoDest ? protoDest : destDoc); + let srcTarg = (protoSrc ? protoSrc : sourceDoc); linkDoc.Set(KeyStore.LinkedToDocs, dstTarg); linkDoc.Set(KeyStore.LinkedFromDocs, srcTarg); dstTarg.GetOrCreateAsync(KeyStore.LinkedFromDocs, ListField, field => { (field as ListField).Data.push(linkDoc) }) srcTarg.GetOrCreateAsync(KeyStore.LinkedToDocs, ListField, field => { (field as ListField).Data.push(linkDoc) }) + if (this.props.AddDocument) + this.props.AddDocument(linkDoc, false); })) ) e.stopPropagation(); -- cgit v1.2.3-70-g09d2 From b2558d67608ae20f291c6a1fdbaf1ed09b8c91d2 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 28 Mar 2019 10:04:28 -0400 Subject: made links show up on collections --- src/client/util/DocumentManager.ts | 27 ++++++-- .../views/collections/CollectionFreeFormView.tsx | 72 ++++++++++++++++++++-- .../views/nodes/CollectionFreeFormDocumentView.tsx | 38 ------------ src/client/views/nodes/DocumentView.tsx | 2 - 4 files changed, 89 insertions(+), 50 deletions(-) (limited to 'src') diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts index 03df11ad7..5bc16343e 100644 --- a/src/client/util/DocumentManager.ts +++ b/src/client/util/DocumentManager.ts @@ -35,12 +35,6 @@ export class DocumentManager { DocumentManager.Instance.DocumentViews.map(view => { let doc = view.props.Document; // if (view.props.ContainingCollectionView instanceof CollectionFreeFormView) { - // if (Object.is(doc, toFind)) { - // toReturn = view; - // return; - // } - // } - if (Object.is(doc, toFind)) { toReturn = view; @@ -52,6 +46,27 @@ export class DocumentManager { } }) + return (toReturn); + } + public getDocumentViews(toFind: Document): DocumentView[] { + + let toReturn: DocumentView[] = []; + + //gets document view that is in a freeform canvas collection + DocumentManager.Instance.DocumentViews.map(view => { + let doc = view.props.Document; + // if (view.props.ContainingCollectionView instanceof CollectionFreeFormView) { + + if (Object.is(doc, toFind)) { + toReturn.push(view); + } else { + let docSrc = doc.GetT(KeyStore.Prototype, Document); + if (docSrc && docSrc != FieldWaiting && Object.is(docSrc, toFind)) { + toReturn.push(view); + } + } + }) + return (toReturn); } } \ No newline at end of file diff --git a/src/client/views/collections/CollectionFreeFormView.tsx b/src/client/views/collections/CollectionFreeFormView.tsx index 1eab3e475..d75c53b7e 100644 --- a/src/client/views/collections/CollectionFreeFormView.tsx +++ b/src/client/views/collections/CollectionFreeFormView.tsx @@ -1,7 +1,7 @@ -import { action, computed, observable } from "mobx"; +import { action, computed, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../../fields/Document"; -import { FieldWaiting } from "../../../fields/Field"; +import { FieldWaiting, Field } from "../../../fields/Field"; import { KeyStore } from "../../../fields/KeyStore"; import { ListField } from "../../../fields/ListField"; import { TextField } from "../../../fields/TextField"; @@ -11,14 +11,16 @@ import { undoBatch } from "../../util/UndoManager"; import { InkingCanvas } from "../InkingCanvas"; import { CollectionFreeFormDocumentView } from "../nodes/CollectionFreeFormDocumentView"; import { DocumentContentsView } from "../nodes/DocumentContentsView"; -import { DocumentViewProps } from "../nodes/DocumentView"; +import { DocumentViewProps, DocumentView } from "../nodes/DocumentView"; import "./CollectionFreeFormView.scss"; import { COLLECTION_BORDER_WIDTH } from "./CollectionView"; -import { CollectionViewBase } from "./CollectionViewBase"; +import { CollectionViewBase, CollectionViewProps } from "./CollectionViewBase"; import { MarqueeView } from "./MarqueeView"; import { PreviewCursor } from "./PreviewCursor"; import React = require("react"); import v5 = require("uuid/v5"); +import { DocumentManager } from "../../util/DocumentManager"; +import { Utils } from "../../../Utils"; @observer export class CollectionFreeFormView extends CollectionViewBase { @@ -360,6 +362,7 @@ export class CollectionFreeFormView extends CollectionViewBase { {this.views} + {super.getCursors().map(entry => { if (entry.Data.length > 0) { let id = entry.Data[0][0]; @@ -411,4 +414,65 @@ export class CollectionFreeFormView extends CollectionViewBase {
    ); } +} + +@observer +export class LinksView extends React.Component { + private _mainCont = React.createRef(); + + constructor(props: CollectionViewProps) { + super(props); + } + + @observable _pairs: { a: DocumentView, b: DocumentView }[] = []; + + findPairs() { + return DocumentManager.Instance.DocumentViews.filter(dv => dv.props.ContainingCollectionView && dv.props.ContainingCollectionView.props.Document === this.props.Document).reduce((pairs, dv) => { + let linksList = dv.props.Document.GetT(KeyStore.LinkedToDocs, ListField); + if (linksList && linksList != FieldWaiting && linksList.Data.length) { + pairs.push(...linksList.Data.reduce((pairs, link) => { + if (link instanceof Document) { + let linkToDoc = link.GetT(KeyStore.LinkedToDocs, Document); + if (linkToDoc && linkToDoc != FieldWaiting) { + DocumentManager.Instance.getDocumentViews(linkToDoc).map(docView1 => + pairs.push({ a: dv, b: docView1 }) + ) + } + } + return pairs; + }, [] as { a: DocumentView, b: DocumentView }[])); + } + return pairs; + }, [] as { a: DocumentView, b: DocumentView }[]); + } + componentDidMount() { + reaction(() => this.findPairs() + , (pairs) => runInAction(() => this._pairs = pairs)); + } + + render() { + if (!this._pairs.length) + return (null); + return
    + {this._pairs.map(pair => { + let doc1 = pair.a.props.Document; + let doc2 = pair.b.props.Document; + let x1 = doc1.GetNumber(KeyStore.X, 0) + doc1.GetNumber(KeyStore.Width, 0) / 2; + let y1 = doc1.GetNumber(KeyStore.Y, 0) + doc1.GetNumber(KeyStore.Height, 0) / 2; + let x2 = doc2.GetNumber(KeyStore.X, 0) + doc2.GetNumber(KeyStore.Width, 0) / 2; + let y2 = doc2.GetNumber(KeyStore.Y, 0) + doc2.GetNumber(KeyStore.Height, 0) / 2; + let lx = Math.min(x1, x2); + let ly = Math.min(y1, y2); + let w = Math.max(x1, x2) - lx; + let h = Math.max(y1, y2) - ly; + let unflipped = (x1 == lx && y1 == ly) || (x2 == lx && y2 == ly); + return ( +
    + + + +
    ); + })} +
    + } } \ No newline at end of file diff --git a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx index ed3468400..7f951864e 100644 --- a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx +++ b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx @@ -69,46 +69,8 @@ export class CollectionFreeFormDocumentView extends React.Component } - @observable _docView1: DocumentView | null = null; - @observable _docView2: DocumentView | null = null; - - componentDidMount() { - reaction(() => { - let linkFrom = this.props.Document.GetT(KeyStore.LinkedFromDocs, Document); - let linkTo = this.props.Document.GetT(KeyStore.LinkedToDocs, Document); - let docView1: DocumentView | null = null; - let docView2: DocumentView | null = null; - if (linkFrom instanceof Document && linkTo instanceof Document) { - docView1 = DocumentManager.Instance.getDocumentView(linkFrom); - docView2 = DocumentManager.Instance.getDocumentView(linkTo); - } - return [docView1, docView2]; - }, (vals) => runInAction(() => { - this._docView1 = vals[0]; - this._docView2 = vals[1]; - }), { fireImmediately: true }); - } render() { - if (this._docView1 != null && this._docView2 != null) { - let doc1 = this._docView1.props.Document; - let doc2 = this._docView2.props.Document; - let x1 = doc1.GetNumber(KeyStore.X, 0) + doc1.GetNumber(KeyStore.Width, 0) / 2; - let y1 = doc1.GetNumber(KeyStore.Y, 0) + doc1.GetNumber(KeyStore.Height, 0) / 2; - let x2 = doc2.GetNumber(KeyStore.X, 0) + doc2.GetNumber(KeyStore.Width, 0) / 2; - let y2 = doc2.GetNumber(KeyStore.Y, 0) + doc2.GetNumber(KeyStore.Height, 0) / 2; - let lx = Math.min(x1, x2); - let ly = Math.min(y1, y2); - let w = Math.max(x1, x2) - lx; - let h = Math.max(y1, y2) - ly; - let unflipped = (x1 == lx && y1 == ly) || (x2 == lx && y2 == ly); - return ( -
    - - - -
    ); - } return (
    { linkDoc.Set(KeyStore.LinkedFromDocs, srcTarg); dstTarg.GetOrCreateAsync(KeyStore.LinkedFromDocs, ListField, field => { (field as ListField).Data.push(linkDoc) }) srcTarg.GetOrCreateAsync(KeyStore.LinkedToDocs, ListField, field => { (field as ListField).Data.push(linkDoc) }) - if (this.props.AddDocument) - this.props.AddDocument(linkDoc, false); })) ) e.stopPropagation(); -- cgit v1.2.3-70-g09d2 From cbf88ae3466e17fef57c7d63cc72ee42b75ccce6 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 28 Mar 2019 10:36:03 -0400 Subject: cleaned up --- .../views/collections/CollectionFreeFormView.scss | 17 ++++++++++ .../views/collections/CollectionFreeFormView.tsx | 39 +++++++++------------- 2 files changed, 32 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/client/views/collections/CollectionFreeFormView.scss b/src/client/views/collections/CollectionFreeFormView.scss index bdc597a25..2dd345b6f 100644 --- a/src/client/views/collections/CollectionFreeFormView.scss +++ b/src/client/views/collections/CollectionFreeFormView.scss @@ -1,5 +1,22 @@ @import "../global_variables"; +.collectionfreeformview-linkLine { + stroke: black; + stroke-width: 3; + transform: translate(10000px,10000px) +} +.collectionfreeformview-svgContainer{ + transform: translate(-10000px,-10000px); + position: absolute; + width: 20000px; + height: 20000px; +} +.collectionfreeformview-svgCanvas{ + transform: translate(-10000px,-10000px); + position: absolute; + width: 20000px; + height: 20000px; +} .collectionfreeformview-container { .collectionfreeformview > .jsx-parser { position: absolute; diff --git a/src/client/views/collections/CollectionFreeFormView.tsx b/src/client/views/collections/CollectionFreeFormView.tsx index d75c53b7e..cba1110a1 100644 --- a/src/client/views/collections/CollectionFreeFormView.tsx +++ b/src/client/views/collections/CollectionFreeFormView.tsx @@ -424,7 +424,7 @@ export class LinksView extends React.Component { super(props); } - @observable _pairs: { a: DocumentView, b: DocumentView }[] = []; + @observable _pairs: { a: Document, b: Document }[] = []; findPairs() { return DocumentManager.Instance.DocumentViews.filter(dv => dv.props.ContainingCollectionView && dv.props.ContainingCollectionView.props.Document === this.props.Document).reduce((pairs, dv) => { @@ -435,44 +435,35 @@ export class LinksView extends React.Component { let linkToDoc = link.GetT(KeyStore.LinkedToDocs, Document); if (linkToDoc && linkToDoc != FieldWaiting) { DocumentManager.Instance.getDocumentViews(linkToDoc).map(docView1 => - pairs.push({ a: dv, b: docView1 }) + pairs.push({ a: dv.props.Document, b: docView1.props.Document }) ) } } return pairs; - }, [] as { a: DocumentView, b: DocumentView }[])); + }, [] as { a: Document, b: Document }[])); } return pairs; - }, [] as { a: DocumentView, b: DocumentView }[]); + }, [] as { a: Document, b: Document }[]); } componentDidMount() { - reaction(() => this.findPairs() - , (pairs) => runInAction(() => this._pairs = pairs)); + reaction(() => this.findPairs(), (pairs) => runInAction(() => this._pairs = pairs)); } render() { if (!this._pairs.length) return (null); - return
    + return {this._pairs.map(pair => { - let doc1 = pair.a.props.Document; - let doc2 = pair.b.props.Document; - let x1 = doc1.GetNumber(KeyStore.X, 0) + doc1.GetNumber(KeyStore.Width, 0) / 2; - let y1 = doc1.GetNumber(KeyStore.Y, 0) + doc1.GetNumber(KeyStore.Height, 0) / 2; - let x2 = doc2.GetNumber(KeyStore.X, 0) + doc2.GetNumber(KeyStore.Width, 0) / 2; - let y2 = doc2.GetNumber(KeyStore.Y, 0) + doc2.GetNumber(KeyStore.Height, 0) / 2; - let lx = Math.min(x1, x2); - let ly = Math.min(y1, y2); - let w = Math.max(x1, x2) - lx; - let h = Math.max(y1, y2) - ly; - let unflipped = (x1 == lx && y1 == ly) || (x2 == lx && y2 == ly); + let x1 = pair.a.GetNumber(KeyStore.X, 0) + pair.a.GetNumber(KeyStore.Width, 0) / 2; + let y1 = pair.a.GetNumber(KeyStore.Y, 0) + pair.a.GetNumber(KeyStore.Height, 0) / 2; + let x2 = pair.b.GetNumber(KeyStore.X, 0) + pair.b.GetNumber(KeyStore.Width, 0) / 2; + let y2 = pair.b.GetNumber(KeyStore.Y, 0) + pair.b.GetNumber(KeyStore.Height, 0) / 2; return ( -
    - - - -
    ); + + ) })} -
    + } } \ No newline at end of file -- cgit v1.2.3-70-g09d2 From fddd13da196a26affe61b30d93a3fe1b24f391a6 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 28 Mar 2019 12:59:35 -0400 Subject: works better with prototypes and links --- src/client/util/DocumentManager.ts | 5 ++ .../views/collections/CollectionFreeFormView.tsx | 53 +++++++++++++++++----- src/client/views/collections/CollectionView.tsx | 4 +- src/client/views/nodes/LinkBox.tsx | 2 +- 4 files changed, 50 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts index 5bc16343e..28624dba8 100644 --- a/src/client/util/DocumentManager.ts +++ b/src/client/util/DocumentManager.ts @@ -26,6 +26,11 @@ export class DocumentManager { // this.DocumentViews = new Array(); } + public getAllDocumentViews(collection: Document) { + return this.DocumentViews.filter(dv => + dv.props.ContainingCollectionView && dv.props.ContainingCollectionView.props.Document == collection); + } + public getDocumentView(toFind: Document): DocumentView | null { let toReturn: DocumentView | null; diff --git a/src/client/views/collections/CollectionFreeFormView.tsx b/src/client/views/collections/CollectionFreeFormView.tsx index cba1110a1..0843d3670 100644 --- a/src/client/views/collections/CollectionFreeFormView.tsx +++ b/src/client/views/collections/CollectionFreeFormView.tsx @@ -1,7 +1,7 @@ import { action, computed, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../../fields/Document"; -import { FieldWaiting, Field } from "../../../fields/Field"; +import { FieldWaiting, Field, Opt } from "../../../fields/Field"; import { KeyStore } from "../../../fields/KeyStore"; import { ListField } from "../../../fields/ListField"; import { TextField } from "../../../fields/TextField"; @@ -21,6 +21,8 @@ import React = require("react"); import v5 = require("uuid/v5"); import { DocumentManager } from "../../util/DocumentManager"; import { Utils } from "../../../Utils"; +import { Server } from "../../Server"; +import { AverageAggregateParameters } from "../../northstar/model/idea/idea"; @observer export class CollectionFreeFormView extends CollectionViewBase { @@ -424,42 +426,71 @@ export class LinksView extends React.Component { super(props); } - @observable _pairs: { a: Document, b: Document }[] = []; + @observable _triples: { a: Document, b: Document, l: Document }[] = []; findPairs() { return DocumentManager.Instance.DocumentViews.filter(dv => dv.props.ContainingCollectionView && dv.props.ContainingCollectionView.props.Document === this.props.Document).reduce((pairs, dv) => { + + return DocumentManager.Instance.DocumentViews.reduce((pairs, dv) => { + let srcViews = [dv]; + let srcAnnot = dv.props.Document.GetT(KeyStore.AnnotationOn, Document); + if (srcAnnot && srcAnnot != FieldWaiting && srcAnnot instanceof Document) { + srcViews = DocumentManager.Instance.getDocumentViews(srcAnnot.GetPrototype() as Document) + } + srcViews = srcViews.filter(sv => + sv.props.ContainingCollectionView && sv.props.ContainingCollectionView.props.Document == self + ); let linksList = dv.props.Document.GetT(KeyStore.LinkedToDocs, ListField); if (linksList && linksList != FieldWaiting && linksList.Data.length) { pairs.push(...linksList.Data.reduce((pairs, link) => { if (link instanceof Document) { let linkToDoc = link.GetT(KeyStore.LinkedToDocs, Document); if (linkToDoc && linkToDoc != FieldWaiting) { - DocumentManager.Instance.getDocumentViews(linkToDoc).map(docView1 => - pairs.push({ a: dv.props.Document, b: docView1.props.Document }) - ) + DocumentManager.Instance.getDocumentViews(linkToDoc).map(docView1 => { + + let targetViews = [docView1]; + let docAnnot = docView1.props.Document.GetT(KeyStore.AnnotationOn, Document); + if (docAnnot && docAnnot != FieldWaiting && docAnnot instanceof Document) { + targetViews = DocumentManager.Instance.getDocumentViews(docAnnot.GetPrototype() as Document) + } + targetViews.filter(tv => + tv.props.ContainingCollectionView && tv.props.ContainingCollectionView.props.Document == self + ).map(tv => srcViews.map(sv => + pairs.push({ a: sv.props.Document, b: tv.props.Document, l: link }))) + }) } } return pairs; - }, [] as { a: Document, b: Document }[])); + }, [] as { a: Document, b: Document, l: Document }[])); } return pairs; - }, [] as { a: Document, b: Document }[]); + }, [] as { a: Document, b: Document, l: Document }[]); } componentDidMount() { - reaction(() => this.findPairs(), (pairs) => runInAction(() => this._pairs = pairs)); + reaction(() => this.findPairs(), (pairs) => runInAction(() => this._triples = pairs)); + } + + onPointerDown(e: React.PointerEvent) { + let line = (e.nativeEvent as any).path[0]; + line.style.stroke = "red"; + Server.GetField(line.id, action((f: Opt) => { + if (f instanceof Document) { + console.log(f.Title); + } + })); } render() { - if (!this._pairs.length) + if (!this._triples.length) return (null); return - {this._pairs.map(pair => { + {this._triples.map(pair => { let x1 = pair.a.GetNumber(KeyStore.X, 0) + pair.a.GetNumber(KeyStore.Width, 0) / 2; let y1 = pair.a.GetNumber(KeyStore.Y, 0) + pair.a.GetNumber(KeyStore.Height, 0) / 2; let x2 = pair.b.GetNumber(KeyStore.X, 0) + pair.b.GetNumber(KeyStore.Width, 0) / 2; let y2 = pair.b.GetNumber(KeyStore.Y, 0) + pair.b.GetNumber(KeyStore.Height, 0) / 2; return ( - ) diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 2fa2c9086..789f07e8c 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -69,9 +69,9 @@ export class CollectionView extends React.Component { @action public static AddDocument(props: CollectionViewProps, doc: Document, allowDuplicates: boolean): boolean { var curPage = props.Document.GetNumber(KeyStore.CurPage, -1); - doc.SetNumber(KeyStore.Page, curPage); + doc.SetOnPrototype(KeyStore.Page, new NumberField(curPage)); if (curPage > 0) { - doc.Set(KeyStore.AnnotationOn, props.Document); + doc.SetOnPrototype(KeyStore.AnnotationOn, props.Document); } if (props.Document.Get(props.fieldKey) instanceof Field) { //TODO This won't create the field if it doesn't already exist diff --git a/src/client/views/nodes/LinkBox.tsx b/src/client/views/nodes/LinkBox.tsx index 457fecee3..e81f8fec7 100644 --- a/src/client/views/nodes/LinkBox.tsx +++ b/src/client/views/nodes/LinkBox.tsx @@ -45,7 +45,7 @@ export class LinkBox extends React.Component { } else { this.props.pairedDoc.GetAsync(KeyStore.AnnotationOn, (contextDoc: any) => { if (!contextDoc) { - CollectionDockingView.Instance.AddRightSplit(this.props.pairedDoc); + CollectionDockingView.Instance.AddRightSplit(this.props.pairedDoc.MakeDelegate()); } else if (contextDoc instanceof Document) { this.props.pairedDoc.GetTAsync(KeyStore.Page, NumberField).then((pfield: any) => { contextDoc.GetTAsync(KeyStore.CurPage, NumberField).then((cfield: any) => { -- cgit v1.2.3-70-g09d2 From e64ec4345b8403347e86ac8c472507343f6b7548 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 28 Mar 2019 13:00:03 -0400 Subject: from last --- src/client/views/collections/CollectionFreeFormView.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/client/views/collections/CollectionFreeFormView.tsx b/src/client/views/collections/CollectionFreeFormView.tsx index 0843d3670..5ce42acc9 100644 --- a/src/client/views/collections/CollectionFreeFormView.tsx +++ b/src/client/views/collections/CollectionFreeFormView.tsx @@ -429,7 +429,7 @@ export class LinksView extends React.Component { @observable _triples: { a: Document, b: Document, l: Document }[] = []; findPairs() { - return DocumentManager.Instance.DocumentViews.filter(dv => dv.props.ContainingCollectionView && dv.props.ContainingCollectionView.props.Document === this.props.Document).reduce((pairs, dv) => { + let self = this.props.Document; return DocumentManager.Instance.DocumentViews.reduce((pairs, dv) => { let srcViews = [dv]; -- cgit v1.2.3-70-g09d2 From bdea88507ce2ba4da32b7f89c995021d0a058413 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 28 Mar 2019 15:24:57 -0400 Subject: fixed some things with linking. still some real inefficiencies. --- src/client/documents/Documents.ts | 1 + .../views/collections/CollectionFreeFormView.scss | 10 +-- .../views/collections/CollectionFreeFormView.tsx | 87 ++++++++++++++-------- src/client/views/collections/CollectionView.tsx | 2 +- 4 files changed, 59 insertions(+), 41 deletions(-) (limited to 'src') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 1d23b8c2c..837dfe815 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -119,6 +119,7 @@ export namespace Documents { imageProto = setupPrototypeOptions(imageProtoId, "IMAGE_PROTO", CollectionView.LayoutString("AnnotationsKey"), { x: 0, y: 0, nativeWidth: 300, width: 300, layoutKeys: [KeyStore.Data, KeyStore.Annotations, KeyStore.Caption] }); imageProto.SetText(KeyStore.BackgroundLayout, ImageBox.LayoutString()); + imageProto.SetNumber(KeyStore.CurPage, 0); } return imageProto; } diff --git a/src/client/views/collections/CollectionFreeFormView.scss b/src/client/views/collections/CollectionFreeFormView.scss index 2dd345b6f..7012ce6b9 100644 --- a/src/client/views/collections/CollectionFreeFormView.scss +++ b/src/client/views/collections/CollectionFreeFormView.scss @@ -3,19 +3,15 @@ .collectionfreeformview-linkLine { stroke: black; stroke-width: 3; - transform: translate(10000px,10000px) -} -.collectionfreeformview-svgContainer{ - transform: translate(-10000px,-10000px); - position: absolute; - width: 20000px; - height: 20000px; + transform: translate(10000px,10000px); + pointer-events: all; } .collectionfreeformview-svgCanvas{ transform: translate(-10000px,-10000px); position: absolute; width: 20000px; height: 20000px; + pointer-events: none; } .collectionfreeformview-container { .collectionfreeformview > .jsx-parser { diff --git a/src/client/views/collections/CollectionFreeFormView.tsx b/src/client/views/collections/CollectionFreeFormView.tsx index 5ce42acc9..91faf0907 100644 --- a/src/client/views/collections/CollectionFreeFormView.tsx +++ b/src/client/views/collections/CollectionFreeFormView.tsx @@ -1,4 +1,4 @@ -import { action, computed, observable, reaction, runInAction } from "mobx"; +import { action, computed, observable, reaction, runInAction, trace, untracked } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../../fields/Document"; import { FieldWaiting, Field, Opt } from "../../../fields/Field"; @@ -424,6 +424,7 @@ export class LinksView extends React.Component { constructor(props: CollectionViewProps) { super(props); + console.log("Create links View"); } @observable _triples: { a: Document, b: Document, l: Document }[] = []; @@ -432,42 +433,47 @@ export class LinksView extends React.Component { let self = this.props.Document; return DocumentManager.Instance.DocumentViews.reduce((pairs, dv) => { - let srcViews = [dv]; - let srcAnnot = dv.props.Document.GetT(KeyStore.AnnotationOn, Document); - if (srcAnnot && srcAnnot != FieldWaiting && srcAnnot instanceof Document) { - srcViews = DocumentManager.Instance.getDocumentViews(srcAnnot.GetPrototype() as Document) - } - srcViews = srcViews.filter(sv => - sv.props.ContainingCollectionView && sv.props.ContainingCollectionView.props.Document == self - ); - let linksList = dv.props.Document.GetT(KeyStore.LinkedToDocs, ListField); - if (linksList && linksList != FieldWaiting && linksList.Data.length) { - pairs.push(...linksList.Data.reduce((pairs, link) => { - if (link instanceof Document) { - let linkToDoc = link.GetT(KeyStore.LinkedToDocs, Document); - if (linkToDoc && linkToDoc != FieldWaiting) { - DocumentManager.Instance.getDocumentViews(linkToDoc).map(docView1 => { - - let targetViews = [docView1]; - let docAnnot = docView1.props.Document.GetT(KeyStore.AnnotationOn, Document); - if (docAnnot && docAnnot != FieldWaiting && docAnnot instanceof Document) { - targetViews = DocumentManager.Instance.getDocumentViews(docAnnot.GetPrototype() as Document) - } - targetViews.filter(tv => - tv.props.ContainingCollectionView && tv.props.ContainingCollectionView.props.Document == self - ).map(tv => srcViews.map(sv => - pairs.push({ a: sv.props.Document, b: tv.props.Document, l: link }))) - }) + untracked(() => { + let srcViews = [dv]; + let srcAnnot = dv.props.Document.GetT(KeyStore.AnnotationOn, Document); + if (srcAnnot && srcAnnot != FieldWaiting && srcAnnot instanceof Document) { + srcViews = DocumentManager.Instance.getDocumentViews(srcAnnot.GetPrototype() as Document) + } + srcViews = srcViews.filter(sv => + sv.props.ContainingCollectionView && sv.props.ContainingCollectionView.props.Document == self + ); + let linksList = dv.props.Document.GetT(KeyStore.LinkedToDocs, ListField); + if (linksList && linksList != FieldWaiting && linksList.Data.length) { + pairs.push(...linksList.Data.reduce((pairs, link) => { + if (link instanceof Document) { + let linkToDoc = link.GetT(KeyStore.LinkedToDocs, Document); + if (linkToDoc && linkToDoc != FieldWaiting) { + DocumentManager.Instance.getDocumentViews(linkToDoc).map(docView1 => { + let targetViews = [docView1]; + let docAnnot = docView1.props.Document.GetT(KeyStore.AnnotationOn, Document); + if (docAnnot && docAnnot != FieldWaiting && docAnnot instanceof Document) { + targetViews = DocumentManager.Instance.getDocumentViews(docAnnot.GetPrototype() as Document) + } + targetViews.filter(tv => + tv.props.ContainingCollectionView && tv.props.ContainingCollectionView.props.Document == self + ).map(tv => srcViews.map(sv => + pairs.push({ a: sv.props.Document, b: tv.props.Document, l: link }))) + }) + } } - } - return pairs; - }, [] as { a: Document, b: Document, l: Document }[])); - } + return pairs; + }, [] as { a: Document, b: Document, l: Document }[])); + } + }) return pairs; }, [] as { a: Document, b: Document, l: Document }[]); } componentDidMount() { - reaction(() => this.findPairs(), (pairs) => runInAction(() => this._triples = pairs)); + reaction(() => DocumentManager.Instance.DocumentViews.map(dv => [ + dv.props.Document.Get(KeyStore.AnnotationOn, false), + dv.props.Document.Get(KeyStore.LinkedFromDocs, false), + dv.props.Document.Get(KeyStore.LinkedToDocs, false) + ]), () => runInAction(() => this._triples = this.findPairs())); } onPointerDown(e: React.PointerEvent) { @@ -483,14 +489,29 @@ export class LinksView extends React.Component { render() { if (!this._triples.length) return (null); + let y: { a: Document, b: Document, l: Document, n: number }[] = [] + this._triples.map(t => { + if (!y.reduce((found, yi) => { + if (yi.a == t.a && yi.b == t.b) { + if (yi.l != t.l) + yi.n++; + return true; + } + return found; + }, false)) { + y.push({ a: t.a, b: t.b, l: t.l, n: 1 }); + } + }) + console.log("RENDERING " + y.length) return - {this._triples.map(pair => { + {y.map(pair => { let x1 = pair.a.GetNumber(KeyStore.X, 0) + pair.a.GetNumber(KeyStore.Width, 0) / 2; let y1 = pair.a.GetNumber(KeyStore.Y, 0) + pair.a.GetNumber(KeyStore.Height, 0) / 2; let x2 = pair.b.GetNumber(KeyStore.X, 0) + pair.b.GetNumber(KeyStore.Width, 0) / 2; let y2 = pair.b.GetNumber(KeyStore.Y, 0) + pair.b.GetNumber(KeyStore.Height, 0) / 2; return ( ) diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 789f07e8c..c804085df 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -70,7 +70,7 @@ export class CollectionView extends React.Component { public static AddDocument(props: CollectionViewProps, doc: Document, allowDuplicates: boolean): boolean { var curPage = props.Document.GetNumber(KeyStore.CurPage, -1); doc.SetOnPrototype(KeyStore.Page, new NumberField(curPage)); - if (curPage > 0) { + if (curPage >= 0) { doc.SetOnPrototype(KeyStore.AnnotationOn, props.Document); } if (props.Document.Get(props.fieldKey) instanceof Field) { -- cgit v1.2.3-70-g09d2 From c5cd6c5716ca7a66db367f1e3859feb1c7302f6f Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 28 Mar 2019 18:26:35 -0400 Subject: reordered --- .../views/collections/CollectionFreeFormView.tsx | 74 ++++++++++++---------- 1 file changed, 39 insertions(+), 35 deletions(-) (limited to 'src') diff --git a/src/client/views/collections/CollectionFreeFormView.tsx b/src/client/views/collections/CollectionFreeFormView.tsx index 91faf0907..44f4eadaa 100644 --- a/src/client/views/collections/CollectionFreeFormView.tsx +++ b/src/client/views/collections/CollectionFreeFormView.tsx @@ -1,4 +1,4 @@ -import { action, computed, observable, reaction, runInAction, trace, untracked } from "mobx"; +import { action, computed, observable, reaction, runInAction, trace, untracked, IReactionDisposer } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../../fields/Document"; import { FieldWaiting, Field, Opt } from "../../../fields/Field"; @@ -420,18 +420,31 @@ export class CollectionFreeFormView extends CollectionViewBase { @observer export class LinksView extends React.Component { - private _mainCont = React.createRef(); + @observable _connections: { a: Document, b: Document, l: Document }[] = []; - constructor(props: CollectionViewProps) { - super(props); - console.log("Create links View"); + private _reactionDisposer: Opt; + + componentDidMount() { + this._reactionDisposer = reaction(() => DocumentManager.Instance.DocumentViews.map(dv => [ + dv.props.Document.Get(KeyStore.AnnotationOn, false), + dv.props.Document.Get(KeyStore.LinkedFromDocs, false), + dv.props.Document.Get(KeyStore.LinkedToDocs, false) + ]), () => runInAction(() => this._connections = this.findPairs()), { fireImmediately: true }); + } + componentWillUnmount() { + if (this._reactionDisposer) { + this._reactionDisposer(); + } + this._reactionDisposer = undefined; } - @observable _triples: { a: Document, b: Document, l: Document }[] = []; + filtered(views: DocumentView[]) { + return views.filter(sv => + sv.props.ContainingCollectionView && sv.props.ContainingCollectionView.props.Document == this.props.Document + ); + } findPairs() { - let self = this.props.Document; - return DocumentManager.Instance.DocumentViews.reduce((pairs, dv) => { untracked(() => { let srcViews = [dv]; @@ -439,9 +452,6 @@ export class LinksView extends React.Component { if (srcAnnot && srcAnnot != FieldWaiting && srcAnnot instanceof Document) { srcViews = DocumentManager.Instance.getDocumentViews(srcAnnot.GetPrototype() as Document) } - srcViews = srcViews.filter(sv => - sv.props.ContainingCollectionView && sv.props.ContainingCollectionView.props.Document == self - ); let linksList = dv.props.Document.GetT(KeyStore.LinkedToDocs, ListField); if (linksList && linksList != FieldWaiting && linksList.Data.length) { pairs.push(...linksList.Data.reduce((pairs, link) => { @@ -454,9 +464,7 @@ export class LinksView extends React.Component { if (docAnnot && docAnnot != FieldWaiting && docAnnot instanceof Document) { targetViews = DocumentManager.Instance.getDocumentViews(docAnnot.GetPrototype() as Document) } - targetViews.filter(tv => - tv.props.ContainingCollectionView && tv.props.ContainingCollectionView.props.Document == self - ).map(tv => srcViews.map(sv => + this.filtered(targetViews).map(tv => this.filtered(srcViews).map(sv => pairs.push({ a: sv.props.Document, b: tv.props.Document, l: link }))) }) } @@ -468,13 +476,6 @@ export class LinksView extends React.Component { return pairs; }, [] as { a: Document, b: Document, l: Document }[]); } - componentDidMount() { - reaction(() => DocumentManager.Instance.DocumentViews.map(dv => [ - dv.props.Document.Get(KeyStore.AnnotationOn, false), - dv.props.Document.Get(KeyStore.LinkedFromDocs, false), - dv.props.Document.Get(KeyStore.LinkedToDocs, false) - ]), () => runInAction(() => this._triples = this.findPairs())); - } onPointerDown(e: React.PointerEvent) { let line = (e.nativeEvent as any).path[0]; @@ -486,11 +487,9 @@ export class LinksView extends React.Component { })); } - render() { - if (!this._triples.length) - return (null); - let y: { a: Document, b: Document, l: Document, n: number }[] = [] - this._triples.map(t => { + @computed + get uniqueConnections() { + return this._connections.reduce((y, t) => { if (!y.reduce((found, yi) => { if (yi.a == t.a && yi.b == t.b) { if (yi.l != t.l) @@ -501,17 +500,22 @@ export class LinksView extends React.Component { }, false)) { y.push({ a: t.a, b: t.b, l: t.l, n: 1 }); } - }) - console.log("RENDERING " + y.length) + return y + }, [] as { a: Document, b: Document, l: Document, n: number }[]); + } + + render() { + if (!this._connections.length) + return (null); return - {y.map(pair => { - let x1 = pair.a.GetNumber(KeyStore.X, 0) + pair.a.GetNumber(KeyStore.Width, 0) / 2; - let y1 = pair.a.GetNumber(KeyStore.Y, 0) + pair.a.GetNumber(KeyStore.Height, 0) / 2; - let x2 = pair.b.GetNumber(KeyStore.X, 0) + pair.b.GetNumber(KeyStore.Width, 0) / 2; - let y2 = pair.b.GetNumber(KeyStore.Y, 0) + pair.b.GetNumber(KeyStore.Height, 0) / 2; + {this.uniqueConnections.map(c => { + let x1 = c.a.GetNumber(KeyStore.X, 0) + c.a.GetNumber(KeyStore.Width, 0) / 2; + let y1 = c.a.GetNumber(KeyStore.Y, 0) + c.a.GetNumber(KeyStore.Height, 0) / 2; + let x2 = c.b.GetNumber(KeyStore.X, 0) + c.b.GetNumber(KeyStore.Width, 0) / 2; + let y2 = c.b.GetNumber(KeyStore.Y, 0) + c.b.GetNumber(KeyStore.Height, 0) / 2; return ( - ) -- cgit v1.2.3-70-g09d2 From c3eea60fa586e8ff9cf59497c041044fd0143bb1 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 28 Mar 2019 21:03:17 -0400 Subject: organized collectionfreeformview. fixed issues with showing links --- src/client/util/DocumentManager.ts | 24 +- .../views/collections/CollectionFreeFormView.scss | 116 ----- .../views/collections/CollectionFreeFormView.tsx | 525 --------------------- src/client/views/collections/CollectionView.tsx | 7 +- src/client/views/collections/MarqueeView.scss | 8 - src/client/views/collections/MarqueeView.tsx | 175 ------- src/client/views/collections/PreviewCursor.scss | 18 - src/client/views/collections/PreviewCursor.tsx | 76 --- .../CollectionFreeFormLinkView.scss | 6 + .../CollectionFreeFormLinkView.tsx | 37 ++ .../CollectionFreeFormLinksView.scss | 7 + .../CollectionFreeFormLinksView.tsx | 56 +++ .../collectionFreeForm/CollectionFreeFormView.scss | 95 ++++ .../collectionFreeForm/CollectionFreeFormView.tsx | 416 ++++++++++++++++ .../collectionFreeForm/MarqueeView.scss | 8 + .../collections/collectionFreeForm/MarqueeView.tsx | 175 +++++++ .../collectionFreeForm/PreviewCursor.scss | 18 + .../collectionFreeForm/PreviewCursor.tsx | 76 +++ src/client/views/nodes/DocumentContentsView.tsx | 2 +- 19 files changed, 924 insertions(+), 921 deletions(-) delete mode 100644 src/client/views/collections/CollectionFreeFormView.scss delete mode 100644 src/client/views/collections/CollectionFreeFormView.tsx delete mode 100644 src/client/views/collections/MarqueeView.scss delete mode 100644 src/client/views/collections/MarqueeView.tsx delete mode 100644 src/client/views/collections/PreviewCursor.scss delete mode 100644 src/client/views/collections/PreviewCursor.tsx create mode 100644 src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.scss create mode 100644 src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx create mode 100644 src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.scss create mode 100644 src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx create mode 100644 src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss create mode 100644 src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx create mode 100644 src/client/views/collections/collectionFreeForm/MarqueeView.scss create mode 100644 src/client/views/collections/collectionFreeForm/MarqueeView.tsx create mode 100644 src/client/views/collections/collectionFreeForm/PreviewCursor.scss create mode 100644 src/client/views/collections/collectionFreeForm/PreviewCursor.tsx (limited to 'src') diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts index 28624dba8..bf59fbb43 100644 --- a/src/client/util/DocumentManager.ts +++ b/src/client/util/DocumentManager.ts @@ -1,10 +1,11 @@ import React = require('react') import { observer } from 'mobx-react'; -import { observable, action } from 'mobx'; +import { observable, action, computed } from 'mobx'; import { Document } from "../../fields/Document" import { DocumentView } from '../views/nodes/DocumentView'; import { KeyStore } from '../../fields/KeyStore'; import { FieldWaiting } from '../../fields/Field'; +import { ListField } from '../../fields/ListField'; export class DocumentManager { @@ -74,4 +75,25 @@ export class DocumentManager { return (toReturn); } + + @computed + public get LinkedDocumentViews() { + return DocumentManager.Instance.DocumentViews.reduce((pairs, dv) => { + let linksList = dv.props.Document.GetT(KeyStore.LinkedToDocs, ListField); + if (linksList && linksList != FieldWaiting && linksList.Data.length) { + pairs.push(...linksList.Data.reduce((pairs, link) => { + if (link instanceof Document) { + let linkToDoc = link.GetT(KeyStore.LinkedToDocs, Document); + if (linkToDoc && linkToDoc != FieldWaiting) { + DocumentManager.Instance.getDocumentViews(linkToDoc).map(docView1 => { + pairs.push({ a: dv, b: docView1, l: link }) + }) + } + } + return pairs; + }, [] as { a: DocumentView, b: DocumentView, l: Document }[])); + } + return pairs; + }, [] as { a: DocumentView, b: DocumentView, l: Document }[]); + } } \ No newline at end of file diff --git a/src/client/views/collections/CollectionFreeFormView.scss b/src/client/views/collections/CollectionFreeFormView.scss deleted file mode 100644 index 7012ce6b9..000000000 --- a/src/client/views/collections/CollectionFreeFormView.scss +++ /dev/null @@ -1,116 +0,0 @@ -@import "../global_variables"; - -.collectionfreeformview-linkLine { - stroke: black; - stroke-width: 3; - transform: translate(10000px,10000px); - pointer-events: all; -} -.collectionfreeformview-svgCanvas{ - transform: translate(-10000px,-10000px); - position: absolute; - width: 20000px; - height: 20000px; - pointer-events: none; -} -.collectionfreeformview-container { - .collectionfreeformview > .jsx-parser { - position: absolute; - height: 100%; - width: 100%; - } - - .inking-canvas { - transform-origin: 50000px 50000px; - } - //nested freeform views - // .collectionfreeformview-container { - // background-image: linear-gradient(to right, $light-color-secondary 1px, transparent 1px), - // linear-gradient(to bottom, $light-color-secondary 1px, transparent 1px); - // background-size: 30px 30px; - // } - - box-shadow: $intermediate-color 0.2vw 0.2vw 0.8vw; - border: 0px solid $light-color-secondary; - border-radius: $border-radius; - box-sizing: border-box; - position: relative; - overflow: hidden; - top: 0; - left: 0; - width: 100%; - height: 100%; - .collectionfreeformview { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - .inking-canvas { - transform-origin: 50000px 50000px; - } - } -} -.collectionfreeformview-overlay { - .collectionfreeformview > .jsx-parser { - position: absolute; - height: 100%; - } - .formattedTextBox-cont { - background: $light-color-secondary; - } - - .inking-canvas { - transform-origin: 50000px 50000px; - } - - opacity: 0.99; - border: 0px solid transparent; - border-radius: $border-radius; - box-sizing: border-box; - position:relative; - overflow: hidden; - top: 0; - left: 0; - width: 100%; - height: 100%; - .collectionfreeformview { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - .inking-canvas { - transform-origin: 50000px 50000px; - } - .formattedTextBox-cont { - background:yellow; - } - } -} - -// selection border...? -.border { - border-style: solid; - box-sizing: border-box; - width: 98%; - height: 98%; - border-radius: $border-radius; -} - -//this is an animation for the blinking cursor! -@keyframes blink { - 0% { - opacity: 0; - } - 49% { - opacity: 0; - } - 50% { - opacity: 1; - } -} - -#prevCursor { - animation: blink 1s infinite; -} diff --git a/src/client/views/collections/CollectionFreeFormView.tsx b/src/client/views/collections/CollectionFreeFormView.tsx deleted file mode 100644 index 44f4eadaa..000000000 --- a/src/client/views/collections/CollectionFreeFormView.tsx +++ /dev/null @@ -1,525 +0,0 @@ -import { action, computed, observable, reaction, runInAction, trace, untracked, IReactionDisposer } from "mobx"; -import { observer } from "mobx-react"; -import { Document } from "../../../fields/Document"; -import { FieldWaiting, Field, Opt } from "../../../fields/Field"; -import { KeyStore } from "../../../fields/KeyStore"; -import { ListField } from "../../../fields/ListField"; -import { TextField } from "../../../fields/TextField"; -import { DragManager } from "../../util/DragManager"; -import { Transform } from "../../util/Transform"; -import { undoBatch } from "../../util/UndoManager"; -import { InkingCanvas } from "../InkingCanvas"; -import { CollectionFreeFormDocumentView } from "../nodes/CollectionFreeFormDocumentView"; -import { DocumentContentsView } from "../nodes/DocumentContentsView"; -import { DocumentViewProps, DocumentView } from "../nodes/DocumentView"; -import "./CollectionFreeFormView.scss"; -import { COLLECTION_BORDER_WIDTH } from "./CollectionView"; -import { CollectionViewBase, CollectionViewProps } from "./CollectionViewBase"; -import { MarqueeView } from "./MarqueeView"; -import { PreviewCursor } from "./PreviewCursor"; -import React = require("react"); -import v5 = require("uuid/v5"); -import { DocumentManager } from "../../util/DocumentManager"; -import { Utils } from "../../../Utils"; -import { Server } from "../../Server"; -import { AverageAggregateParameters } from "../../northstar/model/idea/idea"; - -@observer -export class CollectionFreeFormView extends CollectionViewBase { - public _canvasRef = React.createRef(); - private _selectOnLoaded: string = ""; // id of document that should be selected once it's loaded (used for click-to-type) - - public addLiveTextBox = (newBox: Document) => { - // mark this collection so that when the text box is created we can send it the SelectOnLoad prop to focus itself - this._selectOnLoaded = newBox.Id; - //set text to be the typed key and get focus on text box - this.props.addDocument(newBox, false); - //remove cursor from screen - this.PreviewCursorVisible = false; - } - - public selectDocuments = (docs: Document[]) => { - this.props.CollectionView.SelectedDocs.length = 0; - docs.map(d => this.props.CollectionView.SelectedDocs.push(d.Id)); - } - - public getActiveDocuments = () => { - var curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1); - const lvalue = this.props.Document.GetT>(this.props.fieldKey, ListField); - let active: Document[] = []; - if (lvalue && lvalue != FieldWaiting) { - lvalue.Data.map(doc => { - var page = doc.GetNumber(KeyStore.Page, -1); - if (page == curPage || page == -1) { - active.push(doc); - } - }) - } - - return active; - } - - //determines whether the blinking cursor for indicating whether a text will be made on key down is visible - @observable public PreviewCursorVisible: boolean = false; - @observable public MarqueeVisible = false; - @observable public DownX: number = 0; - @observable public DownY: number = 0; - @observable private _lastX: number = 0; - @observable private _lastY: number = 0; - - @computed get panX(): number { return this.props.Document.GetNumber(KeyStore.PanX, 0) } - @computed get panY(): number { return this.props.Document.GetNumber(KeyStore.PanY, 0) } - @computed get scale(): number { return this.props.Document.GetNumber(KeyStore.Scale, 1); } - @computed get isAnnotationOverlay() { return this.props.fieldKey.Id === KeyStore.Annotations.Id; } // bcz: ? Why do we need to compare Id's? - @computed get nativeWidth() { return this.props.Document.GetNumber(KeyStore.NativeWidth, 0); } - @computed get nativeHeight() { return this.props.Document.GetNumber(KeyStore.NativeHeight, 0); } - @computed get zoomScaling() { return this.props.Document.GetNumber(KeyStore.Scale, 1); } - @computed get centeringShiftX() { return !this.props.Document.GetNumber(KeyStore.NativeWidth, 0) ? this.props.panelWidth() / 2 : 0; } // shift so pan position is at center of window for non-overlay collections - @computed get centeringShiftY() { return !this.props.Document.GetNumber(KeyStore.NativeHeight, 0) ? this.props.panelHeight() / 2 : 0; }// shift so pan position is at center of window for non-overlay collections - - @undoBatch - @action - drop = (e: Event, de: DragManager.DropEvent) => { - if (super.drop(e, de)) { - if (de.data instanceof DragManager.DocumentDragData) { - let screenX = de.x - (de.data.xOffset as number || 0); - let screenY = de.y - (de.data.yOffset as number || 0); - const [x, y] = this.getTransform().transformPoint(screenX, screenY); - de.data.droppedDocument.SetNumber(KeyStore.X, x); - de.data.droppedDocument.SetNumber(KeyStore.Y, y); - if (!de.data.droppedDocument.GetNumber(KeyStore.Width, 0)) { - de.data.droppedDocument.SetNumber(KeyStore.Width, 300); - de.data.droppedDocument.SetNumber(KeyStore.Height, 300); - } - this.bringToFront(de.data.droppedDocument); - } - return true; - } - return false; - } - - - @action - cleanupInteractions = () => { - document.removeEventListener("pointermove", this.onPointerMove); - document.removeEventListener("pointerup", this.onPointerUp); - this.MarqueeVisible = false; - } - - @action - onPointerDown = (e: React.PointerEvent): void => { - this.PreviewCursorVisible = false; - if ((e.button === 2 && this.props.active() && (!this.isAnnotationOverlay || this.zoomScaling != 1)) || e.button == 0) { - document.removeEventListener("pointermove", this.onPointerMove); - document.addEventListener("pointermove", this.onPointerMove); - document.removeEventListener("pointerup", this.onPointerUp); - document.addEventListener("pointerup", this.onPointerUp); - this._lastX = this.DownX = e.pageX; - this._lastY = this.DownY = e.pageY; - } - } - - @action - onPointerUp = (e: PointerEvent): void => { - e.stopPropagation(); - - if (Math.abs(this.DownX - e.clientX) < 4 && Math.abs(this.DownY - e.clientY) < 4) { - //show preview text cursor on tap - this.PreviewCursorVisible = true; - //select is not already selected - if (!this.props.isSelected()) { - this.props.select(false); - } - } - this.cleanupInteractions(); - } - - @action - onPointerMove = (e: PointerEvent): void => { - if (!e.cancelBubble && this.props.active()) { - if (e.buttons == 1 && !e.altKey && !e.metaKey) { - this.MarqueeVisible = true; - } - if (this.MarqueeVisible) { - e.stopPropagation(); - e.preventDefault(); - } - else if ((!this.isAnnotationOverlay || this.zoomScaling != 1) && !e.shiftKey) { - let x = this.props.Document.GetNumber(KeyStore.PanX, 0); - let y = this.props.Document.GetNumber(KeyStore.PanY, 0); - let [dx, dy] = this.getTransform().transformDirection(e.clientX - this._lastX, e.clientY - this._lastY); - this.SetPan(x - dx, y - dy); - this._lastX = e.pageX; - this._lastY = e.pageY; - e.stopPropagation(); - e.preventDefault(); - } - } - } - - @action - onPointerWheel = (e: React.WheelEvent): void => { - this.props.select(false); - e.stopPropagation(); - e.preventDefault(); - let coefficient = 1000; - - if (e.ctrlKey) { - var nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 0); - var nativeHeight = this.props.Document.GetNumber(KeyStore.NativeHeight, 0); - const coefficient = 1000; - let deltaScale = (1 - (e.deltaY / coefficient)); - this.props.Document.SetNumber(KeyStore.NativeWidth, nativeWidth * deltaScale); - this.props.Document.SetNumber(KeyStore.NativeHeight, nativeHeight * deltaScale); - e.stopPropagation(); - e.preventDefault(); - } else { - // if (modes[e.deltaMode] == 'pixels') coefficient = 50; - // else if (modes[e.deltaMode] == 'lines') coefficient = 1000; // This should correspond to line-height?? - let transform = this.getTransform(); - - let deltaScale = (1 - (e.deltaY / coefficient)); - if (deltaScale * this.zoomScaling < 1 && this.isAnnotationOverlay) - deltaScale = 1 / this.zoomScaling; - let [x, y] = transform.transformPoint(e.clientX, e.clientY); - - let localTransform = this.getLocalTransform() - localTransform = localTransform.inverse().scaleAbout(deltaScale, x, y) - // console.log(localTransform) - - this.props.Document.SetNumber(KeyStore.Scale, localTransform.Scale); - this.SetPan(-localTransform.TranslateX / localTransform.Scale, -localTransform.TranslateY / localTransform.Scale); - } - } - - @action - private SetPan(panX: number, panY: number) { - var x1 = this.getLocalTransform().inverse().Scale; - const newPanX = Math.min((1 - 1 / x1) * this.nativeWidth, Math.max(0, panX)); - const newPanY = Math.min((1 - 1 / x1) * this.nativeHeight, Math.max(0, panY)); - this.props.Document.SetNumber(KeyStore.PanX, this.isAnnotationOverlay ? newPanX : panX); - this.props.Document.SetNumber(KeyStore.PanY, this.isAnnotationOverlay ? newPanY : panY); - } - - @action - onDrop = (e: React.DragEvent): void => { - var pt = this.getTransform().transformPoint(e.pageX, e.pageY); - super.onDrop(e, { x: pt[0], y: pt[1] }); - } - - onDragOver = (): void => { - } - - @action - bringToFront(doc: Document) { - const { fieldKey: fieldKey, Document: Document } = this.props; - - const value: Document[] = Document.GetList(fieldKey, []).slice(); - value.sort((doc1, doc2) => { - if (doc1 === doc) { - return 1; - } - if (doc2 === doc) { - return -1; - } - return doc1.GetNumber(KeyStore.ZIndex, 0) - doc2.GetNumber(KeyStore.ZIndex, 0); - }).map((doc, index) => { - doc.SetNumber(KeyStore.ZIndex, index + 1) - }); - } - - @computed get backgroundLayout(): string | undefined { - let field = this.props.Document.GetT(KeyStore.BackgroundLayout, TextField); - if (field && field !== FieldWaiting) { - return field.Data; - } - } - @computed get overlayLayout(): string | undefined { - let field = this.props.Document.GetT(KeyStore.OverlayLayout, TextField); - if (field && field !== FieldWaiting) { - return field.Data; - } - } - - focusDocument = (doc: Document) => { - let x = doc.GetNumber(KeyStore.X, 0) + doc.GetNumber(KeyStore.Width, 0) / 2; - let y = doc.GetNumber(KeyStore.Y, 0) + doc.GetNumber(KeyStore.Height, 0) / 2; - this.SetPan(x, y); - this.props.focus(this.props.Document); - } - - getDocumentViewProps(document: Document): DocumentViewProps { - return { - Document: document, - AddDocument: this.props.addDocument, - RemoveDocument: this.props.removeDocument, - ScreenToLocalTransform: this.getTransform, - isTopMost: false, - SelectOnLoad: document.Id == this._selectOnLoaded, - PanelWidth: document.Width, - PanelHeight: document.Height, - ContentScaling: this.noScaling, - ContainingCollectionView: this.props.CollectionView, - focus: this.focusDocument - } - } - - @computed - get views() { - var curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1); - const lvalue = this.props.Document.GetT>(this.props.fieldKey, ListField); - if (lvalue && lvalue != FieldWaiting) { - return lvalue.Data.map(doc => { - if (!doc) return null; - var page = doc.GetNumber(KeyStore.Page, 0); - return (page != curPage && page != 0) ? (null) : - (); - }) - } - return null; - } - - @computed - get backgroundView() { - return !this.backgroundLayout ? (null) : - ( false} select={() => { }} />); - } - @computed - get overlayView() { - return !this.overlayLayout ? (null) : - ( false} select={() => { }} />); - } - - getTransform = (): Transform => this.props.ScreenToLocalTransform().translate(-COLLECTION_BORDER_WIDTH, -COLLECTION_BORDER_WIDTH).translate(-this.centeringShiftX, -this.centeringShiftY).transform(this.getLocalTransform()) - getMarqueeTransform = (): Transform => this.props.ScreenToLocalTransform().translate(-COLLECTION_BORDER_WIDTH, -COLLECTION_BORDER_WIDTH) - getLocalTransform = (): Transform => Transform.Identity.scale(1 / this.scale).translate(this.panX, this.panY); - noScaling = () => 1; - - //when focus is lost, this will remove the preview cursor - @action - onBlur = (): void => { - this.PreviewCursorVisible = false; - } - - private crosshairs?: HTMLCanvasElement; - drawCrosshairs = (backgroundColor: string) => { - if (this.crosshairs) { - let c = this.crosshairs; - let ctx = c.getContext('2d'); - if (ctx) { - ctx.fillStyle = backgroundColor; - ctx.fillRect(0, 0, 20, 20); - - ctx.fillStyle = "black"; - ctx.lineWidth = 0.5; - - ctx.beginPath(); - - ctx.moveTo(10, 0); - ctx.lineTo(10, 8); - - ctx.moveTo(10, 20); - ctx.lineTo(10, 12); - - ctx.moveTo(0, 10); - ctx.lineTo(8, 10); - - ctx.moveTo(20, 10); - ctx.lineTo(12, 10); - - ctx.stroke(); - - // ctx.font = "10px Arial"; - // ctx.fillText(CurrentUserUtils.email[0].toUpperCase(), 10, 10); - } - } - } - - render() { - let [dx, dy] = [this.centeringShiftX, this.centeringShiftY]; - - const panx: number = -this.props.Document.GetNumber(KeyStore.PanX, 0); - const pany: number = -this.props.Document.GetNumber(KeyStore.PanY, 0); - // const panx: number = this.props.Document.GetNumber(KeyStore.PanX, 0) + this.centeringShiftX; - // const pany: number = this.props.Document.GetNumber(KeyStore.PanY, 0) + this.centeringShiftY; - // console.log("center:", this.getLocalTransform().transformPoint(this.centeringShiftX, this.centeringShiftY)); - - return ( -
    super.setCursorPosition(this.getTransform().transformPoint(e.clientX, e.clientY))} - onWheel={this.onPointerWheel} - onDrop={this.onDrop.bind(this)} - onDragOver={this.onDragOver} - onBlur={this.onBlur} - style={{ borderWidth: `${COLLECTION_BORDER_WIDTH}px` }}// , zIndex: !this.props.isTopMost ? -1 : undefined }} - tabIndex={0} - ref={this.createDropTarget}> -
    - {this.backgroundView} - - - {this.views} - - {super.getCursors().map(entry => { - if (entry.Data.length > 0) { - let id = entry.Data[0][0]; - let email = entry.Data[0][1]; - let point = entry.Data[1]; - this.drawCrosshairs("#" + v5(id, v5.URL).substring(0, 6).toUpperCase() + "22") - return ( -
    - { if (el) this.crosshairs = el }} - width={20} - height={20} - style={{ - position: 'absolute', - width: "20px", - height: "20px", - opacity: 0.5, - borderRadius: "50%", - border: "2px solid black" - }} - /> -

    {email[0].toUpperCase()}

    -
    - ); - } - })} -
    - - {this.overlayView} - -
    - ); - } -} - -@observer -export class LinksView extends React.Component { - @observable _connections: { a: Document, b: Document, l: Document }[] = []; - - private _reactionDisposer: Opt; - - componentDidMount() { - this._reactionDisposer = reaction(() => DocumentManager.Instance.DocumentViews.map(dv => [ - dv.props.Document.Get(KeyStore.AnnotationOn, false), - dv.props.Document.Get(KeyStore.LinkedFromDocs, false), - dv.props.Document.Get(KeyStore.LinkedToDocs, false) - ]), () => runInAction(() => this._connections = this.findPairs()), { fireImmediately: true }); - } - componentWillUnmount() { - if (this._reactionDisposer) { - this._reactionDisposer(); - } - this._reactionDisposer = undefined; - } - - filtered(views: DocumentView[]) { - return views.filter(sv => - sv.props.ContainingCollectionView && sv.props.ContainingCollectionView.props.Document == this.props.Document - ); - } - - findPairs() { - return DocumentManager.Instance.DocumentViews.reduce((pairs, dv) => { - untracked(() => { - let srcViews = [dv]; - let srcAnnot = dv.props.Document.GetT(KeyStore.AnnotationOn, Document); - if (srcAnnot && srcAnnot != FieldWaiting && srcAnnot instanceof Document) { - srcViews = DocumentManager.Instance.getDocumentViews(srcAnnot.GetPrototype() as Document) - } - let linksList = dv.props.Document.GetT(KeyStore.LinkedToDocs, ListField); - if (linksList && linksList != FieldWaiting && linksList.Data.length) { - pairs.push(...linksList.Data.reduce((pairs, link) => { - if (link instanceof Document) { - let linkToDoc = link.GetT(KeyStore.LinkedToDocs, Document); - if (linkToDoc && linkToDoc != FieldWaiting) { - DocumentManager.Instance.getDocumentViews(linkToDoc).map(docView1 => { - let targetViews = [docView1]; - let docAnnot = docView1.props.Document.GetT(KeyStore.AnnotationOn, Document); - if (docAnnot && docAnnot != FieldWaiting && docAnnot instanceof Document) { - targetViews = DocumentManager.Instance.getDocumentViews(docAnnot.GetPrototype() as Document) - } - this.filtered(targetViews).map(tv => this.filtered(srcViews).map(sv => - pairs.push({ a: sv.props.Document, b: tv.props.Document, l: link }))) - }) - } - } - return pairs; - }, [] as { a: Document, b: Document, l: Document }[])); - } - }) - return pairs; - }, [] as { a: Document, b: Document, l: Document }[]); - } - - onPointerDown(e: React.PointerEvent) { - let line = (e.nativeEvent as any).path[0]; - line.style.stroke = "red"; - Server.GetField(line.id, action((f: Opt) => { - if (f instanceof Document) { - console.log(f.Title); - } - })); - } - - @computed - get uniqueConnections() { - return this._connections.reduce((y, t) => { - if (!y.reduce((found, yi) => { - if (yi.a == t.a && yi.b == t.b) { - if (yi.l != t.l) - yi.n++; - return true; - } - return found; - }, false)) { - y.push({ a: t.a, b: t.b, l: t.l, n: 1 }); - } - return y - }, [] as { a: Document, b: Document, l: Document, n: number }[]); - } - - render() { - if (!this._connections.length) - return (null); - return - {this.uniqueConnections.map(c => { - let x1 = c.a.GetNumber(KeyStore.X, 0) + c.a.GetNumber(KeyStore.Width, 0) / 2; - let y1 = c.a.GetNumber(KeyStore.Y, 0) + c.a.GetNumber(KeyStore.Height, 0) / 2; - let x2 = c.b.GetNumber(KeyStore.X, 0) + c.b.GetNumber(KeyStore.Width, 0) / 2; - let y2 = c.b.GetNumber(KeyStore.Y, 0) + c.b.GetNumber(KeyStore.Height, 0) / 2; - return ( - - ) - })} - - } -} \ No newline at end of file diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index c804085df..a1498e0ae 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -7,7 +7,7 @@ import { ContextMenu } from "../ContextMenu"; import React = require("react"); import { KeyStore } from "../../../fields/KeyStore"; import { NumberField } from "../../../fields/NumberField"; -import { CollectionFreeFormView } from "./CollectionFreeFormView"; +import { CollectionFreeFormView } from "./collectionFreeForm/CollectionFreeFormView"; import { CollectionDockingView } from "./CollectionDockingView"; import { CollectionSchemaView } from "./CollectionSchemaView"; import { CollectionViewProps } from "./CollectionViewBase"; @@ -104,6 +104,11 @@ export class CollectionView extends React.Component { break; } } + doc.GetTAsync(KeyStore.AnnotationOn, Document).then((annotationOn) => { + if (annotationOn == props.Document) { + doc.Set(KeyStore.AnnotationOn, undefined, true); + } + }) if (index !== -1) { value.splice(index, 1) diff --git a/src/client/views/collections/MarqueeView.scss b/src/client/views/collections/MarqueeView.scss deleted file mode 100644 index 6d9a79344..000000000 --- a/src/client/views/collections/MarqueeView.scss +++ /dev/null @@ -1,8 +0,0 @@ - -.marqueeView { - border-style: dashed; - box-sizing: border-box; - position: absolute; - border-width: 1px; - border-color: black; -} \ No newline at end of file diff --git a/src/client/views/collections/MarqueeView.tsx b/src/client/views/collections/MarqueeView.tsx deleted file mode 100644 index b48ad9c64..000000000 --- a/src/client/views/collections/MarqueeView.tsx +++ /dev/null @@ -1,175 +0,0 @@ -import { action, IReactionDisposer, observable, reaction } from "mobx"; -import { observer } from "mobx-react"; -import { Document } from "../../../fields/Document"; -import { FieldWaiting, Opt } from "../../../fields/Field"; -import { KeyStore } from "../../../fields/KeyStore"; -import { Documents } from "../../documents/Documents"; -import { SelectionManager } from "../../util/SelectionManager"; -import { Transform } from "../../util/Transform"; -import { CollectionFreeFormView } from "./CollectionFreeFormView"; -import "./MarqueeView.scss"; -import React = require("react"); -import { InkField, StrokeData } from "../../../fields/InkField"; -import { Utils } from "../../../Utils"; -import { InkingCanvas } from "../InkingCanvas"; - -interface MarqueeViewProps { - getMarqueeTransform: () => Transform; - getTransform: () => Transform; - container: CollectionFreeFormView; - addDocument: (doc: Document, allowDuplicates: false) => boolean; - activeDocuments: () => Document[]; - selectDocuments: (docs: Document[]) => void; - removeDocument: (doc: Document) => boolean; -} - -@observer -export class MarqueeView extends React.Component -{ - private _reactionDisposer: Opt; - - @observable _lastX: number = 0; - @observable _lastY: number = 0; - @observable _downX: number = 0; - @observable _downY: number = 0; - - componentDidMount() { - this._reactionDisposer = reaction( - () => this.props.container.MarqueeVisible, - (visible: boolean) => this.onPointerDown(visible, this.props.container.DownX, this.props.container.DownY)) - } - componentWillUnmount() { - if (this._reactionDisposer) { - this._reactionDisposer(); - } - this.cleanupInteractions(); - } - - @action - cleanupInteractions = () => { - document.removeEventListener("pointermove", this.onPointerMove, true) - document.removeEventListener("pointerup", this.onPointerUp, true); - document.removeEventListener("keydown", this.marqueeCommand, true); - } - - @action - onPointerDown = (visible: boolean, downX: number, downY: number): void => { - if (visible) { - this._downX = this._lastX = downX; - this._downY = this._lastY = downY; - document.addEventListener("pointermove", this.onPointerMove, true) - document.addEventListener("pointerup", this.onPointerUp, true); - document.addEventListener("keydown", this.marqueeCommand, true); - } - } - - @action - onPointerMove = (e: PointerEvent): void => { - this._lastX = e.pageX; - this._lastY = e.pageY; - } - - @action - onPointerUp = (e: PointerEvent): void => { - this.cleanupInteractions(); - if (!e.shiftKey) { - SelectionManager.DeselectAll(); - } - this.props.selectDocuments(this.marqueeSelect()); - } - - intersectRect(r1: { left: number, top: number, width: number, height: number }, - r2: { left: number, top: number, width: number, height: number }) { - return !(r2.left > r1.left + r1.width || r2.left + r2.width < r1.left || r2.top > r1.top + r1.height || r2.top + r2.height < r1.top); - } - - get Bounds() { - let left = this._downX < this._lastX ? this._downX : this._lastX; - let top = this._downY < this._lastY ? this._downY : this._lastY; - let topLeft = this.props.getTransform().transformPoint(left, top); - let size = this.props.getTransform().transformDirection(this._lastX - this._downX, this._lastY - this._downY); - return { left: topLeft[0], top: topLeft[1], width: Math.abs(size[0]), height: Math.abs(size[1]) } - } - - @action - marqueeCommand = (e: KeyboardEvent) => { - if (e.key == "Backspace" || e.key == "Delete") { - this.marqueeSelect().map(d => this.props.removeDocument(d)); - this.props.container.props.Document.SetData(KeyStore.Ink, this.marqueeInkSelect(false), InkField); - this.cleanupInteractions(); - } - if (e.key == "c") { - let bounds = this.Bounds; - let selected = this.marqueeSelect().map(d => { - this.props.removeDocument(d); - d.SetNumber(KeyStore.X, d.GetNumber(KeyStore.X, 0) - bounds.left - bounds.width / 2); - d.SetNumber(KeyStore.Y, d.GetNumber(KeyStore.Y, 0) - bounds.top - bounds.height / 2); - d.SetNumber(KeyStore.Page, 0); - d.SetText(KeyStore.Title, "" + d.GetNumber(KeyStore.Width, 0) + " " + d.GetNumber(KeyStore.Height, 0)); - return d; - }); - let liftedInk = this.marqueeInkSelect(true); - this.props.container.props.Document.SetData(KeyStore.Ink, this.marqueeInkSelect(false), InkField); - //setTimeout(() => { - let newCollection = Documents.FreeformDocument(selected, { - x: bounds.left, - y: bounds.top, - panx: 0, - pany: 0, - width: bounds.width, - height: bounds.height, - backgroundColor: "Transparent", - ink: liftedInk, - title: "a nested collection" - }); - this.props.addDocument(newCollection, false); - // }, 100); - this.cleanupInteractions(); - } - } - marqueeInkSelect(select: boolean) { - let selRect = this.Bounds; - let centerShiftX = 0 - (selRect.left + selRect.width / 2); // moves each point by the offset that shifts the selection's center to the origin. - let centerShiftY = 0 - (selRect.top + selRect.height / 2); - let ink = this.props.container.props.Document.GetT(KeyStore.Ink, InkField); - if (ink && ink != FieldWaiting && ink.Data) { - let idata = new Map(); - ink.Data.forEach((value: StrokeData, key: string, map: any) => { - let inside = InkingCanvas.IntersectStrokeRect(value, selRect); - if (inside && select) { - idata.set(key, - { - pathData: value.pathData.map(val => { return { x: val.x + centerShiftX, y: val.y + centerShiftY } }), - color: value.color, - width: value.width, - tool: value.tool, - page: -1 - }); - } else if (!inside && !select) { - idata.set(key, value); - } - }) - return idata; - } - } - - marqueeSelect() { - let selRect = this.Bounds; - let selection: Document[] = []; - this.props.activeDocuments().map(doc => { - var x = doc.GetNumber(KeyStore.X, 0); - var y = doc.GetNumber(KeyStore.Y, 0); - var w = doc.GetNumber(KeyStore.Width, 0); - var h = doc.GetNumber(KeyStore.Height, 0); - if (this.intersectRect({ left: x, top: y, width: w, height: h }, selRect)) - selection.push(doc) - }) - return selection; - } - - render() { - let p = this.props.getMarqueeTransform().transformPoint(this._downX < this._lastX ? this._downX : this._lastX, this._downY < this._lastY ? this._downY : this._lastY); - let v = this.props.getMarqueeTransform().transformDirection(this._lastX - this._downX, this._lastY - this._downY); - return (!this.props.container.MarqueeVisible ? (null) :
    ); - } -} \ No newline at end of file diff --git a/src/client/views/collections/PreviewCursor.scss b/src/client/views/collections/PreviewCursor.scss deleted file mode 100644 index a797411f6..000000000 --- a/src/client/views/collections/PreviewCursor.scss +++ /dev/null @@ -1,18 +0,0 @@ - -.previewCursor { - color: black; - position: absolute; - transform-origin: left top; - pointer-events: none; -} - -//this is an animation for the blinking cursor! -@keyframes blink { - 0% {opacity: 0} - 49%{opacity: 0} - 50% {opacity: 1} -} - -#previewCursor { - animation: blink 1s infinite; -} \ No newline at end of file diff --git a/src/client/views/collections/PreviewCursor.tsx b/src/client/views/collections/PreviewCursor.tsx deleted file mode 100644 index 8ae59a83a..000000000 --- a/src/client/views/collections/PreviewCursor.tsx +++ /dev/null @@ -1,76 +0,0 @@ -import { action, IReactionDisposer, observable, reaction } from "mobx"; -import { observer } from "mobx-react"; -import { Document } from "../../../fields/Document"; -import { Opt } from "../../../fields/Field"; -import { Documents } from "../../documents/Documents"; -import { Transform } from "../../util/Transform"; -import { CollectionFreeFormView } from "./CollectionFreeFormView"; -import "./PreviewCursor.scss"; -import React = require("react"); - - -export interface PreviewCursorProps { - getTransform: () => Transform; - container: CollectionFreeFormView; - addLiveTextDocument: (doc: Document) => void; -} - -@observer -export class PreviewCursor extends React.Component { - private _reactionDisposer: Opt; - - @observable _lastX: number = 0; - @observable _lastY: number = 0; - - componentDidMount() { - this._reactionDisposer = reaction( - () => this.props.container.PreviewCursorVisible, - (visible: boolean) => this.onCursorPlaced(visible, this.props.container.DownX, this.props.container.DownY)) - } - componentWillUnmount() { - if (this._reactionDisposer) { - this._reactionDisposer(); - } - this.cleanupInteractions(); - } - - - @action - cleanupInteractions = () => { - document.removeEventListener("keypress", this.onKeyPress, false); - } - - @action - onCursorPlaced = (visible: boolean, downX: number, downY: number): void => { - if (visible) { - document.addEventListener("keypress", this.onKeyPress, false); - this._lastX = downX; - this._lastY = downY; - } else - this.cleanupInteractions(); - } - - @action - onKeyPress = (e: KeyboardEvent) => { - // Mixing events between React and Native is finicky. In FormattedTextBox, we set the - // DASHFormattedTextBoxHandled flag when a text box consumes a key press so that we can ignore - // the keyPress here. - //if not these keys, make a textbox if preview cursor is active! - if (!e.ctrlKey && !e.altKey && !e.defaultPrevented && !(e as any).DASHFormattedTextBoxHandled) { - //make textbox and add it to this collection - let [x, y] = this.props.getTransform().transformPoint(this._lastX, this._lastY); - let newBox = Documents.TextDocument({ width: 200, height: 100, x: x, y: y, title: "typed text" }); - this.props.addLiveTextDocument(newBox); - e.stopPropagation(); - } - } - - render() { - //get local position and place cursor there! - let [x, y] = this.props.getTransform().transformPoint(this._lastX, this._lastY); - return ( - !this.props.container.PreviewCursorVisible ? (null) : -
    I
    ) - - } -} \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.scss b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.scss new file mode 100644 index 000000000..3b2f79be1 --- /dev/null +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.scss @@ -0,0 +1,6 @@ +.collectionfreeformlinkview-linkLine { + stroke: black; + stroke-width: 3; + transform: translate(10000px,10000px); + pointer-events: all; +} \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx new file mode 100644 index 000000000..e84f0c5ad --- /dev/null +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx @@ -0,0 +1,37 @@ +import { observer } from "mobx-react"; +import { Document } from "../../../../fields/Document"; +import { KeyStore } from "../../../../fields/KeyStore"; +import { Utils } from "../../../../Utils"; +import "./CollectionFreeFormLinkView.scss"; +import React = require("react"); +import v5 = require("uuid/v5"); + +export interface CollectionFreeFormLinkViewProps { + A: Document; + B: Document; + LinkDocs: Document[]; +} + +@observer +export class CollectionFreeFormLinkView extends React.Component { + + onPointerDown = (e: React.PointerEvent) => { + this.props.LinkDocs.map(l => + console.log("Link:" + l.Title)); + } + render() { + let l = this.props.LinkDocs; + let a = this.props.A; + let b = this.props.B; + let x1 = a.GetNumber(KeyStore.X, 0) + a.GetNumber(KeyStore.Width, 0) / 2; + let y1 = a.GetNumber(KeyStore.Y, 0) + a.GetNumber(KeyStore.Height, 0) / 2; + let x2 = b.GetNumber(KeyStore.X, 0) + b.GetNumber(KeyStore.Width, 0) / 2; + let y2 = b.GetNumber(KeyStore.Y, 0) + b.GetNumber(KeyStore.Height, 0) / 2; + return ( + + ) + } +} \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.scss b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.scss new file mode 100644 index 000000000..9af0df7f5 --- /dev/null +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.scss @@ -0,0 +1,7 @@ +.collectionfreeformlinksview-svgCanvas{ + transform: translate(-10000px,-10000px); + position: absolute; + width: 20000px; + height: 20000px; + pointer-events: none; + } \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx new file mode 100644 index 000000000..4f28f43eb --- /dev/null +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx @@ -0,0 +1,56 @@ +import { computed } from "mobx"; +import { observer } from "mobx-react"; +import { Document } from "../../../../fields/Document"; +import { FieldWaiting } from "../../../../fields/Field"; +import { KeyStore } from "../../../../fields/KeyStore"; +import { Utils } from "../../../../Utils"; +import { DocumentManager } from "../../../util/DocumentManager"; +import { DocumentView } from "../../nodes/DocumentView"; +import { CollectionViewProps } from "../CollectionViewBase"; +import "./CollectionFreeFormLinksView.scss"; +import React = require("react"); +import v5 = require("uuid/v5"); +import { CollectionFreeFormLinkView } from "./CollectionFreeFormLinkView"; + +@observer +export class CollectionFreeFormLinksView extends React.Component { + + documentAnchors(view: DocumentView) { + let equalViews = [view]; + let containerDoc = view.props.Document.GetT(KeyStore.AnnotationOn, Document); + if (containerDoc && containerDoc != FieldWaiting && containerDoc instanceof Document) { + equalViews = DocumentManager.Instance.getDocumentViews(containerDoc.GetPrototype() as Document) + } + return equalViews.filter(sv => sv.props.ContainingCollectionView && sv.props.ContainingCollectionView.props.Document == this.props.Document); + } + + @computed + get uniqueConnections() { + return DocumentManager.Instance.LinkedDocumentViews.reduce((drawnPairs, connection) => { + let srcViews = this.documentAnchors(connection.a); + let targetViews = this.documentAnchors(connection.b); + let possiblePairs: { a: Document, b: Document, }[] = []; + srcViews.map(sv => targetViews.map(tv => possiblePairs.push({ a: sv.props.Document, b: tv.props.Document }))); + possiblePairs.map(possiblePair => { + if (!drawnPairs.reduce((found, drawnPair) => { + let match = (possiblePair.a == drawnPair.a && possiblePair.b == drawnPair.b); + if (match) { + if (!drawnPair.l.reduce((found, link) => found || link.Id == connection.l.Id, false)) + drawnPair.l.push(connection.l); + } + return match || found; + }, false)) { + drawnPairs.push({ a: possiblePair.a, b: possiblePair.b, l: [connection.l] as Document[] }); + } + }) + return drawnPairs + }, [] as { a: Document, b: Document, l: Document[] }[]); + } + + render() { + return ( + + {this.uniqueConnections.map(c => )} + ); + } +} \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss new file mode 100644 index 000000000..9c5e98005 --- /dev/null +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss @@ -0,0 +1,95 @@ +@import "../../global_variables"; + +.collectionfreeformview-container { + .collectionfreeformview > .jsx-parser { + position: absolute; + height: 100%; + width: 100%; + } + + .inking-canvas { + transform-origin: 50000px 50000px; + } + //nested freeform views + // .collectionfreeformview-container { + // background-image: linear-gradient(to right, $light-color-secondary 1px, transparent 1px), + // linear-gradient(to bottom, $light-color-secondary 1px, transparent 1px); + // background-size: 30px 30px; + // } + + box-shadow: $intermediate-color 0.2vw 0.2vw 0.8vw; + border: 0px solid $light-color-secondary; + border-radius: $border-radius; + box-sizing: border-box; + position: relative; + overflow: hidden; + top: 0; + left: 0; + width: 100%; + height: 100%; + .collectionfreeformview { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + .inking-canvas { + transform-origin: 50000px 50000px; + } + } +} +.collectionfreeformview-overlay { + .collectionfreeformview > .jsx-parser { + position: absolute; + height: 100%; + } + .formattedTextBox-cont { + background: $light-color-secondary; + } + + .inking-canvas { + transform-origin: 50000px 50000px; + } + + opacity: 0.99; + border: 0px solid transparent; + border-radius: $border-radius; + box-sizing: border-box; + position:relative; + overflow: hidden; + top: 0; + left: 0; + width: 100%; + height: 100%; + .collectionfreeformview { + .formattedTextBox-cont { + background:yellow; + } + } +} + +// selection border...? +.border { + border-style: solid; + box-sizing: border-box; + width: 98%; + height: 98%; + border-radius: $border-radius; +} + +//this is an animation for the blinking cursor! +@keyframes blink { + 0% { + opacity: 0; + } + 49% { + opacity: 0; + } + 50% { + opacity: 1; + } +} + +#prevCursor { + animation: blink 1s infinite; +} diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx new file mode 100644 index 000000000..1f90b0d46 --- /dev/null +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -0,0 +1,416 @@ +import { action, computed, observable } from "mobx"; +import { observer } from "mobx-react"; +import { Document } from "../../../../fields/Document"; +import { FieldWaiting } from "../../../../fields/Field"; +import { KeyStore } from "../../../../fields/KeyStore"; +import { ListField } from "../../../../fields/ListField"; +import { TextField } from "../../../../fields/TextField"; +import { DragManager } from "../../../util/DragManager"; +import { Transform } from "../../../util/Transform"; +import { undoBatch } from "../../../util/UndoManager"; +import { InkingCanvas } from "../../InkingCanvas"; +import { CollectionFreeFormDocumentView } from "../../nodes/CollectionFreeFormDocumentView"; +import { DocumentContentsView } from "../../nodes/DocumentContentsView"; +import { DocumentViewProps } from "../../nodes/DocumentView"; +import { COLLECTION_BORDER_WIDTH } from "../CollectionView"; +import { CollectionViewBase } from "../CollectionViewBase"; +import { MarqueeView } from "./MarqueeView"; +import { PreviewCursor } from "./PreviewCursor"; +import { CollectionFreeFormLinksView } from "./CollectionFreeFormLinksView"; +import "./CollectionFreeFormView.scss"; +import React = require("react"); +import v5 = require("uuid/v5"); + +@observer +export class CollectionFreeFormView extends CollectionViewBase { + public _canvasRef = React.createRef(); + private _selectOnLoaded: string = ""; // id of document that should be selected once it's loaded (used for click-to-type) + + public addLiveTextBox = (newBox: Document) => { + // mark this collection so that when the text box is created we can send it the SelectOnLoad prop to focus itself + this._selectOnLoaded = newBox.Id; + //set text to be the typed key and get focus on text box + this.props.addDocument(newBox, false); + //remove cursor from screen + this.PreviewCursorVisible = false; + } + + public selectDocuments = (docs: Document[]) => { + this.props.CollectionView.SelectedDocs.length = 0; + docs.map(d => this.props.CollectionView.SelectedDocs.push(d.Id)); + } + + public getActiveDocuments = () => { + var curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1); + const lvalue = this.props.Document.GetT>(this.props.fieldKey, ListField); + let active: Document[] = []; + if (lvalue && lvalue != FieldWaiting) { + lvalue.Data.map(doc => { + var page = doc.GetNumber(KeyStore.Page, -1); + if (page == curPage || page == -1) { + active.push(doc); + } + }) + } + + return active; + } + + //determines whether the blinking cursor for indicating whether a text will be made on key down is visible + @observable public PreviewCursorVisible: boolean = false; + @observable public MarqueeVisible = false; + @observable public DownX: number = 0; + @observable public DownY: number = 0; + @observable private _lastX: number = 0; + @observable private _lastY: number = 0; + + @computed get panX(): number { return this.props.Document.GetNumber(KeyStore.PanX, 0) } + @computed get panY(): number { return this.props.Document.GetNumber(KeyStore.PanY, 0) } + @computed get scale(): number { return this.props.Document.GetNumber(KeyStore.Scale, 1); } + @computed get isAnnotationOverlay() { return this.props.fieldKey.Id === KeyStore.Annotations.Id; } // bcz: ? Why do we need to compare Id's? + @computed get nativeWidth() { return this.props.Document.GetNumber(KeyStore.NativeWidth, 0); } + @computed get nativeHeight() { return this.props.Document.GetNumber(KeyStore.NativeHeight, 0); } + @computed get zoomScaling() { return this.props.Document.GetNumber(KeyStore.Scale, 1); } + @computed get centeringShiftX() { return !this.props.Document.GetNumber(KeyStore.NativeWidth, 0) ? this.props.panelWidth() / 2 : 0; } // shift so pan position is at center of window for non-overlay collections + @computed get centeringShiftY() { return !this.props.Document.GetNumber(KeyStore.NativeHeight, 0) ? this.props.panelHeight() / 2 : 0; }// shift so pan position is at center of window for non-overlay collections + + @undoBatch + @action + drop = (e: Event, de: DragManager.DropEvent) => { + if (super.drop(e, de)) { + if (de.data instanceof DragManager.DocumentDragData) { + let screenX = de.x - (de.data.xOffset as number || 0); + let screenY = de.y - (de.data.yOffset as number || 0); + const [x, y] = this.getTransform().transformPoint(screenX, screenY); + de.data.droppedDocument.SetNumber(KeyStore.X, x); + de.data.droppedDocument.SetNumber(KeyStore.Y, y); + if (!de.data.droppedDocument.GetNumber(KeyStore.Width, 0)) { + de.data.droppedDocument.SetNumber(KeyStore.Width, 300); + de.data.droppedDocument.SetNumber(KeyStore.Height, 300); + } + this.bringToFront(de.data.droppedDocument); + } + return true; + } + return false; + } + + + @action + cleanupInteractions = () => { + document.removeEventListener("pointermove", this.onPointerMove); + document.removeEventListener("pointerup", this.onPointerUp); + this.MarqueeVisible = false; + } + + @action + onPointerDown = (e: React.PointerEvent): void => { + this.PreviewCursorVisible = false; + if ((e.button === 2 && this.props.active() && (!this.isAnnotationOverlay || this.zoomScaling != 1)) || e.button == 0) { + document.removeEventListener("pointermove", this.onPointerMove); + document.addEventListener("pointermove", this.onPointerMove); + document.removeEventListener("pointerup", this.onPointerUp); + document.addEventListener("pointerup", this.onPointerUp); + this._lastX = this.DownX = e.pageX; + this._lastY = this.DownY = e.pageY; + } + } + + @action + onPointerUp = (e: PointerEvent): void => { + e.stopPropagation(); + + if (Math.abs(this.DownX - e.clientX) < 4 && Math.abs(this.DownY - e.clientY) < 4) { + //show preview text cursor on tap + this.PreviewCursorVisible = true; + //select is not already selected + if (!this.props.isSelected()) { + this.props.select(false); + } + } + this.cleanupInteractions(); + } + + @action + onPointerMove = (e: PointerEvent): void => { + if (!e.cancelBubble && this.props.active()) { + if (e.buttons == 1 && !e.altKey && !e.metaKey) { + this.MarqueeVisible = true; + } + if (this.MarqueeVisible) { + e.stopPropagation(); + e.preventDefault(); + } + else if ((!this.isAnnotationOverlay || this.zoomScaling != 1) && !e.shiftKey) { + let x = this.props.Document.GetNumber(KeyStore.PanX, 0); + let y = this.props.Document.GetNumber(KeyStore.PanY, 0); + let [dx, dy] = this.getTransform().transformDirection(e.clientX - this._lastX, e.clientY - this._lastY); + this.SetPan(x - dx, y - dy); + this._lastX = e.pageX; + this._lastY = e.pageY; + e.stopPropagation(); + e.preventDefault(); + } + } + } + + @action + onPointerWheel = (e: React.WheelEvent): void => { + this.props.select(false); + e.stopPropagation(); + e.preventDefault(); + let coefficient = 1000; + + if (e.ctrlKey) { + var nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 0); + var nativeHeight = this.props.Document.GetNumber(KeyStore.NativeHeight, 0); + const coefficient = 1000; + let deltaScale = (1 - (e.deltaY / coefficient)); + this.props.Document.SetNumber(KeyStore.NativeWidth, nativeWidth * deltaScale); + this.props.Document.SetNumber(KeyStore.NativeHeight, nativeHeight * deltaScale); + e.stopPropagation(); + e.preventDefault(); + } else { + // if (modes[e.deltaMode] == 'pixels') coefficient = 50; + // else if (modes[e.deltaMode] == 'lines') coefficient = 1000; // This should correspond to line-height?? + let transform = this.getTransform(); + + let deltaScale = (1 - (e.deltaY / coefficient)); + if (deltaScale * this.zoomScaling < 1 && this.isAnnotationOverlay) + deltaScale = 1 / this.zoomScaling; + let [x, y] = transform.transformPoint(e.clientX, e.clientY); + + let localTransform = this.getLocalTransform() + localTransform = localTransform.inverse().scaleAbout(deltaScale, x, y) + // console.log(localTransform) + + this.props.Document.SetNumber(KeyStore.Scale, localTransform.Scale); + this.SetPan(-localTransform.TranslateX / localTransform.Scale, -localTransform.TranslateY / localTransform.Scale); + } + } + + @action + private SetPan(panX: number, panY: number) { + var x1 = this.getLocalTransform().inverse().Scale; + const newPanX = Math.min((1 - 1 / x1) * this.nativeWidth, Math.max(0, panX)); + const newPanY = Math.min((1 - 1 / x1) * this.nativeHeight, Math.max(0, panY)); + this.props.Document.SetNumber(KeyStore.PanX, this.isAnnotationOverlay ? newPanX : panX); + this.props.Document.SetNumber(KeyStore.PanY, this.isAnnotationOverlay ? newPanY : panY); + } + + @action + onDrop = (e: React.DragEvent): void => { + var pt = this.getTransform().transformPoint(e.pageX, e.pageY); + super.onDrop(e, { x: pt[0], y: pt[1] }); + } + + onDragOver = (): void => { + } + + @action + bringToFront(doc: Document) { + const { fieldKey: fieldKey, Document: Document } = this.props; + + const value: Document[] = Document.GetList(fieldKey, []).slice(); + value.sort((doc1, doc2) => { + if (doc1 === doc) { + return 1; + } + if (doc2 === doc) { + return -1; + } + return doc1.GetNumber(KeyStore.ZIndex, 0) - doc2.GetNumber(KeyStore.ZIndex, 0); + }).map((doc, index) => { + doc.SetNumber(KeyStore.ZIndex, index + 1) + }); + } + + @computed get backgroundLayout(): string | undefined { + let field = this.props.Document.GetT(KeyStore.BackgroundLayout, TextField); + if (field && field !== FieldWaiting) { + return field.Data; + } + } + @computed get overlayLayout(): string | undefined { + let field = this.props.Document.GetT(KeyStore.OverlayLayout, TextField); + if (field && field !== FieldWaiting) { + return field.Data; + } + } + + focusDocument = (doc: Document) => { + let x = doc.GetNumber(KeyStore.X, 0) + doc.GetNumber(KeyStore.Width, 0) / 2; + let y = doc.GetNumber(KeyStore.Y, 0) + doc.GetNumber(KeyStore.Height, 0) / 2; + this.SetPan(x, y); + this.props.focus(this.props.Document); + } + + getDocumentViewProps(document: Document): DocumentViewProps { + return { + Document: document, + AddDocument: this.props.addDocument, + RemoveDocument: this.props.removeDocument, + ScreenToLocalTransform: this.getTransform, + isTopMost: false, + SelectOnLoad: document.Id == this._selectOnLoaded, + PanelWidth: document.Width, + PanelHeight: document.Height, + ContentScaling: this.noScaling, + ContainingCollectionView: this.props.CollectionView, + focus: this.focusDocument + } + } + + @computed + get views() { + var curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1); + const lvalue = this.props.Document.GetT>(this.props.fieldKey, ListField); + if (lvalue && lvalue != FieldWaiting) { + return lvalue.Data.map(doc => { + if (!doc) return null; + var page = doc.GetNumber(KeyStore.Page, 0); + return (page != curPage && page != 0) ? (null) : + (); + }) + } + return null; + } + + @computed + get backgroundView() { + return !this.backgroundLayout ? (null) : + ( false} select={() => { }} />); + } + @computed + get overlayView() { + return !this.overlayLayout ? (null) : + ( false} select={() => { }} />); + } + + getTransform = (): Transform => this.props.ScreenToLocalTransform().translate(-COLLECTION_BORDER_WIDTH, -COLLECTION_BORDER_WIDTH).translate(-this.centeringShiftX, -this.centeringShiftY).transform(this.getLocalTransform()) + getMarqueeTransform = (): Transform => this.props.ScreenToLocalTransform().translate(-COLLECTION_BORDER_WIDTH, -COLLECTION_BORDER_WIDTH) + getLocalTransform = (): Transform => Transform.Identity.scale(1 / this.scale).translate(this.panX, this.panY); + noScaling = () => 1; + + //when focus is lost, this will remove the preview cursor + @action + onBlur = (): void => { + this.PreviewCursorVisible = false; + } + + private crosshairs?: HTMLCanvasElement; + drawCrosshairs = (backgroundColor: string) => { + if (this.crosshairs) { + let c = this.crosshairs; + let ctx = c.getContext('2d'); + if (ctx) { + ctx.fillStyle = backgroundColor; + ctx.fillRect(0, 0, 20, 20); + + ctx.fillStyle = "black"; + ctx.lineWidth = 0.5; + + ctx.beginPath(); + + ctx.moveTo(10, 0); + ctx.lineTo(10, 8); + + ctx.moveTo(10, 20); + ctx.lineTo(10, 12); + + ctx.moveTo(0, 10); + ctx.lineTo(8, 10); + + ctx.moveTo(20, 10); + ctx.lineTo(12, 10); + + ctx.stroke(); + + // ctx.font = "10px Arial"; + // ctx.fillText(CurrentUserUtils.email[0].toUpperCase(), 10, 10); + } + } + } + + render() { + let [dx, dy] = [this.centeringShiftX, this.centeringShiftY]; + + const panx: number = -this.props.Document.GetNumber(KeyStore.PanX, 0); + const pany: number = -this.props.Document.GetNumber(KeyStore.PanY, 0); + // const panx: number = this.props.Document.GetNumber(KeyStore.PanX, 0) + this.centeringShiftX; + // const pany: number = this.props.Document.GetNumber(KeyStore.PanY, 0) + this.centeringShiftY; + // console.log("center:", this.getLocalTransform().transformPoint(this.centeringShiftX, this.centeringShiftY)); + + return ( +
    super.setCursorPosition(this.getTransform().transformPoint(e.clientX, e.clientY))} + onWheel={this.onPointerWheel} + onDrop={this.onDrop.bind(this)} + onDragOver={this.onDragOver} + onBlur={this.onBlur} + style={{ borderWidth: `${COLLECTION_BORDER_WIDTH}px` }}// , zIndex: !this.props.isTopMost ? -1 : undefined }} + tabIndex={0} + ref={this.createDropTarget}> +
    + {this.backgroundView} + + + {this.views} + + {super.getCursors().map(entry => { + if (entry.Data.length > 0) { + let id = entry.Data[0][0]; + let email = entry.Data[0][1]; + let point = entry.Data[1]; + this.drawCrosshairs("#" + v5(id, v5.URL).substring(0, 6).toUpperCase() + "22") + return ( +
    + { if (el) this.crosshairs = el }} + width={20} + height={20} + style={{ + position: 'absolute', + width: "20px", + height: "20px", + opacity: 0.5, + borderRadius: "50%", + border: "2px solid black" + }} + /> +

    {email[0].toUpperCase()}

    +
    + ); + } + })} +
    + + {this.overlayView} + +
    + ); + } +} \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.scss b/src/client/views/collections/collectionFreeForm/MarqueeView.scss new file mode 100644 index 000000000..6d9a79344 --- /dev/null +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.scss @@ -0,0 +1,8 @@ + +.marqueeView { + border-style: dashed; + box-sizing: border-box; + position: absolute; + border-width: 1px; + border-color: black; +} \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx new file mode 100644 index 000000000..2692690dd --- /dev/null +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -0,0 +1,175 @@ +import { action, IReactionDisposer, observable, reaction } from "mobx"; +import { observer } from "mobx-react"; +import { Document } from "../../../../fields/Document"; +import { FieldWaiting, Opt } from "../../../../fields/Field"; +import { KeyStore } from "../../../../fields/KeyStore"; +import { Documents } from "../../../documents/Documents"; +import { SelectionManager } from "../../../util/SelectionManager"; +import { Transform } from "../../../util/Transform"; +import { CollectionFreeFormView } from "./CollectionFreeFormView"; +import "./MarqueeView.scss"; +import React = require("react"); +import { InkField, StrokeData } from "../../../../fields/InkField"; +import { Utils } from "../../../../Utils"; +import { InkingCanvas } from "../../InkingCanvas"; + +interface MarqueeViewProps { + getMarqueeTransform: () => Transform; + getTransform: () => Transform; + container: CollectionFreeFormView; + addDocument: (doc: Document, allowDuplicates: false) => boolean; + activeDocuments: () => Document[]; + selectDocuments: (docs: Document[]) => void; + removeDocument: (doc: Document) => boolean; +} + +@observer +export class MarqueeView extends React.Component +{ + private _reactionDisposer: Opt; + + @observable _lastX: number = 0; + @observable _lastY: number = 0; + @observable _downX: number = 0; + @observable _downY: number = 0; + + componentDidMount() { + this._reactionDisposer = reaction( + () => this.props.container.MarqueeVisible, + (visible: boolean) => this.onPointerDown(visible, this.props.container.DownX, this.props.container.DownY)) + } + componentWillUnmount() { + if (this._reactionDisposer) { + this._reactionDisposer(); + } + this.cleanupInteractions(); + } + + @action + cleanupInteractions = () => { + document.removeEventListener("pointermove", this.onPointerMove, true) + document.removeEventListener("pointerup", this.onPointerUp, true); + document.removeEventListener("keydown", this.marqueeCommand, true); + } + + @action + onPointerDown = (visible: boolean, downX: number, downY: number): void => { + if (visible) { + this._downX = this._lastX = downX; + this._downY = this._lastY = downY; + document.addEventListener("pointermove", this.onPointerMove, true) + document.addEventListener("pointerup", this.onPointerUp, true); + document.addEventListener("keydown", this.marqueeCommand, true); + } + } + + @action + onPointerMove = (e: PointerEvent): void => { + this._lastX = e.pageX; + this._lastY = e.pageY; + } + + @action + onPointerUp = (e: PointerEvent): void => { + this.cleanupInteractions(); + if (!e.shiftKey) { + SelectionManager.DeselectAll(); + } + this.props.selectDocuments(this.marqueeSelect()); + } + + intersectRect(r1: { left: number, top: number, width: number, height: number }, + r2: { left: number, top: number, width: number, height: number }) { + return !(r2.left > r1.left + r1.width || r2.left + r2.width < r1.left || r2.top > r1.top + r1.height || r2.top + r2.height < r1.top); + } + + get Bounds() { + let left = this._downX < this._lastX ? this._downX : this._lastX; + let top = this._downY < this._lastY ? this._downY : this._lastY; + let topLeft = this.props.getTransform().transformPoint(left, top); + let size = this.props.getTransform().transformDirection(this._lastX - this._downX, this._lastY - this._downY); + return { left: topLeft[0], top: topLeft[1], width: Math.abs(size[0]), height: Math.abs(size[1]) } + } + + @action + marqueeCommand = (e: KeyboardEvent) => { + if (e.key == "Backspace" || e.key == "Delete") { + this.marqueeSelect().map(d => this.props.removeDocument(d)); + this.props.container.props.Document.SetData(KeyStore.Ink, this.marqueeInkSelect(false), InkField); + this.cleanupInteractions(); + } + if (e.key == "c") { + let bounds = this.Bounds; + let selected = this.marqueeSelect().map(d => { + this.props.removeDocument(d); + d.SetNumber(KeyStore.X, d.GetNumber(KeyStore.X, 0) - bounds.left - bounds.width / 2); + d.SetNumber(KeyStore.Y, d.GetNumber(KeyStore.Y, 0) - bounds.top - bounds.height / 2); + d.SetNumber(KeyStore.Page, 0); + d.SetText(KeyStore.Title, "" + d.GetNumber(KeyStore.Width, 0) + " " + d.GetNumber(KeyStore.Height, 0)); + return d; + }); + let liftedInk = this.marqueeInkSelect(true); + this.props.container.props.Document.SetData(KeyStore.Ink, this.marqueeInkSelect(false), InkField); + //setTimeout(() => { + let newCollection = Documents.FreeformDocument(selected, { + x: bounds.left, + y: bounds.top, + panx: 0, + pany: 0, + width: bounds.width, + height: bounds.height, + backgroundColor: "Transparent", + ink: liftedInk, + title: "a nested collection" + }); + this.props.addDocument(newCollection, false); + // }, 100); + this.cleanupInteractions(); + } + } + marqueeInkSelect(select: boolean) { + let selRect = this.Bounds; + let centerShiftX = 0 - (selRect.left + selRect.width / 2); // moves each point by the offset that shifts the selection's center to the origin. + let centerShiftY = 0 - (selRect.top + selRect.height / 2); + let ink = this.props.container.props.Document.GetT(KeyStore.Ink, InkField); + if (ink && ink != FieldWaiting && ink.Data) { + let idata = new Map(); + ink.Data.forEach((value: StrokeData, key: string, map: any) => { + let inside = InkingCanvas.IntersectStrokeRect(value, selRect); + if (inside && select) { + idata.set(key, + { + pathData: value.pathData.map(val => { return { x: val.x + centerShiftX, y: val.y + centerShiftY } }), + color: value.color, + width: value.width, + tool: value.tool, + page: -1 + }); + } else if (!inside && !select) { + idata.set(key, value); + } + }) + return idata; + } + } + + marqueeSelect() { + let selRect = this.Bounds; + let selection: Document[] = []; + this.props.activeDocuments().map(doc => { + var x = doc.GetNumber(KeyStore.X, 0); + var y = doc.GetNumber(KeyStore.Y, 0); + var w = doc.GetNumber(KeyStore.Width, 0); + var h = doc.GetNumber(KeyStore.Height, 0); + if (this.intersectRect({ left: x, top: y, width: w, height: h }, selRect)) + selection.push(doc) + }) + return selection; + } + + render() { + let p = this.props.getMarqueeTransform().transformPoint(this._downX < this._lastX ? this._downX : this._lastX, this._downY < this._lastY ? this._downY : this._lastY); + let v = this.props.getMarqueeTransform().transformDirection(this._lastX - this._downX, this._lastY - this._downY); + return (!this.props.container.MarqueeVisible ? (null) :
    ); + } +} \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/PreviewCursor.scss b/src/client/views/collections/collectionFreeForm/PreviewCursor.scss new file mode 100644 index 000000000..a797411f6 --- /dev/null +++ b/src/client/views/collections/collectionFreeForm/PreviewCursor.scss @@ -0,0 +1,18 @@ + +.previewCursor { + color: black; + position: absolute; + transform-origin: left top; + pointer-events: none; +} + +//this is an animation for the blinking cursor! +@keyframes blink { + 0% {opacity: 0} + 49%{opacity: 0} + 50% {opacity: 1} +} + +#previewCursor { + animation: blink 1s infinite; +} \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx b/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx new file mode 100644 index 000000000..95364f04b --- /dev/null +++ b/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx @@ -0,0 +1,76 @@ +import { action, IReactionDisposer, observable, reaction } from "mobx"; +import { observer } from "mobx-react"; +import { Document } from "../../../../fields/Document"; +import { Opt } from "../../../../fields/Field"; +import { Documents } from "../../../documents/Documents"; +import { Transform } from "../../../util/Transform"; +import { CollectionFreeFormView } from "./CollectionFreeFormView"; +import "./PreviewCursor.scss"; +import React = require("react"); + + +export interface PreviewCursorProps { + getTransform: () => Transform; + container: CollectionFreeFormView; + addLiveTextDocument: (doc: Document) => void; +} + +@observer +export class PreviewCursor extends React.Component { + private _reactionDisposer: Opt; + + @observable _lastX: number = 0; + @observable _lastY: number = 0; + + componentDidMount() { + this._reactionDisposer = reaction( + () => this.props.container.PreviewCursorVisible, + (visible: boolean) => this.onCursorPlaced(visible, this.props.container.DownX, this.props.container.DownY)) + } + componentWillUnmount() { + if (this._reactionDisposer) { + this._reactionDisposer(); + } + this.cleanupInteractions(); + } + + + @action + cleanupInteractions = () => { + document.removeEventListener("keypress", this.onKeyPress, false); + } + + @action + onCursorPlaced = (visible: boolean, downX: number, downY: number): void => { + if (visible) { + document.addEventListener("keypress", this.onKeyPress, false); + this._lastX = downX; + this._lastY = downY; + } else + this.cleanupInteractions(); + } + + @action + onKeyPress = (e: KeyboardEvent) => { + // Mixing events between React and Native is finicky. In FormattedTextBox, we set the + // DASHFormattedTextBoxHandled flag when a text box consumes a key press so that we can ignore + // the keyPress here. + //if not these keys, make a textbox if preview cursor is active! + if (!e.ctrlKey && !e.altKey && !e.defaultPrevented && !(e as any).DASHFormattedTextBoxHandled) { + //make textbox and add it to this collection + let [x, y] = this.props.getTransform().transformPoint(this._lastX, this._lastY); + let newBox = Documents.TextDocument({ width: 200, height: 100, x: x, y: y, title: "typed text" }); + this.props.addLiveTextDocument(newBox); + e.stopPropagation(); + } + } + + render() { + //get local position and place cursor there! + let [x, y] = this.props.getTransform().transformPoint(this._lastX, this._lastY); + return ( + !this.props.container.PreviewCursorVisible ? (null) : +
    I
    ) + + } +} \ No newline at end of file diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index f48be2047..b54744337 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -5,7 +5,7 @@ import { Key } from "../../../fields/Key"; import { KeyStore } from "../../../fields/KeyStore"; import { ListField } from "../../../fields/ListField"; import { CollectionDockingView } from "../collections/CollectionDockingView"; -import { CollectionFreeFormView } from "../collections/CollectionFreeFormView"; +import { CollectionFreeFormView } from "../collections/collectionFreeForm/CollectionFreeFormView"; import { CollectionPDFView } from "../collections/CollectionPDFView"; import { CollectionSchemaView } from "../collections/CollectionSchemaView"; import { CollectionVideoView } from "../collections/CollectionVideoView"; -- cgit v1.2.3-70-g09d2 From 1bd678851632bbbb302363574eb5e3e19dc343e9 Mon Sep 17 00:00:00 2001 From: bob Date: Fri, 29 Mar 2019 13:18:35 -0400 Subject: reorganized and mostly working northstar histograms. --- src/client/documents/Documents.ts | 13 +- src/client/northstar/core/filter/FilterModel.ts | 2 +- src/client/northstar/dash-fields/HistogramField.ts | 64 ++++ src/client/northstar/dash-nodes/HistogramBox.scss | 34 ++ src/client/northstar/dash-nodes/HistogramBox.tsx | 161 ++++++++++ .../dash-nodes/HistogramBoxPrimitives.scss | 26 ++ .../dash-nodes/HistogramBoxPrimitives.tsx | 341 +++++++++++++++++++++ .../dash-nodes/HistogramLabelPrimitives.scss | 13 + .../dash-nodes/HistogramLabelPrimitives.tsx | 78 +++++ src/client/northstar/model/ModelHelpers.ts | 18 +- .../model/binRanges/VisualBinRangeHelper.ts | 6 +- src/client/northstar/operations/BaseOperation.ts | 4 +- .../northstar/operations/HistogramOperation.ts | 13 +- src/client/northstar/utils/SizeConverter.ts | 6 +- src/client/views/Main.tsx | 39 +-- src/client/views/nodes/DocumentContentsView.tsx | 5 +- src/client/views/nodes/DocumentView.tsx | 3 - src/client/views/nodes/HistogramBox.scss | 22 -- src/client/views/nodes/HistogramBox.tsx | 105 ------- src/client/views/nodes/HistogramBoxPrimitives.scss | 25 -- src/client/views/nodes/HistogramBoxPrimitives.tsx | 336 -------------------- .../views/nodes/HistogramLabelPrimitives.scss | 12 - .../views/nodes/HistogramLabelPrimitives.tsx | 78 ----- src/fields/HistogramField.ts | 59 ---- src/fields/KeyStore.ts | 1 - src/server/ServerUtil.ts | 3 +- .../authentication/models/current_user_utils.ts | 27 +- 27 files changed, 789 insertions(+), 705 deletions(-) create mode 100644 src/client/northstar/dash-fields/HistogramField.ts create mode 100644 src/client/northstar/dash-nodes/HistogramBox.scss create mode 100644 src/client/northstar/dash-nodes/HistogramBox.tsx create mode 100644 src/client/northstar/dash-nodes/HistogramBoxPrimitives.scss create mode 100644 src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx create mode 100644 src/client/northstar/dash-nodes/HistogramLabelPrimitives.scss create mode 100644 src/client/northstar/dash-nodes/HistogramLabelPrimitives.tsx delete mode 100644 src/client/views/nodes/HistogramBox.scss delete mode 100644 src/client/views/nodes/HistogramBox.tsx delete mode 100644 src/client/views/nodes/HistogramBoxPrimitives.scss delete mode 100644 src/client/views/nodes/HistogramBoxPrimitives.tsx delete mode 100644 src/client/views/nodes/HistogramLabelPrimitives.scss delete mode 100644 src/client/views/nodes/HistogramLabelPrimitives.tsx delete mode 100644 src/fields/HistogramField.ts (limited to 'src') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 837dfe815..663ccae61 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -1,6 +1,6 @@ import { AudioField } from "../../fields/AudioField"; import { Document } from "../../fields/Document"; -import { Field, FieldWaiting } from "../../fields/Field"; +import { Field } from "../../fields/Field"; import { HtmlField } from "../../fields/HtmlField"; import { ImageField } from "../../fields/ImageField"; import { InkField, StrokeData } from "../../fields/InkField"; @@ -11,6 +11,9 @@ import { PDFField } from "../../fields/PDFField"; import { TextField } from "../../fields/TextField"; import { VideoField } from "../../fields/VideoField"; import { WebField } from "../../fields/WebField"; +import { HistogramField } from "../northstar/dash-fields/HistogramField"; +import { HistogramBox } from "../northstar/dash-nodes/HistogramBox"; +import { HistogramOperation } from "../northstar/operations/HistogramOperation"; import { Server } from "../Server"; import { CollectionPDFView } from "../views/collections/CollectionPDFView"; import { CollectionVideoView } from "../views/collections/CollectionVideoView"; @@ -22,10 +25,6 @@ import { KeyValueBox } from "../views/nodes/KeyValueBox"; import { PDFBox } from "../views/nodes/PDFBox"; import { VideoBox } from "../views/nodes/VideoBox"; import { WebBox } from "../views/nodes/WebBox"; -import { HistogramBox } from "../views/nodes/HistogramBox"; -import { FieldView } from "../views/nodes/FieldView"; -import { HistogramField } from "../../fields/HistogramField"; -import { HistogramOperation } from "../northstar/operations/HistogramOperation"; export interface DocumentOptions { x?: number; @@ -44,7 +43,6 @@ export interface DocumentOptions { layoutKeys?: Key[]; viewType?: number; backgroundColor?: string; - northstarSchema?: string; } export namespace Documents { @@ -88,7 +86,6 @@ export namespace Documents { if (options.ink !== undefined) { doc.Set(KeyStore.Ink, new InkField(options.ink)); } if (options.layout !== undefined) { doc.SetText(KeyStore.Layout, options.layout); } if (options.layoutKeys !== undefined) { doc.Set(KeyStore.LayoutKeys, new ListField(options.layoutKeys)); } - if (options.northstarSchema !== undefined) { doc.SetText(KeyStore.NorthstarSchema, options.northstarSchema); } return doc; } @@ -126,7 +123,7 @@ export namespace Documents { function GetHistogramPrototype(): Document { if (!histoProto) { histoProto = setupPrototypeOptions(histoProtoId, "HISTO PROTO", CollectionView.LayoutString("AnnotationsKey"), - { x: 0, y: 0, width: 300, height: 300, layoutKeys: [KeyStore.Data, KeyStore.Annotations, KeyStore.Caption] }); + { x: 0, y: 0, width: 300, height: 300, backgroundColor: "black", layoutKeys: [KeyStore.Data, KeyStore.Annotations, KeyStore.Caption] }); histoProto.SetText(KeyStore.BackgroundLayout, HistogramBox.LayoutString()); } return histoProto; diff --git a/src/client/northstar/core/filter/FilterModel.ts b/src/client/northstar/core/filter/FilterModel.ts index bc7938947..aee99d2b6 100644 --- a/src/client/northstar/core/filter/FilterModel.ts +++ b/src/client/northstar/core/filter/FilterModel.ts @@ -2,10 +2,10 @@ import { ValueComparison } from "./ValueComparision"; import { Utils } from "../../utils/Utils"; import { IBaseFilterProvider } from "./IBaseFilterProvider"; import { FilterOperand } from "./FilterOperand"; -import { HistogramField } from "../../../../fields/HistogramField"; import { KeyStore } from "../../../../fields/KeyStore"; import { FieldWaiting } from "../../../../fields/Field"; import { Document } from "../../../../fields/Document"; +import { HistogramField } from "../../dash-fields/HistogramField"; export class FilterModel { public ValueComparisons: ValueComparison[]; diff --git a/src/client/northstar/dash-fields/HistogramField.ts b/src/client/northstar/dash-fields/HistogramField.ts new file mode 100644 index 000000000..00912c595 --- /dev/null +++ b/src/client/northstar/dash-fields/HistogramField.ts @@ -0,0 +1,64 @@ +import { BasicField } from "../../../fields/BasicField"; +import { Field, FieldId } from "../../../fields/Field"; +import { Types } from "../../../server/Message"; +import { HistogramOperation } from "../../../client/northstar/operations/HistogramOperation"; +import { action } from "mobx"; +import { AttributeTransformationModel } from "../../../client/northstar/core/attribute/AttributeTransformationModel"; +import { ColumnAttributeModel } from "../../../client/northstar/core/attribute/AttributeModel"; +import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; +import { ArrayUtil } from "../utils/ArrayUtil"; +import { Schema } from "../model/idea/idea"; + + +export class HistogramField extends BasicField { + constructor(data?: HistogramOperation, id?: FieldId, save: boolean = true) { + super(data ? data : HistogramOperation.Empty, save, id); + } + + toString(): string { + return JSON.stringify(this.Data); + } + + Copy(): Field { + return new HistogramField(this.Data); + } + + ToScriptString(): string { + return `new HistogramField("${this.Data}")`; + } + + ToJson(): { type: Types, data: string, _id: string } { + return { + type: Types.HistogramOp, + data: JSON.stringify(this.Data), + _id: this.Id + } + } + + @action + static FromJson(id: string, data: any): HistogramField { + let jp = JSON.parse(data); + let X: AttributeTransformationModel | undefined; + let Y: AttributeTransformationModel | undefined; + let V: AttributeTransformationModel | undefined; + + let 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 HistogramField(new HistogramOperation(jp.SchemaName, X, Y, V, jp.Normalization), id, false); + } + } + return new HistogramField(HistogramOperation.Empty, id, false); + } +} \ No newline at end of file diff --git a/src/client/northstar/dash-nodes/HistogramBox.scss b/src/client/northstar/dash-nodes/HistogramBox.scss new file mode 100644 index 000000000..b11840a65 --- /dev/null +++ b/src/client/northstar/dash-nodes/HistogramBox.scss @@ -0,0 +1,34 @@ +.histogrambox-container { + padding: 0vw; + position: absolute; + text-align: center; + width: 100%; + height: 100%; + background: black; + } + .histogrambox-xaxislabel { + position:absolute; + width:100%; + text-align: center; + bottom:0; + background: lightgray; + font-size: 14; + font-weight: bold; + } + .histogrambox-yaxislabel { + position:absolute; + height:100%; + width: 25px; + bottom:0; + background: lightgray; + } + .histogrambox-yaxislabel-text { + position:absolute; + transform-origin: left; + transform: rotate(-90deg); + text-align: center; + 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 new file mode 100644 index 000000000..9f8c2cfd0 --- /dev/null +++ b/src/client/northstar/dash-nodes/HistogramBox.tsx @@ -0,0 +1,161 @@ +import React = require("react") +import { action, computed, observable, reaction, runInAction } from "mobx"; +import { observer } from "mobx-react"; +import Measure from "react-measure"; +import { Dictionary } from "typescript-collections"; +import { FieldWaiting, Opt } from "../../../fields/Field"; +import { KeyStore } from "../../../fields/KeyStore"; +import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; +import { FilterModel } from '../../northstar/core/filter/FilterModel'; +import { ChartType, VisualBinRange } from '../../northstar/model/binRanges/VisualBinRange'; +import { VisualBinRangeHelper } from "../../northstar/model/binRanges/VisualBinRangeHelper"; +import { AggregateBinRange, BinRange, DoubleValueAggregateResult, HistogramResult, Catalog } from "../../northstar/model/idea/idea"; +import { ModelHelpers } from "../../northstar/model/ModelHelpers"; +import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; +import { PIXIRectangle } from "../../northstar/utils/MathUtil"; +import { SizeConverter } from "../../northstar/utils/SizeConverter"; +import { DragManager } from "../../util/DragManager"; +import { FieldView, FieldViewProps } from "../../views/nodes/FieldView"; +import { HistogramField } from "../dash-fields/HistogramField"; +import "../utils/Extensions" +import "./HistogramBox.scss"; +import { HistogramBoxPrimitives } from './HistogramBoxPrimitives'; +import { HistogramLabelPrimitives } from "./HistogramLabelPrimitives"; + +export interface HistogramPrimitivesProps { + HistoBox: HistogramBox; +} + +@observer +export class HistogramBox extends React.Component { + public static LayoutString(fieldStr: string = "DataKey") { return FieldView.LayoutString(HistogramBox, fieldStr) } + private _dropXRef = React.createRef(); + private _dropYRef = React.createRef(); + private _dropXDisposer?: DragManager.DragDropDisposer; + private _dropYDisposer?: DragManager.DragDropDisposer; + + @observable public PanelWidth: number = 100; + @observable public PanelHeight: number = 100; + @observable public HistoOp: HistogramOperation = HistogramOperation.Empty; + @observable public VisualBinRanges: VisualBinRange[] = []; + @observable public ValueRange: number[] = []; + @observable public SizeConverter: SizeConverter = new SizeConverter(); + + @computed get createOperationParamsCache() { return this.HistoOp.CreateOperationParameters(); } + @computed get HistogramResult() { return this.HistoOp ? this.HistoOp.Result as HistogramResult : undefined; } + @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; + } + + constructor(props: FieldViewProps) { + super(props); + } + + @action + dropX = (e: Event, de: DragManager.DropEvent) => { + if (de.data instanceof DragManager.DocumentDragData) { + let h = de.data.draggedDocument.GetT(KeyStore.Data, HistogramField); + if (h && h != FieldWaiting) { + this.HistoOp.X = h.Data.X; + } + e.stopPropagation(); + e.preventDefault(); + } + } + @action + dropY = (e: Event, de: DragManager.DropEvent) => { + if (de.data instanceof DragManager.DocumentDragData) { + let h = de.data.draggedDocument.GetT(KeyStore.Data, HistogramField); + if (h && h != FieldWaiting) { + this.HistoOp.Y = h.Data.X; + } + e.stopPropagation(); + e.preventDefault(); + } + } + + componentDidMount() { + if (this._dropXRef.current) { + this._dropXDisposer = DragManager.MakeDropTarget(this._dropXRef.current, { handlers: { drop: this.dropX.bind(this) } }); + } + if (this._dropYRef.current) { + this._dropYDisposer = DragManager.MakeDropTarget(this._dropYRef.current, { handlers: { drop: 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.PanelHeight, this.PanelWidth], () => this.SizeConverter.SetIsSmall(this.PanelWidth < 40 && this.PanelHeight < 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]); + } + }); + } + + @action + xLabelPointerDown = (e: React.PointerEvent) => { + + } + + componentWillUnmount() { + if (this._dropXDisposer) + this._dropXDisposer(); + if (this._dropYDisposer) + this._dropYDisposer(); + } + + activateHistogramOperation(catalog?: Catalog) { + if (catalog) { + this.props.doc.GetTAsync(this.props.fieldKey, HistogramField).then((histoOp: Opt) => runInAction(() => { + this.HistoOp = histoOp ? histoOp.Data : HistogramOperation.Empty; + if (this.HistoOp != HistogramOperation.Empty) { + reaction(() => this.props.doc.GetList(KeyStore.LinkedFromDocs, []), docs => this.HistoOp.Links.splice(0, this.HistoOp.Links.length, ...docs), { fireImmediately: true }); + reaction(() => this.createOperationParamsCache, () => this.HistoOp.Update(), { fireImmediately: true }); + } + })); + } + } + render() { + let labelY = this.HistoOp && this.HistoOp.Y ? this.HistoOp.Y.PresentedName : "<...>"; + let labelX = this.HistoOp && this.HistoOp.X ? this.HistoOp.X.PresentedName : "<...>"; + var h = this.props.isTopMost ? this.PanelHeight : this.props.doc.GetNumber(KeyStore.Height, 0); + var w = this.props.isTopMost ? this.PanelWidth : this.props.doc.GetNumber(KeyStore.Width, 0); + let loff = this.SizeConverter.LeftOffset; + let toff = this.SizeConverter.TopOffset; + let roff = this.SizeConverter.RightOffset; + let boff = this.SizeConverter.BottomOffset; + return ( + runInAction(() => { this.PanelWidth = r.entry.width; this.PanelHeight = r.entry.height })}> + {({ measureRef }) => +
    +
    + + {labelY} + +
    +
    + + +
    +
    {labelX}
    +
    + } +
    + ) + } +} + diff --git a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.scss b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.scss new file mode 100644 index 000000000..9d42219cc --- /dev/null +++ b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.scss @@ -0,0 +1,26 @@ +.histogramboxprimitives-border { + border: 3px; + border-style: solid; + border-color: white; + pointer-events: none; + position: absolute; +} +.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-line { + position: absolute; + background: darkGray; + 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 new file mode 100644 index 000000000..d2f1be4fd --- /dev/null +++ b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx @@ -0,0 +1,341 @@ +import React = require("react") +import { computed, observable, runInAction } from "mobx"; +import { observer } from "mobx-react"; +import { Utils as DashUtils } from '../../../Utils'; +import { AttributeTransformationModel } from "../../northstar/core/attribute/AttributeTransformationModel"; +import { FilterModel } from "../../northstar/core/filter/FilterModel"; +import { ChartType } from '../../northstar/model/binRanges/VisualBinRange'; +import { AggregateFunction, Bin, Brush, HistogramResult, MarginAggregateParameters, MarginAggregateResult } from "../../northstar/model/idea/idea"; +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 { HistogramBox, HistogramPrimitivesProps } from "./HistogramBox"; +import "./HistogramBoxPrimitives.scss"; + + +@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 binPrimitives() { + 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, key) => { + 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[]); + } + + private getSelectionToggle(binPrimitives: HistogramBinPrimitive[], allBrushIndex: number, filterModel: FilterModel) { + let allBrushPrim = ArrayUtil.FirstOrDefault(binPrimitives, bp => bp.BrushIndex == allBrushIndex); + return !allBrushPrim ? () => { } : () => 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[]); + } + + drawEntity(xFrom: number, yFrom: number, entity: JSX.Element) { + let transXpercent = xFrom / this.renderDimension * 100; + let transYpercent = yFrom / this.renderDimension * 100; + return (
    + {entity} +
    ); + } + 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 = width == 0 ? `1px` : `${(xFrom + width) / this.renderDimension * 100}%`; + let trans2Ypercent = height == 0 ? `1px` : `${(yFrom + height) / this.renderDimension * 100}%`; + let line = (
    ); + return this.drawEntity(xFrom, yFrom, line); + } + + drawRect(r: PIXIRectangle, barAxis: number, color: number | undefined, classExt: string, tapHandler: () => void = () => { }) { + 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 widthPercent = r.width / this.renderDimension * 100; + let heightPercent = r.height / this.renderDimension * 100; + let rect = (
    { if (e.button == 0) tapHandler() }} + style={{ + borderBottomStyle: barAxis == 1 ? "none" : "solid", + borderLeftStyle: barAxis == 0 ? "none" : "solid", + width: `${widthPercent}%`, + height: `${heightPercent}%`, + background: color ? `${LABColor.RGBtoHexString(color)}` : "" + }} + />); + return this.drawEntity(r.x, r.y, rect); + } + render() { + return
    + {this.xaxislines} + {this.yaxislines} + {this.binPrimitives} + {this.selectedPrimitives} +
    + } +} + +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.X.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.histoOp.getValue(normalization, bin, this.histoResult, Brush.brushIndex!); + return aggResult != undefined && aggResult > prev ? aggResult : prev; + }, Number.MIN_VALUE) + }; + } + private createHeatmapBinPrimitives(bin: Bin, brush: Brush, brushFactorSum: number): number { + + let unNormalizedValue = this.histoOp.getValue(2, bin, this.histoResult, 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.histoOp.getValue(2, bin, this.histoResult, 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._histoBox.HistoOp.getValue(2, bin, this.histoResult, 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.histoOp.getValue(1, bin, this.histoResult, 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.histoOp.getValue(0, bin, this.histoResult, 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; + } + + + 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); + var marginResult = ModelHelpers.GetAggregateResult(bin, marginAggregateKey) as MarginAggregateResult; + return !marginResult ? 0 : marginResult.absolutMargin!; + } + + 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 { + 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 (this.histoOp.BrushColors.length > 0) { + return this.histoOp.BrushColors[brush.brushIndex! % this.histoOp.BrushColors.length]; + } + return StyleConstants.HIGHLIGHT_COLOR; + } +} \ No newline at end of file diff --git a/src/client/northstar/dash-nodes/HistogramLabelPrimitives.scss b/src/client/northstar/dash-nodes/HistogramLabelPrimitives.scss new file mode 100644 index 000000000..304d33771 --- /dev/null +++ b/src/client/northstar/dash-nodes/HistogramLabelPrimitives.scss @@ -0,0 +1,13 @@ + + .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 new file mode 100644 index 000000000..45b23874d --- /dev/null +++ b/src/client/northstar/dash-nodes/HistogramLabelPrimitives.tsx @@ -0,0 +1,78 @@ +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, HistogramPrimitivesProps } from "./HistogramBox"; +import "./HistogramLabelPrimitives.scss"; + +@observer +export class HistogramLabelPrimitives extends React.Component { + componentDidMount() { + reaction(() => [this.props.HistoBox.PanelWidth, this.props.HistoBox.SizeConverter.LeftOffset, this.props.HistoBox.VisualBinRanges.length], + (fields) => HistogramLabelPrimitives.computeLabelAngle(fields[0] as number, fields[1] as number, 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.PanelWidth : this.props.HistoBox.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.PanelWidth; + xStart += Math.max(textWidth / 2, (1 - textWidth / space) * textWidth / 2) - textHeight / 2; + } + + let xPercent = axis == 1 ? `${xStart}px` : `${xStart / sc.RenderDimension * 100}%` + let yPercent = axis == 0 ? `${this.props.HistoBox.PanelHeight - sc.BottomOffset - textHeight}px` : `${yStart / sc.RenderDimension * 100}%` + + 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/model/ModelHelpers.ts b/src/client/northstar/model/ModelHelpers.ts index 8de0bd260..d0711fb69 100644 --- a/src/client/northstar/model/ModelHelpers.ts +++ b/src/client/northstar/model/ModelHelpers.ts @@ -13,11 +13,11 @@ import { CurrentUserUtils } from "../../../server/authentication/models/current_ export class ModelHelpers { - public static CreateAggregateKey(atm: AttributeTransformationModel, histogramResult: HistogramResult, + public static CreateAggregateKey(distinctAttributeParameters: AttributeParameters | undefined, atm: AttributeTransformationModel, histogramResult: HistogramResult, brushIndex: number, aggParameters?: SingleDimensionAggregateParameters): AggregateKey { { if (aggParameters == undefined) { - aggParameters = ModelHelpers.GetAggregateParameter(atm); + aggParameters = ModelHelpers.GetAggregateParameter(distinctAttributeParameters, atm); } else { aggParameters.attributeParameters = ModelHelpers.GetAttributeParameters(atm.AttributeModel); @@ -34,40 +34,40 @@ export class ModelHelpers { return ArrayUtil.IndexOfWithEqual(histogramResult.aggregateParameters!, aggParameters); } - public static GetAggregateParameter(atm: AttributeTransformationModel): AggregateParameters | undefined { + 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 = CurrentUserUtils.ActiveSchema!.distinctAttributeParameters; + avg.distinctAttributeParameters = distinctAttributeParameters; aggParam = avg; } else if (atm.AggregateFunction === AggregateFunction.Count) { var cnt = new CountAggregateParameters(); cnt.attributeParameters = ModelHelpers.GetAttributeParameters(atm.AttributeModel); - cnt.distinctAttributeParameters = CurrentUserUtils.ActiveSchema!.distinctAttributeParameters; + cnt.distinctAttributeParameters = distinctAttributeParameters; aggParam = cnt; } else if (atm.AggregateFunction === AggregateFunction.Sum) { var sum = new SumAggregateParameters(); sum.attributeParameters = ModelHelpers.GetAttributeParameters(atm.AttributeModel); - sum.distinctAttributeParameters = CurrentUserUtils.ActiveSchema!.distinctAttributeParameters; + sum.distinctAttributeParameters = distinctAttributeParameters; aggParam = sum; } return aggParam; } - public static GetAggregateParametersWithMargins(atms: Array): Array { + public static GetAggregateParametersWithMargins(distinctAttributeParameters: AttributeParameters | undefined, atms: Array): Array { var aggregateParameters = new Array(); atms.forEach(agg => { - var aggParams = ModelHelpers.GetAggregateParameter(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 = CurrentUserUtils.ActiveSchema!.distinctAttributeParameters; + margin.distinctAttributeParameters = distinctAttributeParameters; aggregateParameters.push(margin); } }); diff --git a/src/client/northstar/model/binRanges/VisualBinRangeHelper.ts b/src/client/northstar/model/binRanges/VisualBinRangeHelper.ts index 9eae39800..53d585bb4 100644 --- a/src/client/northstar/model/binRanges/VisualBinRangeHelper.ts +++ b/src/client/northstar/model/binRanges/VisualBinRangeHelper.ts @@ -1,4 +1,4 @@ -import { BinRange, NominalBinRange, QuantitativeBinRange, Exception, AlphabeticBinRange, DateTimeBinRange, AggregateBinRange, DoubleValueAggregateResult, HistogramResult } from "../idea/idea"; +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"; @@ -30,13 +30,13 @@ export class VisualBinRangeHelper { throw new Exception() } - public static GetVisualBinRange(dataBinRange: BinRange, histoResult: HistogramResult, attr: AttributeTransformationModel, chartType: ChartType): VisualBinRange { + 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(attr, histoResult, ModelHelpers.AllBrushIndex(histoResult)); + var aggregateKey = ModelHelpers.CreateAggregateKey(distinctAttributeParameters, attr, histoResult, ModelHelpers.AllBrushIndex(histoResult)); var minValue = Number.MAX_VALUE; var maxValue = Number.MIN_VALUE; for (var b = 0; b < histoResult.brushes!.length; b++) { diff --git a/src/client/northstar/operations/BaseOperation.ts b/src/client/northstar/operations/BaseOperation.ts index 7db6fcb91..94e0849af 100644 --- a/src/client/northstar/operations/BaseOperation.ts +++ b/src/client/northstar/operations/BaseOperation.ts @@ -10,9 +10,9 @@ export abstract class BaseOperation { @observable public Error: string = ""; @observable public OverridingFilters: FilterModel[] = []; - @observable public Result: Result | undefined; + @observable public Result?: Result = undefined; @observable public ComputationStarted: boolean = false; - public OperationReference: OperationReference | undefined = undefined; + public OperationReference?: OperationReference = undefined; private static _nextId = 0; public RequestSalt: string = ""; diff --git a/src/client/northstar/operations/HistogramOperation.ts b/src/client/northstar/operations/HistogramOperation.ts index 6c7288d42..8a0f648f6 100644 --- a/src/client/northstar/operations/HistogramOperation.ts +++ b/src/client/northstar/operations/HistogramOperation.ts @@ -27,6 +27,8 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons @observable public V: AttributeTransformationModel; @observable public BrusherModels: BrushLinkModel[] = []; @observable public BrushableModels: BrushLinkModel[] = []; + @observable public SchemaName: string; + @computed public get Schema() { return CurrentUserUtils.GetNorthstarSchema(this.SchemaName); } @action public AddFilterModels(filterModels: FilterModel[]): void { @@ -38,23 +40,24 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons } public getValue(axis: number, bin: Bin, result: HistogramResult, brushIndex: number) { - var aggregateKey = ModelHelpers.CreateAggregateKey(axis == 0 ? this.X : axis == 1 ? this.Y : this.V, result, brushIndex); + var aggregateKey = ModelHelpers.CreateAggregateKey(this.Schema!.distinctAttributeParameters, axis == 0 ? this.X : axis == 1 ? this.Y : this.V, result, brushIndex); let dataValue = ModelHelpers.GetAggregateResult(bin, aggregateKey) as DoubleValueAggregateResult; return dataValue != null && dataValue.hasResult ? dataValue.result : undefined; } - public static Empty = new HistogramOperation(new AttributeTransformationModel(new ColumnAttributeModel(new Attribute())), new AttributeTransformationModel(new ColumnAttributeModel(new Attribute())), new AttributeTransformationModel(new ColumnAttributeModel(new Attribute()))); + 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()))); Equals(other: Object): boolean { throw new Error("Method not implemented."); } - constructor(x: AttributeTransformationModel, y: AttributeTransformationModel, v: AttributeTransformationModel, normalized?: number) { + 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; } @computed @@ -93,7 +96,7 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons allAttributes = ArrayUtil.Distinct(allAttributes.filter(a => a.AggregateFunction !== AggregateFunction.None)); let numericDataTypes = [DataType.Int, DataType.Double, DataType.Float]; - let perBinAggregateParameters: AggregateParameters[] = ModelHelpers.GetAggregateParametersWithMargins(allAttributes); + 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)) @@ -112,7 +115,7 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons let [perBinAggregateParameters, globalAggregateParameters] = this.GetAggregateParameters(this.X, this.Y, this.V); return new HistogramOperationParameters({ enableBrushComputation: true, - adapterName: CurrentUserUtils.ActiveSchema!.displayName, + 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), diff --git a/src/client/northstar/utils/SizeConverter.ts b/src/client/northstar/utils/SizeConverter.ts index ffd162a83..30627dfd5 100644 --- a/src/client/northstar/utils/SizeConverter.ts +++ b/src/client/northstar/utils/SizeConverter.ts @@ -68,10 +68,14 @@ export class SizeConverter { return [undefined, undefined]; } - public DataToScreenAxisRange(visualBinRanges: VisualBinRange[], index: number, bin: Bin) { + 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; diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index 09778ac77..2f20b102c 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -58,7 +58,7 @@ export class Main extends React.Component { @observable private mainfreeform?: Document; @observable public pwidth: number = 0; @observable public pheight: number = 0; - private _northstarColumns: Document[] = []; + private _northstarSchemas: Document[] = []; @computed private get mainContainer(): Document | undefined { let doc = this.userDocument.GetT(KeyStore.ActiveWorkspace, Document); @@ -245,7 +245,7 @@ export class Main extends React.Component { let addTextNode = action(() => Documents.TextDocument({ width: 200, height: 200, title: "a text note" })) let addColNode = action(() => Documents.FreeformDocument([], { width: 200, height: 200, title: "a freeform collection" })); let addSchemaNode = action(() => Documents.SchemaDocument([], { width: 200, height: 200, title: "a schema collection" })); - let addTreeNode = action(() => Documents.TreeDocument(this._northstarColumns, { width: 200, height: 200, title: "a tree collection" })); + let addTreeNode = action(() => Documents.TreeDocument(this._northstarSchemas, { width: 100, height: 400, title: "northstar schemas" })); let addVideoNode = action(() => Documents.VideoDocument(videourl, { width: 200, height: 200, title: "video node" })); let addPDFNode = action(() => Documents.PdfDocument(pdfurl, { width: 200, height: 200, title: "a schema collection" })); let addImageNode = action(() => Documents.ImageDocument(imgurl, { width: 200, height: 200, title: "an image of a cat" })); @@ -334,24 +334,27 @@ export class Main extends React.Component { // --------------- Northstar hooks ------------- / @action SetNorthstarCatalog(ctlog: Catalog) { + CurrentUserUtils.NorthstarDBCatalog = ctlog; if (ctlog && ctlog.schemas) { - CurrentUserUtils.ActiveSchema = ArrayUtil.FirstOrDefault(ctlog.schemas!, (s: Schema) => s.displayName === "mimic"); - CurrentUserUtils.GetAllNorthstarColumnAttributes().map(attr => { - Server.GetField(attr.displayName!, action((field: Opt) => { - if (field instanceof Document) { - this._northstarColumns.push(field); - } else { - var atmod = new ColumnAttributeModel(attr); - let histoOp = new HistogramOperation( - new AttributeTransformationModel(atmod, AggregateFunction.None), - new AttributeTransformationModel(atmod, AggregateFunction.Count), - new AttributeTransformationModel(atmod, AggregateFunction.Count)); - this._northstarColumns.push(Documents.HistogramDocument(histoOp, { width: 200, height: 200, title: attr.displayName!, northstarSchema: CurrentUserUtils.ActiveSchema!.displayName! }, attr.displayName!)); - } - })); + this._northstarSchemas = ctlog.schemas.map(schema => { + let schemaDoc = Documents.TreeDocument([], { width: 50, height: 100, title: schema.displayName! }); + let schemaDocuments = schemaDoc.GetList(KeyStore.Data, [] as Document[]); + CurrentUserUtils.GetAllNorthstarColumnAttributes(schema).map(attr => { + Server.GetField(attr.displayName!, action((field: Opt) => { + if (field instanceof Document) { + 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(Documents.HistogramDocument(histoOp, { width: 200, height: 200, title: attr.displayName! }, attr.displayName!)); + } + })); + }); + return schemaDoc; }) - console.log("Activating schema " + CurrentUserUtils.ActiveSchema!.displayName!) - CurrentUserUtils.ActiveSchemaName = CurrentUserUtils.ActiveSchema!.displayName!; } } async initializeNorthstar(): Promise { diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index b54744337..77551649c 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -19,8 +19,7 @@ import { KeyValueBox } from "./KeyValueBox"; import { PDFBox } from "./PDFBox"; import { VideoBox } from "./VideoBox"; import { WebBox } from "./WebBox"; -import { HistogramBox } from "./HistogramBox"; -import { HistogramBoxPrimitives } from "./HistogramBoxPrimitives"; +import { HistogramBox } from "../../northstar/dash-nodes/HistogramBox"; import React = require("react"); const JsxParser = require('react-jsx-parser').default; //TODO Why does this need to be imported like this? @@ -54,7 +53,7 @@ export class DocumentContentsView extends React.ComponentError loading layout keys

    ; } return { } private dropDisposer?: DragManager.DragDropDisposer; - protected createDropTarget = (ele: HTMLDivElement) => { - - } componentDidMount() { if (this._mainCont.current) { diff --git a/src/client/views/nodes/HistogramBox.scss b/src/client/views/nodes/HistogramBox.scss deleted file mode 100644 index 2660b1b75..000000000 --- a/src/client/views/nodes/HistogramBox.scss +++ /dev/null @@ -1,22 +0,0 @@ -.histogrambox-container { - padding: 0vw; - position: absolute; - text-align: center; - width: 100%; - height: 100%; - } - .histogrambox-xaxislabel { - position:absolute; - width:100%; - text-align: center; - bottom:0; - font-size: 14; - font-weight: bold; - } - - .histogrambox-container { - position:absolute; - width:100%; - height: 100%; - } - \ No newline at end of file diff --git a/src/client/views/nodes/HistogramBox.tsx b/src/client/views/nodes/HistogramBox.tsx deleted file mode 100644 index 3307925a2..000000000 --- a/src/client/views/nodes/HistogramBox.tsx +++ /dev/null @@ -1,105 +0,0 @@ -import React = require("react") -import { computed, observable, reaction, runInAction } from "mobx"; -import { observer } from "mobx-react"; -import Measure from "react-measure"; -import { Dictionary } from "typescript-collections"; -import { Opt } from "../../../fields/Field"; -import { HistogramField } from "../../../fields/HistogramField"; -import { KeyStore } from "../../../fields/KeyStore"; -import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; -import { FilterModel } from '../../northstar/core/filter/FilterModel'; -import { ChartType, VisualBinRange } from '../../northstar/model/binRanges/VisualBinRange'; -import { VisualBinRangeHelper } from "../../northstar/model/binRanges/VisualBinRangeHelper"; -import { AggregateBinRange, BinRange, DoubleValueAggregateResult, HistogramResult } from "../../northstar/model/idea/idea"; -import { ModelHelpers } from "../../northstar/model/ModelHelpers"; -import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; -import { PIXIRectangle } from "../../northstar/utils/MathUtil"; -import { SizeConverter } from "../../northstar/utils/SizeConverter"; -import "./../../northstar/utils/Extensions"; -import { FieldView, FieldViewProps } from './FieldView'; -import "./HistogramBox.scss"; -import { HistogramBoxPrimitives } from './HistogramBoxPrimitives'; -import { HistogramLabelPrimitives } from "./HistogramLabelPrimitives"; - -export interface HistogramPrimitivesProps { - HistoBox: HistogramBox; -} - -@observer -export class HistogramBox extends React.Component { - public static LayoutString(fieldStr: string = "DataKey") { return FieldView.LayoutString(HistogramBox, fieldStr) } - public HitTargets: Dictionary = new Dictionary(); - - @observable public PanelWidth: number = 100; - @observable public PanelHeight: number = 100; - @observable public HistoOp?: HistogramOperation; - @observable public VisualBinRanges: VisualBinRange[] = []; - @observable public ValueRange: number[] = []; - @observable public SizeConverter: SizeConverter = new SizeConverter(); - - @computed get createOperationParamsCache() { return this.HistoOp!.CreateOperationParameters(); } - @computed get HistogramResult() { return this.HistoOp ? this.HistoOp.Result as HistogramResult : undefined; } - @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; - } - - componentDidMount() { - reaction(() => [CurrentUserUtils.ActiveSchemaName, this.props.doc.GetText(KeyStore.NorthstarSchema, "?")], - (params: string[]) => params[0] === params[1] && this.activateHistogramOperation(), { fireImmediately: true }); - reaction(() => [this.VisualBinRanges && this.VisualBinRanges.slice()], () => this.SizeConverter.SetVisualBinRanges(this.VisualBinRanges)); - reaction(() => [this.PanelHeight, this.PanelWidth], () => this.SizeConverter.SetIsSmall(this.PanelWidth < 40 && this.PanelHeight < 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(br, this.HistogramResult!, ind ? this.HistoOp!.Y : this.HistoOp!.X, this.ChartType))); - - let valueAggregateKey = ModelHelpers.CreateAggregateKey(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.MIN_VALUE, Number.MAX_VALUE]); - } - }); - } - - activateHistogramOperation() { - this.props.doc.GetTAsync(this.props.fieldKey, HistogramField).then((histoOp: Opt) => { - if (histoOp) { - runInAction(() => this.HistoOp = histoOp.Data); - reaction(() => this.props.doc.GetList(KeyStore.LinkedFromDocs, []), docs => this.HistoOp!.Links.splice(0, this.HistoOp!.Links.length, ...docs), { fireImmediately: true }); - reaction(() => this.createOperationParamsCache, () => this.HistoOp!.Update(), { fireImmediately: true }); - } - }) - } - render() { - let label = this.HistoOp && this.HistoOp.X ? this.HistoOp.X.AttributeModel.DisplayName : "<...>"; - var h = this.props.isTopMost ? this.PanelHeight : this.props.doc.GetNumber(KeyStore.Height, 0); - var w = this.props.isTopMost ? this.PanelWidth : this.props.doc.GetNumber(KeyStore.Width, 0); - let loff = this.SizeConverter.LeftOffset; - let toff = this.SizeConverter.TopOffset; - let roff = this.SizeConverter.RightOffset; - let boff = this.SizeConverter.BottomOffset; - return ( - runInAction(() => { this.PanelWidth = r.entry.width; this.PanelHeight = r.entry.height })}> - {({ measureRef }) => -
    -
    - - -
    -
    {label}
    -
    - } -
    - ) - } -} - diff --git a/src/client/views/nodes/HistogramBoxPrimitives.scss b/src/client/views/nodes/HistogramBoxPrimitives.scss deleted file mode 100644 index 85f2c092d..000000000 --- a/src/client/views/nodes/HistogramBoxPrimitives.scss +++ /dev/null @@ -1,25 +0,0 @@ -.histogramboxprimitives-border { - border: 3px; - border-style: solid; - border-color: #282828; - pointer-events: none; - position: absolute; -} -.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-line { - position: absolute; - background: lightgray; -} \ No newline at end of file diff --git a/src/client/views/nodes/HistogramBoxPrimitives.tsx b/src/client/views/nodes/HistogramBoxPrimitives.tsx deleted file mode 100644 index f15cb5689..000000000 --- a/src/client/views/nodes/HistogramBoxPrimitives.tsx +++ /dev/null @@ -1,336 +0,0 @@ -import React = require("react") -import { computed, observable, runInAction, trace } from "mobx"; -import { observer } from "mobx-react"; -import { Utils as DashUtils } from '../../../Utils'; -import { AttributeTransformationModel } from "../../northstar/core/attribute/AttributeTransformationModel"; -import { ChartType } from '../../northstar/model/binRanges/VisualBinRange'; -import { AggregateFunction, Bin, Brush, HistogramResult, MarginAggregateParameters, MarginAggregateResult, BinLabel } from "../../northstar/model/idea/idea"; -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 { HistogramBox, HistogramPrimitivesProps } from "./HistogramBox"; -import "./HistogramBoxPrimitives.scss"; -import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; -import { FilterModel } from "../../northstar/core/filter/FilterModel"; - - -@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 binPrimitives() { - 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, key) => { - let drawPrims = new HistogramBinPrimitiveCollection(histoResult!.bins![key], this.props.HistoBox); - let filterModel = ModelHelpers.GetBinFilterModel(histoResult!.bins![key], allBrushIndex, histoResult!, this.histoOp!.X, this.histoOp!.Y); - - this.props.HistoBox.HitTargets.setValue(drawPrims.HitGeom, filterModel); - - let toggle = this.getSelectionToggle(drawPrims.BinPrimitives, allBrushIndex, filterModel); - 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[]); - } - - private getSelectionToggle(binPrimitives: HistogramBinPrimitive[], allBrushIndex: number, filterModel: FilterModel) { - let allBrushPrim = ArrayUtil.FirstOrDefault(binPrimitives, bp => bp.BrushIndex == allBrushIndex); - return !allBrushPrim ? () => { } : () => 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[]); - } - - drawEntity(xFrom: number, yFrom: number, entity: JSX.Element) { - let transXpercent = xFrom / this.renderDimension * 100; - let transYpercent = yFrom / this.renderDimension * 100; - return (
    - {entity} -
    ); - } - 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 = width == 0 ? `1px` : `${(xFrom + width) / this.renderDimension * 100}%`; - let trans2Ypercent = height == 0 ? `1px` : `${(yFrom + height) / this.renderDimension * 100}%`; - let line = (
    ); - return this.drawEntity(xFrom, yFrom, line); - } - - drawRect(r: PIXIRectangle, barAxis: number, color: number | undefined, classExt: string, tapHandler: () => void = () => { }) { - let widthPercent = r.width / this.renderDimension * 100; - let heightPercent = r.height / this.renderDimension * 100; - let rect = (
    { if (e.button == 0) tapHandler() }} - style={{ - borderBottomStyle: barAxis == 1 ? "none" : "solid", - borderLeftStyle: barAxis == 0 ? "none" : "solid", - width: `${widthPercent}%`, - height: `${heightPercent}%`, - background: color ? `${LABColor.RGBtoHexString(color)}` : "" - }} - />); - return this.drawEntity(r.x, r.y, rect); - } - render() { - return
    - {this.xaxislines} - {this.yaxislines} - {this.binPrimitives} - {this.selectedPrimitives} -
    - } -} - -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.X.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.histoOp.getValue(normalization, bin, this.histoResult, Brush.brushIndex!); - return aggResult != undefined && aggResult > prev ? aggResult : prev; - }, Number.MIN_VALUE) - }; - } - private createHeatmapBinPrimitives(bin: Bin, brush: Brush, brushFactorSum: number): number { - - let unNormalizedValue = this.histoOp!.getValue(2, bin, this.histoResult, 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.histoOp.getValue(2, bin, this.histoResult, ModelHelpers.AllBrushIndex(this.histoResult)) - - // bcz: are these calls needed? - let [xFrom, xTo] = this.sizeConverter.DataToScreenAxisRange(this._histoBox.VisualBinRanges, 0, bin); - let [yFrom, yTo] = this.sizeConverter.DataToScreenAxisRange(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._histoBox.HistoOp!.getValue(2, bin, this.histoResult, brush.brushIndex!); - if (unNormalizedValue != undefined) { - let [xFrom, xTo] = this.sizeConverter.DataToScreenPointRange(0, bin, ModelHelpers.CreateAggregateKey(this.histoOp.X, this.histoResult, brush.brushIndex!)); - let [yFrom, yTo] = this.sizeConverter.DataToScreenPointRange(1, bin, ModelHelpers.CreateAggregateKey(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.histoOp.getValue(1, bin, this.histoResult, brush.brushIndex!); - if (dataValue != undefined) { - let [yFrom, yValue, yTo] = this.sizeConverter.DataToScreenNormalizedRange(dataValue, normalization, 1, binBrushMaxAxis); - let [xFrom, xTo] = this.sizeConverter.DataToScreenAxisRange(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.histoOp.getValue(0, bin, this.histoResult, brush.brushIndex!); - if (dataValue != undefined) { - let [xFrom, xValue, xTo] = this.sizeConverter.DataToScreenNormalizedRange(dataValue, normalization, 0, binBrushMaxAxis); - let [yFrom, yTo] = this.sizeConverter.DataToScreenAxisRange(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; - } - - - private getMargin(bin: Bin, brush: Brush, axis: AttributeTransformationModel) { - var marginParams = new MarginAggregateParameters(); - marginParams.aggregateFunction = axis.AggregateFunction; - var marginAggregateKey = ModelHelpers.CreateAggregateKey(axis, this.histoResult, brush.brushIndex!, marginParams); - var marginResult = ModelHelpers.GetAggregateResult(bin, marginAggregateKey) as MarginAggregateResult; - return !marginResult ? 0 : marginResult.absolutMargin!; - } - - 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 { - 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 (this.histoOp.BrushColors.length > 0) { - return this.histoOp.BrushColors[brush.brushIndex! % this.histoOp.BrushColors.length]; - } - return StyleConstants.HIGHLIGHT_COLOR; - } -} \ No newline at end of file diff --git a/src/client/views/nodes/HistogramLabelPrimitives.scss b/src/client/views/nodes/HistogramLabelPrimitives.scss deleted file mode 100644 index d8ee88d72..000000000 --- a/src/client/views/nodes/HistogramLabelPrimitives.scss +++ /dev/null @@ -1,12 +0,0 @@ - - .histogramLabelPrimitives-gridlabel { - position:absolute; - transform-origin: left top; - font-size: 11; - } - .histogramLabelPrimitives-placer { - position:absolute; - width:100%; - height:100%; - pointer-events: none; - } \ No newline at end of file diff --git a/src/client/views/nodes/HistogramLabelPrimitives.tsx b/src/client/views/nodes/HistogramLabelPrimitives.tsx deleted file mode 100644 index 7f365e45b..000000000 --- a/src/client/views/nodes/HistogramLabelPrimitives.tsx +++ /dev/null @@ -1,78 +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 "../../northstar/model/binRanges/NominalVisualBinRange"; -import { StyleConstants } from "../../northstar/utils/StyleContants"; -import "./../../northstar/utils/Extensions"; -import "./HistogramLabelPrimitives.scss"; -import { HistogramBox, HistogramPrimitivesProps } from "./HistogramBox"; - -@observer -export class HistogramLabelPrimitives extends React.Component { - componentDidMount() { - reaction(() => [this.props.HistoBox.PanelWidth, this.props.HistoBox.SizeConverter.LeftOffset, this.props.HistoBox.VisualBinRanges.length], - (fields) => HistogramLabelPrimitives.computeLabelAngle(fields[0] as number, fields[1] as number, 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.PanelWidth : this.props.HistoBox.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.PanelWidth; - xStart += Math.max(textWidth / 2, (1 - textWidth / space) * textWidth / 2) - textHeight / 2; - } - - let xPercent = axis == 1 ? `${xStart}px` : `${xStart / sc.RenderDimension * 100}%` - let yPercent = axis == 0 ? `${this.props.HistoBox.PanelHeight - sc.BottomOffset - textHeight}px` : `${yStart / sc.RenderDimension * 100}%` - - 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/fields/HistogramField.ts b/src/fields/HistogramField.ts deleted file mode 100644 index bb0014ab3..000000000 --- a/src/fields/HistogramField.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { BasicField } from "./BasicField"; -import { Field, FieldId } from "./Field"; -import { Types } from "../server/Message"; -import { HistogramOperation } from "../client/northstar/operations/HistogramOperation"; -import { action } from "mobx"; -import { AttributeTransformationModel } from "../client/northstar/core/attribute/AttributeTransformationModel"; -import { ColumnAttributeModel } from "../client/northstar/core/attribute/AttributeModel"; -import { CurrentUserUtils } from "../server/authentication/models/current_user_utils"; - - -export class HistogramField extends BasicField { - constructor(data?: HistogramOperation, id?: FieldId, save: boolean = true) { - super(data ? data : HistogramOperation.Empty, save, id); - } - - toString(): string { - return JSON.stringify(this.Data); - } - - Copy(): Field { - return new HistogramField(this.Data); - } - - ToScriptString(): string { - return `new HistogramField("${this.Data}")`; - } - - ToJson(): { type: Types, data: string, _id: string } { - return { - type: Types.HistogramOp, - data: JSON.stringify(this.Data), - _id: this.Id - } - } - - @action - static FromJson(id: string, data: any): HistogramField { - let jp = JSON.parse(data); - let X: AttributeTransformationModel | undefined; - let Y: AttributeTransformationModel | undefined; - let V: AttributeTransformationModel | undefined; - - CurrentUserUtils.GetAllNorthstarColumnAttributes().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 HistogramField(new HistogramOperation(X, Y, V, jp.Normalization), id, false); - } - return new HistogramField(HistogramOperation.Empty, id, false); - } -} \ No newline at end of file diff --git a/src/fields/KeyStore.ts b/src/fields/KeyStore.ts index 09dddf962..aa0b9ce92 100644 --- a/src/fields/KeyStore.ts +++ b/src/fields/KeyStore.ts @@ -44,5 +44,4 @@ export namespace KeyStore { export const Archives = new Key("Archives"); export const Updated = new Key("Updated"); export const Workspaces = new Key("Workspaces"); - export const NorthstarSchema = new Key("NorthstarSchema"); } diff --git a/src/server/ServerUtil.ts b/src/server/ServerUtil.ts index f958df04b..98a7a1451 100644 --- a/src/server/ServerUtil.ts +++ b/src/server/ServerUtil.ts @@ -17,8 +17,7 @@ import { VideoField } from '../fields/VideoField'; import { InkField } from '../fields/InkField'; import { PDFField } from '../fields/PDFField'; import { TupleField } from '../fields/TupleField'; -import { HistogramField } from '../fields/HistogramField'; - +import { HistogramField } from '../client/northstar/dash-fields/HistogramField'; diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 4b42e40b6..0ac85b446 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -7,8 +7,9 @@ import { Document } from "../../../fields/Document"; import { KeyStore } from "../../../fields/KeyStore"; import { ListField } from "../../../fields/ListField"; import { Documents } from "../../../client/documents/Documents"; -import { Schema, Attribute, AttributeGroup } from "../../../client/northstar/model/idea/idea"; +import { Schema, Attribute, AttributeGroup, Catalog } from "../../../client/northstar/model/idea/idea"; import { observable, computed, action } from "mobx"; +import { ArrayUtil } from "../../../client/northstar/utils/ArrayUtil"; export class CurrentUserUtils { private static curr_email: string; @@ -16,8 +17,7 @@ export class CurrentUserUtils { private static user_document: Document; //TODO tfs: these should be temporary... private static mainDocId: string | undefined; - private static activeSchema: Schema | undefined; - @observable public static ActiveSchemaName: string = ""; + @observable private static catalog?: Catalog; public static get email(): string { return this.curr_email; @@ -39,12 +39,18 @@ export class CurrentUserUtils { this.mainDocId = id; } - - public static get ActiveSchema(): Schema | undefined { - return this.activeSchema; + @computed public static get NorthstarDBCatalog(): Catalog | undefined { + return this.catalog; + } + public static set NorthstarDBCatalog(ctlog: Catalog | undefined) { + this.catalog = ctlog; } - public static GetAllNorthstarColumnAttributes() { - if (!this.ActiveSchema || !this.ActiveSchema.rootAttributeGroup) { + public static GetNorthstarSchema(name: string): Schema | undefined { + return !this.catalog || !this.catalog.schemas ? undefined : + ArrayUtil.FirstOrDefault(this.catalog.schemas, (s: Schema) => s.displayName === name); + } + public static GetAllNorthstarColumnAttributes(schema: Schema) { + if (!schema || !schema.rootAttributeGroup) { return []; } const recurs = (attrs: Attribute[], g: AttributeGroup) => { @@ -56,13 +62,10 @@ export class CurrentUserUtils { } }; const allAttributes: Attribute[] = new Array(); - recurs(allAttributes, this.ActiveSchema.rootAttributeGroup); + recurs(allAttributes, schema.rootAttributeGroup); return allAttributes; } - public static set ActiveSchema(id: Schema | undefined) { - this.activeSchema = id; - } private static createUserDocument(id: string): Document { let doc = new Document(id); -- cgit v1.2.3-70-g09d2 From da7a12f9b49b43534658524b1da846948fbf3947 Mon Sep 17 00:00:00 2001 From: bob Date: Fri, 29 Mar 2019 14:37:26 -0400 Subject: fixed some bugs added some small features to histograms. --- src/client/Server.ts | 4 ++-- src/client/documents/Documents.ts | 4 ++-- src/client/northstar/dash-nodes/HistogramBox.tsx | 17 ++++++++++++----- .../northstar/dash-nodes/HistogramBoxPrimitives.tsx | 5 ++++- src/client/northstar/utils/SizeConverter.ts | 2 +- src/client/util/DragManager.ts | 2 ++ src/client/views/Main.tsx | 6 +++--- .../collectionFreeForm/CollectionFreeFormView.scss | 20 ++++++++++---------- 8 files changed, 36 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/client/Server.ts b/src/client/Server.ts index feafe9eb4..37e3c2c0d 100644 --- a/src/client/Server.ts +++ b/src/client/Server.ts @@ -75,7 +75,7 @@ export class Server { existingFields[id] = field; } } - SocketStub.SEND_FIELDS_REQUEST(neededFieldIds, (fields) => { + SocketStub.SEND_FIELDS_REQUEST(neededFieldIds, action((fields: FieldMap) => { for (let id of neededFieldIds) { let field = fields[id]; if (field) { @@ -104,7 +104,7 @@ export class Server { cb({ ...fields, ...existingFields }) } }, { fireImmediately: true }) - }); + })); }; if (callback) { fn(callback); diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 663ccae61..0bf275df8 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -190,8 +190,8 @@ export namespace Documents { return assignToDelegate(SetInstanceOptions(GetAudioPrototype(), options, [new URL(url), AudioField]), options); } - export function HistogramDocument(histoOp: HistogramOperation, options: DocumentOptions = {}, id?: string) { - return assignToDelegate(SetInstanceOptions(GetHistogramPrototype(), options, [histoOp, HistogramField], id).MakeDelegate(), options); + export function HistogramDocument(histoOp: HistogramOperation, options: DocumentOptions = {}, id?: string, delegId?: string) { + return assignToDelegate(SetInstanceOptions(GetHistogramPrototype(), options, [histoOp, HistogramField], id).MakeDelegate(delegId), options); } export function TextDocument(options: DocumentOptions = {}) { return assignToDelegate(SetInstanceOptions(GetTextPrototype(), options, ["", TextField]).MakeDelegate(), options); diff --git a/src/client/northstar/dash-nodes/HistogramBox.tsx b/src/client/northstar/dash-nodes/HistogramBox.tsx index 9f8c2cfd0..dba4ce900 100644 --- a/src/client/northstar/dash-nodes/HistogramBox.tsx +++ b/src/client/northstar/dash-nodes/HistogramBox.tsx @@ -9,7 +9,7 @@ import { CurrentUserUtils } from "../../../server/authentication/models/current_ import { FilterModel } from '../../northstar/core/filter/FilterModel'; import { ChartType, VisualBinRange } from '../../northstar/model/binRanges/VisualBinRange'; import { VisualBinRangeHelper } from "../../northstar/model/binRanges/VisualBinRangeHelper"; -import { AggregateBinRange, BinRange, DoubleValueAggregateResult, HistogramResult, Catalog } from "../../northstar/model/idea/idea"; +import { AggregateBinRange, BinRange, DoubleValueAggregateResult, HistogramResult, Catalog, AggregateFunction } from "../../northstar/model/idea/idea"; import { ModelHelpers } from "../../northstar/model/ModelHelpers"; import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; import { PIXIRectangle } from "../../northstar/utils/MathUtil"; @@ -21,6 +21,7 @@ import "../utils/Extensions" import "./HistogramBox.scss"; import { HistogramBoxPrimitives } from './HistogramBoxPrimitives'; import { HistogramLabelPrimitives } from "./HistogramLabelPrimitives"; +import { AttributeTransformationModel } from "../core/attribute/AttributeTransformationModel"; export interface HistogramPrimitivesProps { HistoBox: HistogramBox; @@ -104,7 +105,11 @@ export class HistogramBox extends React.Component { @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); } componentWillUnmount() { @@ -138,12 +143,12 @@ export class HistogramBox extends React.Component { runInAction(() => { this.PanelWidth = r.entry.width; this.PanelHeight = r.entry.height })}> {({ measureRef }) =>
    -
    +
    {labelY}
    -
    {
    -
    {labelX}
    +
    + {labelX} +
    } diff --git a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx index d2f1be4fd..5e403eb9c 100644 --- a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx +++ b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx @@ -1,5 +1,5 @@ import React = require("react") -import { computed, observable, runInAction } from "mobx"; +import { computed, observable, runInAction, reaction } from "mobx"; import { observer } from "mobx-react"; import { Utils as DashUtils } from '../../../Utils'; import { AttributeTransformationModel } from "../../northstar/core/attribute/AttributeTransformationModel"; @@ -19,6 +19,9 @@ import "./HistogramBoxPrimitives.scss"; export class HistogramBoxPrimitives extends React.Component { private get histoOp() { return this.props.HistoBox.HistoOp; } private get renderDimension() { return this.props.HistoBox.SizeConverter.RenderDimension; } + componentDidMount() { + reaction(() => this.props.HistoBox.HistogramResult, () => this._selectedPrims.length = 0); + } @observable _selectedPrims: HistogramBinPrimitive[] = []; @computed get xaxislines() { return this.renderGridLinesAndLabels(0); } @computed get yaxislines() { return this.renderGridLinesAndLabels(1); } diff --git a/src/client/northstar/utils/SizeConverter.ts b/src/client/northstar/utils/SizeConverter.ts index 30627dfd5..bb91ed4a7 100644 --- a/src/client/northstar/utils/SizeConverter.ts +++ b/src/client/northstar/utils/SizeConverter.ts @@ -62,7 +62,7 @@ export class SizeConverter { public DataToScreenPointRange(axis: number, bin: Bin, aggregateKey: AggregateKey) { var value = ModelHelpers.GetAggregateResult(bin, aggregateKey) as DoubleValueAggregateResult; - if (value.hasResult) + if (value && value.hasResult) return [this.DataToScreenCoord(value.result!, axis) - 5, this.DataToScreenCoord(value.result!, axis) + 5]; return [undefined, undefined]; diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index 661fa4dc8..70b1c9829 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -186,6 +186,8 @@ export namespace DragManager { e.preventDefault(); x += e.movementX; y += e.movementY; + if (dragData instanceof DocumentDragData) + dragData.aliasOnDrop = e.ctrlKey || e.altKey; if (e.shiftKey) { abortDrag(); CollectionDockingView.Instance.StartOtherDrag(doc, { pageX: e.pageX, pageY: e.pageY, preventDefault: () => { }, button: 0 }); diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index 2f20b102c..75855c3d1 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -245,7 +245,7 @@ export class Main extends React.Component { let addTextNode = action(() => Documents.TextDocument({ width: 200, height: 200, title: "a text note" })) let addColNode = action(() => Documents.FreeformDocument([], { width: 200, height: 200, title: "a freeform collection" })); let addSchemaNode = action(() => Documents.SchemaDocument([], { width: 200, height: 200, title: "a schema collection" })); - let addTreeNode = action(() => Documents.TreeDocument(this._northstarSchemas, { width: 100, height: 400, title: "northstar schemas" })); + let addTreeNode = action(() => Documents.TreeDocument(this._northstarSchemas, { width: 250, height: 400, title: "northstar schemas" })); let addVideoNode = action(() => Documents.VideoDocument(videourl, { width: 200, height: 200, title: "video node" })); let addPDFNode = action(() => Documents.PdfDocument(pdfurl, { width: 200, height: 200, title: "a schema collection" })); let addImageNode = action(() => Documents.ImageDocument(imgurl, { width: 200, height: 200, title: "an image of a cat" })); @@ -340,7 +340,7 @@ export class Main extends React.Component { let schemaDoc = Documents.TreeDocument([], { width: 50, height: 100, title: schema.displayName! }); let schemaDocuments = schemaDoc.GetList(KeyStore.Data, [] as Document[]); CurrentUserUtils.GetAllNorthstarColumnAttributes(schema).map(attr => { - Server.GetField(attr.displayName!, action((field: Opt) => { + Server.GetField(attr.displayName! + ".alias", action((field: Opt) => { if (field instanceof Document) { schemaDocuments.push(field); } else { @@ -349,7 +349,7 @@ export class Main extends React.Component { new AttributeTransformationModel(atmod, AggregateFunction.None), new AttributeTransformationModel(atmod, AggregateFunction.Count), new AttributeTransformationModel(atmod, AggregateFunction.Count)); - schemaDocuments.push(Documents.HistogramDocument(histoOp, { width: 200, height: 200, title: attr.displayName! }, attr.displayName!)); + schemaDocuments.push(Documents.HistogramDocument(histoOp, { width: 200, height: 200, title: attr.displayName! }, undefined, attr.displayName! + ".alias")); } })); }); diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss index 9c5e98005..215a75243 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss @@ -1,5 +1,15 @@ @import "../../global_variables"; +.collectionfreeformview { + position: absolute; + top: 0; + left: 0; + width: 100%; + height: 100%; + .inking-canvas { + transform-origin: 50000px 50000px; + } +} .collectionfreeformview-container { .collectionfreeformview > .jsx-parser { position: absolute; @@ -27,16 +37,6 @@ left: 0; width: 100%; height: 100%; - .collectionfreeformview { - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - .inking-canvas { - transform-origin: 50000px 50000px; - } - } } .collectionfreeformview-overlay { .collectionfreeformview > .jsx-parser { -- cgit v1.2.3-70-g09d2 From a10bbd686a825ee38caceb7ecfc388715c14a817 Mon Sep 17 00:00:00 2001 From: bob Date: Fri, 29 Mar 2019 16:18:55 -0400 Subject: added basic brushing placeholder --- .../northstar/core/brusher/BrushLinkModel.ts | 40 ------------------ .../northstar/core/brusher/IBaseBrushable.ts | 4 +- src/client/northstar/dash-nodes/HistogramBox.tsx | 19 +++++---- .../dash-nodes/HistogramBoxPrimitives.tsx | 5 ++- .../northstar/operations/HistogramOperation.ts | 48 +++++++++++----------- 5 files changed, 43 insertions(+), 73 deletions(-) delete mode 100644 src/client/northstar/core/brusher/BrushLinkModel.ts (limited to 'src') diff --git a/src/client/northstar/core/brusher/BrushLinkModel.ts b/src/client/northstar/core/brusher/BrushLinkModel.ts deleted file mode 100644 index e3ac43367..000000000 --- a/src/client/northstar/core/brusher/BrushLinkModel.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { IBaseBrushable } from '../brusher/IBaseBrushable' -import { IBaseBrusher } from '../brusher/IBaseBrusher' -import { Utils } from '../../utils/Utils' -import { IEquatable } from '../../utils/IEquatable'; - -export class BrushLinkModel implements IEquatable { - - public From: IBaseBrusher; - - public To: IBaseBrushable; - - public Color: number = 0; - - constructor(from: IBaseBrusher, to: IBaseBrushable) { - this.From = from; - this.To = to; - } - - public static overlaps(start: number, end: number, otherstart: number, otherend: number): boolean { - if (start > otherend || otherstart > end) - return false; - return true; - } - public static Connected(from: IBaseBrusher, to: IBaseBrushable): boolean { - var connected = (Math.abs(from.Position.x + from.Size.x - to.Position.x) <= 60 && - this.overlaps(from.Position.y, from.Position.y + from.Size.y, to.Position.y, to.Position.y + to.Size.y) - ) || - (Math.abs(to.Position.x + to.Size.x - from.Position.x) <= 60 && - this.overlaps(to.Position.y, to.Position.y + to.Size.y, from.Position.y, from.Position.y + from.Size.y) - ); - return connected; - } - - public Equals(other: Object): boolean { - if (!Utils.EqualityHelper(this, other)) return false; - if (!this.From.Equals((other as BrushLinkModel).From)) return false; - if (!this.To.Equals((other as BrushLinkModel).To)) return false; - return true; - } -} \ No newline at end of file diff --git a/src/client/northstar/core/brusher/IBaseBrushable.ts b/src/client/northstar/core/brusher/IBaseBrushable.ts index 07d4e7580..99a36636f 100644 --- a/src/client/northstar/core/brusher/IBaseBrushable.ts +++ b/src/client/northstar/core/brusher/IBaseBrushable.ts @@ -1,9 +1,9 @@ -import { BrushLinkModel } from '../brusher/BrushLinkModel' import { PIXIPoint } from '../../utils/MathUtil' import { IEquatable } from '../../utils/IEquatable'; +import { Document } from '../../../../fields/Document' export interface IBaseBrushable extends IEquatable { - BrusherModels: Array>; + BrusherModels: Array; BrushColors: Array; Position: PIXIPoint; Size: PIXIPoint; diff --git a/src/client/northstar/dash-nodes/HistogramBox.tsx b/src/client/northstar/dash-nodes/HistogramBox.tsx index dba4ce900..b464e125c 100644 --- a/src/client/northstar/dash-nodes/HistogramBox.tsx +++ b/src/client/northstar/dash-nodes/HistogramBox.tsx @@ -2,26 +2,25 @@ import React = require("react") import { action, computed, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; import Measure from "react-measure"; -import { Dictionary } from "typescript-collections"; import { FieldWaiting, Opt } from "../../../fields/Field"; +import { Document } from "../../../fields/Document"; import { KeyStore } from "../../../fields/KeyStore"; import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; -import { FilterModel } from '../../northstar/core/filter/FilterModel'; import { ChartType, VisualBinRange } from '../../northstar/model/binRanges/VisualBinRange'; import { VisualBinRangeHelper } from "../../northstar/model/binRanges/VisualBinRangeHelper"; -import { AggregateBinRange, BinRange, DoubleValueAggregateResult, HistogramResult, Catalog, AggregateFunction } from "../../northstar/model/idea/idea"; +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 { PIXIRectangle } from "../../northstar/utils/MathUtil"; 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 "../utils/Extensions"; import "./HistogramBox.scss"; import { HistogramBoxPrimitives } from './HistogramBoxPrimitives'; import { HistogramLabelPrimitives } from "./HistogramLabelPrimitives"; -import { AttributeTransformationModel } from "../core/attribute/AttributeTransformationModel"; +import { StyleConstants } from "../utils/StyleContants"; export interface HistogramPrimitivesProps { HistoBox: HistogramBox; @@ -124,7 +123,13 @@ export class HistogramBox extends React.Component { this.props.doc.GetTAsync(this.props.fieldKey, HistogramField).then((histoOp: Opt) => runInAction(() => { this.HistoOp = histoOp ? histoOp.Data : HistogramOperation.Empty; if (this.HistoOp != HistogramOperation.Empty) { - reaction(() => this.props.doc.GetList(KeyStore.LinkedFromDocs, []), docs => this.HistoOp.Links.splice(0, this.HistoOp.Links.length, ...docs), { fireImmediately: true }); + reaction(() => this.props.doc.GetList(KeyStore.LinkedFromDocs, []), + (docs: Document[]) => { + var availableColors = StyleConstants.BRUSH_COLORS.map(c => c); + docs.map((brush, i) => brush.SetNumber(KeyStore.BackgroundColor, availableColors[i % availableColors.length])); + this.HistoOp.BrushLinks.splice(0, this.HistoOp.BrushLinks.length, ...docs); + //this.HistoOp.Links.splice(0, this.HistoOp.Links.length, ...docs) + }, { fireImmediately: true }); reaction(() => this.createOperationParamsCache, () => this.HistoOp.Update(), { fireImmediately: true }); } })); diff --git a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx index 5e403eb9c..b8020c28c 100644 --- a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx +++ b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx @@ -168,7 +168,7 @@ export class HistogramBinPrimitiveCollection { 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.X.AggregateFunction == AggregateFunction.Count) { + 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; @@ -269,6 +269,9 @@ export class HistogramBinPrimitiveCollection { private createVerticalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number): number { let dataValue = this.histoOp.getValue(1, bin, this.histoResult, brush.brushIndex!); if (dataValue != undefined) { + if (bin.binIndex!.indices![0] == 0 && bin.binIndex!.indices![1] == 0) { + console.log("DV = " + dataValue) + } let [yFrom, yValue, yTo] = this.sizeConverter.DataToScreenNormalizedRange(dataValue, normalization, 1, binBrushMaxAxis); let [xFrom, xTo] = this.sizeConverter.DataToScreenXAxisRange(this._histoBox.VisualBinRanges, 0, bin); diff --git a/src/client/northstar/operations/HistogramOperation.ts b/src/client/northstar/operations/HistogramOperation.ts index 8a0f648f6..fa51e2a8c 100644 --- a/src/client/northstar/operations/HistogramOperation.ts +++ b/src/client/northstar/operations/HistogramOperation.ts @@ -4,29 +4,30 @@ import { CurrentUserUtils } from "../../../server/authentication/models/current_ import { ColumnAttributeModel } from "../core/attribute/AttributeModel"; import { AttributeTransformationModel } from "../core/attribute/AttributeTransformationModel"; import { CalculatedAttributeManager } from "../core/attribute/CalculatedAttributeModel"; -import { BrushLinkModel } from "../core/brusher/BrushLinkModel"; 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 { IBaseFilterProvider, instanceOfIBaseFilterProvider } from "../core/filter/IBaseFilterProvider"; import { SETTINGS_SAMPLE_SIZE, SETTINGS_X_BINS, SETTINGS_Y_BINS } from "../model/binRanges/VisualBinRangeHelper"; import { AggregateFunction, AggregateParameters, Attribute, AverageAggregateParameters, DataType, HistogramOperationParameters, QuantitativeBinRange, HistogramResult, Brush, DoubleValueAggregateResult, Bin } from "../model/idea/idea"; import { ModelHelpers } from "../model/ModelHelpers"; import { ArrayUtil } from "../utils/ArrayUtil"; import { BaseOperation } from "./BaseOperation"; +import { KeyStore } from "../../../fields/KeyStore"; +import { HistogramField } from "../dash-fields/HistogramField"; +import { FieldWaiting } from "../../../fields/Field"; export class HistogramOperation extends BaseOperation implements IBaseFilterConsumer, IBaseFilterProvider { @observable public FilterOperand: FilterOperand = FilterOperand.AND; @observable public Links: Document[] = []; + @observable public BrushLinks: Document[] = []; @observable public BrushColors: number[] = []; @observable public Normalization: number = -1; @observable public FilterModels: FilterModel[] = []; @observable public X: AttributeTransformationModel; @observable public Y: AttributeTransformationModel; @observable public V: AttributeTransformationModel; - @observable public BrusherModels: BrushLinkModel[] = []; - @observable public BrushableModels: BrushLinkModel[] = []; @observable public SchemaName: string; @computed public get Schema() { return CurrentUserUtils.GetNorthstarSchema(this.SchemaName); } @@ -63,25 +64,24 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons @computed public get FilterString(): string { let filterModels: FilterModel[] = []; - let fstring = FilterModel.GetFilterModelsRecursive(this, new Set(), filterModels, true) - return fstring; + return FilterModel.GetFilterModelsRecursive(this, new Set(), filterModels, true) } - @computed.struct - public get BrushString() { - return []; - // let brushes = []; - // this.TypedViewModel.BrusherModels.map(brushLinkModel => { - // if (instanceOfIBaseFilterProvider(brushLinkModel.From) && brushLinkModel.From.FilterModels.some && brushLinkModel.From instanceof BaseOperationViewModel) { - // let brushFilterModels = []; - // let gnode = MainManager.Instance.MainViewModel.FilterDependencyGraph.has(brushLinkModel.From) ? - // MainManager.Instance.MainViewModel.FilterDependencyGraph.get(brushLinkModel.From) : - // new GraphNode(brushLinkModel.From); - // let brush = FilterModel.GetFilterModelsRecursive(gnode, new Set>(), brushFilterModels, false); - // brushes.push(brush); - // } - // }); - // return brushes; + @computed + public get BrushString(): string[] { + let brushes: string[] = []; + this.BrushLinks.map(brushLink => { + let brusherDoc = brushLink.Get(KeyStore.LinkedFromDocs); + if (brusherDoc && brusherDoc != FieldWaiting && brusherDoc instanceof Document) { + let brushHistogram = brusherDoc.GetT(KeyStore.Data, HistogramField); + if (brushHistogram && brushHistogram != FieldWaiting) { + let filterModels: FilterModel[] = []; + let brush = FilterModel.GetFilterModelsRecursive(brushHistogram!.Data, new Set(), filterModels, false) + brushes.push(brush); + } + } + }); + return brushes; } @@ -131,11 +131,13 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons }); } } - + get_random_color(): number { + return (Math.floor(Math.random() * 256) << 16) + (Math.floor(Math.random() * 256) << 8) + (Math.floor(Math.random() * 256)); + } @action public async Update(): Promise { - this.BrushColors = this.BrusherModels.map(e => e.Color); + this.BrushColors = this.BrushLinks.map(e => e.GetNumber(KeyStore.BackgroundColor, 0)); return super.Update(); } } -- cgit v1.2.3-70-g09d2 From 6e0439f36216af6ee25ff9a65d296e6f9ff28fd3 Mon Sep 17 00:00:00 2001 From: bob Date: Fri, 29 Mar 2019 16:24:44 -0400 Subject: from last --- src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx | 3 --- 1 file changed, 3 deletions(-) (limited to 'src') diff --git a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx index b8020c28c..648070241 100644 --- a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx +++ b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx @@ -269,9 +269,6 @@ export class HistogramBinPrimitiveCollection { private createVerticalBarChartBinPrimitives(bin: Bin, brush: Brush, binBrushMaxAxis: number, normalization: number): number { let dataValue = this.histoOp.getValue(1, bin, this.histoResult, brush.brushIndex!); if (dataValue != undefined) { - if (bin.binIndex!.indices![0] == 0 && bin.binIndex!.indices![1] == 0) { - console.log("DV = " + dataValue) - } let [yFrom, yValue, yTo] = this.sizeConverter.DataToScreenNormalizedRange(dataValue, normalization, 1, binBrushMaxAxis); let [xFrom, xTo] = this.sizeConverter.DataToScreenXAxisRange(this._histoBox.VisualBinRanges, 0, bin); -- cgit v1.2.3-70-g09d2 From 6e993fb5817e8ddce756396e53883a42530f52bb Mon Sep 17 00:00:00 2001 From: bob Date: Fri, 29 Mar 2019 18:49:22 -0400 Subject: brushes mostly working - some problems with cycles. --- src/client/northstar/dash-fields/HistogramField.ts | 17 +++++++- src/client/northstar/dash-nodes/HistogramBox.tsx | 27 ++++++++---- .../dash-nodes/HistogramBoxPrimitives.tsx | 14 ++++--- src/client/northstar/operations/BaseOperation.ts | 6 ++- .../northstar/operations/HistogramOperation.ts | 22 +++++----- .../CollectionFreeFormLinksView.tsx | 49 +++++++++++++++++++++- src/fields/KeyStore.ts | 1 + 7 files changed, 107 insertions(+), 29 deletions(-) (limited to 'src') diff --git a/src/client/northstar/dash-fields/HistogramField.ts b/src/client/northstar/dash-fields/HistogramField.ts index 00912c595..1929f8dcd 100644 --- a/src/client/northstar/dash-fields/HistogramField.ts +++ b/src/client/northstar/dash-fields/HistogramField.ts @@ -16,7 +16,8 @@ export class HistogramField extends BasicField { } toString(): string { - return JSON.stringify(this.Data); + let omitted = this.omitKeys(this.Data, ['Links', 'BrushLinks']); + return JSON.stringify(omitted); } Copy(): Field { @@ -27,10 +28,22 @@ export class HistogramField extends BasicField { return `new HistogramField("${this.Data}")`; } + omitKeys(obj: any, keys: any) { + var dup: any = {}; + for (var key in obj) { + if (keys.indexOf(key) == -1) { + dup[key] = obj[key]; + } + } + return dup; + } + ToJson(): { type: Types, data: string, _id: string } { + let omitted = this.omitKeys(this.Data, ['Links', 'BrushLinks']); return { type: Types.HistogramOp, - data: JSON.stringify(this.Data), + + data: JSON.stringify(omitted), _id: this.Id } } diff --git a/src/client/northstar/dash-nodes/HistogramBox.tsx b/src/client/northstar/dash-nodes/HistogramBox.tsx index b464e125c..9976ff6ad 100644 --- a/src/client/northstar/dash-nodes/HistogramBox.tsx +++ b/src/client/northstar/dash-nodes/HistogramBox.tsx @@ -1,5 +1,5 @@ import React = require("react") -import { action, computed, observable, reaction, runInAction } from "mobx"; +import { action, computed, observable, reaction, runInAction, trace } from "mobx"; import { observer } from "mobx-react"; import Measure from "react-measure"; import { FieldWaiting, Opt } from "../../../fields/Field"; @@ -8,7 +8,7 @@ import { KeyStore } from "../../../fields/KeyStore"; 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 { AggregateBinRange, AggregateFunction, BinRange, Catalog, DoubleValueAggregateResult, HistogramResult, Result } from "../../northstar/model/idea/idea"; import { ModelHelpers } from "../../northstar/model/ModelHelpers"; import { HistogramOperation } from "../../northstar/operations/HistogramOperation"; import { SizeConverter } from "../../northstar/utils/SizeConverter"; @@ -39,10 +39,10 @@ export class HistogramBox extends React.Component { @observable public HistoOp: HistogramOperation = HistogramOperation.Empty; @observable public VisualBinRanges: VisualBinRange[] = []; @observable public ValueRange: number[] = []; + @observable public HistogramResult: HistogramResult = new HistogramResult(); @observable public SizeConverter: SizeConverter = new SizeConverter(); - @computed get createOperationParamsCache() { return this.HistoOp.CreateOperationParameters(); } - @computed get HistogramResult() { return this.HistoOp ? this.HistoOp.Result as HistogramResult : undefined; } + @computed get createOperationParamsCache() { trace(); 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 ? @@ -123,12 +123,21 @@ export class HistogramBox extends React.Component { this.props.doc.GetTAsync(this.props.fieldKey, HistogramField).then((histoOp: Opt) => runInAction(() => { this.HistoOp = histoOp ? histoOp.Data : HistogramOperation.Empty; if (this.HistoOp != HistogramOperation.Empty) { - reaction(() => this.props.doc.GetList(KeyStore.LinkedFromDocs, []), - (docs: Document[]) => { + this.HistoOp.YieldResult = (r: Result) => action(() => this.HistogramResult = r as HistogramResult)(); + reaction(() => this.props.doc.GetList(KeyStore.LinkedFromDocs, []), (docs: Document[]) => this.HistoOp.Links.splice(0, this.HistoOp.Links.length, ...docs), { fireImmediately: true }); + reaction(() => this.props.doc.GetList(KeyStore.BrushingDocs, []).length, + () => { + let brushingDocs = this.props.doc.GetList(KeyStore.BrushingDocs, [] as Document[]); var availableColors = StyleConstants.BRUSH_COLORS.map(c => c); - docs.map((brush, i) => brush.SetNumber(KeyStore.BackgroundColor, availableColors[i % availableColors.length])); - this.HistoOp.BrushLinks.splice(0, this.HistoOp.BrushLinks.length, ...docs); - //this.HistoOp.Links.splice(0, this.HistoOp.Links.length, ...docs) + let proto = this.props.doc.GetPrototype() as Document; + let brushingLinks = brushingDocs.map((brush, i) => { + // brush.SetNumber(KeyStore.BackgroundColor, availableColors[i % availableColors.length]); + let brushed = brush.GetList(KeyStore.BrushingDocs, [] as Document[]); + if (!brushed || brushed.length < 2) + return undefined; + return { l: brush, b: brushed[0].Id == proto.Id ? brushed[1] : brushed[0] } + }).filter(x => x != undefined) as { l: Document, b: Document }[]; + this.HistoOp.BrushLinks.splice(0, this.HistoOp.BrushLinks.length, ...brushingLinks); }, { fireImmediately: true }); reaction(() => this.createOperationParamsCache, () => this.HistoOp.Update(), { fireImmediately: true }); } diff --git a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx index 648070241..c97acb064 100644 --- a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx +++ b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx @@ -1,5 +1,5 @@ import React = require("react") -import { computed, observable, runInAction, reaction } from "mobx"; +import { computed, observable, runInAction, reaction, untracked, trace } from "mobx"; import { observer } from "mobx-react"; import { Utils as DashUtils } from '../../../Utils'; import { AttributeTransformationModel } from "../../northstar/core/attribute/AttributeTransformationModel"; @@ -20,7 +20,7 @@ export class HistogramBoxPrimitives extends React.Component this.props.HistoBox.HistogramResult, () => this._selectedPrims.length = 0); + reaction(() => this.props.HistoBox.HistoOp.FilterString, () => this._selectedPrims.length = this.histoOp.FilterModels.length = 0); } @observable _selectedPrims: HistogramBinPrimitive[] = []; @computed get xaxislines() { return this.renderGridLinesAndLabels(0); } @@ -30,10 +30,10 @@ export class HistogramBoxPrimitives extends React.Component { 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 => @@ -327,6 +327,7 @@ export class HistogramBinPrimitiveCollection { } private baseColorFromBrush(brush: Brush): number { + let bc = StyleConstants.BRUSH_COLORS; if (brush.brushIndex == ModelHelpers.RestBrushIndex(this.histoResult)) { return StyleConstants.HIGHLIGHT_COLOR; } @@ -336,9 +337,12 @@ export class HistogramBinPrimitiveCollection { else if (brush.brushIndex == ModelHelpers.AllBrushIndex(this.histoResult)) { return 0x00ff00; } - else if (this.histoOp.BrushColors.length > 0) { - return this.histoOp.BrushColors[brush.brushIndex! % this.histoOp.BrushColors.length]; + 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; } } \ No newline at end of file diff --git a/src/client/northstar/operations/BaseOperation.ts b/src/client/northstar/operations/BaseOperation.ts index 94e0849af..21d1db749 100644 --- a/src/client/northstar/operations/BaseOperation.ts +++ b/src/client/northstar/operations/BaseOperation.ts @@ -10,7 +10,8 @@ export abstract class BaseOperation { @observable public Error: string = ""; @observable public OverridingFilters: FilterModel[] = []; - @observable public Result?: Result = undefined; + //@observable + public Result?: Result = undefined; @observable public ComputationStarted: boolean = false; public OperationReference?: OperationReference = undefined; @@ -45,8 +46,11 @@ export abstract class BaseOperation { } + public YieldResult: ((result: Result) => void) | undefined; @action public SetResult(result: Result): void { + if (this.YieldResult) + this.YieldResult(result); this.Result = result; } diff --git a/src/client/northstar/operations/HistogramOperation.ts b/src/client/northstar/operations/HistogramOperation.ts index fa51e2a8c..48bad73df 100644 --- a/src/client/northstar/operations/HistogramOperation.ts +++ b/src/client/northstar/operations/HistogramOperation.ts @@ -1,4 +1,4 @@ -import { action, computed, observable } from "mobx"; +import { action, computed, observable, trace } from "mobx"; import { Document } from "../../../fields/Document"; import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; import { ColumnAttributeModel } from "../core/attribute/AttributeModel"; @@ -16,12 +16,13 @@ import { BaseOperation } from "./BaseOperation"; import { KeyStore } from "../../../fields/KeyStore"; import { HistogramField } from "../dash-fields/HistogramField"; import { FieldWaiting } from "../../../fields/Field"; +import { StyleConstants } from "../utils/StyleContants"; export class HistogramOperation extends BaseOperation implements IBaseFilterConsumer, IBaseFilterProvider { @observable public FilterOperand: FilterOperand = FilterOperand.AND; @observable public Links: Document[] = []; - @observable public BrushLinks: Document[] = []; + @observable public BrushLinks: { l: Document, b: Document }[] = []; @observable public BrushColors: number[] = []; @observable public Normalization: number = -1; @observable public FilterModels: FilterModel[] = []; @@ -69,16 +70,15 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons @computed public get BrushString(): string[] { + trace(); let brushes: string[] = []; this.BrushLinks.map(brushLink => { - let brusherDoc = brushLink.Get(KeyStore.LinkedFromDocs); - if (brusherDoc && brusherDoc != FieldWaiting && brusherDoc instanceof Document) { - let brushHistogram = brusherDoc.GetT(KeyStore.Data, HistogramField); - if (brushHistogram && brushHistogram != FieldWaiting) { - let filterModels: FilterModel[] = []; - let brush = FilterModel.GetFilterModelsRecursive(brushHistogram!.Data, new Set(), filterModels, false) - brushes.push(brush); - } + let brusherDoc = brushLink.b; + let brushHistogram = brusherDoc.GetT(KeyStore.Data, HistogramField); + if (brushHistogram && brushHistogram != FieldWaiting) { + let filterModels: FilterModel[] = []; + let brush = FilterModel.GetFilterModelsRecursive(brushHistogram!.Data, new Set(), filterModels, false) + brushes.push(brush); } }); return brushes; @@ -137,7 +137,7 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons @action public async Update(): Promise { - this.BrushColors = this.BrushLinks.map(e => e.GetNumber(KeyStore.BackgroundColor, 0)); + //this.BrushColors = this.BrushLinks.map(e => e.l.GetNumber(KeyStore.BackgroundColor, 0)); return super.Update(); } } diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx index 4f28f43eb..8dbf80533 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx @@ -1,4 +1,4 @@ -import { computed } from "mobx"; +import { computed, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../../../fields/Document"; import { FieldWaiting } from "../../../../fields/Field"; @@ -11,10 +11,57 @@ import "./CollectionFreeFormLinksView.scss"; import React = require("react"); import v5 = require("uuid/v5"); import { CollectionFreeFormLinkView } from "./CollectionFreeFormLinkView"; +import { ListField } from "../../../../fields/ListField"; +import { TextField } from "../../../../fields/TextField"; +import { StyleConstants } from "../../../northstar/utils/StyleContants"; @observer export class CollectionFreeFormLinksView extends React.Component { + componentDidMount() { + reaction(() => { + return DocumentManager.Instance.getAllDocumentViews(this.props.Document).map(dv => dv.props.Document.GetNumber(KeyStore.X, 0)) + }, () => { + let views = DocumentManager.Instance.getAllDocumentViews(this.props.Document); + for (let i = 0; i < views.length; i++) { + for (let j = i + 1; j < views.length; j++) { + let srcDoc = views[j].props.Document; + let dstDoc = views[i].props.Document; + let x1 = srcDoc.GetNumber(KeyStore.X, 0); + let x1w = srcDoc.GetNumber(KeyStore.Width, 0); + let x2 = dstDoc.GetNumber(KeyStore.X, 0); + let x2w = dstDoc.GetNumber(KeyStore.Width, 0); + if (Math.abs(x1 + x1w - x2) < 20 || Math.abs(x2 + x2w - x1) < 20) { + let linkDoc: Document = new Document(); + dstDoc.GetTAsync(KeyStore.Prototype, Document).then((protoDest) => + srcDoc.GetTAsync(KeyStore.Prototype, Document).then((protoSrc) => runInAction(() => { + linkDoc.Set(KeyStore.Title, new TextField("New Brush")); + linkDoc.Set(KeyStore.LinkDescription, new TextField("")); + linkDoc.Set(KeyStore.LinkTags, new TextField("Default")); + linkDoc.SetNumber(KeyStore.BackgroundColor, StyleConstants.BRUSH_COLORS[0]); + + let dstTarg = (protoDest ? protoDest : dstDoc); + let srcTarg = (protoSrc ? protoSrc : srcDoc); + linkDoc.SetData(KeyStore.BrushingDocs, [dstTarg, srcTarg], ListField); + dstTarg.GetOrCreateAsync(KeyStore.BrushingDocs, ListField, field => { (field as ListField).Data.push(linkDoc) }) + srcTarg.GetOrCreateAsync(KeyStore.BrushingDocs, ListField, field => { (field as ListField).Data.push(linkDoc) }) + })) + ) + } else { + dstDoc.GetTAsync(KeyStore.Prototype, Document).then((protoDest) => + srcDoc.GetTAsync(KeyStore.Prototype, Document).then((protoSrc) => runInAction(() => { + + let dstTarg = (protoDest ? protoDest : dstDoc); + let srcTarg = (protoSrc ? protoSrc : srcDoc); + dstTarg.GetOrCreateAsync(KeyStore.BrushingDocs, ListField, field => { (field as ListField).Data.length = 0 }) + srcTarg.GetOrCreateAsync(KeyStore.BrushingDocs, ListField, field => { (field as ListField).Data.length = 0 }) + })) + ) + } + } + } + }); + } documentAnchors(view: DocumentView) { let equalViews = [view]; let containerDoc = view.props.Document.GetT(KeyStore.AnnotationOn, Document); diff --git a/src/fields/KeyStore.ts b/src/fields/KeyStore.ts index aa0b9ce92..1f039e592 100644 --- a/src/fields/KeyStore.ts +++ b/src/fields/KeyStore.ts @@ -29,6 +29,7 @@ export namespace KeyStore { export const Caption = new Key("Caption"); export const ActiveWorkspace = new Key("ActiveWorkspace"); export const DocumentText = new Key("DocumentText"); + export const BrushingDocs = new Key("BrushingDocs"); export const LinkedToDocs = new Key("LinkedToDocs"); export const LinkedFromDocs = new Key("LinkedFromDocs"); export const LinkDescription = new Key("LinkDescription"); -- cgit v1.2.3-70-g09d2 From 79f9bc805f281a13fe59162f2e25dd1fdcefaae0 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Fri, 29 Mar 2019 20:13:06 -0400 Subject: code cleanup --- src/client/northstar/dash-fields/HistogramField.ts | 24 +- .../dash-nodes/HistogramBinPrimitiveCollection.ts | 238 ++++++++++++++++++++ src/client/northstar/dash-nodes/HistogramBox.tsx | 21 +- .../dash-nodes/HistogramBoxPrimitives.scss | 4 + .../dash-nodes/HistogramBoxPrimitives.tsx | 246 +-------------------- .../dash-nodes/HistogramLabelPrimitives.tsx | 3 +- .../northstar/operations/HistogramOperation.ts | 73 +++--- 7 files changed, 301 insertions(+), 308 deletions(-) create mode 100644 src/client/northstar/dash-nodes/HistogramBinPrimitiveCollection.ts (limited to 'src') diff --git a/src/client/northstar/dash-fields/HistogramField.ts b/src/client/northstar/dash-fields/HistogramField.ts index 1929f8dcd..ae83ea5ba 100644 --- a/src/client/northstar/dash-fields/HistogramField.ts +++ b/src/client/northstar/dash-fields/HistogramField.ts @@ -15,9 +15,17 @@ export class HistogramField extends BasicField { super(data ? data : HistogramOperation.Empty, save, id); } + omitKeys(obj: any, keys: any) { + var dup: any = {}; + for (var key in obj) { + if (keys.indexOf(key) == -1) { + dup[key] = obj[key]; + } + } + return dup; + } toString(): string { - let omitted = this.omitKeys(this.Data, ['Links', 'BrushLinks']); - return JSON.stringify(omitted); + return JSON.stringify(this.omitKeys(this.Data, ['Links', 'BrushLinks', 'Result'])); } Copy(): Field { @@ -28,22 +36,12 @@ export class HistogramField extends BasicField { return `new HistogramField("${this.Data}")`; } - omitKeys(obj: any, keys: any) { - var dup: any = {}; - for (var key in obj) { - if (keys.indexOf(key) == -1) { - dup[key] = obj[key]; - } - } - return dup; - } ToJson(): { type: Types, data: string, _id: string } { - let omitted = this.omitKeys(this.Data, ['Links', 'BrushLinks']); return { type: Types.HistogramOp, - data: JSON.stringify(omitted), + data: this.toString(), _id: this.Id } } diff --git a/src/client/northstar/dash-nodes/HistogramBinPrimitiveCollection.ts b/src/client/northstar/dash-nodes/HistogramBinPrimitiveCollection.ts new file mode 100644 index 000000000..43e768c62 --- /dev/null +++ b/src/client/northstar/dash-nodes/HistogramBinPrimitiveCollection.ts @@ -0,0 +1,238 @@ +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); + var marginResult = ModelHelpers.GetAggregateResult(bin, marginAggregateKey) as MarginAggregateResult; + return !marginResult ? 0 : marginResult.absolutMargin!; + } + + 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; + } +} \ No newline at end of file diff --git a/src/client/northstar/dash-nodes/HistogramBox.tsx b/src/client/northstar/dash-nodes/HistogramBox.tsx index 9976ff6ad..6bf2697fc 100644 --- a/src/client/northstar/dash-nodes/HistogramBox.tsx +++ b/src/client/northstar/dash-nodes/HistogramBox.tsx @@ -22,9 +22,6 @@ import { HistogramBoxPrimitives } from './HistogramBoxPrimitives'; import { HistogramLabelPrimitives } from "./HistogramLabelPrimitives"; import { StyleConstants } from "../utils/StyleContants"; -export interface HistogramPrimitivesProps { - HistoBox: HistogramBox; -} @observer export class HistogramBox extends React.Component { @@ -77,6 +74,15 @@ export class HistogramBox extends React.Component { } } + @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, { handlers: { drop: this.dropX.bind(this) } }); @@ -102,15 +108,6 @@ export class HistogramBox extends React.Component { }); } - @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); - } - componentWillUnmount() { if (this._dropXDisposer) this._dropXDisposer(); diff --git a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.scss b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.scss index 9d42219cc..ce9edd65e 100644 --- a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.scss +++ b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.scss @@ -1,3 +1,7 @@ +.histogramboxprimitives-container { + width: 100%; + height: 100%; +} .histogramboxprimitives-border { border: 3px; border-style: solid; diff --git a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx index c97acb064..e9adb3ce5 100644 --- a/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx +++ b/src/client/northstar/dash-nodes/HistogramBoxPrimitives.tsx @@ -1,27 +1,24 @@ import React = require("react") -import { computed, observable, runInAction, reaction, untracked, trace } from "mobx"; +import { computed, observable, reaction, runInAction, trace } from "mobx"; import { observer } from "mobx-react"; import { Utils as DashUtils } from '../../../Utils'; -import { AttributeTransformationModel } from "../../northstar/core/attribute/AttributeTransformationModel"; import { FilterModel } from "../../northstar/core/filter/FilterModel"; -import { ChartType } from '../../northstar/model/binRanges/VisualBinRange'; -import { AggregateFunction, Bin, Brush, HistogramResult, MarginAggregateParameters, MarginAggregateResult } from "../../northstar/model/idea/idea"; 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 { HistogramBox, HistogramPrimitivesProps } from "./HistogramBox"; +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; } - componentDidMount() { - reaction(() => this.props.HistoBox.HistoOp.FilterString, () => this._selectedPrims.length = this.histoOp.FilterModels.length = 0); - } @observable _selectedPrims: HistogramBinPrimitive[] = []; @computed get xaxislines() { return this.renderGridLinesAndLabels(0); } @computed get yaxislines() { return this.renderGridLinesAndLabels(1); } @@ -42,6 +39,10 @@ export class HistogramBoxPrimitives extends React.Component this.props.HistoBox.HistoOp.FilterString, () => this._selectedPrims.length = this.histoOp.FilterModels.length = 0); + } + private getSelectionToggle(binPrimitives: HistogramBinPrimitive[], allBrushIndex: number, filterModel: FilterModel) { let allBrushPrim = ArrayUtil.FirstOrDefault(binPrimitives, bp => bp.BrushIndex == allBrushIndex); return !allBrushPrim ? () => { } : () => runInAction(() => { @@ -90,7 +91,6 @@ export class HistogramBoxPrimitives extends React.Component); return this.drawEntity(xFrom, yFrom, line); } - drawRect(r: PIXIRectangle, barAxis: number, color: number | undefined, classExt: string, tapHandler: () => void = () => { }) { if (r.height < 0) { r.y += r.height; @@ -114,235 +114,11 @@ export class HistogramBoxPrimitives extends React.Component + return
    {this.xaxislines} {this.yaxislines} {this.binPrimitives} {this.selectedPrimitives}
    } -} - -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.histoOp.getValue(normalization, bin, this.histoResult, Brush.brushIndex!); - return aggResult != undefined && aggResult > prev ? aggResult : prev; - }, Number.MIN_VALUE) - }; - } - private createHeatmapBinPrimitives(bin: Bin, brush: Brush, brushFactorSum: number): number { - - let unNormalizedValue = this.histoOp.getValue(2, bin, this.histoResult, 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.histoOp.getValue(2, bin, this.histoResult, 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._histoBox.HistoOp.getValue(2, bin, this.histoResult, 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.histoOp.getValue(1, bin, this.histoResult, 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.histoOp.getValue(0, bin, this.histoResult, 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; - } - - - 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); - var marginResult = ModelHelpers.GetAggregateResult(bin, marginAggregateKey) as MarginAggregateResult; - return !marginResult ? 0 : marginResult.absolutMargin!; - } - - 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; - } } \ No newline at end of file diff --git a/src/client/northstar/dash-nodes/HistogramLabelPrimitives.tsx b/src/client/northstar/dash-nodes/HistogramLabelPrimitives.tsx index 45b23874d..93b237deb 100644 --- a/src/client/northstar/dash-nodes/HistogramLabelPrimitives.tsx +++ b/src/client/northstar/dash-nodes/HistogramLabelPrimitives.tsx @@ -5,8 +5,9 @@ import { Utils as DashUtils } from '../../../Utils'; import { NominalVisualBinRange } from "../model/binRanges/NominalVisualBinRange"; import "../utils/Extensions"; import { StyleConstants } from "../utils/StyleContants"; -import { HistogramBox, HistogramPrimitivesProps } from "./HistogramBox"; +import { HistogramBox } from "./HistogramBox"; import "./HistogramLabelPrimitives.scss"; +import { HistogramPrimitivesProps } from "./HistogramBoxPrimitives"; @observer export class HistogramLabelPrimitives extends React.Component { diff --git a/src/client/northstar/operations/HistogramOperation.ts b/src/client/northstar/operations/HistogramOperation.ts index 48bad73df..4689cb233 100644 --- a/src/client/northstar/operations/HistogramOperation.ts +++ b/src/client/northstar/operations/HistogramOperation.ts @@ -1,5 +1,7 @@ import { action, computed, observable, trace } from "mobx"; import { Document } from "../../../fields/Document"; +import { FieldWaiting } from "../../../fields/Field"; +import { KeyStore } from "../../../fields/KeyStore"; import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; import { ColumnAttributeModel } from "../core/attribute/AttributeModel"; import { AttributeTransformationModel } from "../core/attribute/AttributeTransformationModel"; @@ -7,52 +9,30 @@ import { CalculatedAttributeManager } from "../core/attribute/CalculatedAttribut import { FilterModel } from "../core/filter/FilterModel"; import { FilterOperand } from "../core/filter/FilterOperand"; import { IBaseFilterConsumer } from "../core/filter/IBaseFilterConsumer"; -import { IBaseFilterProvider, instanceOfIBaseFilterProvider } from "../core/filter/IBaseFilterProvider"; +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, DataType, HistogramOperationParameters, QuantitativeBinRange, HistogramResult, Brush, DoubleValueAggregateResult, Bin } from "../model/idea/idea"; +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 { KeyStore } from "../../../fields/KeyStore"; -import { HistogramField } from "../dash-fields/HistogramField"; -import { FieldWaiting } from "../../../fields/Field"; -import { StyleConstants } from "../utils/StyleContants"; - 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: Document[] = []; @observable public BrushLinks: { l: Document, b: Document }[] = []; @observable public BrushColors: number[] = []; - @observable public Normalization: number = -1; @observable public FilterModels: 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; @computed public get Schema() { return CurrentUserUtils.GetNorthstarSchema(this.SchemaName); } - @action - public AddFilterModels(filterModels: FilterModel[]): void { - filterModels.filter(f => f !== null).forEach(fm => this.FilterModels.push(fm)); - } - @action - public RemoveFilterModels(filterModels: FilterModel[]): void { - ArrayUtil.RemoveMany(this.FilterModels, filterModels); - } - - public getValue(axis: number, bin: Bin, result: HistogramResult, brushIndex: number) { - var aggregateKey = ModelHelpers.CreateAggregateKey(this.Schema!.distinctAttributeParameters, axis == 0 ? this.X : axis == 1 ? this.Y : this.V, result, brushIndex); - let dataValue = ModelHelpers.GetAggregateResult(bin, aggregateKey) as DoubleValueAggregateResult; - return dataValue != null && dataValue.hasResult ? dataValue.result : undefined; - } - - 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()))); - - Equals(other: Object): boolean { - throw new Error("Method not implemented."); - } - constructor(schemaName: string, x: AttributeTransformationModel, y: AttributeTransformationModel, v: AttributeTransformationModel, normalized?: number) { super(); this.X = x; @@ -62,6 +42,19 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons this.SchemaName = schemaName; } + Equals(other: Object): boolean { + throw new Error("Method not implemented."); + } + + @action + public AddFilterModels(filterModels: FilterModel[]): void { + filterModels.filter(f => f !== null).forEach(fm => this.FilterModels.push(fm)); + } + @action + public RemoveFilterModels(filterModels: FilterModel[]): void { + ArrayUtil.RemoveMany(this.FilterModels, filterModels); + } + @computed public get FilterString(): string { let filterModels: FilterModel[] = []; @@ -73,25 +66,16 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons trace(); let brushes: string[] = []; this.BrushLinks.map(brushLink => { - let brusherDoc = brushLink.b; - let brushHistogram = brusherDoc.GetT(KeyStore.Data, HistogramField); + let brushHistogram = brushLink.b.GetT(KeyStore.Data, HistogramField); if (brushHistogram && brushHistogram != FieldWaiting) { let filterModels: FilterModel[] = []; - let brush = FilterModel.GetFilterModelsRecursive(brushHistogram!.Data, new Set(), filterModels, false) - brushes.push(brush); + brushes.push(FilterModel.GetFilterModelsRecursive(brushHistogram.Data, new Set(), filterModels, false)); } }); return brushes; } - - @computed.struct - public get SelectionString() { - let filterModels = new Array(); - return FilterModel.GetFilterModelsRecursive(this, new Set(), filterModels, false); - } - - GetAggregateParameters(histoX: AttributeTransformationModel, histoY: AttributeTransformationModel, histoValue: AttributeTransformationModel) { + 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)); @@ -108,11 +92,9 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons return [perBinAggregateParameters, globalAggregateParameters]; } - public QRange: QuantitativeBinRange | undefined; - public CreateOperationParameters(): HistogramOperationParameters | undefined { if (this.X && this.Y && this.V) { - let [perBinAggregateParameters, globalAggregateParameters] = this.GetAggregateParameters(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, @@ -131,9 +113,6 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons }); } } - get_random_color(): number { - return (Math.floor(Math.random() * 256) << 16) + (Math.floor(Math.random() * 256) << 8) + (Math.floor(Math.random() * 256)); - } @action public async Update(): Promise { -- cgit v1.2.3-70-g09d2 From a2e4321eb23bedda9b78f012d3eb061045c5b33c Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Fri, 29 Mar 2019 22:50:49 -0400 Subject: improved brushing --- src/client/northstar/dash-nodes/HistogramBox.tsx | 5 +- src/client/northstar/operations/BaseOperation.ts | 5 +- .../CollectionFreeFormLinksView.tsx | 56 ++++++++++------------ 3 files changed, 29 insertions(+), 37 deletions(-) (limited to 'src') diff --git a/src/client/northstar/dash-nodes/HistogramBox.tsx b/src/client/northstar/dash-nodes/HistogramBox.tsx index 6bf2697fc..65d917fd3 100644 --- a/src/client/northstar/dash-nodes/HistogramBox.tsx +++ b/src/client/northstar/dash-nodes/HistogramBox.tsx @@ -36,7 +36,7 @@ export class HistogramBox extends React.Component { @observable public HistoOp: HistogramOperation = HistogramOperation.Empty; @observable public VisualBinRanges: VisualBinRange[] = []; @observable public ValueRange: number[] = []; - @observable public HistogramResult: HistogramResult = new HistogramResult(); + @computed public get HistogramResult(): HistogramResult { return this.HistoOp.Result as HistogramResult; } @observable public SizeConverter: SizeConverter = new SizeConverter(); @computed get createOperationParamsCache() { trace(); return this.HistoOp.CreateOperationParameters(); } @@ -120,7 +120,6 @@ export class HistogramBox extends React.Component { this.props.doc.GetTAsync(this.props.fieldKey, HistogramField).then((histoOp: Opt) => runInAction(() => { this.HistoOp = histoOp ? histoOp.Data : HistogramOperation.Empty; if (this.HistoOp != HistogramOperation.Empty) { - this.HistoOp.YieldResult = (r: Result) => action(() => this.HistogramResult = r as HistogramResult)(); reaction(() => this.props.doc.GetList(KeyStore.LinkedFromDocs, []), (docs: Document[]) => this.HistoOp.Links.splice(0, this.HistoOp.Links.length, ...docs), { fireImmediately: true }); reaction(() => this.props.doc.GetList(KeyStore.BrushingDocs, []).length, () => { @@ -128,7 +127,7 @@ export class HistogramBox extends React.Component { var availableColors = StyleConstants.BRUSH_COLORS.map(c => c); let proto = this.props.doc.GetPrototype() as Document; let brushingLinks = brushingDocs.map((brush, i) => { - // brush.SetNumber(KeyStore.BackgroundColor, availableColors[i % availableColors.length]); + brush.SetNumber(KeyStore.BackgroundColor, availableColors[i % availableColors.length]); let brushed = brush.GetList(KeyStore.BrushingDocs, [] as Document[]); if (!brushed || brushed.length < 2) return undefined; diff --git a/src/client/northstar/operations/BaseOperation.ts b/src/client/northstar/operations/BaseOperation.ts index 21d1db749..f545b2c58 100644 --- a/src/client/northstar/operations/BaseOperation.ts +++ b/src/client/northstar/operations/BaseOperation.ts @@ -11,7 +11,7 @@ export abstract class BaseOperation { @observable public Error: string = ""; @observable public OverridingFilters: FilterModel[] = []; //@observable - public Result?: Result = undefined; + @observable public Result?: Result = undefined; @observable public ComputationStarted: boolean = false; public OperationReference?: OperationReference = undefined; @@ -46,11 +46,8 @@ export abstract class BaseOperation { } - public YieldResult: ((result: Result) => void) | undefined; @action public SetResult(result: Result): void { - if (this.YieldResult) - this.YieldResult(result); this.Result = result; } diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx index 8dbf80533..2dcf7fbbe 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx @@ -3,17 +3,15 @@ import { observer } from "mobx-react"; import { Document } from "../../../../fields/Document"; import { FieldWaiting } from "../../../../fields/Field"; import { KeyStore } from "../../../../fields/KeyStore"; +import { ListField } from "../../../../fields/ListField"; import { Utils } from "../../../../Utils"; import { DocumentManager } from "../../../util/DocumentManager"; import { DocumentView } from "../../nodes/DocumentView"; import { CollectionViewProps } from "../CollectionViewBase"; import "./CollectionFreeFormLinksView.scss"; +import { CollectionFreeFormLinkView } from "./CollectionFreeFormLinkView"; import React = require("react"); import v5 = require("uuid/v5"); -import { CollectionFreeFormLinkView } from "./CollectionFreeFormLinkView"; -import { ListField } from "../../../../fields/ListField"; -import { TextField } from "../../../../fields/TextField"; -import { StyleConstants } from "../../../northstar/utils/StyleContants"; @observer export class CollectionFreeFormLinksView extends React.Component { @@ -31,36 +29,34 @@ export class CollectionFreeFormLinksView extends React.Component - srcDoc.GetTAsync(KeyStore.Prototype, Document).then((protoSrc) => runInAction(() => { - linkDoc.Set(KeyStore.Title, new TextField("New Brush")); - linkDoc.Set(KeyStore.LinkDescription, new TextField("")); - linkDoc.Set(KeyStore.LinkTags, new TextField("Default")); - linkDoc.SetNumber(KeyStore.BackgroundColor, StyleConstants.BRUSH_COLORS[0]); - - let dstTarg = (protoDest ? protoDest : dstDoc); - let srcTarg = (protoSrc ? protoSrc : srcDoc); + dstDoc.GetTAsync(KeyStore.Prototype, Document).then((protoDest) => + srcDoc.GetTAsync(KeyStore.Prototype, Document).then((protoSrc) => runInAction(() => { + let dstTarg = (protoDest ? protoDest : dstDoc); + let srcTarg = (protoSrc ? protoSrc : srcDoc); + let findBrush = (field: ListField) => field.Data.findIndex(brush => { + let bdocs = brush.GetList(KeyStore.BrushingDocs, [] as Document[]); + return (bdocs[0] == dstTarg && bdocs[1] == srcTarg) || (bdocs[0] == srcTarg && bdocs[1] == dstTarg) + }); + let brushAction = (field: ListField) => { + let found = findBrush(field); + if (found != -1) + field.Data.splice(found, 1); + }; + if (Math.abs(x1 + x1w - x2) < 20 || Math.abs(x2 + x2w - x1) < 20) { + let linkDoc: Document = new Document(); + linkDoc.SetText(KeyStore.Title, "Histogram Brush"); + linkDoc.SetText(KeyStore.LinkDescription, "Brush between " + srcTarg.Title + " and " + dstTarg.Title); linkDoc.SetData(KeyStore.BrushingDocs, [dstTarg, srcTarg], ListField); - dstTarg.GetOrCreateAsync(KeyStore.BrushingDocs, ListField, field => { (field as ListField).Data.push(linkDoc) }) - srcTarg.GetOrCreateAsync(KeyStore.BrushingDocs, ListField, field => { (field as ListField).Data.push(linkDoc) }) - })) - ) - } else { - dstDoc.GetTAsync(KeyStore.Prototype, Document).then((protoDest) => - srcDoc.GetTAsync(KeyStore.Prototype, Document).then((protoSrc) => runInAction(() => { - let dstTarg = (protoDest ? protoDest : dstDoc); - let srcTarg = (protoSrc ? protoSrc : srcDoc); - dstTarg.GetOrCreateAsync(KeyStore.BrushingDocs, ListField, field => { (field as ListField).Data.length = 0 }) - srcTarg.GetOrCreateAsync(KeyStore.BrushingDocs, ListField, field => { (field as ListField).Data.length = 0 }) - })) - ) - } + brushAction = (field: ListField) => (findBrush(field) == -1) && field.Data.push(linkDoc); + } + dstTarg.GetOrCreateAsync(KeyStore.BrushingDocs, ListField, brushAction); + srcTarg.GetOrCreateAsync(KeyStore.BrushingDocs, ListField, brushAction); + } + ))) } } - }); + }) } documentAnchors(view: DocumentView) { let equalViews = [view]; -- cgit v1.2.3-70-g09d2 From 74e95e596d9876e90c294ade30df3d666d167139 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Fri, 29 Mar 2019 23:48:34 -0400 Subject: fixed brush colors. --- src/client/northstar/dash-fields/HistogramField.ts | 2 +- src/client/northstar/dash-nodes/HistogramBox.tsx | 10 +++------- src/client/northstar/operations/HistogramOperation.ts | 2 +- .../collectionFreeForm/CollectionFreeFormLinksView.tsx | 10 ++++++---- 4 files changed, 11 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/client/northstar/dash-fields/HistogramField.ts b/src/client/northstar/dash-fields/HistogramField.ts index ae83ea5ba..4a557e123 100644 --- a/src/client/northstar/dash-fields/HistogramField.ts +++ b/src/client/northstar/dash-fields/HistogramField.ts @@ -25,7 +25,7 @@ export class HistogramField extends BasicField { return dup; } toString(): string { - return JSON.stringify(this.omitKeys(this.Data, ['Links', 'BrushLinks', 'Result'])); + return JSON.stringify(this.omitKeys(this.Data, ['Links', 'BrushLinks', 'Result', 'BrushColors'])); } Copy(): Field { diff --git a/src/client/northstar/dash-nodes/HistogramBox.tsx b/src/client/northstar/dash-nodes/HistogramBox.tsx index 65d917fd3..a968def96 100644 --- a/src/client/northstar/dash-nodes/HistogramBox.tsx +++ b/src/client/northstar/dash-nodes/HistogramBox.tsx @@ -124,16 +124,12 @@ export class HistogramBox extends React.Component { reaction(() => this.props.doc.GetList(KeyStore.BrushingDocs, []).length, () => { let brushingDocs = this.props.doc.GetList(KeyStore.BrushingDocs, [] as Document[]); - var availableColors = StyleConstants.BRUSH_COLORS.map(c => c); let proto = this.props.doc.GetPrototype() as Document; - let brushingLinks = brushingDocs.map((brush, i) => { - brush.SetNumber(KeyStore.BackgroundColor, availableColors[i % availableColors.length]); + this.HistoOp.BrushLinks.splice(0, this.HistoOp.BrushLinks.length, ...brushingDocs.map((brush, i) => { + brush.SetNumber(KeyStore.BackgroundColor, StyleConstants.BRUSH_COLORS[i % StyleConstants.BRUSH_COLORS.length]); let brushed = brush.GetList(KeyStore.BrushingDocs, [] as Document[]); - if (!brushed || brushed.length < 2) - return undefined; return { l: brush, b: brushed[0].Id == proto.Id ? brushed[1] : brushed[0] } - }).filter(x => x != undefined) as { l: Document, b: Document }[]; - this.HistoOp.BrushLinks.splice(0, this.HistoOp.BrushLinks.length, ...brushingLinks); + })); }, { fireImmediately: true }); reaction(() => this.createOperationParamsCache, () => this.HistoOp.Update(), { fireImmediately: true }); } diff --git a/src/client/northstar/operations/HistogramOperation.ts b/src/client/northstar/operations/HistogramOperation.ts index 4689cb233..e63de1632 100644 --- a/src/client/northstar/operations/HistogramOperation.ts +++ b/src/client/northstar/operations/HistogramOperation.ts @@ -116,7 +116,7 @@ export class HistogramOperation extends BaseOperation implements IBaseFilterCons @action public async Update(): Promise { - //this.BrushColors = this.BrushLinks.map(e => e.l.GetNumber(KeyStore.BackgroundColor, 0)); + this.BrushColors = this.BrushLinks.map(e => e.l.GetNumber(KeyStore.BackgroundColor, 0)); return super.Update(); } } diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx index 2dcf7fbbe..f793b3a49 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx @@ -26,16 +26,18 @@ export class CollectionFreeFormLinksView extends React.Component srcDoc.GetTAsync(KeyStore.Prototype, Document).then((protoSrc) => runInAction(() => { let dstTarg = (protoDest ? protoDest : dstDoc); let srcTarg = (protoSrc ? protoSrc : srcDoc); let findBrush = (field: ListField) => field.Data.findIndex(brush => { let bdocs = brush.GetList(KeyStore.BrushingDocs, [] as Document[]); - return (bdocs[0] == dstTarg && bdocs[1] == srcTarg) || (bdocs[0] == srcTarg && bdocs[1] == dstTarg) + return (bdocs.length == 0 || (bdocs[0] == dstTarg && bdocs[1] == srcTarg) || (bdocs[0] == srcTarg && bdocs[1] == dstTarg)) }); let brushAction = (field: ListField) => { let found = findBrush(field); @@ -48,7 +50,7 @@ export class CollectionFreeFormLinksView extends React.Component) => (findBrush(field) == -1) && field.Data.push(linkDoc); + brushAction = brushAction = (field: ListField) => (findBrush(field) == -1) && field.Data.push(linkDoc); } dstTarg.GetOrCreateAsync(KeyStore.BrushingDocs, ListField, brushAction); srcTarg.GetOrCreateAsync(KeyStore.BrushingDocs, ListField, brushAction); -- cgit v1.2.3-70-g09d2 From 0ae1eac2e2b26c0eee747c81ea1478118b4ec874 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Fri, 29 Mar 2019 23:58:43 -0400 Subject: from last --- src/client/northstar/dash-fields/HistogramField.ts | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/client/northstar/dash-fields/HistogramField.ts b/src/client/northstar/dash-fields/HistogramField.ts index 4a557e123..90be70b80 100644 --- a/src/client/northstar/dash-fields/HistogramField.ts +++ b/src/client/northstar/dash-fields/HistogramField.ts @@ -1,13 +1,11 @@ -import { BasicField } from "../../../fields/BasicField"; -import { Field, FieldId } from "../../../fields/Field"; -import { Types } from "../../../server/Message"; -import { HistogramOperation } from "../../../client/northstar/operations/HistogramOperation"; import { action } from "mobx"; -import { AttributeTransformationModel } from "../../../client/northstar/core/attribute/AttributeTransformationModel"; import { ColumnAttributeModel } from "../../../client/northstar/core/attribute/AttributeModel"; +import { AttributeTransformationModel } from "../../../client/northstar/core/attribute/AttributeTransformationModel"; +import { HistogramOperation } from "../../../client/northstar/operations/HistogramOperation"; +import { BasicField } from "../../../fields/BasicField"; +import { Field, FieldId } from "../../../fields/Field"; import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils"; -import { ArrayUtil } from "../utils/ArrayUtil"; -import { Schema } from "../model/idea/idea"; +import { Types } from "../../../server/Message"; export class HistogramField extends BasicField { @@ -25,7 +23,7 @@ export class HistogramField extends BasicField { return dup; } toString(): string { - return JSON.stringify(this.omitKeys(this.Data, ['Links', 'BrushLinks', 'Result', 'BrushColors'])); + return JSON.stringify(this.omitKeys(this.Data, ['Links', 'BrushLinks', 'Result', 'BrushColors', 'FilterModels', 'FilterOperand'])); } Copy(): Field { -- cgit v1.2.3-70-g09d2 From eb220da697e2383b1e368dee743613158994746e Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sun, 31 Mar 2019 17:58:11 -0400 Subject: restructured marquee and preview cursor to not need reactions. fixed some inking bugs. --- src/client/views/InkingCanvas.tsx | 25 ++- .../CollectionFreeFormLinksView.tsx | 1 + .../collectionFreeForm/CollectionFreeFormView.scss | 1 + .../collectionFreeForm/CollectionFreeFormView.tsx | 199 ++++++++------------- .../collectionFreeForm/MarqueeView.scss | 6 + .../collections/collectionFreeForm/MarqueeView.tsx | 169 +++++++++-------- .../collectionFreeForm/PreviewCursor.scss | 7 +- .../collectionFreeForm/PreviewCursor.tsx | 71 +++++--- 8 files changed, 245 insertions(+), 234 deletions(-) (limited to 'src') diff --git a/src/client/views/InkingCanvas.tsx b/src/client/views/InkingCanvas.tsx index 36a8834a0..8fb74ec48 100644 --- a/src/client/views/InkingCanvas.tsx +++ b/src/client/views/InkingCanvas.tsx @@ -1,16 +1,15 @@ -import { observer } from "mobx-react"; -import { observable } from "mobx"; import { action, computed } from "mobx"; -import { InkingControl } from "./InkingControl"; -import React = require("react"); -import { Transform } from "../util/Transform"; +import { observer } from "mobx-react"; import { Document } from "../../fields/Document"; -import { KeyStore } from "../../fields/KeyStore"; +import { FieldWaiting } from "../../fields/Field"; import { InkField, InkTool, StrokeData, StrokeMap } from "../../fields/InkField"; -import { InkingStroke } from "./InkingStroke"; -import "./InkingCanvas.scss" +import { KeyStore } from "../../fields/KeyStore"; import { Utils } from "../../Utils"; -import { FieldWaiting } from "../../fields/Field"; +import { Transform } from "../util/Transform"; +import "./InkingCanvas.scss"; +import { InkingControl } from "./InkingControl"; +import { InkingStroke } from "./InkingStroke"; +import React = require("react"); interface InkCanvasProps { getScreenTransform: () => Transform; @@ -71,8 +70,7 @@ export class InkingCanvas extends React.Component { // start the new line, saves a uuid to represent the field of the stroke this._idGenerator = Utils.GenerateGuid(); - let data = this.inkData; - data.set(this._idGenerator, + this.inkData.set(this._idGenerator, { pathData: [point], color: InkingControl.Instance.selectedColor, @@ -80,7 +78,6 @@ export class InkingCanvas extends React.Component { tool: InkingControl.Instance.selectedTool, page: this.props.Document.GetNumber(KeyStore.CurPage, -1) }); - this.inkData = data; this._isDrawing = true; } @@ -163,9 +160,7 @@ export class InkingCanvas extends React.Component { }) return ( - -
    +
    {paths} diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx index f793b3a49..ea392eaea 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx @@ -96,6 +96,7 @@ export class CollectionFreeFormLinksView extends React.Component {this.uniqueConnections.map(c => )} + {this.props.children} ); } } \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss index 215a75243..c979b27a9 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss @@ -6,6 +6,7 @@ left: 0; width: 100%; height: 100%; + transform-origin: left top; .inking-canvas { transform-origin: 50000px 50000px; } diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 1f90b0d46..cdc5bdfb0 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -3,7 +3,6 @@ import { observer } from "mobx-react"; import { Document } from "../../../../fields/Document"; import { FieldWaiting } from "../../../../fields/Field"; import { KeyStore } from "../../../../fields/KeyStore"; -import { ListField } from "../../../../fields/ListField"; import { TextField } from "../../../../fields/TextField"; import { DragManager } from "../../../util/DragManager"; import { Transform } from "../../../util/Transform"; @@ -14,10 +13,9 @@ import { DocumentContentsView } from "../../nodes/DocumentContentsView"; import { DocumentViewProps } from "../../nodes/DocumentView"; import { COLLECTION_BORDER_WIDTH } from "../CollectionView"; import { CollectionViewBase } from "../CollectionViewBase"; -import { MarqueeView } from "./MarqueeView"; -import { PreviewCursor } from "./PreviewCursor"; import { CollectionFreeFormLinksView } from "./CollectionFreeFormLinksView"; import "./CollectionFreeFormView.scss"; +import { MarqueeView } from "./MarqueeView"; import React = require("react"); import v5 = require("uuid/v5"); @@ -27,12 +25,15 @@ export class CollectionFreeFormView extends CollectionViewBase { private _selectOnLoaded: string = ""; // id of document that should be selected once it's loaded (used for click-to-type) public addLiveTextBox = (newBox: Document) => { - // mark this collection so that when the text box is created we can send it the SelectOnLoad prop to focus itself + // mark this collection so that when the text box is created we can send it the SelectOnLoad prop to focus itself and receive text input this._selectOnLoaded = newBox.Id; - //set text to be the typed key and get focus on text box - this.props.addDocument(newBox, false); - //remove cursor from screen - this.PreviewCursorVisible = false; + this.addDocument(newBox, false); + } + + public addDocument = (newBox: Document, allowDuplicates: boolean) => { + let added = this.props.addDocument(newBox, false); + this.bringToFront(newBox); + return added; } public selectDocuments = (docs: Document[]) => { @@ -42,23 +43,15 @@ export class CollectionFreeFormView extends CollectionViewBase { public getActiveDocuments = () => { var curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1); - const lvalue = this.props.Document.GetT>(this.props.fieldKey, ListField); - let active: Document[] = []; - if (lvalue && lvalue != FieldWaiting) { - lvalue.Data.map(doc => { - var page = doc.GetNumber(KeyStore.Page, -1); - if (page == curPage || page == -1) { - active.push(doc); - } - }) - } - - return active; + return this.props.Document.GetList(this.props.fieldKey, [] as Document[]).reduce((active, doc) => { + var page = doc.GetNumber(KeyStore.Page, -1); + if (page == curPage || page == -1) { + active.push(doc); + } + return active; + }, [] as Document[]); } - //determines whether the blinking cursor for indicating whether a text will be made on key down is visible - @observable public PreviewCursorVisible: boolean = false; - @observable public MarqueeVisible = false; @observable public DownX: number = 0; @observable public DownY: number = 0; @observable private _lastX: number = 0; @@ -100,12 +93,10 @@ export class CollectionFreeFormView extends CollectionViewBase { cleanupInteractions = () => { document.removeEventListener("pointermove", this.onPointerMove); document.removeEventListener("pointerup", this.onPointerUp); - this.MarqueeVisible = false; } @action onPointerDown = (e: React.PointerEvent): void => { - this.PreviewCursorVisible = false; if ((e.button === 2 && this.props.active() && (!this.isAnnotationOverlay || this.zoomScaling != 1)) || e.button == 0) { document.removeEventListener("pointermove", this.onPointerMove); document.addEventListener("pointermove", this.onPointerMove); @@ -120,28 +111,13 @@ export class CollectionFreeFormView extends CollectionViewBase { onPointerUp = (e: PointerEvent): void => { e.stopPropagation(); - if (Math.abs(this.DownX - e.clientX) < 4 && Math.abs(this.DownY - e.clientY) < 4) { - //show preview text cursor on tap - this.PreviewCursorVisible = true; - //select is not already selected - if (!this.props.isSelected()) { - this.props.select(false); - } - } this.cleanupInteractions(); } @action onPointerMove = (e: PointerEvent): void => { if (!e.cancelBubble && this.props.active()) { - if (e.buttons == 1 && !e.altKey && !e.metaKey) { - this.MarqueeVisible = true; - } - if (this.MarqueeVisible) { - e.stopPropagation(); - e.preventDefault(); - } - else if ((!this.isAnnotationOverlay || this.zoomScaling != 1) && !e.shiftKey) { + if ((!this.isAnnotationOverlay || this.zoomScaling != 1) && !e.shiftKey) { let x = this.props.Document.GetNumber(KeyStore.PanX, 0); let y = this.props.Document.GetNumber(KeyStore.PanY, 0); let [dx, dy] = this.getTransform().transformDirection(e.clientX - this._lastX, e.clientY - this._lastY); @@ -264,16 +240,12 @@ export class CollectionFreeFormView extends CollectionViewBase { @computed get views() { var curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1); - const lvalue = this.props.Document.GetT>(this.props.fieldKey, ListField); - if (lvalue && lvalue != FieldWaiting) { - return lvalue.Data.map(doc => { - if (!doc) return null; - var page = doc.GetNumber(KeyStore.Page, 0); - return (page != curPage && page != 0) ? (null) : - (); - }) - } - return null; + return this.props.Document.GetList(this.props.fieldKey, [] as Document[]).filter(doc => doc).reduce((prev, doc) => { + var page = doc.GetNumber(KeyStore.Page, -1); + if (page == curPage || page == -1) + prev.push(); + return prev; + }, [] as JSX.Element[]) } @computed @@ -290,15 +262,10 @@ export class CollectionFreeFormView extends CollectionViewBase { } getTransform = (): Transform => this.props.ScreenToLocalTransform().translate(-COLLECTION_BORDER_WIDTH, -COLLECTION_BORDER_WIDTH).translate(-this.centeringShiftX, -this.centeringShiftY).transform(this.getLocalTransform()) - getMarqueeTransform = (): Transform => this.props.ScreenToLocalTransform().translate(-COLLECTION_BORDER_WIDTH, -COLLECTION_BORDER_WIDTH) + getContainerTransform = (): Transform => this.props.ScreenToLocalTransform().translate(-COLLECTION_BORDER_WIDTH, -COLLECTION_BORDER_WIDTH) getLocalTransform = (): Transform => Transform.Identity.scale(1 / this.scale).translate(this.panX, this.panY); noScaling = () => 1; - //when focus is lost, this will remove the preview cursor - @action - onBlur = (): void => { - this.PreviewCursorVisible = false; - } private crosshairs?: HTMLCanvasElement; drawCrosshairs = (backgroundColor: string) => { @@ -345,71 +312,63 @@ export class CollectionFreeFormView extends CollectionViewBase { return (
    super.setCursorPosition(this.getTransform().transformPoint(e.clientX, e.clientY))} - onWheel={this.onPointerWheel} - onDrop={this.onDrop.bind(this)} - onDragOver={this.onDragOver} - onBlur={this.onBlur} - style={{ borderWidth: `${COLLECTION_BORDER_WIDTH}px` }}// , zIndex: !this.props.isTopMost ? -1 : undefined }} - tabIndex={0} - ref={this.createDropTarget}> -
    - {this.backgroundView} - - - {this.views} - - {super.getCursors().map(entry => { - if (entry.Data.length > 0) { - let id = entry.Data[0][0]; - let email = entry.Data[0][1]; - let point = entry.Data[1]; - this.drawCrosshairs("#" + v5(id, v5.URL).substring(0, 6).toUpperCase() + "22") - return ( -
    - { if (el) this.crosshairs = el }} - width={20} - height={20} - style={{ - position: 'absolute', - width: "20px", - height: "20px", - opacity: 0.5, - borderRadius: "50%", - border: "2px solid black" - }} - /> -

    super.setCursorPosition(this.getTransform().transformPoint(e.clientX, e.clientY))} + onDrop={this.onDrop.bind(this)} onDragOver={this.onDragOver} onWheel={this.onPointerWheel} + style={{ borderWidth: `${COLLECTION_BORDER_WIDTH}px` }} tabIndex={0} ref={this.createDropTarget}> + +

    + {this.backgroundView} + + {this.views} + + {super.getCursors().map(entry => { + if (entry.Data.length > 0) { + let id = entry.Data[0][0]; + let email = entry.Data[0][1]; + let point = entry.Data[1]; + this.drawCrosshairs("#" + v5(id, v5.URL).substring(0, 6).toUpperCase() + "22") + return ( +
    {email[0].toUpperCase()}

    -
    - ); - } - })} -
    - - {this.overlayView} - + > + { if (el) this.crosshairs = el }} + width={20} + height={20} + style={{ + position: 'absolute', + width: "20px", + height: "20px", + opacity: 0.5, + borderRadius: "50%", + border: "2px solid black" + }} + /> +

    {email[0].toUpperCase()}

    +
    + ); + } + })} +
    + {this.overlayView} +
    ); } diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.scss b/src/client/views/collections/collectionFreeForm/MarqueeView.scss index 6d9a79344..1ee3b244b 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.scss +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.scss @@ -1,8 +1,14 @@ .marqueeView { + position: absolute; + width:100%; + height:100%; +} +.marquee { border-style: dashed; box-sizing: border-box; position: absolute; border-width: 1px; border-color: black; + pointer-events: none; } \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index 2692690dd..2b0e7d228 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -1,62 +1,58 @@ -import { action, IReactionDisposer, observable, reaction } from "mobx"; +import { action, computed, observable } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../../../fields/Document"; -import { FieldWaiting, Opt } from "../../../../fields/Field"; +import { FieldWaiting } from "../../../../fields/Field"; +import { InkField, StrokeData } from "../../../../fields/InkField"; import { KeyStore } from "../../../../fields/KeyStore"; import { Documents } from "../../../documents/Documents"; import { SelectionManager } from "../../../util/SelectionManager"; import { Transform } from "../../../util/Transform"; +import { InkingCanvas } from "../../InkingCanvas"; import { CollectionFreeFormView } from "./CollectionFreeFormView"; import "./MarqueeView.scss"; +import { PreviewCursor } from "./PreviewCursor"; import React = require("react"); -import { InkField, StrokeData } from "../../../../fields/InkField"; -import { Utils } from "../../../../Utils"; -import { InkingCanvas } from "../../InkingCanvas"; interface MarqueeViewProps { - getMarqueeTransform: () => Transform; + getContainerTransform: () => Transform; getTransform: () => Transform; container: CollectionFreeFormView; addDocument: (doc: Document, allowDuplicates: false) => boolean; activeDocuments: () => Document[]; selectDocuments: (docs: Document[]) => void; removeDocument: (doc: Document) => boolean; + addLiveTextDocument: (doc: Document) => void; } @observer export class MarqueeView extends React.Component { - private _reactionDisposer: Opt; - @observable _lastX: number = 0; @observable _lastY: number = 0; @observable _downX: number = 0; @observable _downY: number = 0; - - componentDidMount() { - this._reactionDisposer = reaction( - () => this.props.container.MarqueeVisible, - (visible: boolean) => this.onPointerDown(visible, this.props.container.DownX, this.props.container.DownY)) - } - componentWillUnmount() { - if (this._reactionDisposer) { - this._reactionDisposer(); - } - this.cleanupInteractions(); - } + @observable _used: boolean = false; + @observable _visible: boolean = false; + static DRAG_THRESHOLD = 4; @action - cleanupInteractions = () => { - document.removeEventListener("pointermove", this.onPointerMove, true) - document.removeEventListener("pointerup", this.onPointerUp, true); + cleanupInteractions = (all: boolean = false) => { + if (all) { + document.removeEventListener("pointermove", this.onPointerMove, true) + document.removeEventListener("pointerup", this.onPointerUp, true); + } else { + this._used = true; + } document.removeEventListener("keydown", this.marqueeCommand, true); + this._visible = false; } @action - onPointerDown = (visible: boolean, downX: number, downY: number): void => { - if (visible) { - this._downX = this._lastX = downX; - this._downY = this._lastY = downY; + onPointerDown = (e: React.PointerEvent): void => { + if (e.buttons == 1 && !e.altKey && !e.metaKey && this.props.container.props.active()) { + this._downX = this._lastX = e.pageX; + this._downY = this._lastY = e.pageY; + this._used = false; document.addEventListener("pointermove", this.onPointerMove, true) document.addEventListener("pointerup", this.onPointerUp, true); document.addEventListener("keydown", this.marqueeCommand, true); @@ -67,11 +63,20 @@ export class MarqueeView extends React.Component onPointerMove = (e: PointerEvent): void => { this._lastX = e.pageX; this._lastY = e.pageY; + if (!e.cancelBubble) { + if (!this._used && e.buttons == 1 && !e.altKey && !e.metaKey && + (Math.abs(this._lastX - this._downX) > MarqueeView.DRAG_THRESHOLD || Math.abs(this._lastY - this._downY) > MarqueeView.DRAG_THRESHOLD)) { + this._visible = true; + } + e.stopPropagation(); + e.preventDefault(); + } } @action onPointerUp = (e: PointerEvent): void => { - this.cleanupInteractions(); + this.cleanupInteractions(true); + this._visible = false; if (!e.shiftKey) { SelectionManager.DeselectAll(); } @@ -83,6 +88,7 @@ export class MarqueeView extends React.Component return !(r2.left > r1.left + r1.width || r2.left + r2.width < r1.left || r2.top > r1.top + r1.height || r2.top + r2.height < r1.top); } + @computed get Bounds() { let left = this._downX < this._lastX ? this._downX : this._lastX; let top = this._downY < this._lastY ? this._downY : this._lastY; @@ -95,7 +101,10 @@ export class MarqueeView extends React.Component marqueeCommand = (e: KeyboardEvent) => { if (e.key == "Backspace" || e.key == "Delete") { this.marqueeSelect().map(d => this.props.removeDocument(d)); - this.props.container.props.Document.SetData(KeyStore.Ink, this.marqueeInkSelect(false), InkField); + let ink = this.props.container.props.Document.GetT(KeyStore.Ink, InkField); + if (ink && ink != FieldWaiting && ink.Data) { + this.marqueeInkDelete(ink.Data); + } this.cleanupInteractions(); } if (e.key == "c") { @@ -104,53 +113,61 @@ export class MarqueeView extends React.Component this.props.removeDocument(d); d.SetNumber(KeyStore.X, d.GetNumber(KeyStore.X, 0) - bounds.left - bounds.width / 2); d.SetNumber(KeyStore.Y, d.GetNumber(KeyStore.Y, 0) - bounds.top - bounds.height / 2); - d.SetNumber(KeyStore.Page, 0); + d.SetNumber(KeyStore.Page, -1); d.SetText(KeyStore.Title, "" + d.GetNumber(KeyStore.Width, 0) + " " + d.GetNumber(KeyStore.Height, 0)); return d; }); - let liftedInk = this.marqueeInkSelect(true); - this.props.container.props.Document.SetData(KeyStore.Ink, this.marqueeInkSelect(false), InkField); - //setTimeout(() => { - let newCollection = Documents.FreeformDocument(selected, { - x: bounds.left, - y: bounds.top, - panx: 0, - pany: 0, - width: bounds.width, - height: bounds.height, - backgroundColor: "Transparent", - ink: liftedInk, - title: "a nested collection" - }); - this.props.addDocument(newCollection, false); + let ink = this.props.container.props.Document.GetT(KeyStore.Ink, InkField); + if (ink && ink != FieldWaiting && ink.Data) { + //setTimeout(() => { + let newCollection = Documents.FreeformDocument(selected, { + x: bounds.left, + y: bounds.top, + panx: 0, + pany: 0, + width: bounds.width, + height: bounds.height, + backgroundColor: "Transparent", + ink: this.marqueeInkSelect(ink.Data), + title: "a nested collection" + }); + this.props.addDocument(newCollection, false); + this.marqueeInkDelete(ink.Data); + } // }, 100); this.cleanupInteractions(); } } - marqueeInkSelect(select: boolean) { - let selRect = this.Bounds; - let centerShiftX = 0 - (selRect.left + selRect.width / 2); // moves each point by the offset that shifts the selection's center to the origin. - let centerShiftY = 0 - (selRect.top + selRect.height / 2); - let ink = this.props.container.props.Document.GetT(KeyStore.Ink, InkField); - if (ink && ink != FieldWaiting && ink.Data) { - let idata = new Map(); - ink.Data.forEach((value: StrokeData, key: string, map: any) => { - let inside = InkingCanvas.IntersectStrokeRect(value, selRect); - if (inside && select) { - idata.set(key, - { - pathData: value.pathData.map(val => { return { x: val.x + centerShiftX, y: val.y + centerShiftY } }), - color: value.color, - width: value.width, - tool: value.tool, - page: -1 - }); - } else if (!inside && !select) { - idata.set(key, value); - } - }) - return idata; - } + @action + marqueeInkSelect(ink: Map) { + let idata = new Map(); + let centerShiftX = 0 - (this.Bounds.left + this.Bounds.width / 2); // moves each point by the offset that shifts the selection's center to the origin. + let centerShiftY = 0 - (this.Bounds.top + this.Bounds.height / 2); + ink.forEach((value: StrokeData, key: string, map: any) => { + if (InkingCanvas.IntersectStrokeRect(value, this.Bounds)) { + idata.set(key, + { + pathData: value.pathData.map(val => { return { x: val.x + centerShiftX, y: val.y + centerShiftY } }), + color: value.color, + width: value.width, + tool: value.tool, + page: -1 + }); + } + }); + return idata; + } + + @action + marqueeInkDelete(ink: Map, ) { + // bcz: this appears to work but when you restart all the deleted strokes come back -- InkField isn't observing its changes so they aren't written to the DB. + // ink.forEach((value: StrokeData, key: string, map: any) => + // InkingCanvas.IntersectStrokeRect(value, this.Bounds) && ink.delete(key)); + + let idata = new Map(); + ink.forEach((value: StrokeData, key: string, map: any) => + !InkingCanvas.IntersectStrokeRect(value, this.Bounds) && idata.set(key, value)); + this.props.container.props.Document.SetDataOnPrototype(KeyStore.Ink, idata, InkField); } marqueeSelect() { @@ -168,8 +185,16 @@ export class MarqueeView extends React.Component } render() { - let p = this.props.getMarqueeTransform().transformPoint(this._downX < this._lastX ? this._downX : this._lastX, this._downY < this._lastY ? this._downY : this._lastY); - let v = this.props.getMarqueeTransform().transformDirection(this._lastX - this._downX, this._lastY - this._downY); - return (!this.props.container.MarqueeVisible ? (null) :
    ); + let p = this.props.getContainerTransform().transformPoint(this._downX < this._lastX ? this._downX : this._lastX, this._downY < this._lastY ? this._downY : this._lastY); + let v = this.props.getContainerTransform().transformDirection(this._lastX - this._downX, this._lastY - this._downY); + return
    + + {this.props.children} + {!this._visible ? (null) : +
    } + + +
    ; } } \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/PreviewCursor.scss b/src/client/views/collections/collectionFreeForm/PreviewCursor.scss index a797411f6..7d6d5aaab 100644 --- a/src/client/views/collections/collectionFreeForm/PreviewCursor.scss +++ b/src/client/views/collections/collectionFreeForm/PreviewCursor.scss @@ -5,6 +5,11 @@ transform-origin: left top; pointer-events: none; } +.previewCursorView { + position: absolute; + width:100%; + height:100%; +} //this is an animation for the blinking cursor! @keyframes blink { @@ -14,5 +19,5 @@ } #previewCursor { - animation: blink 1s infinite; + animation: blink 1s infinite; } \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx b/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx index 95364f04b..339e056a8 100644 --- a/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx +++ b/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx @@ -1,7 +1,6 @@ -import { action, IReactionDisposer, observable, reaction } from "mobx"; +import { action, observable } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../../../fields/Document"; -import { Opt } from "../../../../fields/Field"; import { Documents } from "../../../documents/Documents"; import { Transform } from "../../../util/Transform"; import { CollectionFreeFormView } from "./CollectionFreeFormView"; @@ -11,43 +10,50 @@ import React = require("react"); export interface PreviewCursorProps { getTransform: () => Transform; + getContainerTransform: () => Transform; container: CollectionFreeFormView; addLiveTextDocument: (doc: Document) => void; } @observer export class PreviewCursor extends React.Component { - private _reactionDisposer: Opt; - @observable _lastX: number = 0; @observable _lastY: number = 0; + @observable public _visible: boolean = false; + @observable public DownX: number = 0; + @observable public DownY: number = 0; + _showOnUp: boolean = false; + public _previewDivRef = React.createRef(); - componentDidMount() { - this._reactionDisposer = reaction( - () => this.props.container.PreviewCursorVisible, - (visible: boolean) => this.onCursorPlaced(visible, this.props.container.DownX, this.props.container.DownY)) - } - componentWillUnmount() { - if (this._reactionDisposer) { - this._reactionDisposer(); - } - this.cleanupInteractions(); + @action + cleanupInteractions = () => { + document.removeEventListener("pointerup", this.onPointerUp, true); } - @action - cleanupInteractions = () => { + onPointerDown = (e: React.PointerEvent) => { + this._visible = false; document.removeEventListener("keypress", this.onKeyPress, false); + this._showOnUp = true; + this._lastX = this.DownX = e.pageX; + this._lastY = this.DownY = e.pageY; + document.addEventListener("pointerup", this.onPointerUp, true); + document.addEventListener("pointermove", this.onPointerMove, true); + } + @action + onPointerMove = (e: PointerEvent): void => { + if (Math.abs(this.DownX - e.clientX) > 4 || Math.abs(this.DownY - e.clientY) > 4) { + this._showOnUp = false; + } } @action - onCursorPlaced = (visible: boolean, downX: number, downY: number): void => { - if (visible) { + onPointerUp = (e: PointerEvent): void => { + if (this._showOnUp) { document.addEventListener("keypress", this.onKeyPress, false); - this._lastX = downX; - this._lastY = downY; - } else - this.cleanupInteractions(); + this._visible = true; + } + this.cleanupInteractions(); } @action @@ -61,16 +67,29 @@ export class PreviewCursor extends React.Component { let [x, y] = this.props.getTransform().transformPoint(this._lastX, this._lastY); let newBox = Documents.TextDocument({ width: 200, height: 100, x: x, y: y, title: "typed text" }); this.props.addLiveTextDocument(newBox); + document.removeEventListener("keypress", this.onKeyPress, false); + this._visible = false; e.stopPropagation(); } } + //when focus is lost, this will remove the preview cursor + @action + onBlur = (): void => { + this._visible = false; + document.removeEventListener("keypress", this.onKeyPress, false); + } render() { //get local position and place cursor there! - let [x, y] = this.props.getTransform().transformPoint(this._lastX, this._lastY); + let p = this.props.getContainerTransform().transformPoint(this._lastX, this._lastY); + if (this._visible && this._previewDivRef.current) + this._previewDivRef.current!.focus(); return ( - !this.props.container.PreviewCursorVisible ? (null) : -
    I
    ) - +
    + {this.props.children} + {!this._visible ? (null) : +
    I
    } +
    + ) } } \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 2ac86b53d28abb8be2f3abd501b801e543973e28 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sun, 31 Mar 2019 22:45:43 -0400 Subject: restructured inkingCanvas and linksViews --- src/client/views/InkingCanvas.scss | 164 +++------------------ src/client/views/InkingCanvas.tsx | 121 +++++++-------- src/client/views/InkingControl.scss | 135 +++++++++++++++++ src/client/views/InkingControl.tsx | 3 +- .../CollectionFreeFormLinksView.scss | 3 + .../CollectionFreeFormLinksView.tsx | 9 +- .../collectionFreeForm/CollectionFreeFormView.scss | 10 -- .../collectionFreeForm/CollectionFreeFormView.tsx | 10 +- .../views/nodes/CollectionFreeFormDocumentView.tsx | 6 +- src/client/views/nodes/PDFBox.tsx | 10 +- 10 files changed, 233 insertions(+), 238 deletions(-) create mode 100644 src/client/views/InkingControl.scss (limited to 'src') diff --git a/src/client/views/InkingCanvas.scss b/src/client/views/InkingCanvas.scss index e79b146b9..6d7821cd2 100644 --- a/src/client/views/InkingCanvas.scss +++ b/src/client/views/InkingCanvas.scss @@ -1,149 +1,25 @@ @import "global_variables"; -.inking-canvas { + +.inkingCanvas-paths, .inkingCanvas-paths-none { position: absolute; top: -50000px; - left: -50000px; // z-index: 99; //overlays ink on top of everything - svg { - position:absolute; - width: 100000px; - height: 100000px; - .highlight { - mix-blend-mode: multiply; - } - } + left: -50000px; + width: 100000px; + height: 100000px; + //z-index: 10000; // z-index: 99; //overlays ink on top of everything but that messes up blending and events don't propagate down to nested collections + .highlight { + mix-blend-mode: multiply; + } + .inkingCanvas-children { + transform: translate(50000px, 50000px); + pointer-events: none; + } + cursor:"crosshair"; + pointer-events: auto; + +} +.inkingCanvas-paths-none { + pointer-events: none; + cursor: "arrow"; } -.inking-control { - position: absolute; - left: 70px; - bottom: 70px; - margin: 0; - padding: 0; - display: flex; - label, - input, - option { - font-size: 12px; - } - input[type="range"] { - -webkit-appearance: none; - background-color: transparent; - vertical-align: middle; - margin-top: 8px; - &:focus { - outline: none; - } - &::-webkit-slider-runnable-track { - width: 100%; - height: 3px; - border-radius: 1.5px; - cursor: pointer; - background: $intermediate-color; - } - &::-webkit-slider-thumb { - height: 12px; - width: 12px; - border: 1px solid $intermediate-color; - border-radius: 6px; - background: $light-color; - cursor: pointer; - -webkit-appearance: none; - margin-top: -4px; - } - &::-moz-range-track { - width: 100%; - height: 3px; - border-radius: 1.5px; - cursor: pointer; - background: $light-color; - } - &::-moz-range-thumb { - height: 12px; - width: 12px; - border: 1px solid $intermediate-color; - border-radius: 6px; - background: $light-color; - cursor: pointer; - -webkit-appearance: none; - margin-top: -4px; - } - } - input[type="text"] { - border: none; - padding: 0 0px; - background: transparent; - color: $dark-color; - font-size: 12px; - margin-top: 4px; - } - .ink-panel { - margin: 6px 12px 6px 0; - height: 30px; - vertical-align: middle; - line-height: 36px; - padding: 0 10px; - color: $intermediate-color; - &:first { - margin-top: 0; - } - } - .ink-tools { - display: flex; - background-color: transparent; - border-radius: 0; - padding: 0; - button { - height: 36px; - padding: 0px; - padding-bottom: 3px; - margin-left: 10px; - background-color: transparent; - color: $intermediate-color; - } - button:hover { - transform: scale(1.15); - } - } - .ink-size { - display: flex; - justify-content: space-between; - input[type="text"] { - width: 42px; - } - >* { - margin-right: 6px; - &:last-child { - margin-right: 0; - } - } - } - .ink-color { - display: flex; - position: relative; - padding-right: 0; - label { - margin-right: 6px; - } - .ink-color-display { - border-radius: 11px; - width: 22px; - height: 22px; - margin-top: 6px; - cursor: pointer; - text-align: center; // span { - // color: $light-color; - // font-size: 8px; - // user-select: none; - // } - } - .ink-color-picker { - background-color: $light-color; - border-radius: 5px; - padding: 12px; - position: absolute; - bottom: 36px; - left: -3px; - box-shadow: $intermediate-color 0.2vw 0.2vw 0.8vw; - } - } -} \ No newline at end of file diff --git a/src/client/views/InkingCanvas.tsx b/src/client/views/InkingCanvas.tsx index 8fb74ec48..a971264b9 100644 --- a/src/client/views/InkingCanvas.tsx +++ b/src/client/views/InkingCanvas.tsx @@ -57,51 +57,62 @@ export class InkingCanvas extends React.Component { } @action - handleMouseDown = (e: React.PointerEvent): void => { - if (e.button != 0 || + onPointerDown = (e: React.PointerEvent): void => { + this._isDrawing = false; + if (e.button != 0 || e.altKey || e.ctrlKey || InkingControl.Instance.selectedTool === InkTool.None) { return; } - e.stopPropagation() - if (InkingControl.Instance.selectedTool === InkTool.Eraser) { - return - } - const point = this.relativeCoordinatesForEvent(e); - - // start the new line, saves a uuid to represent the field of the stroke - this._idGenerator = Utils.GenerateGuid(); - this.inkData.set(this._idGenerator, - { - pathData: [point], - color: InkingControl.Instance.selectedColor, - width: InkingControl.Instance.selectedWidth, - tool: InkingControl.Instance.selectedTool, - page: this.props.Document.GetNumber(KeyStore.CurPage, -1) - }); + document.addEventListener("pointermove", this.onPointerMove, true); + document.addEventListener("pointerup", this.onPointerUp, true); + e.stopPropagation(); + this._isDrawing = true; + if (InkingControl.Instance.selectedTool != InkTool.Eraser) { + const point = this.relativeCoordinatesForEvent(e.clientX, e.clientY); + + // start the new line, saves a uuid to represent the field of the stroke + this._idGenerator = Utils.GenerateGuid(); + this.inkData.set(this._idGenerator, + { + pathData: [point], + color: InkingControl.Instance.selectedColor, + width: InkingControl.Instance.selectedWidth, + tool: InkingControl.Instance.selectedTool, + page: this.props.Document.GetNumber(KeyStore.CurPage, -1) + }); + } } - @action - handleMouseMove = (e: React.PointerEvent): void => { - if (!this._isDrawing || - InkingControl.Instance.selectedTool === InkTool.None) { - return; + onPointerUp = (e: PointerEvent): void => { + if (this._isDrawing) { + document.removeEventListener("pointermove", this.onPointerMove); + document.removeEventListener("pointerup", this.onPointerUp); + this._isDrawing = false; + e.stopPropagation(); } - e.stopPropagation() - if (InkingControl.Instance.selectedTool === InkTool.Eraser) { - return - } - const point = this.relativeCoordinatesForEvent(e); + } - // add points to new line as it is being drawn - let data = this.inkData; - let strokeData = data.get(this._idGenerator); - if (strokeData) { - strokeData.pathData.push(point); - data.set(this._idGenerator, strokeData); + @action + onPointerMove = (e: PointerEvent): void => { + if (this._isDrawing) { + e.stopPropagation() + e.preventDefault(); + if (InkingControl.Instance.selectedTool === InkTool.Eraser) { + return + } + const point = this.relativeCoordinatesForEvent(e.clientX, e.clientY); + + // add points to new line as it is being drawn + let data = this.inkData; + let strokeData = data.get(this._idGenerator); + if (strokeData) { + strokeData.pathData.push(point); + data.set(this._idGenerator, strokeData); + } + + this.inkData = data; } - - this.inkData = data; } @action @@ -109,8 +120,8 @@ export class InkingCanvas extends React.Component { this._isDrawing = false; } - relativeCoordinatesForEvent = (e: React.MouseEvent): { x: number, y: number } => { - let [x, y] = this.props.getScreenTransform().transformPoint(e.clientX, e.clientY); + relativeCoordinatesForEvent = (ex: number, ey: number): { x: number, y: number } => { + let [x, y] = this.props.getScreenTransform().transformPoint(ex, ey); x += InkingCanvas.InkOffset; y += InkingCanvas.InkOffset; return { x, y }; @@ -124,32 +135,9 @@ export class InkingCanvas extends React.Component { } render() { - // styling for cursor - let canvasStyle = {}; - if (InkingControl.Instance.selectedTool === InkTool.None) { - canvasStyle = { pointerEvents: "none" }; - } else { - canvasStyle = { pointerEvents: "auto", cursor: "crosshair" }; - } - - // get data from server - // let inkField = this.props.Document.GetT(KeyStore.Ink, InkField); - // if (!inkField || inkField == FieldWaiting) { - // return (
    - // - // - //
    ) - // } - - let lines = this.inkData; - // parse data from server - let paths: Array = [] let curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1) - Array.from(lines).map(item => { - let id = item[0]; - let strokeData = item[1]; + let paths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { if (strokeData.page == -1 || strokeData.page == curPage) paths.push( { width={strokeData.width} tool={strokeData.tool} deleteCallback={this.removeLine} />) - }) + return paths; + }, [] as JSX.Element[]); + let svgCanvasStyle = InkingControl.Instance.selectedTool == InkTool.None ? "-none" : ""; return ( -
    - +
    + {paths} + {this.props.children}
    ) } diff --git a/src/client/views/InkingControl.scss b/src/client/views/InkingControl.scss new file mode 100644 index 000000000..0d8fd8784 --- /dev/null +++ b/src/client/views/InkingControl.scss @@ -0,0 +1,135 @@ +@import "global_variables"; +.inking-control { + position: absolute; + left: 70px; + bottom: 70px; + margin: 0; + padding: 0; + display: flex; + label, + input, + option { + font-size: 12px; + } + input[type="range"] { + -webkit-appearance: none; + background-color: transparent; + vertical-align: middle; + margin-top: 8px; + &:focus { + outline: none; + } + &::-webkit-slider-runnable-track { + width: 100%; + height: 3px; + border-radius: 1.5px; + cursor: pointer; + background: $intermediate-color; + } + &::-webkit-slider-thumb { + height: 12px; + width: 12px; + border: 1px solid $intermediate-color; + border-radius: 6px; + background: $light-color; + cursor: pointer; + -webkit-appearance: none; + margin-top: -4px; + } + &::-moz-range-track { + width: 100%; + height: 3px; + border-radius: 1.5px; + cursor: pointer; + background: $light-color; + } + &::-moz-range-thumb { + height: 12px; + width: 12px; + border: 1px solid $intermediate-color; + border-radius: 6px; + background: $light-color; + cursor: pointer; + -webkit-appearance: none; + margin-top: -4px; + } + } + input[type="text"] { + border: none; + padding: 0 0px; + background: transparent; + color: $dark-color; + font-size: 12px; + margin-top: 4px; + } + .ink-panel { + margin: 6px 12px 6px 0; + height: 30px; + vertical-align: middle; + line-height: 36px; + padding: 0 10px; + color: $intermediate-color; + &:first { + margin-top: 0; + } + } + .ink-tools { + display: flex; + background-color: transparent; + border-radius: 0; + padding: 0; + button { + height: 36px; + padding: 0px; + padding-bottom: 3px; + margin-left: 10px; + background-color: transparent; + color: $intermediate-color; + } + button:hover { + transform: scale(1.15); + } + } + .ink-size { + display: flex; + justify-content: space-between; + input[type="text"] { + width: 42px; + } + >* { + margin-right: 6px; + &:last-child { + margin-right: 0; + } + } + } + .ink-color { + display: flex; + position: relative; + padding-right: 0; + label { + margin-right: 6px; + } + .ink-color-display { + border-radius: 11px; + width: 22px; + height: 22px; + margin-top: 6px; + cursor: pointer; + text-align: center; // span { + // color: $light-color; + // font-size: 8px; + // user-select: none; + // } + } + .ink-color-picker { + background-color: $light-color; + border-radius: 5px; + padding: 12px; + position: absolute; + bottom: 36px; + left: -3px; + box-shadow: $intermediate-color 0.2vw 0.2vw 0.8vw; + } + } +} \ No newline at end of file diff --git a/src/client/views/InkingControl.tsx b/src/client/views/InkingControl.tsx index eb2172d03..c1519dff8 100644 --- a/src/client/views/InkingControl.tsx +++ b/src/client/views/InkingControl.tsx @@ -2,10 +2,9 @@ import { observable, action, computed } from "mobx"; import { CirclePicker, ColorResult } from 'react-color' import React = require("react"); -import "./InkingCanvas.scss" import { InkTool } from "../../fields/InkField"; import { observer } from "mobx-react"; -import "./InkingCanvas.scss" +import "./InkingControl.scss" import { library } from '@fortawesome/fontawesome-svg-core'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faPen, faHighlighter, faEraser, faBan } from '@fortawesome/free-solid-svg-icons'; diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.scss b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.scss index 9af0df7f5..4341c82f7 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.scss +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.scss @@ -4,4 +4,7 @@ width: 20000px; height: 20000px; pointer-events: none; + } + .collectionfreeformlinksview-container { + pointer-events: none; } \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx index ea392eaea..ef60aa672 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx @@ -94,9 +94,12 @@ export class CollectionFreeFormLinksView extends React.Component - {this.uniqueConnections.map(c => )} +
    + + {this.uniqueConnections.map(c => )} + {this.props.children} - ); +
    + ); } } \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss index c979b27a9..81d21d89a 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss @@ -7,9 +7,6 @@ width: 100%; height: 100%; transform-origin: left top; - .inking-canvas { - transform-origin: 50000px 50000px; - } } .collectionfreeformview-container { .collectionfreeformview > .jsx-parser { @@ -18,9 +15,6 @@ width: 100%; } - .inking-canvas { - transform-origin: 50000px 50000px; - } //nested freeform views // .collectionfreeformview-container { // background-image: linear-gradient(to right, $light-color-secondary 1px, transparent 1px), @@ -48,10 +42,6 @@ background: $light-color-secondary; } - .inking-canvas { - transform-origin: 50000px 50000px; - } - opacity: 0.99; border: 0px solid transparent; border-radius: $border-radius; diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index cdc5bdfb0..ae1c775e6 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -314,16 +314,18 @@ export class CollectionFreeFormView extends CollectionViewBase {
    super.setCursorPosition(this.getTransform().transformPoint(e.clientX, e.clientY))} onDrop={this.onDrop.bind(this)} onDragOver={this.onDragOver} onWheel={this.onPointerWheel} - style={{ borderWidth: `${COLLECTION_BORDER_WIDTH}px` }} tabIndex={0} ref={this.createDropTarget}> + style={{ borderWidth: `${COLLECTION_BORDER_WIDTH}px` }} ref={this.createDropTarget}>
    {this.backgroundView} - - {this.views} - + + + {this.views} + + {super.getCursors().map(entry => { if (entry.Data.length > 0) { let id = entry.Data[0][0]; diff --git a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx index 7f951864e..d52b662bd 100644 --- a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx +++ b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx @@ -1,4 +1,4 @@ -import { computed, trace, reaction, runInAction, observable } from "mobx"; +import { computed } from "mobx"; import { observer } from "mobx-react"; import { KeyStore } from "../../../fields/KeyStore"; import { NumberField } from "../../../fields/NumberField"; @@ -6,8 +6,7 @@ import { Transform } from "../../util/Transform"; import { DocumentView, DocumentViewProps } from "./DocumentView"; import "./DocumentView.scss"; import React = require("react"); -import { Document } from "../../../fields/Document"; -import { DocumentManager } from "../../util/DocumentManager"; +import { thisExpression } from "babel-types"; @observer @@ -75,6 +74,7 @@ export class CollectionFreeFormDocumentView extends React.Component { @observable private _interactive: boolean = false; @observable private _loaded: boolean = false; - @computed private get curPage() { return this.props.doc.GetNumber(KeyStore.CurPage, -1); } + @computed private get curPage() { return this.props.doc.GetNumber(KeyStore.CurPage, 1); } @computed private get thumbnailPage() { return this.props.doc.GetNumber(KeyStore.ThumbnailPage, -1); } componentDidMount() { @@ -435,8 +435,6 @@ export class PDFBox extends React.Component { @computed get pdfContent() { let page = this.curPage; - if (page == 0) - page = 1; const renderHeight = 2400; let pdfUrl = this.props.doc.GetT(this.props.fieldKey, PDFField); let xf = this.props.doc.GetNumber(KeyStore.NativeHeight, 0) / renderHeight; @@ -463,10 +461,8 @@ export class PDFBox extends React.Component { return [ this._pageInfo.area.filter(() => this._pageInfo.area).map((element: any) => element), this._currAnno.map((element: any) => element), -
    - {this.pdfContent} - {proxy} -
    + this.pdfContent, + proxy ]; } -- cgit v1.2.3-70-g09d2 From feef2c656b7f4cee5375d41322be7a65ba098379 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sun, 31 Mar 2019 23:36:12 -0400 Subject: fixed ink to draw over documents --- src/client/views/InkingCanvas.scss | 9 ++++++--- src/client/views/InkingCanvas.tsx | 27 +++++++++++++++++++++------ 2 files changed, 27 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/client/views/InkingCanvas.scss b/src/client/views/InkingCanvas.scss index 6d7821cd2..abe6990b6 100644 --- a/src/client/views/InkingCanvas.scss +++ b/src/client/views/InkingCanvas.scss @@ -1,12 +1,11 @@ @import "global_variables"; -.inkingCanvas-paths, .inkingCanvas-paths-none { +.inkingCanvas-paths-ink, .inkingCanvas-paths-markers, .inkingCanvas-paths { position: absolute; top: -50000px; left: -50000px; width: 100000px; height: 100000px; - //z-index: 10000; // z-index: 99; //overlays ink on top of everything but that messes up blending and events don't propagate down to nested collections .highlight { mix-blend-mode: multiply; } @@ -18,8 +17,12 @@ pointer-events: auto; } -.inkingCanvas-paths-none { +.inkingCanvas-paths-ink, .inkingCanvas-paths-markers { pointer-events: none; + z-index: 10000; // overlays ink on top of everything cursor: "arrow"; } +.inkingCanvas-paths-markers { + mix-blend-mode: multiply; +} diff --git a/src/client/views/InkingCanvas.tsx b/src/client/views/InkingCanvas.tsx index a971264b9..fd9e6826a 100644 --- a/src/client/views/InkingCanvas.tsx +++ b/src/client/views/InkingCanvas.tsx @@ -137,8 +137,20 @@ export class InkingCanvas extends React.Component { render() { // parse data from server let curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1) - let paths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { - if (strokeData.page == -1 || strokeData.page == curPage) + let markerpaths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { + if ((strokeData.page == -1 || strokeData.page == curPage) && + strokeData.tool == InkTool.Highlighter) + paths.push() + return paths; + }, [] as JSX.Element[]); + let penpaths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { + if ((strokeData.page == -1 || strokeData.page == curPage) && + strokeData.tool == InkTool.Pen) paths.push( { deleteCallback={this.removeLine} />) return paths; }, [] as JSX.Element[]); - let svgCanvasStyle = InkingControl.Instance.selectedTool == InkTool.None ? "-none" : ""; return (
    - - {paths} - + {this.props.children} + + {markerpaths} + + + {penpaths} +
    ) } -- cgit v1.2.3-70-g09d2 From 90ac1190d6e2413d13b1f24d36987f74c3f0ba9e Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Sun, 31 Mar 2019 23:42:50 -0400 Subject: the last change seems to cause some major performance problem, so reverting. --- src/client/views/InkingCanvas.scss | 8 ++------ src/client/views/InkingCanvas.tsx | 25 +++++-------------------- 2 files changed, 7 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/src/client/views/InkingCanvas.scss b/src/client/views/InkingCanvas.scss index abe6990b6..0e2d7f8c1 100644 --- a/src/client/views/InkingCanvas.scss +++ b/src/client/views/InkingCanvas.scss @@ -1,6 +1,6 @@ @import "global_variables"; -.inkingCanvas-paths-ink, .inkingCanvas-paths-markers, .inkingCanvas-paths { +.inkingCanvas-paths, .inkingCanvas-paths-none { position: absolute; top: -50000px; left: -50000px; @@ -17,12 +17,8 @@ pointer-events: auto; } -.inkingCanvas-paths-ink, .inkingCanvas-paths-markers { +.inkingCanvas-paths-none { pointer-events: none; - z-index: 10000; // overlays ink on top of everything cursor: "arrow"; } -.inkingCanvas-paths-markers { - mix-blend-mode: multiply; -} diff --git a/src/client/views/InkingCanvas.tsx b/src/client/views/InkingCanvas.tsx index fd9e6826a..9ae3ade47 100644 --- a/src/client/views/InkingCanvas.tsx +++ b/src/client/views/InkingCanvas.tsx @@ -137,20 +137,8 @@ export class InkingCanvas extends React.Component { render() { // parse data from server let curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1) - let markerpaths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { - if ((strokeData.page == -1 || strokeData.page == curPage) && - strokeData.tool == InkTool.Highlighter) - paths.push() - return paths; - }, [] as JSX.Element[]); - let penpaths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { - if ((strokeData.page == -1 || strokeData.page == curPage) && - strokeData.tool == InkTool.Pen) + let paths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { + if (strokeData.page == -1 || strokeData.page == curPage) paths.push( { deleteCallback={this.removeLine} />) return paths; }, [] as JSX.Element[]); + let svgCanvasStyle = InkingControl.Instance.selectedTool == InkTool.None ? "-none" : ""; return (
    - {this.props.children} - - {markerpaths} - - - {penpaths} + + {paths}
    ) -- cgit v1.2.3-70-g09d2 From 83ad2ff7b64f8ab67a0652192f1fc72ce8e7c1ad Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Mon, 1 Apr 2019 00:49:57 -0400 Subject: since these changes look right, re-committing them and will look at tomorrow. --- src/client/views/InkingCanvas.scss | 11 ++++++----- src/client/views/InkingCanvas.tsx | 28 ++++++++++++++++++++++------ 2 files changed, 28 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/client/views/InkingCanvas.scss b/src/client/views/InkingCanvas.scss index 0e2d7f8c1..fa8b8798a 100644 --- a/src/client/views/InkingCanvas.scss +++ b/src/client/views/InkingCanvas.scss @@ -1,14 +1,11 @@ @import "global_variables"; -.inkingCanvas-paths, .inkingCanvas-paths-none { +.inkingCanvas-paths-ink, .inkingCanvas-paths-markers, .inkingCanvas-paths { position: absolute; top: -50000px; left: -50000px; width: 100000px; height: 100000px; - .highlight { - mix-blend-mode: multiply; - } .inkingCanvas-children { transform: translate(50000px, 50000px); pointer-events: none; @@ -17,8 +14,12 @@ pointer-events: auto; } -.inkingCanvas-paths-none { +.inkingCanvas-paths-ink, .inkingCanvas-paths-markers { pointer-events: none; + z-index: 10000; // overlays ink on top of everything cursor: "arrow"; } +.inkingCanvas-paths-markers { + mix-blend-mode: multiply; +} diff --git a/src/client/views/InkingCanvas.tsx b/src/client/views/InkingCanvas.tsx index 9ae3ade47..86a7a4456 100644 --- a/src/client/views/InkingCanvas.tsx +++ b/src/client/views/InkingCanvas.tsx @@ -1,4 +1,4 @@ -import { action, computed } from "mobx"; +import { action, computed, trace } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../fields/Document"; import { FieldWaiting } from "../../fields/Field"; @@ -137,8 +137,20 @@ export class InkingCanvas extends React.Component { render() { // parse data from server let curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1) - let paths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { - if (strokeData.page == -1 || strokeData.page == curPage) + let markerpaths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { + if ((strokeData.page == -1 || strokeData.page == curPage) && + strokeData.tool == InkTool.Highlighter) + paths.push() + return paths; + }, [] as JSX.Element[]); + let penpaths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { + if ((strokeData.page == -1 || strokeData.page == curPage) && + strokeData.tool == InkTool.Pen) paths.push( { deleteCallback={this.removeLine} />) return paths; }, [] as JSX.Element[]); - let svgCanvasStyle = InkingControl.Instance.selectedTool == InkTool.None ? "-none" : ""; + trace(); return (
    + {this.props.children} - - {paths} + + {markerpaths} + + + {penpaths}
    ) -- cgit v1.2.3-70-g09d2 From 5b348089bdc33e1e3b8e78ce51925b40793cb2cd Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 1 Apr 2019 09:42:43 -0400 Subject: ink event cleanup --- src/client/views/InkingCanvas.scss | 8 ++- src/client/views/InkingCanvas.tsx | 120 +++++++++++++------------------------ 2 files changed, 48 insertions(+), 80 deletions(-) (limited to 'src') diff --git a/src/client/views/InkingCanvas.scss b/src/client/views/InkingCanvas.scss index fa8b8798a..214c70280 100644 --- a/src/client/views/InkingCanvas.scss +++ b/src/client/views/InkingCanvas.scss @@ -1,6 +1,6 @@ @import "global_variables"; -.inkingCanvas-paths-ink, .inkingCanvas-paths-markers, .inkingCanvas-paths { +.inkingCanvas-paths-ink, .inkingCanvas-paths-markers, .inkingCanvas-noSelect, .inkingCanvas-canSelect { position: absolute; top: -50000px; left: -50000px; @@ -14,7 +14,11 @@ pointer-events: auto; } -.inkingCanvas-paths-ink, .inkingCanvas-paths-markers { +.inkingCanvas-noSelect { + pointer-events: none; + cursor: "arrow"; +} +.inkingCanvas-paths-ink, .inkingCanvas-paths-markers { pointer-events: none; z-index: 10000; // overlays ink on top of everything cursor: "arrow"; diff --git a/src/client/views/InkingCanvas.tsx b/src/client/views/InkingCanvas.tsx index 86a7a4456..fc871e108 100644 --- a/src/client/views/InkingCanvas.tsx +++ b/src/client/views/InkingCanvas.tsx @@ -28,8 +28,7 @@ export class InkingCanvas extends React.Component { }); return inside } - private _isDrawing: boolean = false; - private _idGenerator: string = ""; + private _currentStrokeId: string = ""; constructor(props: Readonly) { super(props); @@ -48,78 +47,51 @@ export class InkingCanvas extends React.Component { this.props.Document.SetDataOnPrototype(KeyStore.Ink, value, InkField); } - componentDidMount() { - document.addEventListener("mouseup", this.handleMouseUp); - } - - componentWillUnmount() { - document.removeEventListener("mouseup", this.handleMouseUp); - } - @action onPointerDown = (e: React.PointerEvent): void => { - this._isDrawing = false; - if (e.button != 0 || e.altKey || e.ctrlKey || - InkingControl.Instance.selectedTool === InkTool.None) { + if (e.button != 0 || e.altKey || e.ctrlKey || InkingControl.Instance.selectedTool === InkTool.None) { return; } document.addEventListener("pointermove", this.onPointerMove, true); document.addEventListener("pointerup", this.onPointerUp, true); e.stopPropagation(); + e.preventDefault(); - this._isDrawing = true; if (InkingControl.Instance.selectedTool != InkTool.Eraser) { - const point = this.relativeCoordinatesForEvent(e.clientX, e.clientY); - // start the new line, saves a uuid to represent the field of the stroke - this._idGenerator = Utils.GenerateGuid(); - this.inkData.set(this._idGenerator, - { - pathData: [point], - color: InkingControl.Instance.selectedColor, - width: InkingControl.Instance.selectedWidth, - tool: InkingControl.Instance.selectedTool, - page: this.props.Document.GetNumber(KeyStore.CurPage, -1) - }); + this._currentStrokeId = Utils.GenerateGuid(); + this.inkData.set(this._currentStrokeId, { + pathData: [this.relativeCoordinatesForEvent(e.clientX, e.clientY)], + color: InkingControl.Instance.selectedColor, + width: InkingControl.Instance.selectedWidth, + tool: InkingControl.Instance.selectedTool, + page: this.props.Document.GetNumber(KeyStore.CurPage, -1) + }); } } onPointerUp = (e: PointerEvent): void => { - if (this._isDrawing) { - document.removeEventListener("pointermove", this.onPointerMove); - document.removeEventListener("pointerup", this.onPointerUp); - this._isDrawing = false; - e.stopPropagation(); - } + document.removeEventListener("pointermove", this.onPointerMove, true); + document.removeEventListener("pointerup", this.onPointerUp, true); + e.stopPropagation(); + e.preventDefault(); } @action onPointerMove = (e: PointerEvent): void => { - if (this._isDrawing) { - e.stopPropagation() - e.preventDefault(); - if (InkingControl.Instance.selectedTool === InkTool.Eraser) { - return - } - const point = this.relativeCoordinatesForEvent(e.clientX, e.clientY); - - // add points to new line as it is being drawn - let data = this.inkData; - let strokeData = data.get(this._idGenerator); + e.stopPropagation() + e.preventDefault(); + if (InkingControl.Instance.selectedTool != InkTool.Eraser) { + let data = this.inkData; // add points to new line as it is being drawn + let strokeData = data.get(this._currentStrokeId); if (strokeData) { - strokeData.pathData.push(point); - data.set(this._idGenerator, strokeData); + strokeData.pathData.push(this.relativeCoordinatesForEvent(e.clientX, e.clientY)); + data.set(this._currentStrokeId, strokeData); } - this.inkData = data; } } - @action - handleMouseUp = (e: MouseEvent): void => { - this._isDrawing = false; - } - relativeCoordinatesForEvent = (ex: number, ey: number): { x: number, y: number } => { let [x, y] = this.props.getScreenTransform().transformPoint(ex, ey); x += InkingCanvas.InkOffset; @@ -134,43 +106,35 @@ export class InkingCanvas extends React.Component { this.inkData = data; } - render() { + @computed + get drawnPaths() { + trace(); // parse data from server let curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1) - let markerpaths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { - if ((strokeData.page == -1 || strokeData.page == curPage) && - strokeData.tool == InkTool.Highlighter) - paths.push() - return paths; - }, [] as JSX.Element[]); - let penpaths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { - if ((strokeData.page == -1 || strokeData.page == curPage) && - strokeData.tool == InkTool.Pen) - paths.push() + let paths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { + if (strokeData.page == -1 || strokeData.page == curPage) + paths.push() return paths; }, [] as JSX.Element[]); + return [ + {paths.filter(path => path.props.tool == InkTool.Highlighter)} + , + + {paths.filter(path => path.props.tool != InkTool.Highlighter)} + ]; + } + + render() { + let svgCanvasStyle = InkingControl.Instance.selectedTool != InkTool.None ? "canSelect" : "noSelect"; trace(); return (
    - + {this.props.children} - - {markerpaths} - - - {penpaths} - + {this.drawnPaths}
    ) } -- cgit v1.2.3-70-g09d2 From 5940a2dce5b45382521cd20b4770732dcbc3e732 Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 1 Apr 2019 10:03:06 -0400 Subject: fixed inking problem - blinking cursors don't play nicely with ink --- src/client/views/InkingCanvas.tsx | 15 ++++----------- src/client/views/InkingStroke.tsx | 15 ++++----------- .../collections/collectionFreeForm/PreviewCursor.scss | 16 ++++++++-------- .../collections/collectionFreeForm/PreviewCursor.tsx | 7 ++++--- 4 files changed, 20 insertions(+), 33 deletions(-) (limited to 'src') diff --git a/src/client/views/InkingCanvas.tsx b/src/client/views/InkingCanvas.tsx index fc871e108..15dfb255a 100644 --- a/src/client/views/InkingCanvas.tsx +++ b/src/client/views/InkingCanvas.tsx @@ -19,19 +19,12 @@ interface InkCanvasProps { @observer export class InkingCanvas extends React.Component { static InkOffset: number = 50000; + private _currentStrokeId: string = ""; public static IntersectStrokeRect(stroke: StrokeData, selRect: { left: number, top: number, width: number, height: number }): boolean { - let inside = false; - stroke.pathData.map(val => { - if (selRect.left < val.x - InkingCanvas.InkOffset && selRect.left + selRect.width > val.x - InkingCanvas.InkOffset && + return stroke.pathData.reduce((inside, val) => inside || + (selRect.left < val.x - InkingCanvas.InkOffset && selRect.left + selRect.width > val.x - InkingCanvas.InkOffset && selRect.top < val.y - InkingCanvas.InkOffset && selRect.top + selRect.height > val.y - InkingCanvas.InkOffset) - inside = true; - }); - return inside - } - private _currentStrokeId: string = ""; - - constructor(props: Readonly) { - super(props); + , false); } @computed diff --git a/src/client/views/InkingStroke.tsx b/src/client/views/InkingStroke.tsx index 87b5c43d8..52111c711 100644 --- a/src/client/views/InkingStroke.tsx +++ b/src/client/views/InkingStroke.tsx @@ -21,21 +21,14 @@ export class InkingStroke extends React.Component { @observable private _strokeColor: string = this.props.color; @observable private _strokeWidth: string = this.props.width; - deleteStroke = (e: React.MouseEvent): void => { + deleteStroke = (e: React.PointerEvent): void => { if (InkingControl.Instance.selectedTool === InkTool.Eraser && e.buttons === 1) { this.props.deleteCallback(this.props.id); } } parseData = (line: Array<{ x: number, y: number }>): string => { - if (line.length === 0) { - return ""; - } - const pathData = "M " + - line.map(p => { - return p.x + " " + p.y; - }).join(" L "); - return pathData; + return !line.length ? "" : "M " + line.map(p => p.x + " " + p.y).join(" L "); } createStyle() { @@ -57,8 +50,8 @@ export class InkingStroke extends React.Component { return ( + d={pathData} style={{ ...pathStyle, pointerEvents: "all" }} strokeLinejoin="round" strokeLinecap="round" + onPointerOver={this.deleteStroke} onPointerDown={this.deleteStroke} /> ) } } \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/PreviewCursor.scss b/src/client/views/collections/collectionFreeForm/PreviewCursor.scss index 7d6d5aaab..21210be2b 100644 --- a/src/client/views/collections/collectionFreeForm/PreviewCursor.scss +++ b/src/client/views/collections/collectionFreeForm/PreviewCursor.scss @@ -12,12 +12,12 @@ } //this is an animation for the blinking cursor! -@keyframes blink { - 0% {opacity: 0} - 49%{opacity: 0} - 50% {opacity: 1} -} +// @keyframes blink { +// 0% {opacity: 0} +// 49%{opacity: 0} +// 50% {opacity: 1} +// } -#previewCursor { - animation: blink 1s infinite; -} \ No newline at end of file +// #previewCursor { +// animation: blink 1s infinite; +// } \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx b/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx index 339e056a8..877de8846 100644 --- a/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx +++ b/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx @@ -1,4 +1,4 @@ -import { action, observable } from "mobx"; +import { action, observable, trace } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../../../fields/Document"; import { Documents } from "../../../documents/Documents"; @@ -84,11 +84,12 @@ export class PreviewCursor extends React.Component { let p = this.props.getContainerTransform().transformPoint(this._lastX, this._lastY); if (this._visible && this._previewDivRef.current) this._previewDivRef.current!.focus(); + trace(); return ( -
    +
    {this.props.children} {!this._visible ? (null) : -
    I
    } +
    I
    }
    ) } -- cgit v1.2.3-70-g09d2 From a687a9962c8952074177e52366b69dcce231a18e Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 1 Apr 2019 13:46:32 -0400 Subject: fixed several things related to selections and creating text boxes. moved remote cursor stuff into its own file. --- src/client/util/SelectionManager.ts | 13 ++- src/client/views/InkingCanvas.tsx | 8 +- .../views/collections/CollectionViewBase.tsx | 8 -- .../CollectionFreeFormLinksView.tsx | 7 +- .../CollectionFreeFormRemoteCursors.tsx | 115 ++++++++++++++++++++ .../collectionFreeForm/CollectionFreeFormView.tsx | 118 ++++----------------- .../collections/collectionFreeForm/MarqueeView.tsx | 24 ++--- .../collectionFreeForm/PreviewCursor.tsx | 67 ++++++++---- 8 files changed, 213 insertions(+), 147 deletions(-) create mode 100644 src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx (limited to 'src') diff --git a/src/client/util/SelectionManager.ts b/src/client/util/SelectionManager.ts index 1a711ae64..6d6ae26fc 100644 --- a/src/client/util/SelectionManager.ts +++ b/src/client/util/SelectionManager.ts @@ -1,5 +1,6 @@ import { observable, action } from "mobx"; import { DocumentView } from "../views/nodes/DocumentView"; +import { Document } from "../../fields/Document" export namespace SelectionManager { class Manager { @@ -29,8 +30,16 @@ export namespace SelectionManager { return manager.SelectedDocuments.indexOf(doc) !== -1; } - export function DeselectAll(): void { - manager.SelectedDocuments = [] + export function DeselectAll(except?: Document): void { + let found: DocumentView | undefined = undefined; + if (except) { + for (let i = 0; i < manager.SelectedDocuments.length; i++) { + let view = manager.SelectedDocuments[i]; + if (view.props.Document == except) + found = view; + } + } + manager.SelectedDocuments.length = 0; } export function SelectedDocuments(): Array { diff --git a/src/client/views/InkingCanvas.tsx b/src/client/views/InkingCanvas.tsx index 15dfb255a..123ff679b 100644 --- a/src/client/views/InkingCanvas.tsx +++ b/src/client/views/InkingCanvas.tsx @@ -101,7 +101,6 @@ export class InkingCanvas extends React.Component { @computed get drawnPaths() { - trace(); // parse data from server let curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1) let paths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { @@ -111,10 +110,10 @@ export class InkingCanvas extends React.Component { tool={strokeData.tool} deleteCallback={this.removeLine} />) return paths; }, [] as JSX.Element[]); - return [ + return [ {paths.filter(path => path.props.tool == InkTool.Highlighter)} , - + {paths.filter(path => path.props.tool != InkTool.Highlighter)} ]; } @@ -122,11 +121,10 @@ export class InkingCanvas extends React.Component { render() { let svgCanvasStyle = InkingControl.Instance.selectedTool != InkTool.None ? "canSelect" : "noSelect"; - trace(); return (
    - {this.props.children} + {(this.props.children as any)() /* bcz: is there a better way to know that children is a function? */} {this.drawnPaths}
    ) diff --git a/src/client/views/collections/CollectionViewBase.tsx b/src/client/views/collections/CollectionViewBase.tsx index 48adce4d8..987f3cb6c 100644 --- a/src/client/views/collections/CollectionViewBase.tsx +++ b/src/client/views/collections/CollectionViewBase.tsx @@ -76,14 +76,6 @@ export class CollectionViewBase extends React.Component } } - protected getCursors(): CursorEntry[] { - let doc = this.props.Document; - let id = CurrentUserUtils.id; - let cursors = doc.GetList(KeyStore.Cursors, []); - let notMe = cursors.filter(entry => entry.Data[0][0] !== id); - return id ? notMe : []; - } - @undoBatch @action protected drop(e: Event, de: DragManager.DropEvent): boolean { diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx index ef60aa672..eb20b3100 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx @@ -1,4 +1,4 @@ -import { computed, reaction, runInAction } from "mobx"; +import { computed, reaction, runInAction, trace } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../../../fields/Document"; import { FieldWaiting } from "../../../../fields/Field"; @@ -71,7 +71,7 @@ export class CollectionFreeFormLinksView extends React.Component { + let connections = DocumentManager.Instance.LinkedDocumentViews.reduce((drawnPairs, connection) => { let srcViews = this.documentAnchors(connection.a); let targetViews = this.documentAnchors(connection.b); let possiblePairs: { a: Document, b: Document, }[] = []; @@ -90,13 +90,14 @@ export class CollectionFreeFormLinksView extends React.Component ); } render() { return (
    - {this.uniqueConnections.map(c => )} + {this.uniqueConnections} {this.props.children}
    diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx new file mode 100644 index 000000000..19382e66f --- /dev/null +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx @@ -0,0 +1,115 @@ +import { action, computed, observable } from "mobx"; +import { observer } from "mobx-react"; +import { Document } from "../../../../fields/Document"; +import { FieldWaiting } from "../../../../fields/Field"; +import { KeyStore } from "../../../../fields/KeyStore"; +import { TextField } from "../../../../fields/TextField"; +import { DragManager } from "../../../util/DragManager"; +import { Transform } from "../../../util/Transform"; +import { undoBatch } from "../../../util/UndoManager"; +import { InkingCanvas } from "../../InkingCanvas"; +import { CollectionFreeFormDocumentView } from "../../nodes/CollectionFreeFormDocumentView"; +import { DocumentContentsView } from "../../nodes/DocumentContentsView"; +import { DocumentViewProps } from "../../nodes/DocumentView"; +import { COLLECTION_BORDER_WIDTH } from "../CollectionView"; +import { CollectionViewBase, CollectionViewProps, CursorEntry } from "../CollectionViewBase"; +import { CollectionFreeFormLinksView } from "./CollectionFreeFormLinksView"; +import "./CollectionFreeFormView.scss"; +import { MarqueeView } from "./MarqueeView"; +import React = require("react"); +import v5 = require("uuid/v5"); +import { CurrentUserUtils } from "../../../../server/authentication/models/current_user_utils"; + +@observer +export class CollectionFreeFormRemoteCursors extends React.Component { + protected getCursors(): CursorEntry[] { + let doc = this.props.Document; + let id = CurrentUserUtils.id; + let cursors = doc.GetList(KeyStore.Cursors, []); + let notMe = cursors.filter(entry => entry.Data[0][0] !== id); + return id ? notMe : []; + } + + private crosshairs?: HTMLCanvasElement; + drawCrosshairs = (backgroundColor: string) => { + if (this.crosshairs) { + let c = this.crosshairs; + let ctx = c.getContext('2d'); + if (ctx) { + ctx.fillStyle = backgroundColor; + ctx.fillRect(0, 0, 20, 20); + + ctx.fillStyle = "black"; + ctx.lineWidth = 0.5; + + ctx.beginPath(); + + ctx.moveTo(10, 0); + ctx.lineTo(10, 8); + + ctx.moveTo(10, 20); + ctx.lineTo(10, 12); + + ctx.moveTo(0, 10); + ctx.lineTo(8, 10); + + ctx.moveTo(20, 10); + ctx.lineTo(12, 10); + + ctx.stroke(); + + // ctx.font = "10px Arial"; + // ctx.fillText(CurrentUserUtils.email[0].toUpperCase(), 10, 10); + } + } + } + @computed + get sharedCursors() { + return this.getCursors().map(entry => { + if (entry.Data.length > 0) { + let id = entry.Data[0][0]; + let email = entry.Data[0][1]; + let point = entry.Data[1]; + this.drawCrosshairs("#" + v5(id, v5.URL).substring(0, 6).toUpperCase() + "22") + return ( +
    + { if (el) this.crosshairs = el }} + width={20} + height={20} + style={{ + position: 'absolute', + width: "20px", + height: "20px", + opacity: 0.5, + borderRadius: "50%", + border: "2px solid black" + }} + /> +

    {email[0].toUpperCase()}

    +
    + ); + } + }) + } + + render() { + return this.sharedCursors; + } +} \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index ae1c775e6..60fb95ff5 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -1,4 +1,4 @@ -import { action, computed, observable } from "mobx"; +import { action, computed, observable, trace } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../../../fields/Document"; import { FieldWaiting } from "../../../../fields/Field"; @@ -18,6 +18,8 @@ import "./CollectionFreeFormView.scss"; import { MarqueeView } from "./MarqueeView"; import React = require("react"); import v5 = require("uuid/v5"); +import { CollectionFreeFormRemoteCursors } from "./CollectionFreeFormRemoteCursors"; +import { PreviewCursor } from "./PreviewCursor"; @observer export class CollectionFreeFormView extends CollectionViewBase { @@ -60,7 +62,7 @@ export class CollectionFreeFormView extends CollectionViewBase { @computed get panX(): number { return this.props.Document.GetNumber(KeyStore.PanX, 0) } @computed get panY(): number { return this.props.Document.GetNumber(KeyStore.PanY, 0) } @computed get scale(): number { return this.props.Document.GetNumber(KeyStore.Scale, 1); } - @computed get isAnnotationOverlay() { return this.props.fieldKey.Id === KeyStore.Annotations.Id; } // bcz: ? Why do we need to compare Id's? + @computed get isAnnotationOverlay() { return this.props.fieldKey && this.props.fieldKey.Id === KeyStore.Annotations.Id; } // bcz: ? Why do we need to compare Id's? @computed get nativeWidth() { return this.props.Document.GetNumber(KeyStore.NativeWidth, 0); } @computed get nativeHeight() { return this.props.Document.GetNumber(KeyStore.NativeHeight, 0); } @computed get zoomScaling() { return this.props.Document.GetNumber(KeyStore.Scale, 1); } @@ -97,13 +99,15 @@ export class CollectionFreeFormView extends CollectionViewBase { @action onPointerDown = (e: React.PointerEvent): void => { - if ((e.button === 2 && this.props.active() && (!this.isAnnotationOverlay || this.zoomScaling != 1)) || e.button == 0) { + if (((e.button === 2 && (!this.isAnnotationOverlay || this.zoomScaling != 1)) || e.button == 0) && this.props.active()) { document.removeEventListener("pointermove", this.onPointerMove); document.addEventListener("pointermove", this.onPointerMove); document.removeEventListener("pointerup", this.onPointerUp); document.addEventListener("pointerup", this.onPointerUp); this._lastX = this.DownX = e.pageX; this._lastY = this.DownY = e.pageY; + if (this.props.isSelected()) + e.stopPropagation(); } } @@ -134,7 +138,6 @@ export class CollectionFreeFormView extends CollectionViewBase { onPointerWheel = (e: React.WheelEvent): void => { this.props.select(false); e.stopPropagation(); - e.preventDefault(); let coefficient = 1000; if (e.ctrlKey) { @@ -265,50 +268,13 @@ export class CollectionFreeFormView extends CollectionViewBase { getContainerTransform = (): Transform => this.props.ScreenToLocalTransform().translate(-COLLECTION_BORDER_WIDTH, -COLLECTION_BORDER_WIDTH) getLocalTransform = (): Transform => Transform.Identity.scale(1 / this.scale).translate(this.panX, this.panY); noScaling = () => 1; - - - private crosshairs?: HTMLCanvasElement; - drawCrosshairs = (backgroundColor: string) => { - if (this.crosshairs) { - let c = this.crosshairs; - let ctx = c.getContext('2d'); - if (ctx) { - ctx.fillStyle = backgroundColor; - ctx.fillRect(0, 0, 20, 20); - - ctx.fillStyle = "black"; - ctx.lineWidth = 0.5; - - ctx.beginPath(); - - ctx.moveTo(10, 0); - ctx.lineTo(10, 8); - - ctx.moveTo(10, 20); - ctx.lineTo(10, 12); - - ctx.moveTo(0, 10); - ctx.lineTo(8, 10); - - ctx.moveTo(20, 10); - ctx.lineTo(12, 10); - - ctx.stroke(); - - // ctx.font = "10px Arial"; - // ctx.fillText(CurrentUserUtils.email[0].toUpperCase(), 10, 10); - } - } - } + childViews = () => this.views; render() { let [dx, dy] = [this.centeringShiftX, this.centeringShiftY]; const panx: number = -this.props.Document.GetNumber(KeyStore.PanX, 0); const pany: number = -this.props.Document.GetNumber(KeyStore.PanY, 0); - // const panx: number = this.props.Document.GetNumber(KeyStore.PanX, 0) + this.centeringShiftX; - // const pany: number = this.props.Document.GetNumber(KeyStore.PanY, 0) + this.centeringShiftY; - // console.log("center:", this.getLocalTransform().transformPoint(this.centeringShiftX, this.centeringShiftY)); return (
    -
    - {this.backgroundView} - - - {this.views} - - - {super.getCursors().map(entry => { - if (entry.Data.length > 0) { - let id = entry.Data[0][0]; - let email = entry.Data[0][1]; - let point = entry.Data[1]; - this.drawCrosshairs("#" + v5(id, v5.URL).substring(0, 6).toUpperCase() + "22") - return ( -
    - { if (el) this.crosshairs = el }} - width={20} - height={20} - style={{ - position: 'absolute', - width: "20px", - height: "20px", - opacity: 0.5, - borderRadius: "50%", - border: "2px solid black" - }} - /> -

    {email[0].toUpperCase()}

    -
    - ); - } - })} -
    - {this.overlayView} + +
    + {this.backgroundView} + + + {this.childViews} + + + +
    + {this.overlayView} +
    ); diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index 2b0e7d228..20132a4b1 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -1,4 +1,4 @@ -import { action, computed, observable } from "mobx"; +import { action, computed, observable, trace } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../../../fields/Document"; import { FieldWaiting } from "../../../../fields/Field"; @@ -21,7 +21,6 @@ interface MarqueeViewProps { activeDocuments: () => Document[]; selectDocuments: (docs: Document[]) => void; removeDocument: (doc: Document) => boolean; - addLiveTextDocument: (doc: Document) => void; } @observer @@ -77,10 +76,11 @@ export class MarqueeView extends React.Component onPointerUp = (e: PointerEvent): void => { this.cleanupInteractions(true); this._visible = false; + let mselect = this.marqueeSelect(); if (!e.shiftKey) { - SelectionManager.DeselectAll(); + SelectionManager.DeselectAll(mselect.length ? undefined : this.props.container.props.Document); } - this.props.selectDocuments(this.marqueeSelect()); + this.props.selectDocuments(mselect.length ? mselect : [this.props.container.props.Document]); } intersectRect(r1: { left: number, top: number, width: number, height: number }, @@ -184,17 +184,17 @@ export class MarqueeView extends React.Component return selection; } - render() { + @computed + get marqueeDiv() { let p = this.props.getContainerTransform().transformPoint(this._downX < this._lastX ? this._downX : this._lastX, this._downY < this._lastY ? this._downY : this._lastY); let v = this.props.getContainerTransform().transformDirection(this._lastX - this._downX, this._lastY - this._downY); - return
    - - {this.props.children} - {!this._visible ? (null) : -
    } + return
    + } - + render() { + return
    + {this.props.children} + {!this._visible ? (null) : this.marqueeDiv}
    ; } } \ No newline at end of file diff --git a/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx b/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx index 877de8846..93c98f7b0 100644 --- a/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx +++ b/src/client/views/collections/collectionFreeForm/PreviewCursor.tsx @@ -1,4 +1,4 @@ -import { action, observable, trace } from "mobx"; +import { action, observable, trace, computed, reaction } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../../../fields/Document"; import { Documents } from "../../../documents/Documents"; @@ -6,6 +6,7 @@ import { Transform } from "../../../util/Transform"; import { CollectionFreeFormView } from "./CollectionFreeFormView"; import "./PreviewCursor.scss"; import React = require("react"); +import { interfaceDeclaration } from "babel-types"; export interface PreviewCursorProps { @@ -23,27 +24,29 @@ export class PreviewCursor extends React.Component { @observable public DownX: number = 0; @observable public DownY: number = 0; _showOnUp: boolean = false; - public _previewDivRef = React.createRef(); @action cleanupInteractions = () => { document.removeEventListener("pointerup", this.onPointerUp, true); + document.removeEventListener("pointermove", this.onPointerMove, true); } @action onPointerDown = (e: React.PointerEvent) => { - this._visible = false; - document.removeEventListener("keypress", this.onKeyPress, false); - this._showOnUp = true; - this._lastX = this.DownX = e.pageX; - this._lastY = this.DownY = e.pageY; - document.addEventListener("pointerup", this.onPointerUp, true); - document.addEventListener("pointermove", this.onPointerMove, true); + if (e.button == 0 && this.props.container.props.active()) { + document.removeEventListener("keypress", this.onKeyPress, false); + this._showOnUp = true; + this.DownX = e.pageX; + this.DownY = e.pageY; + document.addEventListener("pointerup", this.onPointerUp, true); + document.addEventListener("pointermove", this.onPointerMove, true); + } } @action onPointerMove = (e: PointerEvent): void => { if (Math.abs(this.DownX - e.clientX) > 4 || Math.abs(this.DownY - e.clientY) > 4) { this._showOnUp = false; + this._visible = false; } } @@ -51,6 +54,8 @@ export class PreviewCursor extends React.Component { onPointerUp = (e: PointerEvent): void => { if (this._showOnUp) { document.addEventListener("keypress", this.onKeyPress, false); + this._lastX = this.DownX; + this._lastY = this.DownY; this._visible = true; } this.cleanupInteractions(); @@ -72,25 +77,43 @@ export class PreviewCursor extends React.Component { e.stopPropagation(); } } - //when focus is lost, this will remove the preview cursor - @action - onBlur = (): void => { - this._visible = false; + + getPoint = () => this.props.getContainerTransform().transformPoint(this._lastX, this._lastY); + getVisible = () => this._visible; + setVisible = (v: boolean) => { + this._visible = v; document.removeEventListener("keypress", this.onKeyPress, false); } - render() { - //get local position and place cursor there! - let p = this.props.getContainerTransform().transformPoint(this._lastX, this._lastY); - if (this._visible && this._previewDivRef.current) - this._previewDivRef.current!.focus(); - trace(); return ( -
    +
    {this.props.children} - {!this._visible ? (null) : -
    I
    } +
    ) } +} + +export interface PromptProps { + getPoint: () => number[]; + getVisible: () => boolean; + setVisible: (v: boolean) => void; +} + +@observer +export class PreviewCursorPrompt extends React.Component { + private _promptRef = React.createRef(); + + //when focus is lost, this will remove the preview cursor + @action onBlur = (): void => this.props.setVisible(false); + + render() { + let p = this.props.getPoint(); + if (this.props.getVisible() && this._promptRef.current) + this._promptRef.current.focus(); + return
    + I +
    ; + } } \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 8448679e0a260ec881c54a10578bc464cd38f04e Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 1 Apr 2019 17:05:42 -0400 Subject: added dragging multiple items. --- src/client/northstar/dash-nodes/HistogramBox.tsx | 4 +- src/client/util/DragManager.ts | 168 +++++++++++---------- src/client/views/DocumentDecorations.scss | 6 + src/client/views/DocumentDecorations.tsx | 109 +++++++++---- src/client/views/Main.tsx | 7 +- .../views/collections/CollectionDockingView.tsx | 11 +- src/client/views/collections/CollectionView.tsx | 2 +- .../views/collections/CollectionViewBase.tsx | 4 +- .../collectionFreeForm/CollectionFreeFormView.tsx | 21 ++- src/client/views/nodes/DocumentView.tsx | 15 +- 10 files changed, 213 insertions(+), 134 deletions(-) (limited to 'src') diff --git a/src/client/northstar/dash-nodes/HistogramBox.tsx b/src/client/northstar/dash-nodes/HistogramBox.tsx index a968def96..49ebe5ebc 100644 --- a/src/client/northstar/dash-nodes/HistogramBox.tsx +++ b/src/client/northstar/dash-nodes/HistogramBox.tsx @@ -54,7 +54,7 @@ export class HistogramBox extends React.Component { @action dropX = (e: Event, de: DragManager.DropEvent) => { if (de.data instanceof DragManager.DocumentDragData) { - let h = de.data.draggedDocument.GetT(KeyStore.Data, HistogramField); + let h = de.data.draggedDocuments[0].GetT(KeyStore.Data, HistogramField); if (h && h != FieldWaiting) { this.HistoOp.X = h.Data.X; } @@ -65,7 +65,7 @@ export class HistogramBox extends React.Component { @action dropY = (e: Event, de: DragManager.DropEvent) => { if (de.data instanceof DragManager.DocumentDragData) { - let h = de.data.draggedDocument.GetT(KeyStore.Data, HistogramField); + let h = de.data.draggedDocuments[0].GetT(KeyStore.Data, HistogramField); if (h && h != FieldWaiting) { this.HistoOp.Y = h.Data.X; } diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index 70b1c9829..9ffe964ef 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -14,9 +14,9 @@ export function setupDrag(_reference: React.RefObject, docFunc: document.removeEventListener("pointermove", onRowMove); document.removeEventListener('pointerup', onRowUp); - var dragData = new DragManager.DocumentDragData(docFunc()); + var dragData = new DragManager.DocumentDragData([docFunc()]); dragData.removeDocument = removeFunc; - DragManager.StartDocumentDrag(_reference.current!, dragData); + DragManager.StartDocumentDrag([_reference.current!], dragData); }); let onRowUp = action((e: PointerEvent): void => { document.removeEventListener("pointermove", onRowMove); @@ -27,7 +27,7 @@ export function setupDrag(_reference: React.RefObject, docFunc: if (e.button == 0) { e.stopPropagation(); if (e.shiftKey) { - CollectionDockingView.Instance.StartOtherDrag(docFunc(), e); + CollectionDockingView.Instance.StartOtherDrag([docFunc()], e); } else { document.addEventListener("pointermove", onRowMove); document.addEventListener('pointerup', onRowUp); @@ -101,20 +101,21 @@ export namespace DragManager { } export class DocumentDragData { - constructor(dragDoc: Document) { - this.draggedDocument = dragDoc; - this.droppedDocument = dragDoc; + constructor(dragDoc: Document[]) { + this.draggedDocuments = dragDoc; + this.droppedDocuments = dragDoc; } - draggedDocument: Document; - droppedDocument: Document; + draggedDocuments: Document[]; + droppedDocuments: Document[]; xOffset?: number; yOffset?: number; aliasOnDrop?: boolean; removeDocument?: (collectionDrop: CollectionView) => void; [id: string]: any; } - export function StartDocumentDrag(ele: HTMLElement, dragData: DocumentDragData, options?: DragOptions) { - StartDrag(ele, dragData, options, (dropData: { [id: string]: any }) => dropData.droppedDocument = dragData.aliasOnDrop ? dragData.draggedDocument.CreateAlias() : dragData.draggedDocument); + + export function StartDocumentDrag(eles: HTMLElement[], dragData: DocumentDragData, options?: DragOptions) { + StartDrag(eles, dragData, options, (dropData: { [id: string]: any }) => dropData.droppedDocuments = dragData.aliasOnDrop ? dragData.draggedDocuments.map(d => d.CreateAlias()) : dragData.draggedDocuments); } export class LinkDragData { @@ -125,49 +126,58 @@ export namespace DragManager { [id: string]: any; } export function StartLinkDrag(ele: HTMLElement, dragData: LinkDragData, options?: DragOptions) { - StartDrag(ele, dragData, options); + StartDrag([ele], dragData, options); } - function StartDrag(ele: HTMLElement, dragData: { [id: string]: any }, options?: DragOptions, finishDrag?: (dropData: { [id: string]: any }) => void) { + function StartDrag(eles: HTMLElement[], dragData: { [id: string]: any }, options?: DragOptions, finishDrag?: (dropData: { [id: string]: any }) => void) { if (!dragDiv) { dragDiv = document.createElement("div"); dragDiv.className = "dragManager-dragDiv" DragManager.Root().appendChild(dragDiv); } - const w = ele.offsetWidth, h = ele.offsetHeight; - const rect = ele.getBoundingClientRect(); - const scaleX = rect.width / w, scaleY = rect.height / h; - let x = rect.left, y = rect.top; - // const offsetX = e.x - rect.left, offsetY = e.y - rect.top; - - let dragElement = ele.cloneNode(true) as HTMLElement; - dragElement.style.opacity = "0.7"; - dragElement.style.position = "absolute"; - dragElement.style.bottom = ""; - dragElement.style.left = ""; - dragElement.style.transformOrigin = "0 0"; - dragElement.style.zIndex = "1000"; - dragElement.style.transform = `translate(${x}px, ${y}px) scale(${scaleX}, ${scaleY})`; - dragElement.style.width = `${rect.width / scaleX}px`; - dragElement.style.height = `${rect.height / scaleY}px`; - - // bcz: PDFs don't show up if you clone them because they contain a canvas. - // however, PDF's have a thumbnail field that contains an image of their canvas. - // So we replace the pdf's canvas with the image thumbnail - const doc: Document = dragData["draggedDocument"]; - if (doc) { - var pdfBox = dragElement.getElementsByClassName("pdfBox-cont")[0] as HTMLElement; - let thumbnail = doc.GetT(KeyStore.Thumbnail, ImageField); - if (pdfBox && pdfBox.childElementCount && thumbnail) { - let img = new Image(); - img!.src = thumbnail.toString(); - img!.style.position = "absolute"; - img!.style.width = `${rect.width / scaleX}px`; - img!.style.height = `${rect.height / scaleY}px`; - pdfBox.replaceChild(img!, pdfBox.children[0]) + + let scaleXs: number[] = []; + let scaleYs: number[] = []; + let xs: number[] = []; + let ys: number[] = []; + + const docs: Document[] = dragData instanceof DocumentDragData ? dragData.draggedDocuments : []; + let dragElements = eles.map(ele => { + const w = ele.offsetWidth, h = ele.offsetHeight; + const rect = ele.getBoundingClientRect(); + const scaleX = rect.width / w, scaleY = rect.height / h; + let x = rect.left, y = rect.top; + xs.push(x); ys.push(y); + scaleXs.push(scaleX); scaleYs.push(scaleY); + let dragElement = ele.cloneNode(true) as HTMLElement; + dragElement.style.opacity = "0.7"; + dragElement.style.position = "absolute"; + dragElement.style.bottom = ""; + dragElement.style.left = ""; + dragElement.style.transformOrigin = "0 0"; + dragElement.style.zIndex = "1000"; + dragElement.style.transform = `translate(${x}px, ${y}px) scale(${scaleX}, ${scaleY})`; + dragElement.style.width = `${rect.width / scaleX}px`; + dragElement.style.height = `${rect.height / scaleY}px`; + + // bcz: PDFs don't show up if you clone them because they contain a canvas. + // however, PDF's have a thumbnail field that contains an image of their canvas. + // So we replace the pdf's canvas with the image thumbnail + if (docs.length) { + var pdfBox = dragElement.getElementsByClassName("pdfBox-cont")[0] as HTMLElement; + let thumbnail = docs[0].GetT(KeyStore.Thumbnail, ImageField); + if (pdfBox && pdfBox.childElementCount && thumbnail) { + let img = new Image(); + img!.src = thumbnail.toString(); + img!.style.position = "absolute"; + img!.style.width = `${rect.width / scaleX}px`; + img!.style.height = `${rect.height / scaleY}px`; + pdfBox.replaceChild(img!, pdfBox.children[0]) + } } - } - dragDiv.appendChild(dragElement); + dragDiv.appendChild(dragElement); + return dragElement; + }); let hideSource = false; if (options) { @@ -177,62 +187,64 @@ export namespace DragManager { hideSource = options.hideSource(); } } - const wasHidden = ele.hidden; - if (hideSource) { - ele.hidden = true; - } + eles.map(ele => ele.hidden = hideSource); + const moveHandler = (e: PointerEvent) => { e.stopPropagation(); e.preventDefault(); - x += e.movementX; - y += e.movementY; if (dragData instanceof DocumentDragData) dragData.aliasOnDrop = e.ctrlKey || e.altKey; if (e.shiftKey) { abortDrag(); - CollectionDockingView.Instance.StartOtherDrag(doc, { pageX: e.pageX, pageY: e.pageY, preventDefault: () => { }, button: 0 }); + CollectionDockingView.Instance.StartOtherDrag(docs, { pageX: e.pageX, pageY: e.pageY, preventDefault: () => { }, button: 0 }); } - dragElement.style.transform = `translate(${x}px, ${y}px) scale(${scaleX}, ${scaleY})`; + dragElements.map((dragElement, i) => dragElement.style.transform = `translate(${xs[i] += e.movementX}px, ${ys[i] += e.movementY}px) scale(${scaleXs[i]}, ${scaleYs[i]})`); }; const abortDrag = () => { document.removeEventListener("pointermove", moveHandler, true); document.removeEventListener("pointerup", upHandler); - dragDiv.removeChild(dragElement); - ele.hidden = false; + dragElements.map(dragElement => dragDiv.removeChild(dragElement)); + eles.map(ele => ele.hidden = false); } const upHandler = (e: PointerEvent) => { abortDrag(); - FinishDrag(ele, e, dragData, options, finishDrag); + FinishDrag(eles, e, dragData, options, finishDrag); }; document.addEventListener("pointermove", moveHandler, true); document.addEventListener("pointerup", upHandler); } - function FinishDrag(dragEle: HTMLElement, e: PointerEvent, dragData: { [index: string]: any }, options?: DragOptions, finishDrag?: (dragData: { [index: string]: any }) => void) { - let parent = dragEle.parentElement; - if (parent) - parent.removeChild(dragEle); + function FinishDrag(dragEles: HTMLElement[], e: PointerEvent, dragData: { [index: string]: any }, options?: DragOptions, finishDrag?: (dragData: { [index: string]: any }) => void) { + let removed = dragEles.map(dragEle => { + let parent = dragEle.parentElement; + if (parent) + parent.removeChild(dragEle); + return [dragEle, parent]; + }); const target = document.elementFromPoint(e.x, e.y); - if (parent) - parent.appendChild(dragEle); - if (!target) { - return; - } - if (finishDrag) - finishDrag(dragData); - - target.dispatchEvent(new CustomEvent("dashOnDrop", { - bubbles: true, - detail: { - x: e.x, - y: e.y, - data: dragData + removed.map(r => { + let dragEle: HTMLElement = r[0]!; + let parent: HTMLElement | null = r[1]; + if (parent) + parent.appendChild(dragEle); + }); + if (target) { + if (finishDrag) + finishDrag(dragData); + + target.dispatchEvent(new CustomEvent("dashOnDrop", { + bubbles: true, + detail: { + x: e.x, + y: e.y, + data: dragData + } + })); + + if (options) { + options.handlers.dragComplete({}); } - })); - - if (options) { - options.handlers.dragComplete({}); } DocumentDecorations.Instance.Hidden = false; } diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 11595aa01..7a43f3087 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -32,6 +32,12 @@ } } +.documentDecorations-background { + background:lightblue; + position: absolute; + opacity: 0.1; +} + // position: absolute; // display: grid; // z-index: 1000; diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 47098c3b5..faba3b6ea 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -1,14 +1,14 @@ -import { observable, computed, action } from "mobx"; -import React = require("react"); -import { SelectionManager } from "../util/SelectionManager"; +import { action, computed, observable, trace } from "mobx"; import { observer } from "mobx-react"; -import './DocumentDecorations.scss' -import { KeyStore } from '../../fields/KeyStore' +import { KeyStore } from '../../fields/KeyStore'; +import { ListField } from "../../fields/ListField"; import { NumberField } from "../../fields/NumberField"; -import { props } from "bluebird"; import { DragManager } from "../util/DragManager"; +import { SelectionManager } from "../util/SelectionManager"; +import { CollectionView } from "./collections/CollectionView"; +import './DocumentDecorations.scss'; import { LinkMenu } from "./nodes/LinkMenu"; -import { ListField } from "../../fields/ListField"; +import React = require("react"); const higflyout = require("@hig/flyout"); export const { anchorPoints } = higflyout; export const Flyout = higflyout.default; @@ -22,6 +22,7 @@ export class DocumentDecorations extends React.Component { private _resizeBorderWidth = 16; private _linkButton = React.createRef(); @observable private _hidden = false; + @observable private _dragging = false; constructor(props: Readonly<{}>) { super(props) @@ -50,6 +51,50 @@ export class DocumentDecorations extends React.Component { public get Hidden() { return this._hidden; } public set Hidden(value: boolean) { this._hidden = value; } + _lastDrag: number[] = [0, 0]; + onBackgroundDown = (e: React.PointerEvent): void => { + document.removeEventListener("pointermove", this.onBackgroundMove); + document.addEventListener("pointermove", this.onBackgroundMove); + document.removeEventListener("pointerup", this.onBackgroundUp); + document.addEventListener("pointerup", this.onBackgroundUp); + this._lastDrag = [e.clientX, e.clientY] + e.stopPropagation(); + e.preventDefault(); + } + + @action + onBackgroundMove = (e: PointerEvent): void => { + let dragDocView = SelectionManager.SelectedDocuments()[0]; + const [left, top] = dragDocView.props.ScreenToLocalTransform().inverse().transformPoint(0, 0); + let dragData = new DragManager.DocumentDragData(SelectionManager.SelectedDocuments().map(dv => dv.props.Document)); + dragData.aliasOnDrop = false; + dragData.xOffset = e.x - left; + dragData.yOffset = e.y - top; + dragData.removeDocument = (dropCollectionView: CollectionView) => + dragData.draggedDocuments.map(d => { + if (dragDocView.props.RemoveDocument && dragDocView.props.ContainingCollectionView !== dropCollectionView) { + dragDocView.props.RemoveDocument(d); + } + }); + this._dragging = true; + document.removeEventListener("pointermove", this.onBackgroundMove); + document.removeEventListener("pointerup", this.onBackgroundUp); + DragManager.StartDocumentDrag(SelectionManager.SelectedDocuments().map(docView => (docView as any)._mainCont!.current!), dragData, { + handlers: { + dragComplete: action(() => this._dragging = false), + }, + hideSource: true + }) + e.stopPropagation(); + } + + onBackgroundUp = (e: PointerEvent): void => { + document.removeEventListener("pointermove", this.onBackgroundMove); + document.removeEventListener("pointerup", this.onBackgroundUp); + e.stopPropagation(); + e.preventDefault(); + } + onPointerDown = (e: React.PointerEvent): void => { e.stopPropagation(); if (e.button === 0) { @@ -191,7 +236,6 @@ export class DocumentDecorations extends React.Component { // buttonOnPointerUp = (e: React.PointerEvent): void => { // e.stopPropagation(); // } - render() { var bounds = this.Bounds; if (this.Hidden) { @@ -218,25 +262,36 @@ export class DocumentDecorations extends React.Component { ); } return ( -
    -
    e.preventDefault()}>
    -
    e.preventDefault()}>
    -
    e.preventDefault()}>
    -
    e.preventDefault()}>
    -
    -
    e.preventDefault()}>
    -
    e.preventDefault()}>
    -
    e.preventDefault()}>
    -
    e.preventDefault()}>
    - -
    {linkButton}
    - -
    +
    +
    1 ? 1000 : 0, + }} onPointerDown={this.onBackgroundDown} onContextMenu={(e: React.MouseEvent) => { e.preventDefault(); e.stopPropagation() }} > +
    +
    +
    e.preventDefault()}>
    +
    e.preventDefault()}>
    +
    e.preventDefault()}>
    +
    e.preventDefault()}>
    +
    +
    e.preventDefault()}>
    +
    e.preventDefault()}>
    +
    e.preventDefault()}>
    +
    e.preventDefault()}>
    + +
    {linkButton}
    + +
    +
    ) } } \ No newline at end of file diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index 75855c3d1..6f66f8f38 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -218,7 +218,8 @@ export class Main extends React.Component { focusDocument = (doc: Document) => { } noScaling = () => 1; - get content() { + @computed + get mainContent() { return !this.mainContainer ? (null) : + runInAction(() => { this.pwidth = r.entry.width; this.pheight = r.entry.height; })}> {({ measureRef }) =>
    - {this.content} + {this.mainContent}
    }
    - {this.nodesMenu} {this.miscButtons} diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index f123149dd..c6cbc05e7 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -47,9 +47,10 @@ export class CollectionDockingView extends React.Component { }, button: 0 }) + public StartOtherDrag(dragDocs: Document[], e: any) { + dragDocs.map(dragDoc => + this.AddRightSplit(dragDoc, true).contentItems[0].tab._dragListener. + onMouseDown({ pageX: e.pageX, pageY: e.pageY, preventDefault: () => { }, button: 0 })); } @action @@ -199,7 +200,7 @@ export class CollectionDockingView extends React.Component) => { if (f instanceof Document) - DragManager.StartDocumentDrag(tab, new DragManager.DocumentDragData(f as Document), + DragManager.StartDocumentDrag([tab], new DragManager.DocumentDragData([f as Document]), { handlers: { dragComplete: action(() => { }), @@ -265,6 +266,7 @@ export class CollectionDockingView extends React.Component { } render() { + trace(); if (!this._document) return (null); var content = diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index a1498e0ae..014aa1d8f 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -113,7 +113,7 @@ export class CollectionView extends React.Component { if (index !== -1) { value.splice(index, 1) - SelectionManager.DeselectAll() + //SelectionManager.DeselectAll() ContextMenu.Instance.clearItems() return true; } diff --git a/src/client/views/collections/CollectionViewBase.tsx b/src/client/views/collections/CollectionViewBase.tsx index 987f3cb6c..316d20c9d 100644 --- a/src/client/views/collections/CollectionViewBase.tsx +++ b/src/client/views/collections/CollectionViewBase.tsx @@ -82,9 +82,9 @@ export class CollectionViewBase extends React.Component if (de.data instanceof DragManager.DocumentDragData) { if (de.data.aliasOnDrop) { [KeyStore.Width, KeyStore.Height, KeyStore.CurPage].map(key => - de.data.draggedDocument.GetTAsync(key, NumberField, (f: Opt) => f ? de.data.droppedDocument.SetNumber(key, f.Data) : null)); + de.data.draggedDocuments.GetTAsync(key, NumberField, (f: Opt) => f ? de.data.droppedDocument.SetNumber(key, f.Data) : null)); } - let added = this.props.addDocument(de.data.droppedDocument, false); + let added = de.data.droppedDocuments.reduce((added, d) => this.props.addDocument(d, false), true); if (added && de.data.removeDocument && !de.data.aliasOnDrop) { de.data.removeDocument(this.props.CollectionView); } diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 60fb95ff5..c5178f69d 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -77,13 +77,20 @@ export class CollectionFreeFormView extends CollectionViewBase { let screenX = de.x - (de.data.xOffset as number || 0); let screenY = de.y - (de.data.yOffset as number || 0); const [x, y] = this.getTransform().transformPoint(screenX, screenY); - de.data.droppedDocument.SetNumber(KeyStore.X, x); - de.data.droppedDocument.SetNumber(KeyStore.Y, y); - if (!de.data.droppedDocument.GetNumber(KeyStore.Width, 0)) { - de.data.droppedDocument.SetNumber(KeyStore.Width, 300); - de.data.droppedDocument.SetNumber(KeyStore.Height, 300); - } - this.bringToFront(de.data.droppedDocument); + let dragDoc = de.data.draggedDocuments[0]; + let dragX = dragDoc.GetNumber(KeyStore.X, 0); + let dragY = dragDoc.GetNumber(KeyStore.Y, 0); + de.data.draggedDocuments.map(d => { + let docX = d.GetNumber(KeyStore.X, 0); + let docY = d.GetNumber(KeyStore.Y, 0); + d.SetNumber(KeyStore.X, x + (docX - dragX)); + d.SetNumber(KeyStore.Y, y + (docY - dragY)); + if (!d.GetNumber(KeyStore.Width, 0)) { + d.SetNumber(KeyStore.Width, 300); + d.SetNumber(KeyStore.Height, 300); + } + this.bringToFront(d); + }) } return true; } diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 71613ca4f..1195128dc 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -106,7 +106,7 @@ export class DocumentView extends React.Component { if (this.props.isTopMost) { this.startDragging(e.pageX, e.pageY, e.altKey || e.ctrlKey); } - else CollectionDockingView.Instance.StartOtherDrag(this.props.Document, e); + else CollectionDockingView.Instance.StartOtherDrag([this.props.Document], e); e.stopPropagation(); } else { if (this.active && !e.isDefaultPrevented()) { @@ -125,9 +125,7 @@ export class DocumentView extends React.Component { if (this._mainCont.current) { this.dropDisposer = DragManager.MakeDropTarget(this._mainCont.current, { handlers: { drop: this.drop.bind(this) } }); } - runInAction(() => { - DocumentManager.Instance.DocumentViews.push(this); - }) + runInAction(() => DocumentManager.Instance.DocumentViews.push(this)) this._reactionDisposer = reaction( () => this.props.ContainingCollectionView && this.props.ContainingCollectionView.SelectedDocs.slice(), () => { @@ -149,10 +147,7 @@ export class DocumentView extends React.Component { if (this.dropDisposer) { this.dropDisposer(); } - runInAction(() => { - DocumentManager.Instance.DocumentViews.splice(DocumentManager.Instance.DocumentViews.indexOf(this), 1); - - }) + runInAction(() => DocumentManager.Instance.DocumentViews.splice(DocumentManager.Instance.DocumentViews.indexOf(this), 1)) if (this._reactionDisposer) { this._reactionDisposer(); } @@ -161,7 +156,7 @@ export class DocumentView extends React.Component { startDragging(x: number, y: number, dropAliasOfDraggedDoc: boolean) { if (this._mainCont.current) { const [left, top] = this.props.ScreenToLocalTransform().inverse().transformPoint(0, 0); - let dragData = new DragManager.DocumentDragData(this.props.Document); + let dragData = new DragManager.DocumentDragData([this.props.Document]); dragData.aliasOnDrop = dropAliasOfDraggedDoc; dragData.xOffset = x - left; dragData.yOffset = y - top; @@ -170,7 +165,7 @@ export class DocumentView extends React.Component { this.props.RemoveDocument(this.props.Document); } } - DragManager.StartDocumentDrag(this._mainCont.current, dragData, { + DragManager.StartDocumentDrag([this._mainCont.current], dragData, { handlers: { dragComplete: action(() => { }), }, -- cgit v1.2.3-70-g09d2 From 8b48b3a4afcd3d09b87f966d26fa9e21029d4cc1 Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 1 Apr 2019 17:06:09 -0400 Subject: from last --- src/client/views/collections/CollectionDockingView.tsx | 2 -- 1 file changed, 2 deletions(-) (limited to 'src') diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index c6cbc05e7..39e0dd989 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -266,7 +266,6 @@ export class CollectionDockingView extends React.Component { } render() { - trace(); if (!this._document) return (null); var content = -- cgit v1.2.3-70-g09d2 From dd561b6b81a2832972d15e6226327a49ec1cdf06 Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 1 Apr 2019 17:19:01 -0400 Subject: from last --- src/client/util/SelectionManager.ts | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/client/util/SelectionManager.ts b/src/client/util/SelectionManager.ts index 6d6ae26fc..1354e32e1 100644 --- a/src/client/util/SelectionManager.ts +++ b/src/client/util/SelectionManager.ts @@ -40,6 +40,8 @@ export namespace SelectionManager { } } manager.SelectedDocuments.length = 0; + if (found) + manager.SelectedDocuments.push(found); } export function SelectedDocuments(): Array { -- cgit v1.2.3-70-g09d2 From 945fb1c28fa94ee1d2448381d7dd55b99214aad4 Mon Sep 17 00:00:00 2001 From: Monika Hedman Date: Mon, 1 Apr 2019 22:04:42 -0400 Subject: icon not working --- build/index.html | 24 +- package.json | 1 + src/client/util/SelectionManager.ts | 82 ++-- src/client/views/nodes/DocumentView.scss | 18 +- src/client/views/nodes/DocumentView.tsx | 669 +++++++++++++++++----------- src/client/views/nodes/FormattedTextBox.tsx | 289 ++++++------ 6 files changed, 635 insertions(+), 448 deletions(-) (limited to 'src') diff --git a/build/index.html b/build/index.html index fda212af4..2818d7c8b 100644 --- a/build/index.html +++ b/build/index.html @@ -1,12 +1,16 @@ + + Dash Web + + - - Dash Web - - - -
    - - - - \ No newline at end of file + +
    + + + diff --git a/package.json b/package.json index 27b3eead1..6e894fd20 100644 --- a/package.json +++ b/package.json @@ -105,6 +105,7 @@ "express-validator": "^5.3.1", "expressjs": "^1.0.1", "flexlayout-react": "^0.3.3", + "font-awesome": "^4.7.0", "formidable": "^1.2.1", "golden-layout": "^1.5.9", "html-to-image": "^0.1.0", diff --git a/src/client/util/SelectionManager.ts b/src/client/util/SelectionManager.ts index 1354e32e1..438659108 100644 --- a/src/client/util/SelectionManager.ts +++ b/src/client/util/SelectionManager.ts @@ -1,50 +1,50 @@ import { observable, action } from "mobx"; import { DocumentView } from "../views/nodes/DocumentView"; -import { Document } from "../../fields/Document" +import { Document } from "../../fields/Document"; export namespace SelectionManager { - class Manager { - @observable - SelectedDocuments: Array = []; - - @action - SelectDoc(doc: DocumentView, ctrlPressed: boolean): void { - // if doc is not in SelectedDocuments, add it - if (!ctrlPressed) { - manager.SelectedDocuments = []; - } - - if (manager.SelectedDocuments.indexOf(doc) === -1) { - manager.SelectedDocuments.push(doc) - } - } + class Manager { + @observable + SelectedDocuments: Array = []; + + @action + SelectDoc(doc: DocumentView, ctrlPressed: boolean): void { + // if doc is not in SelectedDocuments, add it + if (!ctrlPressed) { + manager.SelectedDocuments = []; + } + + if (manager.SelectedDocuments.indexOf(doc) === -1) { + manager.SelectedDocuments.push(doc); + } } + } - const manager = new Manager; + const manager = new Manager(); - export function SelectDoc(doc: DocumentView, ctrlPressed: boolean): void { - manager.SelectDoc(doc, ctrlPressed) + export function SelectDoc(doc: DocumentView, ctrlPressed: boolean): void { + if (!doc.isMinimized()) { + manager.SelectDoc(doc, ctrlPressed); } - - export function IsSelected(doc: DocumentView): boolean { - return manager.SelectedDocuments.indexOf(doc) !== -1; - } - - export function DeselectAll(except?: Document): void { - let found: DocumentView | undefined = undefined; - if (except) { - for (let i = 0; i < manager.SelectedDocuments.length; i++) { - let view = manager.SelectedDocuments[i]; - if (view.props.Document == except) - found = view; - } - } - manager.SelectedDocuments.length = 0; - if (found) - manager.SelectedDocuments.push(found); - } - - export function SelectedDocuments(): Array { - return manager.SelectedDocuments; + } + + export function IsSelected(doc: DocumentView): boolean { + return manager.SelectedDocuments.indexOf(doc) !== -1; + } + + export function DeselectAll(except?: Document): void { + let found: DocumentView | undefined = undefined; + if (except) { + for (let i = 0; i < manager.SelectedDocuments.length; i++) { + let view = manager.SelectedDocuments[i]; + if (view.props.Document == except) found = view; + } } -} \ No newline at end of file + manager.SelectedDocuments.length = 0; + if (found) manager.SelectedDocuments.push(found); + } + + export function SelectedDocuments(): Array { + return manager.SelectedDocuments; + } +} diff --git a/src/client/views/nodes/DocumentView.scss b/src/client/views/nodes/DocumentView.scss index 85a115f1c..4eda50204 100644 --- a/src/client/views/nodes/DocumentView.scss +++ b/src/client/views/nodes/DocumentView.scss @@ -1,23 +1,39 @@ @import "../global_variables"; + .documentView-node { position: absolute; background: $light-color; //overflow: hidden; + &.minimized { width: 30px; height: 30px; } + .top { background: #232323; height: 20px; cursor: pointer; } + .content { padding: 20px 20px; height: auto; box-sizing: border-box; } + .scroll-box { overflow-y: scroll; height: calc(100% - 20px); } -} + + .minimized-box { + height: 10px; + width: 10px; + border-radius: 2px; + background: #232323 + } + + .minimized-box:hover { + background: #232323 + } +} \ No newline at end of file diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 1195128dc..085307461 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -1,4 +1,13 @@ -import { action, computed, IReactionDisposer, reaction, runInAction } from "mobx"; +import { + action, + computed, + IReactionDisposer, + reaction, + runInAction, + observable +} from "mobx"; +import { library } from "@fortawesome/fontawesome-svg-core"; +import { faSquare } from "@fortawesome/free-solid-svg-icons"; import { observer } from "mobx-react"; import { Document } from "../../../fields/Document"; import { Field, Opt, FieldWaiting } from "../../../fields/Field"; @@ -13,30 +22,35 @@ import { DragManager } from "../../util/DragManager"; import { SelectionManager } from "../../util/SelectionManager"; import { Transform } from "../../util/Transform"; import { CollectionDockingView } from "../collections/CollectionDockingView"; -import { CollectionView, CollectionViewType } from "../collections/CollectionView"; +import { + CollectionView, + CollectionViewType +} from "../collections/CollectionView"; import { ContextMenu } from "../ContextMenu"; import { DocumentContentsView } from "./DocumentContentsView"; import "./DocumentView.scss"; import React = require("react"); import { ServerUtils } from "../../../server/ServerUtil"; +import { DocumentDecorations } from "../DocumentDecorations"; +library.add(faSquare); export interface DocumentViewProps { - ContainingCollectionView: Opt; - Document: Document; - AddDocument?: (doc: Document, allowDuplicates: boolean) => boolean; - RemoveDocument?: (doc: Document) => boolean; - ScreenToLocalTransform: () => Transform; - isTopMost: boolean; - ContentScaling: () => number; - PanelWidth: () => number; - PanelHeight: () => number; - focus: (doc: Document) => void; - SelectOnLoad: boolean; + ContainingCollectionView: Opt; + Document: Document; + AddDocument?: (doc: Document, allowDuplicates: boolean) => boolean; + RemoveDocument?: (doc: Document) => boolean; + ScreenToLocalTransform: () => Transform; + isTopMost: boolean; + ContentScaling: () => number; + PanelWidth: () => number; + PanelHeight: () => number; + focus: (doc: Document) => void; + SelectOnLoad: boolean; } export interface JsxArgs extends DocumentViewProps { - Keys: { [name: string]: Key } - Fields: { [name: string]: Field } + Keys: { [name: string]: Key }; + Fields: { [name: string]: Field }; } /* @@ -55,287 +69,426 @@ Example usage of this function: } */ export function FakeJsxArgs(keys: string[], fields: string[] = []): JsxArgs { - let Keys: { [name: string]: any } = {} - let Fields: { [name: string]: any } = {} - for (const key of keys) { - let fn = () => { } - Object.defineProperty(fn, "name", { value: key + "Key" }) - Keys[key] = fn; - } - for (const field of fields) { - let fn = () => { } - Object.defineProperty(fn, "name", { value: field }) - Fields[field] = fn; - } - let args: JsxArgs = { - Document: function Document() { }, - DocumentView: function DocumentView() { }, - Keys, - Fields - } as any; - return args; + let Keys: { [name: string]: any } = {}; + let Fields: { [name: string]: any } = {}; + for (const key of keys) { + let fn = () => {}; + Object.defineProperty(fn, "name", { value: key + "Key" }); + Keys[key] = fn; + } + for (const field of fields) { + let fn = () => {}; + Object.defineProperty(fn, "name", { value: field }); + Fields[field] = fn; + } + let args: JsxArgs = { + Document: function Document() {}, + DocumentView: function DocumentView() {}, + Keys, + Fields + } as any; + return args; } export interface JsxBindings { - Document: Document; - isSelected: () => boolean; - select: (isCtrlPressed: boolean) => void; - isTopMost: boolean; - SelectOnLoad: boolean; - [prop: string]: any; + Document: Document; + isSelected: () => boolean; + select: (isCtrlPressed: boolean) => void; + isTopMost: boolean; + SelectOnLoad: boolean; + [prop: string]: any; } - - @observer export class DocumentView extends React.Component { - private _mainCont = React.createRef(); - private _downX: number = 0; - private _downY: number = 0; - private _reactionDisposer: Opt; - @computed get active(): boolean { return SelectionManager.IsSelected(this) || !this.props.ContainingCollectionView || this.props.ContainingCollectionView.active(); } - @computed get topMost(): boolean { return !this.props.ContainingCollectionView || this.props.ContainingCollectionView.collectionViewType == CollectionViewType.Docking; } - @computed get layout(): string { return this.props.Document.GetText(KeyStore.Layout, "

    Error loading layout data

    "); } - @computed get layoutKeys(): Key[] { return this.props.Document.GetData(KeyStore.LayoutKeys, ListField, new Array()); } - @computed get layoutFields(): Key[] { return this.props.Document.GetData(KeyStore.LayoutFields, ListField, new Array()); } - screenRect = (): ClientRect | DOMRect => this._mainCont.current ? this._mainCont.current.getBoundingClientRect() : new DOMRect(); - onPointerDown = (e: React.PointerEvent): void => { - this._downX = e.clientX; - this._downY = e.clientY; - if (e.shiftKey && e.buttons === 2) { - if (this.props.isTopMost) { - this.startDragging(e.pageX, e.pageY, e.altKey || e.ctrlKey); - } - else CollectionDockingView.Instance.StartOtherDrag([this.props.Document], e); - e.stopPropagation(); - } else { - if (this.active && !e.isDefaultPrevented()) { - e.stopPropagation(); - document.removeEventListener("pointermove", this.onPointerMove) - document.addEventListener("pointermove", this.onPointerMove); - document.removeEventListener("pointerup", this.onPointerUp) - document.addEventListener("pointerup", this.onPointerUp); - } - } + private _mainCont = React.createRef(); + private _downX: number = 0; + private _downY: number = 0; + + @observable + private minimized: boolean = false; + + private _reactionDisposer: Opt; + @computed get active(): boolean { + return ( + SelectionManager.IsSelected(this) || + !this.props.ContainingCollectionView || + this.props.ContainingCollectionView.active() + ); + } + @computed get topMost(): boolean { + return ( + !this.props.ContainingCollectionView || + this.props.ContainingCollectionView.collectionViewType == + CollectionViewType.Docking + ); + } + @computed get layout(): string { + return this.props.Document.GetText( + KeyStore.Layout, + "

    Error loading layout data

    " + ); + } + @computed get layoutKeys(): Key[] { + return this.props.Document.GetData( + KeyStore.LayoutKeys, + ListField, + new Array() + ); + } + @computed get layoutFields(): Key[] { + return this.props.Document.GetData( + KeyStore.LayoutFields, + ListField, + new Array() + ); + } + screenRect = (): ClientRect | DOMRect => + this._mainCont.current + ? this._mainCont.current.getBoundingClientRect() + : new DOMRect(); + onPointerDown = (e: React.PointerEvent): void => { + this._downX = e.clientX; + this._downY = e.clientY; + if (e.shiftKey && e.buttons === 2) { + if (this.props.isTopMost) { + this.startDragging(e.pageX, e.pageY, e.altKey || e.ctrlKey); + } else + CollectionDockingView.Instance.StartOtherDrag([this.props.Document], e); + e.stopPropagation(); + } else { + if (this.active && !e.isDefaultPrevented()) { + e.stopPropagation(); + document.removeEventListener("pointermove", this.onPointerMove); + document.addEventListener("pointermove", this.onPointerMove); + document.removeEventListener("pointerup", this.onPointerUp); + document.addEventListener("pointerup", this.onPointerUp); + } } + }; - private dropDisposer?: DragManager.DragDropDisposer; + private dropDisposer?: DragManager.DragDropDisposer; - componentDidMount() { - if (this._mainCont.current) { - this.dropDisposer = DragManager.MakeDropTarget(this._mainCont.current, { handlers: { drop: this.drop.bind(this) } }); - } - runInAction(() => DocumentManager.Instance.DocumentViews.push(this)) - this._reactionDisposer = reaction( - () => this.props.ContainingCollectionView && this.props.ContainingCollectionView.SelectedDocs.slice(), - () => { - if (this.props.ContainingCollectionView && this.props.ContainingCollectionView.SelectedDocs.indexOf(this.props.Document.Id) != -1) - SelectionManager.SelectDoc(this, true); - }); + componentDidMount() { + if (this._mainCont.current) { + this.dropDisposer = DragManager.MakeDropTarget(this._mainCont.current, { + handlers: { drop: this.drop.bind(this) } + }); } + runInAction(() => DocumentManager.Instance.DocumentViews.push(this)); + this._reactionDisposer = reaction( + () => + this.props.ContainingCollectionView && + this.props.ContainingCollectionView.SelectedDocs.slice(), + () => { + if ( + this.props.ContainingCollectionView && + this.props.ContainingCollectionView.SelectedDocs.indexOf( + this.props.Document.Id + ) != -1 + ) + SelectionManager.SelectDoc(this, true); + } + ); + } - componentDidUpdate() { - if (this.dropDisposer) { - this.dropDisposer(); - } - if (this._mainCont.current) { - this.dropDisposer = DragManager.MakeDropTarget(this._mainCont.current, { handlers: { drop: this.drop.bind(this) } }); - } + componentDidUpdate() { + if (this.dropDisposer) { + this.dropDisposer(); + } + if (this._mainCont.current) { + this.dropDisposer = DragManager.MakeDropTarget(this._mainCont.current, { + handlers: { drop: this.drop.bind(this) } + }); } + } - componentWillUnmount() { - if (this.dropDisposer) { - this.dropDisposer(); - } - runInAction(() => DocumentManager.Instance.DocumentViews.splice(DocumentManager.Instance.DocumentViews.indexOf(this), 1)) - if (this._reactionDisposer) { - this._reactionDisposer(); - } + componentWillUnmount() { + if (this.dropDisposer) { + this.dropDisposer(); + } + runInAction(() => + DocumentManager.Instance.DocumentViews.splice( + DocumentManager.Instance.DocumentViews.indexOf(this), + 1 + ) + ); + if (this._reactionDisposer) { + this._reactionDisposer(); } + } - startDragging(x: number, y: number, dropAliasOfDraggedDoc: boolean) { - if (this._mainCont.current) { - const [left, top] = this.props.ScreenToLocalTransform().inverse().transformPoint(0, 0); - let dragData = new DragManager.DocumentDragData([this.props.Document]); - dragData.aliasOnDrop = dropAliasOfDraggedDoc; - dragData.xOffset = x - left; - dragData.yOffset = y - top; - dragData.removeDocument = (dropCollectionView: CollectionView) => { - if (this.props.RemoveDocument && this.props.ContainingCollectionView !== dropCollectionView) { - this.props.RemoveDocument(this.props.Document); - } - } - DragManager.StartDocumentDrag([this._mainCont.current], dragData, { - handlers: { - dragComplete: action(() => { }), - }, - hideSource: !dropAliasOfDraggedDoc - }) + startDragging(x: number, y: number, dropAliasOfDraggedDoc: boolean) { + if (this._mainCont.current) { + const [left, top] = this.props + .ScreenToLocalTransform() + .inverse() + .transformPoint(0, 0); + let dragData = new DragManager.DocumentDragData([this.props.Document]); + dragData.aliasOnDrop = dropAliasOfDraggedDoc; + dragData.xOffset = x - left; + dragData.yOffset = y - top; + dragData.removeDocument = (dropCollectionView: CollectionView) => { + if ( + this.props.RemoveDocument && + this.props.ContainingCollectionView !== dropCollectionView + ) { + this.props.RemoveDocument(this.props.Document); } + }; + DragManager.StartDocumentDrag([this._mainCont.current], dragData, { + handlers: { + dragComplete: action(() => {}) + }, + hideSource: !dropAliasOfDraggedDoc + }); } + } - onPointerMove = (e: PointerEvent): void => { - if (e.cancelBubble) { - return; - } - if (Math.abs(this._downX - e.clientX) > 3 || Math.abs(this._downY - e.clientY) > 3) { - document.removeEventListener("pointermove", this.onPointerMove) - document.removeEventListener("pointerup", this.onPointerUp); - if (!this.topMost || e.buttons == 2 || e.altKey) { - this.startDragging(e.x, e.y, e.ctrlKey || e.altKey); - } - } - e.stopPropagation(); - e.preventDefault(); + onPointerMove = (e: PointerEvent): void => { + if (e.cancelBubble) { + return; } - onPointerUp = (e: PointerEvent): void => { - document.removeEventListener("pointermove", this.onPointerMove) - document.removeEventListener("pointerup", this.onPointerUp) - e.stopPropagation(); - if (Math.abs(e.clientX - this._downX) < 4 && Math.abs(e.clientY - this._downY) < 4) { - SelectionManager.SelectDoc(this, e.ctrlKey); - } + if ( + Math.abs(this._downX - e.clientX) > 3 || + Math.abs(this._downY - e.clientY) > 3 + ) { + document.removeEventListener("pointermove", this.onPointerMove); + document.removeEventListener("pointerup", this.onPointerUp); + if (!this.topMost || e.buttons == 2 || e.altKey) { + this.startDragging(e.x, e.y, e.ctrlKey || e.altKey); + } } - stopPropogation = (e: React.SyntheticEvent) => { - e.stopPropagation(); + e.stopPropagation(); + e.preventDefault(); + }; + onPointerUp = (e: PointerEvent): void => { + document.removeEventListener("pointermove", this.onPointerMove); + document.removeEventListener("pointerup", this.onPointerUp); + e.stopPropagation(); + if ( + Math.abs(e.clientX - this._downX) < 4 && + Math.abs(e.clientY - this._downY) < 4 + ) { + SelectionManager.SelectDoc(this, e.ctrlKey); } + }; + stopPropogation = (e: React.SyntheticEvent) => { + e.stopPropagation(); + }; - deleteClicked = (): void => { - if (this.props.RemoveDocument) { - this.props.RemoveDocument(this.props.Document); - } + deleteClicked = (): void => { + if (this.props.RemoveDocument) { + this.props.RemoveDocument(this.props.Document); } + }; - fieldsClicked = (e: React.MouseEvent): void => { - if (this.props.AddDocument) { - this.props.AddDocument(Documents.KVPDocument(this.props.Document, { width: 300, height: 300 }), false); - } - } - fullScreenClicked = (e: React.MouseEvent): void => { - CollectionDockingView.Instance.OpenFullScreen(this.props.Document); - ContextMenu.Instance.clearItems(); - ContextMenu.Instance.addItem({ description: "Close Full Screen", event: this.closeFullScreenClicked }); - ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15) + fieldsClicked = (e: React.MouseEvent): void => { + if (this.props.AddDocument) { + this.props.AddDocument( + Documents.KVPDocument(this.props.Document, { width: 300, height: 300 }), + false + ); } + }; + fullScreenClicked = (e: React.MouseEvent): void => { + CollectionDockingView.Instance.OpenFullScreen(this.props.Document); + ContextMenu.Instance.clearItems(); + ContextMenu.Instance.addItem({ + description: "Close Full Screen", + event: this.closeFullScreenClicked + }); + ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); + }; - closeFullScreenClicked = (e: React.MouseEvent): void => { - CollectionDockingView.Instance.CloseFullScreen(); - ContextMenu.Instance.clearItems(); - ContextMenu.Instance.addItem({ description: "Full Screen", event: this.fullScreenClicked }) - ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15) - } + closeFullScreenClicked = (e: React.MouseEvent): void => { + CollectionDockingView.Instance.CloseFullScreen(); + ContextMenu.Instance.clearItems(); + ContextMenu.Instance.addItem({ + description: "Full Screen", + event: this.fullScreenClicked + }); + ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); + }; - @action - drop = (e: Event, de: DragManager.DropEvent) => { - if (de.data instanceof DragManager.LinkDragData) { - let sourceDoc: Document = de.data.linkSourceDocumentView.props.Document; - let destDoc: Document = this.props.Document; - if (this.props.isTopMost) { - return; - } - let linkDoc: Document = new Document(); + @action + minimize = (e: React.MouseEvent): void => { + this.minimized = true; + SelectionManager.DeselectAll(); + }; - destDoc.GetTAsync(KeyStore.Prototype, Document).then((protoDest) => - sourceDoc.GetTAsync(KeyStore.Prototype, Document).then((protoSrc) => runInAction(() => { - linkDoc.Set(KeyStore.Title, new TextField("New Link")); - linkDoc.Set(KeyStore.LinkDescription, new TextField("")); - linkDoc.Set(KeyStore.LinkTags, new TextField("Default")); + @action + drop = (e: Event, de: DragManager.DropEvent) => { + if (de.data instanceof DragManager.LinkDragData) { + let sourceDoc: Document = de.data.linkSourceDocumentView.props.Document; + let destDoc: Document = this.props.Document; + if (this.props.isTopMost) { + return; + } + let linkDoc: Document = new Document(); - let dstTarg = (protoDest ? protoDest : destDoc); - let srcTarg = (protoSrc ? protoSrc : sourceDoc); - linkDoc.Set(KeyStore.LinkedToDocs, dstTarg); - linkDoc.Set(KeyStore.LinkedFromDocs, srcTarg); - dstTarg.GetOrCreateAsync(KeyStore.LinkedFromDocs, ListField, field => { (field as ListField).Data.push(linkDoc) }) - srcTarg.GetOrCreateAsync(KeyStore.LinkedToDocs, ListField, field => { (field as ListField).Data.push(linkDoc) }) - })) - ) - e.stopPropagation(); - } - } + destDoc.GetTAsync(KeyStore.Prototype, Document).then(protoDest => + sourceDoc.GetTAsync(KeyStore.Prototype, Document).then(protoSrc => + runInAction(() => { + linkDoc.Set(KeyStore.Title, new TextField("New Link")); + linkDoc.Set(KeyStore.LinkDescription, new TextField("")); + linkDoc.Set(KeyStore.LinkTags, new TextField("Default")); - onDrop = (e: React.DragEvent) => { - if (e.isDefaultPrevented()) { - return; - } - let text = e.dataTransfer.getData("text/plain"); - if (text && text.startsWith(" { + (field as ListField).Data.push(linkDoc); + } + ); + srcTarg.GetOrCreateAsync( + KeyStore.LinkedToDocs, + ListField, + field => { + (field as ListField).Data.push(linkDoc); + } + ); + }) + ) + ); + e.stopPropagation(); } + }; - @action - onContextMenu = (e: React.MouseEvent): void => { - e.stopPropagation(); - let moved = Math.abs(this._downX - e.clientX) > 3 || Math.abs(this._downY - e.clientY) > 3; - if (moved || e.isDefaultPrevented()) { - e.preventDefault() - return; - } - e.preventDefault() + onDrop = (e: React.DragEvent) => { + if (e.isDefaultPrevented()) { + return; + } + let text = e.dataTransfer.getData("text/plain"); + if (text && text.startsWith(" this.props.focus(this.props.Document) }) - ContextMenu.Instance.addItem({ description: "Open Right", event: () => CollectionDockingView.Instance.AddRightSplit(this.props.Document) }) - ContextMenu.Instance.addItem({ - description: "Copy URL", - event: () => { - Utils.CopyText(ServerUtils.prepend("/doc/" + this.props.Document.Id)); - } - }); - ContextMenu.Instance.addItem({ - description: "Copy ID", - event: () => { - Utils.CopyText(this.props.Document.Id); - } - }); - //ContextMenu.Instance.addItem({ description: "Docking", event: () => this.props.Document.SetNumber(KeyStore.ViewType, CollectionViewType.Docking) }) - ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15) - if (!this.topMost) { - // DocumentViews should stop propagation of this event - e.stopPropagation(); - } + @action + onContextMenu = (e: React.MouseEvent): void => { + e.stopPropagation(); + let moved = + Math.abs(this._downX - e.clientX) > 3 || + Math.abs(this._downY - e.clientY) > 3; + if (moved || e.isDefaultPrevented()) { + e.preventDefault(); + return; + } + e.preventDefault(); - ContextMenu.Instance.addItem({ description: "Delete", event: this.deleteClicked }) - ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15) - SelectionManager.SelectDoc(this, e.ctrlKey); + //for testing purposes + ContextMenu.Instance.addItem({ + description: "Minimize", + event: this.minimize + }); + ContextMenu.Instance.addItem({ + description: "Full Screen", + event: this.fullScreenClicked + }); + ContextMenu.Instance.addItem({ + description: "Fields", + event: this.fieldsClicked + }); + ContextMenu.Instance.addItem({ + description: "Center", + event: () => this.props.focus(this.props.Document) + }); + ContextMenu.Instance.addItem({ + description: "Open Right", + event: () => + CollectionDockingView.Instance.AddRightSplit(this.props.Document) + }); + ContextMenu.Instance.addItem({ + description: "Copy URL", + event: () => { + Utils.CopyText(ServerUtils.prepend("/doc/" + this.props.Document.Id)); + } + }); + ContextMenu.Instance.addItem({ + description: "Copy ID", + event: () => { + Utils.CopyText(this.props.Document.Id); + } + }); + //ContextMenu.Instance.addItem({ description: "Docking", event: () => this.props.Document.SetNumber(KeyStore.ViewType, CollectionViewType.Docking) }) + ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); + if (!this.topMost) { + // DocumentViews should stop propagation of this event + e.stopPropagation(); } + ContextMenu.Instance.addItem({ + description: "Delete", + event: this.deleteClicked + }); + ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); + SelectionManager.SelectDoc(this, e.ctrlKey); + }; - isSelected = () => { - return SelectionManager.IsSelected(this); - } + isMinimized = () => { + return this.minimized; + }; - select = (ctrlPressed: boolean) => { - SelectionManager.SelectDoc(this, ctrlPressed) - } + isSelected = () => { + return SelectionManager.IsSelected(this); + }; - render() { - if (!this.props.Document) { - return (null); - } - var scaling = this.props.ContentScaling(); - var nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 0); - var nativeHeight = this.props.Document.GetNumber(KeyStore.NativeHeight, 0); - var backgroundcolor = this.props.Document.GetText(KeyStore.BackgroundColor, ""); - return ( -
    0 ? nativeWidth.toString() + "px" : "100%", - height: nativeHeight > 0 ? nativeHeight.toString() + "px" : "100%", - transformOrigin: "left top", - transform: `scale(${scaling} , ${scaling})` - }} - onDrop={this.onDrop} - onContextMenu={this.onContextMenu} - onPointerDown={this.onPointerDown} > - -
    - ) + select = (ctrlPressed: boolean) => { + SelectionManager.SelectDoc(this, ctrlPressed); + }; + + render() { + if (!this.props.Document) { + return null; } -} \ No newline at end of file + if (this.minimized) { + return ( + // +
    + ); + } else { + var scaling = this.props.ContentScaling(); + var nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 0); + var nativeHeight = this.props.Document.GetNumber( + KeyStore.NativeHeight, + 0 + ); + var backgroundcolor = this.props.Document.GetText( + KeyStore.BackgroundColor, + "" + ); + return ( +
    0 ? nativeWidth.toString() + "px" : "100%", + height: nativeHeight > 0 ? nativeHeight.toString() + "px" : "100%", + transformOrigin: "left top", + transform: `scale(${scaling} , ${scaling})` + }} + onDrop={this.onDrop} + onContextMenu={this.onContextMenu} + onPointerDown={this.onPointerDown} + > + +
    + ); + } + } +} diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 512ad7d70..0c0efc437 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -3,28 +3,25 @@ import { baseKeymap } from "prosemirror-commands"; import { history, redo, undo } from "prosemirror-history"; import { keymap } from "prosemirror-keymap"; import { schema } from "../../util/RichTextSchema"; -import { EditorState, Transaction, } from "prosemirror-state"; +import { EditorState, Transaction } from "prosemirror-state"; import { EditorView } from "prosemirror-view"; import { Opt, FieldWaiting } from "../../../fields/Field"; import "./FormattedTextBox.scss"; -import React = require("react") +import React = require("react"); import { RichTextField } from "../../../fields/RichTextField"; import { FieldViewProps, FieldView } from "./FieldView"; -import { Plugin } from 'prosemirror-state' -import { Decoration, DecorationSet } from 'prosemirror-view' -import { TooltipTextMenu } from "../../util/TooltipTextMenu" +import { Plugin } from "prosemirror-state"; +import { Decoration, DecorationSet } from "prosemirror-view"; +import { TooltipTextMenu } from "../../util/TooltipTextMenu"; import { ContextMenu } from "../../views/ContextMenu"; import { inpRules } from "../../util/RichTextRules"; const { buildMenuItems } = require("prosemirror-example-setup"); const { menuBar } = require("prosemirror-menu"); - - - // FormattedTextBox: Displays an editable plain text node that maps to a specified Key of a Document // // HTML Markup: Key} />"); // and the node's binding to the specified document KEYNAME as: @@ -33,145 +30,161 @@ const { menuBar } = require("prosemirror-menu"); // 'fieldKey' property to the Key stored in LayoutKeys // and 'doc' property to the document that is being rendered // -// When rendered() by React, this extracts the TextController from the Document stored at the -// specified Key and assigns it to an HTML input node. When changes are made to this node, +// When rendered() by React, this extracts the TextController from the Document stored at the +// specified Key and assigns it to an HTML input node. When changes are made to this node, // this will edit the document and assign the new value to that field. //] export class FormattedTextBox extends React.Component { - - public static LayoutString(fieldStr: string = "DataKey") { return FieldView.LayoutString(FormattedTextBox, fieldStr) } - private _ref: React.RefObject; - private _editorView: Opt; - private _reactionDisposer: Opt; - - constructor(props: FieldViewProps) { - super(props); - - this._ref = React.createRef(); - this.onChange = this.onChange.bind(this); + public static LayoutString(fieldStr: string = "DataKey") { + return FieldView.LayoutString(FormattedTextBox, fieldStr); + } + private _ref: React.RefObject; + private _editorView: Opt; + private _reactionDisposer: Opt; + + constructor(props: FieldViewProps) { + super(props); + + this._ref = React.createRef(); + this.onChange = this.onChange.bind(this); + } + + dispatchTransaction = (tx: Transaction) => { + if (this._editorView) { + const state = this._editorView.state.apply(tx); + this._editorView.updateState(state); + const { doc, fieldKey } = this.props; + doc.SetDataOnPrototype( + fieldKey, + JSON.stringify(state.toJSON()), + RichTextField + ); + // doc.SetData(fieldKey, JSON.stringify(state.toJSON()), RichTextField); } - - dispatchTransaction = (tx: Transaction) => { - if (this._editorView) { - const state = this._editorView.state.apply(tx); - this._editorView.updateState(state); - const { doc, fieldKey } = this.props; - doc.SetDataOnPrototype(fieldKey, JSON.stringify(state.toJSON()), RichTextField); - // doc.SetData(fieldKey, JSON.stringify(state.toJSON()), RichTextField); - } + }; + + componentDidMount() { + let state: EditorState; + const config = { + schema, + inpRules, //these currently don't do anything, but could eventually be helpful + plugins: [ + history(), + keymap({ "Mod-z": undo, "Mod-y": redo }), + keymap(baseKeymap), + this.tooltipMenuPlugin() + ] + }; + + let field = this.props.doc.GetT(this.props.fieldKey, RichTextField); + if (field && field != FieldWaiting && field.Data) { + state = EditorState.fromJSON(config, JSON.parse(field.Data)); + } else { + state = EditorState.create(config); } - - componentDidMount() { - let state: EditorState; - const config = { - schema, - inpRules, //these currently don't do anything, but could eventually be helpful - plugins: [ - history(), - keymap({ "Mod-z": undo, "Mod-y": redo }), - keymap(baseKeymap), - this.tooltipMenuPlugin() - ] - }; - - let field = this.props.doc.GetT(this.props.fieldKey, RichTextField); - if (field && field != FieldWaiting && field.Data) { - state = EditorState.fromJSON(config, JSON.parse(field.Data)); - } else { - state = EditorState.create(config); - } - if (this._ref.current) { - this._editorView = new EditorView(this._ref.current, { - state, - dispatchTransaction: this.dispatchTransaction - }); - } - - this._reactionDisposer = reaction(() => { - const field = this.props.doc.GetT(this.props.fieldKey, RichTextField); - return field && field != FieldWaiting ? field.Data : undefined; - }, (field) => { - if (field && this._editorView) { - this._editorView.updateState(EditorState.fromJSON(config, JSON.parse(field))); - } - }) - if (this.props.selectOnLoad) { - this.props.select(); - this._editorView!.focus(); - } + if (this._ref.current) { + this._editorView = new EditorView(this._ref.current, { + state, + dispatchTransaction: this.dispatchTransaction + }); } - componentWillUnmount() { - if (this._editorView) { - this._editorView.destroy(); + this._reactionDisposer = reaction( + () => { + const field = this.props.doc.GetT(this.props.fieldKey, RichTextField); + return field && field != FieldWaiting ? field.Data : undefined; + }, + field => { + if (field && this._editorView) { + this._editorView.updateState( + EditorState.fromJSON(config, JSON.parse(field)) + ); } - if (this._reactionDisposer) { - this._reactionDisposer(); - } - } - - shouldComponentUpdate() { - return false; - } - - @action - onChange(e: React.ChangeEvent) { - const { fieldKey, doc } = this.props; - doc.SetOnPrototype(fieldKey, new RichTextField(e.target.value)) - // doc.SetData(fieldKey, e.target.value, RichTextField); - } - onPointerDown = (e: React.PointerEvent): void => { - if (e.buttons === 1 && this.props.isSelected() && !e.altKey) { - e.stopPropagation(); - } - } - - //REPLACE THIS WITH CAPABILITIES SPECIFIC TO THIS TYPE OF NODE - textCapability = (e: React.MouseEvent): void => { - } - - specificContextMenu = (e: React.MouseEvent): void => { - ContextMenu.Instance.addItem({ description: "Text Capability", event: this.textCapability }); - // ContextMenu.Instance.addItem({ - // description: "Submenu", - // items: [ - // { - // description: "item 1", event: - // }, - // { - // description: "item 2", event: - // } - // ] - // }) - // e.stopPropagation() - - } - - onPointerWheel = (e: React.WheelEvent): void => { - e.stopPropagation(); + } + ); + if (this.props.selectOnLoad) { + this.props.select(); + this._editorView!.focus(); } + } - tooltipMenuPlugin() { - return new Plugin({ - view(_editorView) { - return new TooltipTextMenu(_editorView) - } - }) + componentWillUnmount() { + if (this._editorView) { + this._editorView.destroy(); } - onKeyPress(e: React.KeyboardEvent) { - e.stopPropagation(); - // stop propagation doesn't seem to stop propagation of native keyboard events. - // so we set a flag on the native event that marks that the event's been handled. - // (e.nativeEvent as any).DASHFormattedTextBoxHandled = true; + if (this._reactionDisposer) { + this._reactionDisposer(); } - render() { - return (
    ) + } + + shouldComponentUpdate() { + return false; + } + + @action + onChange(e: React.ChangeEvent) { + const { fieldKey, doc } = this.props; + doc.SetOnPrototype(fieldKey, new RichTextField(e.target.value)); + // doc.SetData(fieldKey, e.target.value, RichTextField); + } + onPointerDown = (e: React.PointerEvent): void => { + if (e.buttons === 1 && this.props.isSelected() && !e.altKey) { + e.stopPropagation(); } -} \ No newline at end of file + }; + + //REPLACE THIS WITH CAPABILITIES SPECIFIC TO THIS TYPE OF NODE + textCapability = (e: React.MouseEvent): void => {}; + + specificContextMenu = (e: React.MouseEvent): void => { + ContextMenu.Instance.addItem({ + description: "Text Capability", + event: this.textCapability + }); + + // ContextMenu.Instance.addItem({ + // description: "Submenu", + // items: [ + // { + // description: "item 1", event: + // }, + // { + // description: "item 2", event: + // } + // ] + // }) + // e.stopPropagation() + }; + + onPointerWheel = (e: React.WheelEvent): void => { + e.stopPropagation(); + }; + + tooltipMenuPlugin() { + return new Plugin({ + view(_editorView) { + return new TooltipTextMenu(_editorView); + } + }); + } + onKeyPress(e: React.KeyboardEvent) { + e.stopPropagation(); + // stop propagation doesn't seem to stop propagation of native keyboard events. + // so we set a flag on the native event that marks that the event's been handled. + // (e.nativeEvent as any).DASHFormattedTextBoxHandled = true; + } + render() { + return ( +
    + ); + } +} -- cgit v1.2.3-70-g09d2 From 7fdf7396a8bdb2e4f8c3b27ca99a36727d85adae Mon Sep 17 00:00:00 2001 From: Monika Hedman Date: Mon, 1 Apr 2019 23:07:04 -0400 Subject: minimize sorta works??? --- src/client/util/DragManager.ts | 485 +++++++++++++++++------------- src/client/views/DocumentDecorations.scss | 9 +- src/client/views/nodes/DocumentView.scss | 6 +- src/client/views/nodes/DocumentView.tsx | 32 +- src/client/views/nodes/Sticky.tsx | 138 ++++----- 5 files changed, 375 insertions(+), 295 deletions(-) (limited to 'src') diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index 9ffe964ef..ee0b5333c 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -1,251 +1,312 @@ import { DocumentDecorations } from "../views/DocumentDecorations"; import { CollectionDockingView } from "../views/collections/CollectionDockingView"; -import { Document } from "../../fields/Document" +import { Document } from "../../fields/Document"; import { action } from "mobx"; import { ImageField } from "../../fields/ImageField"; import { KeyStore } from "../../fields/KeyStore"; import { CollectionView } from "../views/collections/CollectionView"; import { DocumentView } from "../views/nodes/DocumentView"; -export function setupDrag(_reference: React.RefObject, docFunc: () => Document, removeFunc: (containingCollection: CollectionView) => void = () => { }) { - let onRowMove = action((e: PointerEvent): void => { - e.stopPropagation(); - e.preventDefault(); +export function setupDrag( + _reference: React.RefObject, + docFunc: () => Document, + removeFunc: (containingCollection: CollectionView) => void = () => {} +) { + let onRowMove = action( + (e: PointerEvent): void => { + e.stopPropagation(); + e.preventDefault(); - document.removeEventListener("pointermove", onRowMove); - document.removeEventListener('pointerup', onRowUp); - var dragData = new DragManager.DocumentDragData([docFunc()]); - dragData.removeDocument = removeFunc; - DragManager.StartDocumentDrag([_reference.current!], dragData); - }); - let onRowUp = action((e: PointerEvent): void => { - document.removeEventListener("pointermove", onRowMove); - document.removeEventListener('pointerup', onRowUp); - }); - let onItemDown = (e: React.PointerEvent) => { - // if (this.props.isSelected() || this.props.isTopMost) { - if (e.button == 0) { - e.stopPropagation(); - if (e.shiftKey) { - CollectionDockingView.Instance.StartOtherDrag([docFunc()], e); - } else { - document.addEventListener("pointermove", onRowMove); - document.addEventListener('pointerup', onRowUp); - } - } - //} + document.removeEventListener("pointermove", onRowMove); + document.removeEventListener("pointerup", onRowUp); + var dragData = new DragManager.DocumentDragData([docFunc()]); + dragData.removeDocument = removeFunc; + DragManager.StartDocumentDrag([_reference.current!], dragData); + } + ); + let onRowUp = action( + (e: PointerEvent): void => { + document.removeEventListener("pointermove", onRowMove); + document.removeEventListener("pointerup", onRowUp); + } + ); + let onItemDown = (e: React.PointerEvent) => { + // if (this.props.isSelected() || this.props.isTopMost) { + if (e.button == 0) { + e.stopPropagation(); + if (e.shiftKey) { + CollectionDockingView.Instance.StartOtherDrag([docFunc()], e); + } else { + document.addEventListener("pointermove", onRowMove); + document.addEventListener("pointerup", onRowUp); + } } - return onItemDown; + //} + }; + return onItemDown; } export namespace DragManager { - export function Root() { - const root = document.getElementById("root"); - if (!root) { - throw new Error("No root element found"); - } - return root; + export function Root() { + const root = document.getElementById("root"); + if (!root) { + throw new Error("No root element found"); } + return root; + } - let dragDiv: HTMLDivElement; + let dragDiv: HTMLDivElement; - export enum DragButtons { - Left = 1, Right = 2, Both = Left | Right - } + export enum DragButtons { + Left = 1, + Right = 2, + Both = Left | Right + } - interface DragOptions { - handlers: DragHandlers; + interface DragOptions { + handlers: DragHandlers; - hideSource: boolean | (() => boolean); - } + hideSource: boolean | (() => boolean); + } - export interface DragDropDisposer { - (): void; - } + export interface DragDropDisposer { + (): void; + } - export class DragCompleteEvent { - } + export class DragCompleteEvent {} - export interface DragHandlers { - dragComplete: (e: DragCompleteEvent) => void; - } + export interface DragHandlers { + dragComplete: (e: DragCompleteEvent) => void; + } - export interface DropOptions { - handlers: DropHandlers; - } - export class DropEvent { - constructor(readonly x: number, readonly y: number, readonly data: { [id: string]: any }) { } - } + export interface DropOptions { + handlers: DropHandlers; + } + export class DropEvent { + constructor( + readonly x: number, + readonly y: number, + readonly data: { [id: string]: any } + ) {} + } + export interface DropHandlers { + drop: (e: Event, de: DropEvent) => void; + } + export function MakeDropTarget( + element: HTMLElement, + options: DropOptions + ): DragDropDisposer { + if ("canDrop" in element.dataset) { + throw new Error( + "Element is already droppable, can't make it droppable again" + ); + } + element.dataset["canDrop"] = "true"; + const handler = (e: Event) => { + const ce = e as CustomEvent; + options.handlers.drop(e, ce.detail); + }; + element.addEventListener("dashOnDrop", handler); + return () => { + element.removeEventListener("dashOnDrop", handler); + delete element.dataset["canDrop"]; + }; + } - export interface DropHandlers { - drop: (e: Event, de: DropEvent) => void; + export class DocumentDragData { + constructor(dragDoc: Document[]) { + this.draggedDocuments = dragDoc; + this.droppedDocuments = dragDoc; } + draggedDocuments: Document[]; + droppedDocuments: Document[]; + xOffset?: number; + yOffset?: number; + aliasOnDrop?: boolean; + removeDocument?: (collectionDrop: CollectionView) => void; + [id: string]: any; + } + export function StartDocumentDrag( + eles: HTMLElement[], + dragData: DocumentDragData, + options?: DragOptions + ) { + StartDrag( + eles, + dragData, + options, + (dropData: { [id: string]: any }) => + (dropData.droppedDocuments = dragData.aliasOnDrop + ? dragData.draggedDocuments.map(d => d.CreateAlias()) + : dragData.draggedDocuments) + ); + } - export function MakeDropTarget(element: HTMLElement, options: DropOptions): DragDropDisposer { - if ("canDrop" in element.dataset) { - throw new Error("Element is already droppable, can't make it droppable again"); - } - element.dataset["canDrop"] = "true"; - const handler = (e: Event) => { - const ce = e as CustomEvent; - options.handlers.drop(e, ce.detail); - }; - element.addEventListener("dashOnDrop", handler); - return () => { - element.removeEventListener("dashOnDrop", handler); - delete element.dataset["canDrop"] - }; + export class LinkDragData { + constructor(linkSourceDoc: DocumentView) { + this.linkSourceDocumentView = linkSourceDoc; } - - export class DocumentDragData { - constructor(dragDoc: Document[]) { - this.draggedDocuments = dragDoc; - this.droppedDocuments = dragDoc; - } - draggedDocuments: Document[]; - droppedDocuments: Document[]; - xOffset?: number; - yOffset?: number; - aliasOnDrop?: boolean; - removeDocument?: (collectionDrop: CollectionView) => void; - [id: string]: any; + linkSourceDocumentView: DocumentView; + [id: string]: any; + } + export function StartLinkDrag( + ele: HTMLElement, + dragData: LinkDragData, + options?: DragOptions + ) { + StartDrag([ele], dragData, options); + } + function StartDrag( + eles: HTMLElement[], + dragData: { [id: string]: any }, + options?: DragOptions, + finishDrag?: (dropData: { [id: string]: any }) => void + ) { + if (!dragDiv) { + dragDiv = document.createElement("div"); + dragDiv.className = "dragManager-dragDiv"; + DragManager.Root().appendChild(dragDiv); } - export function StartDocumentDrag(eles: HTMLElement[], dragData: DocumentDragData, options?: DragOptions) { - StartDrag(eles, dragData, options, (dropData: { [id: string]: any }) => dropData.droppedDocuments = dragData.aliasOnDrop ? dragData.draggedDocuments.map(d => d.CreateAlias()) : dragData.draggedDocuments); - } + let scaleXs: number[] = []; + let scaleYs: number[] = []; + let xs: number[] = []; + let ys: number[] = []; - export class LinkDragData { - constructor(linkSourceDoc: DocumentView) { - this.linkSourceDocumentView = linkSourceDoc; - } - linkSourceDocumentView: DocumentView; - [id: string]: any; - } - export function StartLinkDrag(ele: HTMLElement, dragData: LinkDragData, options?: DragOptions) { - StartDrag([ele], dragData, options); - } - function StartDrag(eles: HTMLElement[], dragData: { [id: string]: any }, options?: DragOptions, finishDrag?: (dropData: { [id: string]: any }) => void) { - if (!dragDiv) { - dragDiv = document.createElement("div"); - dragDiv.className = "dragManager-dragDiv" - DragManager.Root().appendChild(dragDiv); + const docs: Document[] = + dragData instanceof DocumentDragData ? dragData.draggedDocuments : []; + let dragElements = eles.map(ele => { + const w = ele.offsetWidth, + h = ele.offsetHeight; + const rect = ele.getBoundingClientRect(); + const scaleX = rect.width / w, + scaleY = rect.height / h; + let x = rect.left, + y = rect.top; + xs.push(x); + ys.push(y); + scaleXs.push(scaleX); + scaleYs.push(scaleY); + let dragElement = ele.cloneNode(true) as HTMLElement; + dragElement.style.opacity = "0.7"; + console.log(dragElement); + dragElement.style.position = "absolute"; + dragElement.style.bottom = ""; + dragElement.style.left = ""; + dragElement.style.transformOrigin = "0 0"; + dragElement.style.zIndex = "1000"; + dragElement.style.transform = `translate(${x}px, ${y}px) scale(${scaleX}, ${scaleY})`; + dragElement.style.width = `${rect.width / scaleX}px`; + dragElement.style.height = `${rect.height / scaleY}px`; + + // bcz: PDFs don't show up if you clone them because they contain a canvas. + // however, PDF's have a thumbnail field that contains an image of their canvas. + // So we replace the pdf's canvas with the image thumbnail + if (docs.length) { + var pdfBox = dragElement.getElementsByClassName( + "pdfBox-cont" + )[0] as HTMLElement; + let thumbnail = docs[0].GetT(KeyStore.Thumbnail, ImageField); + if (pdfBox && pdfBox.childElementCount && thumbnail) { + let img = new Image(); + img!.src = thumbnail.toString(); + img!.style.position = "absolute"; + img!.style.width = `${rect.width / scaleX}px`; + img!.style.height = `${rect.height / scaleY}px`; + pdfBox.replaceChild(img!, pdfBox.children[0]); } + } - let scaleXs: number[] = []; - let scaleYs: number[] = []; - let xs: number[] = []; - let ys: number[] = []; - - const docs: Document[] = dragData instanceof DocumentDragData ? dragData.draggedDocuments : []; - let dragElements = eles.map(ele => { - const w = ele.offsetWidth, h = ele.offsetHeight; - const rect = ele.getBoundingClientRect(); - const scaleX = rect.width / w, scaleY = rect.height / h; - let x = rect.left, y = rect.top; - xs.push(x); ys.push(y); - scaleXs.push(scaleX); scaleYs.push(scaleY); - let dragElement = ele.cloneNode(true) as HTMLElement; - dragElement.style.opacity = "0.7"; - dragElement.style.position = "absolute"; - dragElement.style.bottom = ""; - dragElement.style.left = ""; - dragElement.style.transformOrigin = "0 0"; - dragElement.style.zIndex = "1000"; - dragElement.style.transform = `translate(${x}px, ${y}px) scale(${scaleX}, ${scaleY})`; - dragElement.style.width = `${rect.width / scaleX}px`; - dragElement.style.height = `${rect.height / scaleY}px`; - - // bcz: PDFs don't show up if you clone them because they contain a canvas. - // however, PDF's have a thumbnail field that contains an image of their canvas. - // So we replace the pdf's canvas with the image thumbnail - if (docs.length) { - var pdfBox = dragElement.getElementsByClassName("pdfBox-cont")[0] as HTMLElement; - let thumbnail = docs[0].GetT(KeyStore.Thumbnail, ImageField); - if (pdfBox && pdfBox.childElementCount && thumbnail) { - let img = new Image(); - img!.src = thumbnail.toString(); - img!.style.position = "absolute"; - img!.style.width = `${rect.width / scaleX}px`; - img!.style.height = `${rect.height / scaleY}px`; - pdfBox.replaceChild(img!, pdfBox.children[0]) - } - } - - dragDiv.appendChild(dragElement); - return dragElement; - }); + dragDiv.appendChild(dragElement); + return dragElement; + }); - let hideSource = false; - if (options) { - if (typeof options.hideSource === "boolean") { - hideSource = options.hideSource; - } else { - hideSource = options.hideSource(); - } - } - eles.map(ele => ele.hidden = hideSource); - - const moveHandler = (e: PointerEvent) => { - e.stopPropagation(); - e.preventDefault(); - if (dragData instanceof DocumentDragData) - dragData.aliasOnDrop = e.ctrlKey || e.altKey; - if (e.shiftKey) { - abortDrag(); - CollectionDockingView.Instance.StartOtherDrag(docs, { pageX: e.pageX, pageY: e.pageY, preventDefault: () => { }, button: 0 }); - } - dragElements.map((dragElement, i) => dragElement.style.transform = `translate(${xs[i] += e.movementX}px, ${ys[i] += e.movementY}px) scale(${scaleXs[i]}, ${scaleYs[i]})`); - }; - - const abortDrag = () => { - document.removeEventListener("pointermove", moveHandler, true); - document.removeEventListener("pointerup", upHandler); - dragElements.map(dragElement => dragDiv.removeChild(dragElement)); - eles.map(ele => ele.hidden = false); - } - const upHandler = (e: PointerEvent) => { - abortDrag(); - FinishDrag(eles, e, dragData, options, finishDrag); - }; - document.addEventListener("pointermove", moveHandler, true); - document.addEventListener("pointerup", upHandler); + let hideSource = false; + if (options) { + if (typeof options.hideSource === "boolean") { + hideSource = options.hideSource; + } else { + hideSource = options.hideSource(); + } } + eles.map(ele => (ele.hidden = hideSource)); - function FinishDrag(dragEles: HTMLElement[], e: PointerEvent, dragData: { [index: string]: any }, options?: DragOptions, finishDrag?: (dragData: { [index: string]: any }) => void) { - let removed = dragEles.map(dragEle => { - let parent = dragEle.parentElement; - if (parent) - parent.removeChild(dragEle); - return [dragEle, parent]; - }); - const target = document.elementFromPoint(e.x, e.y); - removed.map(r => { - let dragEle: HTMLElement = r[0]!; - let parent: HTMLElement | null = r[1]; - if (parent) - parent.appendChild(dragEle); + const moveHandler = (e: PointerEvent) => { + e.stopPropagation(); + e.preventDefault(); + if (dragData instanceof DocumentDragData) + dragData.aliasOnDrop = e.ctrlKey || e.altKey; + if (e.shiftKey) { + abortDrag(); + CollectionDockingView.Instance.StartOtherDrag(docs, { + pageX: e.pageX, + pageY: e.pageY, + preventDefault: () => {}, + button: 0 }); - if (target) { - if (finishDrag) - finishDrag(dragData); - - target.dispatchEvent(new CustomEvent("dashOnDrop", { - bubbles: true, - detail: { - x: e.x, - y: e.y, - data: dragData - } - })); - - if (options) { - options.handlers.dragComplete({}); - } - } - DocumentDecorations.Instance.Hidden = false; + } + dragElements.map( + (dragElement, i) => + (dragElement.style.transform = `translate(${(xs[i] += + e.movementX)}px, ${(ys[i] += e.movementY)}px) scale(${ + scaleXs[i] + }, ${scaleYs[i]})`) + ); + }; + + const abortDrag = () => { + document.removeEventListener("pointermove", moveHandler, true); + document.removeEventListener("pointerup", upHandler); + dragElements.map(dragElement => dragDiv.removeChild(dragElement)); + eles.map(ele => (ele.hidden = false)); + }; + const upHandler = (e: PointerEvent) => { + abortDrag(); + FinishDrag(eles, e, dragData, options, finishDrag); + }; + document.addEventListener("pointermove", moveHandler, true); + document.addEventListener("pointerup", upHandler); + } + + function FinishDrag( + dragEles: HTMLElement[], + e: PointerEvent, + dragData: { [index: string]: any }, + options?: DragOptions, + finishDrag?: (dragData: { [index: string]: any }) => void + ) { + let removed = dragEles.map(dragEle => { + let parent = dragEle.parentElement; + if (parent) parent.removeChild(dragEle); + return [dragEle, parent]; + }); + const target = document.elementFromPoint(e.x, e.y); + removed.map(r => { + let dragEle: HTMLElement = r[0]!; + let parent: HTMLElement | null = r[1]; + if (parent) parent.appendChild(dragEle); + }); + if (target) { + if (finishDrag) finishDrag(dragData); + + target.dispatchEvent( + new CustomEvent("dashOnDrop", { + bubbles: true, + detail: { + x: e.x, + y: e.y, + data: dragData + } + }) + ); + + if (options) { + options.handlers.dragComplete({}); + } } -} \ No newline at end of file + DocumentDecorations.Instance.Hidden = false; + } +} diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 7a43f3087..8f5470574 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -1,4 +1,5 @@ @import "global_variables"; + #documentDecorations-container { position: absolute; display: grid; @@ -6,26 +7,32 @@ grid-template-rows: 8px 1fr 8px 30px; grid-template-columns: 8px 1fr 8px; pointer-events: none; + #documentDecorations-centerCont { background: none; } + .documentDecorations-resizer { pointer-events: auto; background: $alt-accent; opacity: 0.8; } + #documentDecorations-topLeftResizer, #documentDecorations-bottomRightResizer { cursor: nwse-resize; } + #documentDecorations-topRightResizer, #documentDecorations-bottomLeftResizer { cursor: nesw-resize; } + #documentDecorations-topResizer, #documentDecorations-bottomResizer { cursor: ns-resize; } + #documentDecorations-leftResizer, #documentDecorations-rightResizer { cursor: ew-resize; @@ -33,7 +40,7 @@ } .documentDecorations-background { - background:lightblue; + background: lightblue; position: absolute; opacity: 0.1; } diff --git a/src/client/views/nodes/DocumentView.scss b/src/client/views/nodes/DocumentView.scss index 4eda50204..23e072344 100644 --- a/src/client/views/nodes/DocumentView.scss +++ b/src/client/views/nodes/DocumentView.scss @@ -30,10 +30,12 @@ height: 10px; width: 10px; border-radius: 2px; - background: #232323 + background: $dark-color } .minimized-box:hover { - background: #232323 + background: $main-accent; + transform: scale(1.15); + cursor: pointer; } } \ No newline at end of file diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 085307461..713c12975 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -7,7 +7,6 @@ import { observable } from "mobx"; import { library } from "@fortawesome/fontawesome-svg-core"; -import { faSquare } from "@fortawesome/free-solid-svg-icons"; import { observer } from "mobx-react"; import { Document } from "../../../fields/Document"; import { Field, Opt, FieldWaiting } from "../../../fields/Field"; @@ -33,8 +32,6 @@ import React = require("react"); import { ServerUtils } from "../../../server/ServerUtil"; import { DocumentDecorations } from "../DocumentDecorations"; -library.add(faSquare); - export interface DocumentViewProps { ContainingCollectionView: Opt; Document: Document; @@ -438,6 +435,11 @@ export class DocumentView extends React.Component { return this.minimized; }; + @action + expand = () => { + this.minimized = false; + }; + isSelected = () => { return SelectionManager.IsSelected(this); }; @@ -450,18 +452,26 @@ export class DocumentView extends React.Component { if (!this.props.Document) { return null; } + + var scaling = this.props.ContentScaling(); + var nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 0); + var nativeHeight = this.props.Document.GetNumber(KeyStore.NativeHeight, 0); + if (this.minimized) { return ( - // -
    +
    ); } else { - var scaling = this.props.ContentScaling(); - var nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 0); - var nativeHeight = this.props.Document.GetNumber( - KeyStore.NativeHeight, - 0 - ); var backgroundcolor = this.props.Document.GetText( KeyStore.BackgroundColor, "" diff --git a/src/client/views/nodes/Sticky.tsx b/src/client/views/nodes/Sticky.tsx index d57dd5c0b..4a4d69e90 100644 --- a/src/client/views/nodes/Sticky.tsx +++ b/src/client/views/nodes/Sticky.tsx @@ -1,83 +1,83 @@ -import 'react-image-lightbox/style.css'; // This only needs to be imported once in your app -import React = require("react") -import { observer } from "mobx-react" -import 'react-pdf/dist/Page/AnnotationLayer.css' +import "react-image-lightbox/style.css"; // This only needs to be imported once in your app +import React = require("react"); +import { observer } from "mobx-react"; +import "react-pdf/dist/Page/AnnotationLayer.css"; interface IProps { - Height: number; - Width: number; - X: number; - Y: number; + Height: number; + Width: number; + X: number; + Y: number; } /** - * Sticky, also known as area highlighting, is used to highlight large selection of the PDF file. - * Improvements that could be made: maybe store line array and store that somewhere for future rerendering. - * - * Written By: Andrew Kim + * Sticky, also known as area highlighting, is used to highlight large selection of the PDF file. + * Improvements that could be made: maybe store line array and store that somewhere for future rerendering. + * + * Written By: Andrew Kim */ @observer export class Sticky extends React.Component { + private initX: number = 0; + private initY: number = 0; - private initX: number = 0; - private initY: number = 0; + private _ref = React.createRef(); + private ctx: any; //context that keeps track of sticky canvas - private _ref = React.createRef(); - private ctx: any; //context that keeps track of sticky canvas - - /** - * drawing. Registers the first point that user clicks when mouse button is pressed down on canvas - */ - drawDown = (e: React.PointerEvent) => { - if (this._ref.current) { - this.ctx = this._ref.current.getContext("2d"); - let mouse = e.nativeEvent; - this.initX = mouse.offsetX; - this.initY = mouse.offsetY; - this.ctx.beginPath(); - this.ctx.lineTo(this.initX, this.initY); - this.ctx.strokeStyle = "black"; - document.addEventListener("pointermove", this.drawMove); - document.addEventListener("pointerup", this.drawUp); - } + /** + * drawing. Registers the first point that user clicks when mouse button is pressed down on canvas + */ + drawDown = (e: React.PointerEvent) => { + if (this._ref.current) { + this.ctx = this._ref.current.getContext("2d"); + let mouse = e.nativeEvent; + this.initX = mouse.offsetX; + this.initY = mouse.offsetY; + this.ctx.beginPath(); + this.ctx.lineTo(this.initX, this.initY); + this.ctx.strokeStyle = "black"; + document.addEventListener("pointermove", this.drawMove); + document.addEventListener("pointerup", this.drawUp); } + }; - //when user drags - drawMove = (e: PointerEvent): void => { - //x and y mouse movement - let x = this.initX += e.movementX, - y = this.initY += e.movementY; - //connects the point - this.ctx.lineTo(x, y); - this.ctx.stroke(); - - } + //when user drags + drawMove = (e: PointerEvent): void => { + //x and y mouse movement + let x = (this.initX += e.movementX), + y = (this.initY += e.movementY); + //connects the point + this.ctx.lineTo(x, y); + this.ctx.stroke(); + }; - /** - * when user lifts the mouse, the drawing ends - */ - drawUp = (e: PointerEvent) => { - this.ctx.closePath(); - console.log(this.ctx); - document.removeEventListener("pointermove", this.drawMove); - } + /** + * when user lifts the mouse, the drawing ends + */ + drawUp = (e: PointerEvent) => { + this.ctx.closePath(); + console.log(this.ctx); + document.removeEventListener("pointermove", this.drawMove); + }; - render() { - return ( -
    - - -
    - ); - } -} \ No newline at end of file + render() { + return ( +
    + +
    + ); + } +} -- cgit v1.2.3-70-g09d2 From dd9d087b62545a7a57ea2651eace72f851127623 Mon Sep 17 00:00:00 2001 From: Monika Hedman Date: Tue, 2 Apr 2019 16:51:08 -0400 Subject: drag working --- src/client/views/nodes/DocumentView.scss | 22 +++++++++++----------- src/client/views/nodes/DocumentView.tsx | 10 ++++++---- 2 files changed, 17 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/client/views/nodes/DocumentView.scss b/src/client/views/nodes/DocumentView.scss index 23e072344..127a6b535 100644 --- a/src/client/views/nodes/DocumentView.scss +++ b/src/client/views/nodes/DocumentView.scss @@ -25,17 +25,17 @@ overflow-y: scroll; height: calc(100% - 20px); } +} - .minimized-box { - height: 10px; - width: 10px; - border-radius: 2px; - background: $dark-color - } +.minimized-box { + height: 10px; + width: 10px; + border-radius: 2px; + background: $dark-color +} - .minimized-box:hover { - background: $main-accent; - transform: scale(1.15); - cursor: pointer; - } +.minimized-box:hover { + background: $main-accent; + transform: scale(1.15); + cursor: pointer; } \ No newline at end of file diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 713c12975..c4f329357 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -383,10 +383,12 @@ export class DocumentView extends React.Component { e.preventDefault(); //for testing purposes - ContextMenu.Instance.addItem({ - description: "Minimize", - event: this.minimize - }); + if (!this.minimized) { + ContextMenu.Instance.addItem({ + description: "Minimize", + event: this.minimize + }); + } ContextMenu.Instance.addItem({ description: "Full Screen", event: this.fullScreenClicked -- cgit v1.2.3-70-g09d2 From 36019dc66ae66bac01118ed05bdb5c6466f9bdc8 Mon Sep 17 00:00:00 2001 From: Monika Hedman Date: Tue, 2 Apr 2019 18:05:56 -0400 Subject: done with minimize to box --- src/client/util/DragManager.ts | 1 - src/client/views/nodes/DocumentView.tsx | 35 +++++-- src/fields/Document.ts | 5 + src/fields/KeyStore.ts | 90 ++++++++--------- src/fields/MinimizedField.tsx | 29 ++++++ src/server/Message.ts | 168 ++++++++++++++++++-------------- src/server/ServerUtil.ts | 151 ++++++++++++++-------------- 7 files changed, 282 insertions(+), 197 deletions(-) create mode 100644 src/fields/MinimizedField.tsx (limited to 'src') diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index ee0b5333c..c0f482e18 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -192,7 +192,6 @@ export namespace DragManager { scaleYs.push(scaleY); let dragElement = ele.cloneNode(true) as HTMLElement; dragElement.style.opacity = "0.7"; - console.log(dragElement); dragElement.style.position = "absolute"; dragElement.style.bottom = ""; dragElement.style.left = ""; diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index c4f329357..05058e63d 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -31,6 +31,7 @@ import "./DocumentView.scss"; import React = require("react"); import { ServerUtils } from "../../../server/ServerUtil"; import { DocumentDecorations } from "../DocumentDecorations"; +import { MinimizedField } from "../../../fields/MinimizedField"; export interface DocumentViewProps { ContainingCollectionView: Opt; @@ -102,8 +103,15 @@ export class DocumentView extends React.Component { private _downX: number = 0; private _downY: number = 0; + // @observable + // private minimized: boolean = false; + @observable - private minimized: boolean = false; + private _minimized: boolean = this.props.Document.GetData( + KeyStore.Minimized, + MinimizedField, + false as boolean + ); private _reactionDisposer: Opt; @computed get active(): boolean { @@ -310,7 +318,13 @@ export class DocumentView extends React.Component { @action minimize = (e: React.MouseEvent): void => { - this.minimized = true; + //hopefully sets field? + this._minimized = true as boolean; + this.props.Document.SetData( + KeyStore.Minimized, + true as boolean, + MinimizedField + ); SelectionManager.DeselectAll(); }; @@ -383,7 +397,7 @@ export class DocumentView extends React.Component { e.preventDefault(); //for testing purposes - if (!this.minimized) { + if (!this.isMinimized()) { ContextMenu.Instance.addItem({ description: "Minimize", event: this.minimize @@ -434,12 +448,21 @@ export class DocumentView extends React.Component { }; isMinimized = () => { - return this.minimized; + let field = this.props.Document.GetT(KeyStore.Minimized, MinimizedField); + if (field && field !== FieldWaiting) { + return field.Data; + } + //return this.minimized; }; @action expand = () => { - this.minimized = false; + //this._minimized = false; + this.props.Document.SetData( + KeyStore.Minimized, + false as boolean, + MinimizedField + ); }; isSelected = () => { @@ -459,7 +482,7 @@ export class DocumentView extends React.Component { var nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 0); var nativeHeight = this.props.Document.GetNumber(KeyStore.NativeHeight, 0); - if (this.minimized) { + if (this.isMinimized()) { return (
    { + constructor( + data: boolean = false as boolean, + id?: FieldId, + save: boolean = true as boolean + ) { + super(data, save, id); + } + + ToScriptString(): string { + return `new MinimizedField("${this.Data}")`; + } + + Copy() { + return new MinimizedField(this.Data); + } + + ToJson(): { type: Types; data: boolean; _id: string } { + return { + type: Types.Minimized, + data: this.Data, + _id: this.Id + }; + } +} diff --git a/src/server/Message.ts b/src/server/Message.ts index 05ae0f19a..29df57419 100644 --- a/src/server/Message.ts +++ b/src/server/Message.ts @@ -1,125 +1,145 @@ import { Utils } from "../Utils"; export class Message { - private name: string; - private guid: string; + private name: string; + private guid: string; - get Name(): string { - return this.name; - } + get Name(): string { + return this.name; + } - get Message(): string { - return this.guid - } + get Message(): string { + return this.guid; + } - constructor(name: string) { - this.name = name; - this.guid = Utils.GenerateDeterministicGuid(name) - } + constructor(name: string) { + this.name = name; + this.guid = Utils.GenerateDeterministicGuid(name); + } - GetValue() { - return this.Name; - } + GetValue() { + return this.Name; + } } class TestMessageArgs { - hello: string = ""; + hello: string = ""; } export class SetFieldArgs { - field: string; - value: any; + field: string; + value: any; - constructor(f: string, v: any) { - this.field = f - this.value = v - } + constructor(f: string, v: any) { + this.field = f; + this.value = v; + } } export class GetFieldArgs { - field: string; + field: string; - constructor(f: string) { - this.field = f - } + constructor(f: string) { + this.field = f; + } } export enum Types { - Number, List, Key, Image, Web, Document, Text, RichText, DocumentReference, Html, Video, Audio, Ink, PDF, Tuple, HistogramOp + Number, + List, + Key, + Image, + Web, + Document, + Text, + RichText, + DocumentReference, + Html, + Video, + Audio, + Ink, + PDF, + Tuple, + HistogramOp, + Minimized } export class DocumentTransfer implements Transferable { - readonly type = Types.Document - _id: string - - constructor(readonly obj: { type: Types, data: [string, string][], _id: string }) { - this._id = obj._id - } + readonly type = Types.Document; + _id: string; + + constructor( + readonly obj: { type: Types; data: [string, string][]; _id: string } + ) { + this._id = obj._id; + } } export class ImageTransfer implements Transferable { - readonly type = Types.Image + readonly type = Types.Image; - constructor(readonly _id: string) { } + constructor(readonly _id: string) {} } export class KeyTransfer implements Transferable { - name: string - readonly _id: string - readonly type = Types.Key - - constructor(i: string, n: string) { - this.name = n - this._id = i - } + name: string; + readonly _id: string; + readonly type = Types.Key; + + constructor(i: string, n: string) { + this.name = n; + this._id = i; + } } export class ListTransfer implements Transferable { - type = Types.List; + type = Types.List; - constructor(readonly _id: string) { } + constructor(readonly _id: string) {} } export class NumberTransfer implements Transferable { - readonly type = Types.Number + readonly type = Types.Number; - constructor(readonly value: number, readonly _id: string) { } + constructor(readonly value: number, readonly _id: string) {} } export class TextTransfer implements Transferable { - value: string - readonly _id: string - readonly type = Types.Text - - constructor(t: string, i: string) { - this.value = t - this._id = i - } + value: string; + readonly _id: string; + readonly type = Types.Text; + + constructor(t: string, i: string) { + this.value = t; + this._id = i; + } } export class RichTextTransfer implements Transferable { - value: string - readonly _id: string - readonly type = Types.Text - - constructor(t: string, i: string) { - this.value = t - this._id = i - } + value: string; + readonly _id: string; + readonly type = Types.Text; + + constructor(t: string, i: string) { + this.value = t; + this._id = i; + } } export interface Transferable { - readonly _id: string - readonly type: Types + readonly _id: string; + readonly type: Types; } export namespace MessageStore { - export const Foo = new Message("Foo"); - export const Bar = new Message("Bar"); - export const AddDocument = new Message("Add Document"); - export const SetField = new Message<{ _id: string, data: any, type: Types }>("Set Field") - export const GetField = new Message("Get Field") - export const GetFields = new Message("Get Fields") - export const GetDocument = new Message("Get Document"); - export const DeleteAll = new Message("Delete All"); -} \ No newline at end of file + export const Foo = new Message("Foo"); + export const Bar = new Message("Bar"); + export const AddDocument = new Message("Add Document"); + export const SetField = new Message<{ _id: string; data: any; type: Types }>( + "Set Field" + ); + export const GetField = new Message("Get Field"); + export const GetFields = new Message("Get Fields"); + export const GetDocument = new Message("Get Document"); + export const DeleteAll = new Message("Delete All"); +} diff --git a/src/server/ServerUtil.ts b/src/server/ServerUtil.ts index 98a7a1451..3e24fed3a 100644 --- a/src/server/ServerUtil.ts +++ b/src/server/ServerUtil.ts @@ -1,78 +1,85 @@ - -import { Field } from './../fields/Field'; -import { TextField } from './../fields/TextField'; -import { NumberField } from './../fields/NumberField'; -import { RichTextField } from './../fields/RichTextField'; -import { Key } from './../fields/Key'; -import { ImageField } from './../fields/ImageField'; -import { ListField } from './../fields/ListField'; -import { Document } from './../fields/Document'; -import { Server } from './../client/Server'; -import { Types } from './Message'; -import { Utils } from '../Utils'; -import { HtmlField } from '../fields/HtmlField'; -import { WebField } from '../fields/WebField'; -import { AudioField } from '../fields/AudioField'; -import { VideoField } from '../fields/VideoField'; -import { InkField } from '../fields/InkField'; -import { PDFField } from '../fields/PDFField'; -import { TupleField } from '../fields/TupleField'; -import { HistogramField } from '../client/northstar/dash-fields/HistogramField'; - - +import { Field } from "./../fields/Field"; +import { TextField } from "./../fields/TextField"; +import { NumberField } from "./../fields/NumberField"; +import { RichTextField } from "./../fields/RichTextField"; +import { Key } from "./../fields/Key"; +import { ImageField } from "./../fields/ImageField"; +import { ListField } from "./../fields/ListField"; +import { Document } from "./../fields/Document"; +import { Server } from "./../client/Server"; +import { Types } from "./Message"; +import { Utils } from "../Utils"; +import { HtmlField } from "../fields/HtmlField"; +import { WebField } from "../fields/WebField"; +import { AudioField } from "../fields/AudioField"; +import { VideoField } from "../fields/VideoField"; +import { InkField } from "../fields/InkField"; +import { PDFField } from "../fields/PDFField"; +import { TupleField } from "../fields/TupleField"; +import { MinimizedField } from "../fields/MinimizedField"; +import { HistogramField } from "../client/northstar/dash-fields/HistogramField"; export class ServerUtils { - public static prepend(extension: string): string { return window.location.origin + extension; } + public static prepend(extension: string): string { + return window.location.origin + extension; + } - public static FromJson(json: any): Field { - let obj = json - let data: any = obj.data - let id: string = obj._id - let type: Types = obj.type + public static FromJson(json: any): Field { + let obj = json; + let data: any = obj.data; + let id: string = obj._id; + let type: Types = obj.type; - if (!(data !== undefined && id && type !== undefined)) { - console.log("how did you manage to get an object that doesn't have a data or an id?") - return new TextField("Something to fill the space", Utils.GenerateGuid()); - } + if (!(data !== undefined && id && type !== undefined)) { + console.log( + "how did you manage to get an object that doesn't have a data or an id?" + ); + return new TextField("Something to fill the space", Utils.GenerateGuid()); + } - switch (type) { - case Types.Number: - return new NumberField(data, id, false) - case Types.Text: - return new TextField(data, id, false) - case Types.Html: - return new HtmlField(data, id, false) - case Types.Web: - return new WebField(new URL(data), id, false) - case Types.RichText: - return new RichTextField(data, id, false) - case Types.Key: - return new Key(data, id, false) - case Types.Image: - return new ImageField(new URL(data), id, false) - case Types.HistogramOp: - return HistogramField.FromJson(id, data); - case Types.PDF: - return new PDFField(new URL(data), id, false) - case Types.List: - return ListField.FromJson(id, data) - case Types.Audio: - return new AudioField(new URL(data), id, false) - case Types.Video: - return new VideoField(new URL(data), id, false) - case Types.Tuple: - return new TupleField(data, id, false); - case Types.Ink: - return InkField.FromJson(id, data); - case Types.Document: - let doc: Document = new Document(id, false) - let fields: [string, string][] = data as [string, string][] - fields.forEach(element => { - doc._proxies.set(element[0], element[1]); - }); - return doc - default: - throw Error("Error, unrecognized field type received from server. If you just created a new field type, be sure to add it here"); - } + switch (type) { + case Types.Minimized: + return new MinimizedField(data, id, false); + case Types.Number: + return new NumberField(data, id, false); + case Types.Text: + return new TextField(data, id, false); + case Types.Html: + return new HtmlField(data, id, false); + case Types.Web: + console.log("LOOK HERE! " + data); + return new WebField(new URL(data), id, false); + case Types.RichText: + return new RichTextField(data, id, false); + case Types.Key: + return new Key(data, id, false); + case Types.Image: + return new ImageField(new URL(data), id, false); + case Types.HistogramOp: + return HistogramField.FromJson(id, data); + case Types.PDF: + return new PDFField(new URL(data), id, false); + case Types.List: + return ListField.FromJson(id, data); + case Types.Audio: + return new AudioField(new URL(data), id, false); + case Types.Video: + return new VideoField(new URL(data), id, false); + case Types.Tuple: + return new TupleField(data, id, false); + case Types.Ink: + return InkField.FromJson(id, data); + case Types.Document: + let doc: Document = new Document(id, false); + let fields: [string, string][] = data as [string, string][]; + fields.forEach(element => { + doc._proxies.set(element[0], element[1]); + }); + return doc; + default: + throw Error( + "Error, unrecognized field type received from server. If you just created a new field type, be sure to add it here" + ); } -} \ No newline at end of file + } +} -- cgit v1.2.3-70-g09d2 From 2d5da2260e6b96d28fdf3d7c243049c67b29f535 Mon Sep 17 00:00:00 2001 From: Monika Hedman Date: Tue, 2 Apr 2019 18:06:40 -0400 Subject: cleanup --- src/server/ServerUtil.ts | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/server/ServerUtil.ts b/src/server/ServerUtil.ts index 3e24fed3a..f3c5e1d1f 100644 --- a/src/server/ServerUtil.ts +++ b/src/server/ServerUtil.ts @@ -47,7 +47,6 @@ export class ServerUtils { case Types.Html: return new HtmlField(data, id, false); case Types.Web: - console.log("LOOK HERE! " + data); return new WebField(new URL(data), id, false); case Types.RichText: return new RichTextField(data, id, false); -- cgit v1.2.3-70-g09d2 From fb5a34562b6855f3c9695e556497203577129a6d Mon Sep 17 00:00:00 2001 From: Monika Hedman Date: Tue, 2 Apr 2019 18:10:56 -0400 Subject: clean up 2 --- src/client/views/nodes/DocumentView.tsx | 15 --------------- 1 file changed, 15 deletions(-) (limited to 'src') diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 05058e63d..2b9372e15 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -103,16 +103,6 @@ export class DocumentView extends React.Component { private _downX: number = 0; private _downY: number = 0; - // @observable - // private minimized: boolean = false; - - @observable - private _minimized: boolean = this.props.Document.GetData( - KeyStore.Minimized, - MinimizedField, - false as boolean - ); - private _reactionDisposer: Opt; @computed get active(): boolean { return ( @@ -318,8 +308,6 @@ export class DocumentView extends React.Component { @action minimize = (e: React.MouseEvent): void => { - //hopefully sets field? - this._minimized = true as boolean; this.props.Document.SetData( KeyStore.Minimized, true as boolean, @@ -396,7 +384,6 @@ export class DocumentView extends React.Component { } e.preventDefault(); - //for testing purposes if (!this.isMinimized()) { ContextMenu.Instance.addItem({ description: "Minimize", @@ -452,12 +439,10 @@ export class DocumentView extends React.Component { if (field && field !== FieldWaiting) { return field.Data; } - //return this.minimized; }; @action expand = () => { - //this._minimized = false; this.props.Document.SetData( KeyStore.Minimized, false as boolean, -- cgit v1.2.3-70-g09d2 From bc572b4459455e6b046972b0f984868acc6701b5 Mon Sep 17 00:00:00 2001 From: Monika Hedman Date: Tue, 2 Apr 2019 18:17:53 -0400 Subject: clean up AGAIN --- build/index.html | 24 +- src/fields/Document.ts | 717 ++++++++++++++++++++++++++----------------------- 2 files changed, 393 insertions(+), 348 deletions(-) (limited to 'src') diff --git a/build/index.html b/build/index.html index 2818d7c8b..fda212af4 100644 --- a/build/index.html +++ b/build/index.html @@ -1,16 +1,12 @@ - - Dash Web - - - -
    - - - + + Dash Web + + + +
    + + + + \ No newline at end of file diff --git a/src/fields/Document.ts b/src/fields/Document.ts index 5131d89ca..8e71019a4 100644 --- a/src/fields/Document.ts +++ b/src/fields/Document.ts @@ -1,6 +1,6 @@ -import { Key } from "./Key" +import { Key } from "./Key"; import { KeyStore } from "./KeyStore"; -import { Field, Cast, FieldWaiting, FieldValue, FieldId, Opt } from "./Field" +import { Field, Cast, FieldWaiting, FieldValue, FieldId, Opt } from "./Field"; import { NumberField } from "./NumberField"; import { ObservableMap, computed, action, runInAction } from "mobx"; import { TextField } from "./TextField"; @@ -9,366 +9,415 @@ import { Server } from "../client/Server"; import { Types } from "../server/Message"; import { UndoManager } from "../client/util/UndoManager"; import { HtmlField } from "./HtmlField"; -import { MinimizedField } from "./MinimizedField"; export class Document extends Field { - //TODO tfs: We should probably store FieldWaiting in fields when we request it from the server so that we don't set up multiple server gets for the same document and field - public fields: ObservableMap = new ObservableMap(); - public _proxies: ObservableMap = new ObservableMap(); - - constructor(id?: string, save: boolean = true) { - super(id) - - if (save) { - Server.UpdateField(this) - } - } - - UpdateFromServer(data: [string, string][]) { - for (const key in data) { - const element = data[key]; - this._proxies.set(element[0], element[1]); - } - } - - public Width = () => { return this.GetNumber(KeyStore.Width, 0) } - public Height = () => { return this.GetNumber(KeyStore.Height, this.GetNumber(KeyStore.NativeWidth, 0) ? this.GetNumber(KeyStore.NativeHeight, 0) / this.GetNumber(KeyStore.NativeWidth, 0) * this.GetNumber(KeyStore.Width, 0) : 0) } - public Scale = () => { return this.GetNumber(KeyStore.Scale, 1) } - - @computed - public get Title(): string { - let title = this.Get(KeyStore.Title, true); - if (title) - if (title != FieldWaiting && title instanceof TextField) - return title.Data; - else return "-waiting-"; - let parTitle = this.GetT(KeyStore.Title, TextField); - if (parTitle) - if (parTitle != FieldWaiting) - return parTitle.Data + ".alias"; - else return "-waiting-.alias"; - return "-untitled-"; + //TODO tfs: We should probably store FieldWaiting in fields when we request it from the server so that we don't set up multiple server gets for the same document and field + public fields: ObservableMap< + string, + { key: Key; field: Field } + > = new ObservableMap(); + public _proxies: ObservableMap = new ObservableMap(); + + constructor(id?: string, save: boolean = true) { + super(id); + + if (save) { + Server.UpdateField(this); } + } - @computed - public get Fields() { - return this.fields; + UpdateFromServer(data: [string, string][]) { + for (const key in data) { + const element = data[key]; + this._proxies.set(element[0], element[1]); } - - /** - * Get the field in the document associated with the given key. If the - * associated field has not yet been filled in from the server, a request - * to the server will automatically be sent, the value will be filled in - * when the request is completed, and {@link Field.ts#FieldWaiting} will be returned. - * @param key - The key of the value to get - * @param ignoreProto - If true, ignore any prototype this document - * might have and only search for the value on this immediate document. - * If false (default), search up the prototype chain, starting at this document, - * for a document that has a field associated with the given key, and return the first - * one found. - * - * @returns If the document does not have a field associated with the given key, returns `undefined`. - * If the document does have an associated field, but the field has not been fetched from the server, returns {@link Field.ts#FieldWaiting}. - * If the document does have an associated field, and the field has not been fetched from the server, returns the associated field. - */ - Get(key: Key, ignoreProto: boolean = false): FieldValue { - let field: FieldValue; - if (ignoreProto) { - if (this.fields.has(key.Id)) { - field = this.fields.get(key.Id)!.field; - } else if (this._proxies.has(key.Id)) { - Server.GetDocumentField(this, key); - /* + } + + public Width = () => { + return this.GetNumber(KeyStore.Width, 0); + }; + public Height = () => { + return this.GetNumber( + KeyStore.Height, + this.GetNumber(KeyStore.NativeWidth, 0) + ? (this.GetNumber(KeyStore.NativeHeight, 0) / + this.GetNumber(KeyStore.NativeWidth, 0)) * + this.GetNumber(KeyStore.Width, 0) + : 0 + ); + }; + public Scale = () => { + return this.GetNumber(KeyStore.Scale, 1); + }; + + @computed + public get Title(): string { + let title = this.Get(KeyStore.Title, true); + if (title) + if (title != FieldWaiting && title instanceof TextField) + return title.Data; + else return "-waiting-"; + let parTitle = this.GetT(KeyStore.Title, TextField); + if (parTitle) + if (parTitle != FieldWaiting) return parTitle.Data + ".alias"; + else return "-waiting-.alias"; + return "-untitled-"; + } + + @computed + public get Fields() { + return this.fields; + } + + /** + * Get the field in the document associated with the given key. If the + * associated field has not yet been filled in from the server, a request + * to the server will automatically be sent, the value will be filled in + * when the request is completed, and {@link Field.ts#FieldWaiting} will be returned. + * @param key - The key of the value to get + * @param ignoreProto - If true, ignore any prototype this document + * might have and only search for the value on this immediate document. + * If false (default), search up the prototype chain, starting at this document, + * for a document that has a field associated with the given key, and return the first + * one found. + * + * @returns If the document does not have a field associated with the given key, returns `undefined`. + * If the document does have an associated field, but the field has not been fetched from the server, returns {@link Field.ts#FieldWaiting}. + * If the document does have an associated field, and the field has not been fetched from the server, returns the associated field. + */ + Get(key: Key, ignoreProto: boolean = false): FieldValue { + let field: FieldValue; + if (ignoreProto) { + if (this.fields.has(key.Id)) { + field = this.fields.get(key.Id)!.field; + } else if (this._proxies.has(key.Id)) { + Server.GetDocumentField(this, key); + /* The field might have been instantly filled from the cache Maybe we want to just switch back to returning the value from Server.GetDocumentField if it's in the cache */ - if (this.fields.has(key.Id)) { - field = this.fields.get(key.Id)!.field; - } else { - field = FieldWaiting; - } - } + if (this.fields.has(key.Id)) { + field = this.fields.get(key.Id)!.field; } else { - let doc: FieldValue = this; - while (doc && doc != FieldWaiting && field != FieldWaiting) { - let curField = doc.fields.get(key.Id); - let curProxy = doc._proxies.get(key.Id); - if (!curField || (curProxy && curField.field.Id !== curProxy)) { - if (curProxy) { - Server.GetDocumentField(doc, key); - /* + field = FieldWaiting; + } + } + } else { + let doc: FieldValue = this; + while (doc && doc != FieldWaiting && field != FieldWaiting) { + let curField = doc.fields.get(key.Id); + let curProxy = doc._proxies.get(key.Id); + if (!curField || (curProxy && curField.field.Id !== curProxy)) { + if (curProxy) { + Server.GetDocumentField(doc, key); + /* The field might have been instantly filled from the cache Maybe we want to just switch back to returning the value from Server.GetDocumentField if it's in the cache */ - if (this.fields.has(key.Id)) { - field = this.fields.get(key.Id)!.field; - } else { - field = FieldWaiting; - } - break; - } - if ((doc.fields.has(KeyStore.Prototype.Id) || doc._proxies.has(KeyStore.Prototype.Id))) { - doc = doc.GetPrototype(); - } else { - break; - } - } else { - field = curField.field; - break; - } + if (this.fields.has(key.Id)) { + field = this.fields.get(key.Id)!.field; + } else { + field = FieldWaiting; } - if (doc == FieldWaiting) - field = FieldWaiting; - } - - return field; - } - - /** - * Tries to get the field associated with the given key, and if there is an - * associated field, calls the given callback with that field. - * @param key - The key of the value to get - * @param callback - A function that will be called with the associated field, if it exists, - * once it is fetched from the server (this may be immediately if the field has already been fetched). - * Note: The callback will not be called if there is no associated field. - * @returns `true` if the field exists on the document and `callback` will be called, and `false` otherwise - */ - GetAsync(key: Key, callback: (field: Opt) => void): void { - //TODO: This currently doesn't deal with prototypes - let field = this.fields.get(key.Id); - if (field && field.field) { - callback(field.field); - } else if (this._proxies.has(key.Id)) { - Server.GetDocumentField(this, key, callback); - } else if (this._proxies.has(KeyStore.Prototype.Id)) { - this.GetTAsync(KeyStore.Prototype, Document, proto => { - if (proto) { - proto.GetAsync(key, callback); - } else { - callback(undefined); - } - }) - } else { - callback(undefined); - } - } - - GetTAsync(key: Key, ctor: { new(): T }): Promise>; - GetTAsync(key: Key, ctor: { new(): T }, callback: (field: Opt) => void): void; - GetTAsync(key: Key, ctor: { new(): T }, callback?: (field: Opt) => void): Promise> | void { - let fn = (cb: (field: Opt) => void) => { - return this.GetAsync(key, (field) => { - cb(Cast(field, ctor)); - }); - } - if (callback) { - fn(callback); + break; + } + if ( + doc.fields.has(KeyStore.Prototype.Id) || + doc._proxies.has(KeyStore.Prototype.Id) + ) { + doc = doc.GetPrototype(); + } else { + break; + } } else { - return new Promise(res => fn(res)); + field = curField.field; + break; } + } + if (doc == FieldWaiting) field = FieldWaiting; } - /** - * Same as {@link Document#GetAsync}, except a field of the given type - * will be created if there is no field associated with the given key, - * or the field associated with the given key is not of the given type. - * @param ctor - Constructor of the field type to get. E.g., TextField, ImageField, etc. - */ - GetOrCreateAsync(key: Key, ctor: { new(): T }, callback: (field: T) => void): void { - //This currently doesn't deal with prototypes - if (this._proxies.has(key.Id)) { - Server.GetDocumentField(this, key, (field) => { - if (field && field instanceof ctor) { - callback(field); - } else { - let newField = new ctor(); - this.Set(key, newField); - callback(newField); - } - }); + return field; + } + + /** + * Tries to get the field associated with the given key, and if there is an + * associated field, calls the given callback with that field. + * @param key - The key of the value to get + * @param callback - A function that will be called with the associated field, if it exists, + * once it is fetched from the server (this may be immediately if the field has already been fetched). + * Note: The callback will not be called if there is no associated field. + * @returns `true` if the field exists on the document and `callback` will be called, and `false` otherwise + */ + GetAsync(key: Key, callback: (field: Opt) => void): void { + //TODO: This currently doesn't deal with prototypes + let field = this.fields.get(key.Id); + if (field && field.field) { + callback(field.field); + } else if (this._proxies.has(key.Id)) { + Server.GetDocumentField(this, key, callback); + } else if (this._proxies.has(KeyStore.Prototype.Id)) { + this.GetTAsync(KeyStore.Prototype, Document, proto => { + if (proto) { + proto.GetAsync(key, callback); } else { - let newField = new ctor(); - this.Set(key, newField); - callback(newField); + callback(undefined); } + }); + } else { + callback(undefined); } - - /** - * Same as {@link Document#Get}, except that it will additionally - * check if the field is of the given type. - * @param ctor - Constructor of the field type to get. E.g., `TextField`, `ImageField`, etc. - * @returns Same as {@link Document#Get}, except will return `undefined` - * if there is an associated field but it is of the wrong type. - */ - GetT(key: Key, ctor: { new(...args: any[]): T }, ignoreProto: boolean = false): FieldValue { - var getfield = this.Get(key, ignoreProto); - if (getfield != FieldWaiting) { - return Cast(getfield, ctor); - } - return FieldWaiting; - } - - GetOrCreate(key: Key, ctor: { new(): T }, ignoreProto: boolean = false): T { - const field = this.GetT(key, ctor, ignoreProto); - if (field && field != FieldWaiting) { - return field; - } - const newField = new ctor(); - this.Set(key, newField); - return newField; - } - - GetData(key: Key, ctor: { new(): U }, defaultVal: T): T { - let val = this.Get(key); - let vval = (val && val instanceof ctor) ? val.Data : defaultVal; - return vval; - } - - // GetMinimized(key: Key, defaultVal: boolean): boolean { - // return this.GetData(key, MinimizedField, defaultVal); - // } - - GetHtml(key: Key, defaultVal: string): string { - return this.GetData(key, HtmlField, defaultVal); - } - - GetNumber(key: Key, defaultVal: number): number { - return this.GetData(key, NumberField, defaultVal); - } - - GetText(key: Key, defaultVal: string): string { - return this.GetData(key, TextField, defaultVal); + } + + GetTAsync(key: Key, ctor: { new (): T }): Promise>; + GetTAsync( + key: Key, + ctor: { new (): T }, + callback: (field: Opt) => void + ): void; + GetTAsync( + key: Key, + ctor: { new (): T }, + callback?: (field: Opt) => void + ): Promise> | void { + let fn = (cb: (field: Opt) => void) => { + return this.GetAsync(key, field => { + cb(Cast(field, ctor)); + }); + }; + if (callback) { + fn(callback); + } else { + return new Promise(res => fn(res)); } - - GetList(key: Key, defaultVal: T[]): T[] { - return this.GetData>(key, ListField, defaultVal) - } - - @action - Set(key: Key, field: Field | undefined, setOnPrototype = false): void { - let old = this.fields.get(key.Id); - let oldField = old ? old.field : undefined; - if (setOnPrototype) { - this.SetOnPrototype(key, field) - } - else { - if (field) { - this.fields.set(key.Id, { key, field }); - this._proxies.set(key.Id, field.Id) - // Server.AddDocumentField(this, key, field); - } else { - this.fields.delete(key.Id); - this._proxies.delete(key.Id) - // Server.DeleteDocumentField(this, key); - } - Server.UpdateField(this); - } - if (oldField || field) { - UndoManager.AddEvent({ - undo: () => this.Set(key, oldField, setOnPrototype), - redo: () => this.Set(key, field, setOnPrototype) - }) - } - } - - @action - SetOnPrototype(key: Key, field: Field | undefined): void { - this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { - f && f.Set(key, field) - }) - } - - @action - SetDataOnPrototype(key: Key, value: T, ctor: { new(): U }, replaceWrongType = true) { - this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { - f && f.SetData(key, value, ctor) - }) - } - - @action - SetData(key: Key, value: T, ctor: { new(data: T): U }, replaceWrongType = true) { - let field = this.Get(key, true); - if (field instanceof ctor) { - field.Data = value; - } else if (!field || replaceWrongType) { - let newField = new ctor(value); - // newField.Data = value; - this.Set(key, newField); - } - } - - @action - SetText(key: Key, value: string, replaceWrongType = true) { - this.SetData(key, value, TextField, replaceWrongType); - } - - @action - SetNumber(key: Key, value: number, replaceWrongType = true) { - this.SetData(key, value, NumberField, replaceWrongType); - } - - GetPrototype(): FieldValue { - return this.GetT(KeyStore.Prototype, Document, true); - } - - GetAllPrototypes(): Document[] { - let protos: Document[] = []; - let doc: FieldValue = this; - while (doc && doc != FieldWaiting) { - protos.push(doc); - doc = doc.GetPrototype(); + } + + /** + * Same as {@link Document#GetAsync}, except a field of the given type + * will be created if there is no field associated with the given key, + * or the field associated with the given key is not of the given type. + * @param ctor - Constructor of the field type to get. E.g., TextField, ImageField, etc. + */ + GetOrCreateAsync( + key: Key, + ctor: { new (): T }, + callback: (field: T) => void + ): void { + //This currently doesn't deal with prototypes + if (this._proxies.has(key.Id)) { + Server.GetDocumentField(this, key, field => { + if (field && field instanceof ctor) { + callback(field); + } else { + let newField = new ctor(); + this.Set(key, newField); + callback(newField); } - return protos; - } - - CreateAlias(id?: string): Document { - let alias = new Document(id) - this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { - f && alias.Set(KeyStore.Prototype, f) - }) - - return alias + }); + } else { + let newField = new ctor(); + this.Set(key, newField); + callback(newField); } - - MakeDelegate(id?: string): Document { - let delegate = new Document(id); - - delegate.Set(KeyStore.Prototype, this); - - return delegate; + } + + /** + * Same as {@link Document#Get}, except that it will additionally + * check if the field is of the given type. + * @param ctor - Constructor of the field type to get. E.g., `TextField`, `ImageField`, etc. + * @returns Same as {@link Document#Get}, except will return `undefined` + * if there is an associated field but it is of the wrong type. + */ + GetT( + key: Key, + ctor: { new (...args: any[]): T }, + ignoreProto: boolean = false + ): FieldValue { + var getfield = this.Get(key, ignoreProto); + if (getfield != FieldWaiting) { + return Cast(getfield, ctor); } - - ToScriptString(): string { - return ""; + return FieldWaiting; + } + + GetOrCreate( + key: Key, + ctor: { new (): T }, + ignoreProto: boolean = false + ): T { + const field = this.GetT(key, ctor, ignoreProto); + if (field && field != FieldWaiting) { + return field; } - - TrySetValue(value: any): boolean { - throw new Error("Method not implemented."); + const newField = new ctor(); + this.Set(key, newField); + return newField; + } + + GetData( + key: Key, + ctor: { new (): U }, + defaultVal: T + ): T { + let val = this.Get(key); + let vval = val && val instanceof ctor ? val.Data : defaultVal; + return vval; + } + + GetHtml(key: Key, defaultVal: string): string { + return this.GetData(key, HtmlField, defaultVal); + } + + GetNumber(key: Key, defaultVal: number): number { + return this.GetData(key, NumberField, defaultVal); + } + + GetText(key: Key, defaultVal: string): string { + return this.GetData(key, TextField, defaultVal); + } + + GetList(key: Key, defaultVal: T[]): T[] { + return this.GetData>(key, ListField, defaultVal); + } + + @action + Set(key: Key, field: Field | undefined, setOnPrototype = false): void { + let old = this.fields.get(key.Id); + let oldField = old ? old.field : undefined; + if (setOnPrototype) { + this.SetOnPrototype(key, field); + } else { + if (field) { + this.fields.set(key.Id, { key, field }); + this._proxies.set(key.Id, field.Id); + // Server.AddDocumentField(this, key, field); + } else { + this.fields.delete(key.Id); + this._proxies.delete(key.Id); + // Server.DeleteDocumentField(this, key); + } + Server.UpdateField(this); } - GetValue() { - return this.Title; - var title = (this._proxies.has(KeyStore.Title.Id) ? "???" : this.Title) + "(" + this.Id + ")"; - return title; - //throw new Error("Method not implemented."); + if (oldField || field) { + UndoManager.AddEvent({ + undo: () => this.Set(key, oldField, setOnPrototype), + redo: () => this.Set(key, field, setOnPrototype) + }); } - Copy(): Field { - throw new Error("Method not implemented."); + } + + @action + SetOnPrototype(key: Key, field: Field | undefined): void { + this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { + f && f.Set(key, field); + }); + } + + @action + SetDataOnPrototype( + key: Key, + value: T, + ctor: { new (): U }, + replaceWrongType = true + ) { + this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { + f && f.SetData(key, value, ctor); + }); + } + + @action + SetData( + key: Key, + value: T, + ctor: { new (data: T): U }, + replaceWrongType = true + ) { + let field = this.Get(key, true); + if (field instanceof ctor) { + field.Data = value; + } else if (!field || replaceWrongType) { + let newField = new ctor(value); + // newField.Data = value; + this.Set(key, newField); } - - ToJson(): { type: Types, data: [string, string][], _id: string } { - let fields: [string, string][] = [] - this._proxies.forEach((field, key) => { - if (field) { - fields.push([key, field as string]) - } - }); - - return { - type: Types.Document, - data: fields, - _id: this.Id - } + } + + @action + SetText(key: Key, value: string, replaceWrongType = true) { + this.SetData(key, value, TextField, replaceWrongType); + } + + @action + SetNumber(key: Key, value: number, replaceWrongType = true) { + this.SetData(key, value, NumberField, replaceWrongType); + } + + GetPrototype(): FieldValue { + return this.GetT(KeyStore.Prototype, Document, true); + } + + GetAllPrototypes(): Document[] { + let protos: Document[] = []; + let doc: FieldValue = this; + while (doc && doc != FieldWaiting) { + protos.push(doc); + doc = doc.GetPrototype(); } -} \ No newline at end of file + return protos; + } + + CreateAlias(id?: string): Document { + let alias = new Document(id); + this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { + f && alias.Set(KeyStore.Prototype, f); + }); + + return alias; + } + + MakeDelegate(id?: string): Document { + let delegate = new Document(id); + + delegate.Set(KeyStore.Prototype, this); + + return delegate; + } + + ToScriptString(): string { + return ""; + } + + TrySetValue(value: any): boolean { + throw new Error("Method not implemented."); + } + GetValue() { + return this.Title; + var title = + (this._proxies.has(KeyStore.Title.Id) ? "???" : this.Title) + + "(" + + this.Id + + ")"; + return title; + //throw new Error("Method not implemented."); + } + Copy(): Field { + throw new Error("Method not implemented."); + } + + ToJson(): { type: Types; data: [string, string][]; _id: string } { + let fields: [string, string][] = []; + this._proxies.forEach((field, key) => { + if (field) { + fields.push([key, field as string]); + } + }); + + return { + type: Types.Document, + data: fields, + _id: this.Id + }; + } +} -- cgit v1.2.3-70-g09d2 From 85e1eeb77241303307ff5f98d550663e18b807b8 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 2 Apr 2019 20:05:13 -0400 Subject: fixed collection from marquee --- .../collections/collectionFreeForm/MarqueeView.tsx | 45 +++++++++++----------- 1 file changed, 23 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index 20132a4b1..e2239c8be 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -102,7 +102,7 @@ export class MarqueeView extends React.Component if (e.key == "Backspace" || e.key == "Delete") { this.marqueeSelect().map(d => this.props.removeDocument(d)); let ink = this.props.container.props.Document.GetT(KeyStore.Ink, InkField); - if (ink && ink != FieldWaiting && ink.Data) { + if (ink && ink != FieldWaiting) { this.marqueeInkDelete(ink.Data); } this.cleanupInteractions(); @@ -118,22 +118,21 @@ export class MarqueeView extends React.Component return d; }); let ink = this.props.container.props.Document.GetT(KeyStore.Ink, InkField); - if (ink && ink != FieldWaiting && ink.Data) { - //setTimeout(() => { - let newCollection = Documents.FreeformDocument(selected, { - x: bounds.left, - y: bounds.top, - panx: 0, - pany: 0, - width: bounds.width, - height: bounds.height, - backgroundColor: "Transparent", - ink: this.marqueeInkSelect(ink.Data), - title: "a nested collection" - }); - this.props.addDocument(newCollection, false); - this.marqueeInkDelete(ink.Data); - } + let inkData = ink && ink != FieldWaiting ? ink.Data : undefined; + //setTimeout(() => { + let newCollection = Documents.FreeformDocument(selected, { + x: bounds.left, + y: bounds.top, + panx: 0, + pany: 0, + width: bounds.width, + height: bounds.height, + backgroundColor: "Transparent", + ink: inkData ? this.marqueeInkSelect(inkData) : undefined, + title: "a nested collection" + }); + this.props.addDocument(newCollection, false); + this.marqueeInkDelete(inkData); // }, 100); this.cleanupInteractions(); } @@ -159,15 +158,17 @@ export class MarqueeView extends React.Component } @action - marqueeInkDelete(ink: Map, ) { + marqueeInkDelete(ink?: Map) { // bcz: this appears to work but when you restart all the deleted strokes come back -- InkField isn't observing its changes so they aren't written to the DB. // ink.forEach((value: StrokeData, key: string, map: any) => // InkingCanvas.IntersectStrokeRect(value, this.Bounds) && ink.delete(key)); - let idata = new Map(); - ink.forEach((value: StrokeData, key: string, map: any) => - !InkingCanvas.IntersectStrokeRect(value, this.Bounds) && idata.set(key, value)); - this.props.container.props.Document.SetDataOnPrototype(KeyStore.Ink, idata, InkField); + if (ink) { + let idata = new Map(); + ink.forEach((value: StrokeData, key: string, map: any) => + !InkingCanvas.IntersectStrokeRect(value, this.Bounds) && idata.set(key, value)); + this.props.container.props.Document.SetDataOnPrototype(KeyStore.Ink, idata, InkField); + } } marqueeSelect() { -- cgit v1.2.3-70-g09d2 From 7304217fd9559c35e34c16d5e4e025875adc3252 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 2 Apr 2019 20:59:10 -0400 Subject: put in a patch for inking up to canvas limit of 8192 --- src/client/views/InkingCanvas.scss | 10 +++++----- src/client/views/InkingCanvas.tsx | 2 +- src/client/views/InkingStroke.tsx | 5 +++-- 3 files changed, 9 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/client/views/InkingCanvas.scss b/src/client/views/InkingCanvas.scss index 214c70280..2128401b8 100644 --- a/src/client/views/InkingCanvas.scss +++ b/src/client/views/InkingCanvas.scss @@ -2,12 +2,12 @@ .inkingCanvas-paths-ink, .inkingCanvas-paths-markers, .inkingCanvas-noSelect, .inkingCanvas-canSelect { position: absolute; - top: -50000px; - left: -50000px; - width: 100000px; - height: 100000px; + top: -4096px; + left: -4096px; + width: 8192px; + height: 8192px; .inkingCanvas-children { - transform: translate(50000px, 50000px); + transform: translate(4096px, 4096px); pointer-events: none; } cursor:"crosshair"; diff --git a/src/client/views/InkingCanvas.tsx b/src/client/views/InkingCanvas.tsx index 123ff679b..fcf6db390 100644 --- a/src/client/views/InkingCanvas.tsx +++ b/src/client/views/InkingCanvas.tsx @@ -18,7 +18,7 @@ interface InkCanvasProps { @observer export class InkingCanvas extends React.Component { - static InkOffset: number = 50000; + static InkOffset: number = 4096; private _currentStrokeId: string = ""; public static IntersectStrokeRect(stroke: StrokeData, selRect: { left: number, top: number, width: number, height: number }): boolean { return stroke.pathData.reduce((inside, val) => inside || diff --git a/src/client/views/InkingStroke.tsx b/src/client/views/InkingStroke.tsx index 52111c711..44048f377 100644 --- a/src/client/views/InkingStroke.tsx +++ b/src/client/views/InkingStroke.tsx @@ -48,9 +48,10 @@ export class InkingStroke extends React.Component { let pathStyle = this.createStyle(); let pathData = this.parseData(this.props.line); + let pointerEvents: any = InkingControl.Instance.selectedTool == InkTool.Eraser ? "all" : "none"; return ( - ) } -- cgit v1.2.3-70-g09d2 From c406c8d123ce0aa9d63fb8a4dd90adfe83d2889d Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Tue, 2 Apr 2019 23:38:59 -0400 Subject: fixed inking to have a moving 8192 window to maximize drawing area --- src/client/views/InkingCanvas.scss | 13 ++++----- src/client/views/InkingCanvas.tsx | 54 ++++++++++++++++++++++++++------------ src/client/views/InkingStroke.tsx | 8 +++--- 3 files changed, 48 insertions(+), 27 deletions(-) (limited to 'src') diff --git a/src/client/views/InkingCanvas.scss b/src/client/views/InkingCanvas.scss index 2128401b8..35c8ee942 100644 --- a/src/client/views/InkingCanvas.scss +++ b/src/client/views/InkingCanvas.scss @@ -2,18 +2,19 @@ .inkingCanvas-paths-ink, .inkingCanvas-paths-markers, .inkingCanvas-noSelect, .inkingCanvas-canSelect { position: absolute; - top: -4096px; - left: -4096px; width: 8192px; height: 8192px; - .inkingCanvas-children { - transform: translate(4096px, 4096px); - pointer-events: none; - } cursor:"crosshair"; pointer-events: auto; } +.inkingCanvas-canSelect, +.inkingCanvas-noSelect { + top:-50000px; + left:-50000px; + width: 100000px; + height: 100000px; +} .inkingCanvas-noSelect { pointer-events: none; cursor: "arrow"; diff --git a/src/client/views/InkingCanvas.tsx b/src/client/views/InkingCanvas.tsx index fcf6db390..cad4b74b1 100644 --- a/src/client/views/InkingCanvas.tsx +++ b/src/client/views/InkingCanvas.tsx @@ -1,4 +1,4 @@ -import { action, computed, trace } from "mobx"; +import { action, computed, trace, observable, runInAction } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../fields/Document"; import { FieldWaiting } from "../../fields/Field"; @@ -14,26 +14,40 @@ import React = require("react"); interface InkCanvasProps { getScreenTransform: () => Transform; Document: Document; + children: () => JSX.Element[]; } @observer export class InkingCanvas extends React.Component { - static InkOffset: number = 4096; + maxCanvasDim = 8192 / 2; // 1/2 of the maximum canvas dimension for Chrome + @observable inkMidX: number = 0; + @observable inkMidY: number = 0; private _currentStrokeId: string = ""; public static IntersectStrokeRect(stroke: StrokeData, selRect: { left: number, top: number, width: number, height: number }): boolean { - return stroke.pathData.reduce((inside, val) => inside || - (selRect.left < val.x - InkingCanvas.InkOffset && selRect.left + selRect.width > val.x - InkingCanvas.InkOffset && - selRect.top < val.y - InkingCanvas.InkOffset && selRect.top + selRect.height > val.y - InkingCanvas.InkOffset) + return stroke.pathData.reduce((inside: boolean, val) => inside || + (selRect.left < val.x && selRect.left + selRect.width > val.x && + selRect.top < val.y && selRect.top + selRect.height > val.y) , false); } + componentDidMount() { + this.props.Document.GetTAsync(KeyStore.Ink, InkField, ink => runInAction(() => { + if (ink) { + let bounds = Array.from(ink.Data).reduce(([mix, max, miy, may], [id, strokeData]) => + strokeData.pathData.reduce(([mix, max, miy, may], p) => + [Math.min(mix, p.x), Math.max(max, p.x), Math.min(miy, p.y), Math.max(may, p.y)], + [mix, max, miy, may]), + [Number.MAX_VALUE, Number.MIN_VALUE, Number.MAX_VALUE, Number.MIN_VALUE]); + this.inkMidX = (bounds[0] + bounds[1]) / 2; + this.inkMidY = (bounds[2] + bounds[3]) / 2; + } + })); + } + @computed get inkData(): StrokeMap { let map = this.props.Document.GetT(KeyStore.Ink, InkField); - if (!map || map === FieldWaiting) { - return new Map; - } - return new Map(map.Data); + return !map || map === FieldWaiting ? new Map : new Map(map.Data); } set inkData(value: StrokeMap) { @@ -63,9 +77,15 @@ export class InkingCanvas extends React.Component { } } + @action onPointerUp = (e: PointerEvent): void => { document.removeEventListener("pointermove", this.onPointerMove, true); document.removeEventListener("pointerup", this.onPointerUp, true); + let coord = this.relativeCoordinatesForEvent(e.clientX, e.clientY); + if (Math.abs(coord.x - this.inkMidX) > 500 || Math.abs(coord.y - this.inkMidY) > 500) { + this.inkMidX = coord.x; + this.inkMidY = coord.y; + } e.stopPropagation(); e.preventDefault(); } @@ -87,8 +107,6 @@ export class InkingCanvas extends React.Component { relativeCoordinatesForEvent = (ex: number, ey: number): { x: number, y: number } => { let [x, y] = this.props.getScreenTransform().transformPoint(ex, ey); - x += InkingCanvas.InkOffset; - y += InkingCanvas.InkOffset; return { x, y }; } @@ -101,30 +119,32 @@ export class InkingCanvas extends React.Component { @computed get drawnPaths() { - // parse data from server let curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1) let paths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => { if (strokeData.page == -1 || strokeData.page == curPage) paths.push() return paths; }, [] as JSX.Element[]); - return [ + return [ {paths.filter(path => path.props.tool == InkTool.Highlighter)} , - + {paths.filter(path => path.props.tool != InkTool.Highlighter)} ]; } render() { let svgCanvasStyle = InkingControl.Instance.selectedTool != InkTool.None ? "canSelect" : "noSelect"; - return (
    - - {(this.props.children as any)() /* bcz: is there a better way to know that children is a function? */} +
    + {this.props.children()} {this.drawnPaths}
    ) diff --git a/src/client/views/InkingStroke.tsx b/src/client/views/InkingStroke.tsx index 44048f377..615f8af7e 100644 --- a/src/client/views/InkingStroke.tsx +++ b/src/client/views/InkingStroke.tsx @@ -6,6 +6,8 @@ import React = require("react"); interface StrokeProps { + offsetX: number; + offsetY: number; id: string; line: Array<{ x: number, y: number }>; color: string; @@ -28,7 +30,7 @@ export class InkingStroke extends React.Component { } parseData = (line: Array<{ x: number, y: number }>): string => { - return !line.length ? "" : "M " + line.map(p => p.x + " " + p.y).join(" L "); + return !line.length ? "" : "M " + line.map(p => (p.x + this.props.offsetX) + " " + (p.y + this.props.offsetY)).join(" L "); } createStyle() { @@ -43,15 +45,13 @@ export class InkingStroke extends React.Component { } } - render() { let pathStyle = this.createStyle(); let pathData = this.parseData(this.props.line); let pointerEvents: any = InkingControl.Instance.selectedTool == InkTool.Eraser ? "all" : "none"; return ( - ) } -- cgit v1.2.3-70-g09d2 From 3b456da9c1d90abcfcf33fc6fd762cad1dff7ca7 Mon Sep 17 00:00:00 2001 From: bob Date: Wed, 3 Apr 2019 12:10:31 -0400 Subject: merged with changes to DocumentDecorations so you can minimize/maximize without menu --- src/client/views/DocumentDecorations.scss | 6 +++++- src/client/views/DocumentDecorations.tsx | 25 ++++++++++++++++++++++++- src/client/views/nodes/DocumentView.tsx | 14 +++++++------- 3 files changed, 36 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index c72623546..befe175b5 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -39,12 +39,16 @@ } .title{ background: lightblue; - grid-column-start:1; + grid-column-start:2; grid-column-end: 4; pointer-events: auto; } } +.documentDecorations-minimizeButton { + background: rgb(250, 57, 9); + pointer-events: all; +} .documentDecorations-background { background: lightblue; position: absolute; diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 572c265f3..b74737ec9 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -139,11 +139,33 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> e.preventDefault(); } + onMinimizeDown = (e: React.PointerEvent): void => { + e.stopPropagation(); + if (e.button === 0) { + document.removeEventListener("pointermove", this.onMinimizeMove); + document.addEventListener("pointermove", this.onMinimizeMove); + document.removeEventListener("pointerup", this.onMinimizeUp); + document.addEventListener("pointerup", this.onMinimizeUp); + } + } + onMinimizeMove = (e: PointerEvent): void => { + e.stopPropagation(); + if (e.button === 0) { + } + } + onMinimizeUp = (e: PointerEvent): void => { + e.stopPropagation(); + if (e.button === 0) { + SelectionManager.SelectedDocuments().map(dv => dv.minimize()); + document.removeEventListener("pointermove", this.onMinimizeMove); + document.removeEventListener("pointerup", this.onMinimizeUp); + } + } + onPointerDown = (e: React.PointerEvent): void => { e.stopPropagation(); if (e.button === 0) { this._isPointerDown = true; - console.log("Pointer down"); this._resizer = e.currentTarget.id; document.removeEventListener("pointermove", this.onPointerMove); document.addEventListener("pointermove", this.onPointerMove); @@ -339,6 +361,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> top: bounds.y - this._resizeBorderWidth / 2 - this._titleHeight, opacity: this._opacity }}> +
    v
    e.preventDefault()}>
    e.preventDefault()}>
    diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 2b9372e15..bc627015c 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -70,18 +70,18 @@ export function FakeJsxArgs(keys: string[], fields: string[] = []): JsxArgs { let Keys: { [name: string]: any } = {}; let Fields: { [name: string]: any } = {}; for (const key of keys) { - let fn = () => {}; + let fn = () => { }; Object.defineProperty(fn, "name", { value: key + "Key" }); Keys[key] = fn; } for (const field of fields) { - let fn = () => {}; + let fn = () => { }; Object.defineProperty(fn, "name", { value: field }); Fields[field] = fn; } let args: JsxArgs = { - Document: function Document() {}, - DocumentView: function DocumentView() {}, + Document: function Document() { }, + DocumentView: function DocumentView() { }, Keys, Fields } as any; @@ -115,7 +115,7 @@ export class DocumentView extends React.Component { return ( !this.props.ContainingCollectionView || this.props.ContainingCollectionView.collectionViewType == - CollectionViewType.Docking + CollectionViewType.Docking ); } @computed get layout(): string { @@ -233,7 +233,7 @@ export class DocumentView extends React.Component { }; DragManager.StartDocumentDrag([this._mainCont.current], dragData, { handlers: { - dragComplete: action(() => {}) + dragComplete: action(() => { }) }, hideSource: !dropAliasOfDraggedDoc }); @@ -307,7 +307,7 @@ export class DocumentView extends React.Component { }; @action - minimize = (e: React.MouseEvent): void => { + public minimize = (): void => { this.props.Document.SetData( KeyStore.Minimized, true as boolean, -- cgit v1.2.3-70-g09d2 From 1ebf40ba117ec063ff58ee750e6cc57aa3f3abfb Mon Sep 17 00:00:00 2001 From: bob Date: Wed, 3 Apr 2019 15:49:42 -0400 Subject: fixed pen ink. fixed alias dropping. switched PDFs to use svg --- src/client/views/InkingCanvas.tsx | 2 +- src/client/views/collections/CollectionViewBase.tsx | 3 ++- src/client/views/nodes/PDFBox.tsx | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/client/views/InkingCanvas.tsx b/src/client/views/InkingCanvas.tsx index cad4b74b1..45ca52d00 100644 --- a/src/client/views/InkingCanvas.tsx +++ b/src/client/views/InkingCanvas.tsx @@ -134,7 +134,7 @@ export class InkingCanvas extends React.Component { {paths.filter(path => path.props.tool == InkTool.Highlighter)} , + style={{ left: `${this.inkMidX - this.maxCanvasDim}px`, top: `${this.inkMidY - this.maxCanvasDim}px` }}> {paths.filter(path => path.props.tool != InkTool.Highlighter)} ]; } diff --git a/src/client/views/collections/CollectionViewBase.tsx b/src/client/views/collections/CollectionViewBase.tsx index 316d20c9d..2b0689800 100644 --- a/src/client/views/collections/CollectionViewBase.tsx +++ b/src/client/views/collections/CollectionViewBase.tsx @@ -82,7 +82,8 @@ export class CollectionViewBase extends React.Component if (de.data instanceof DragManager.DocumentDragData) { if (de.data.aliasOnDrop) { [KeyStore.Width, KeyStore.Height, KeyStore.CurPage].map(key => - de.data.draggedDocuments.GetTAsync(key, NumberField, (f: Opt) => f ? de.data.droppedDocument.SetNumber(key, f.Data) : null)); + de.data.draggedDocuments.map((draggedDocument: Document, i: number) => + draggedDocument.GetTAsync(key, NumberField, (f: Opt) => f ? de.data.droppedDocuments[i].SetNumber(key, f.Data) : null))); } let added = de.data.droppedDocuments.reduce((added, d) => this.props.addDocument(d, false), true); if (added && de.data.removeDocument && !de.data.aliasOnDrop) { diff --git a/src/client/views/nodes/PDFBox.tsx b/src/client/views/nodes/PDFBox.tsx index 28a1f9757..3cb3cf782 100644 --- a/src/client/views/nodes/PDFBox.tsx +++ b/src/client/views/nodes/PDFBox.tsx @@ -439,7 +439,7 @@ export class PDFBox extends React.Component { let pdfUrl = this.props.doc.GetT(this.props.fieldKey, PDFField); let xf = this.props.doc.GetNumber(KeyStore.NativeHeight, 0) / renderHeight; return
    - + {({ measureRef }) =>
    -- cgit v1.2.3-70-g09d2 From 52dade42e61a1d147bf43ece7f2b1d7b3d7b6b6a Mon Sep 17 00:00:00 2001 From: bob Date: Wed, 3 Apr 2019 16:12:31 -0400 Subject: changed boolean. and editor indentation. --- .vscode/settings.json | 3 +- src/client/views/nodes/DocumentView.tsx | 854 ++++++++++----------- src/fields/BooleanField.ts | 25 + src/fields/MinimizedField.tsx | 29 - src/server/ServerUtil.ts | 116 +-- src/server/database.ts | 10 +- .../upload_a6a70d84ebb65febf7900e29f52cc86d.pdf | Bin 0 -> 1043556 bytes 7 files changed, 509 insertions(+), 528 deletions(-) create mode 100644 src/fields/BooleanField.ts delete mode 100644 src/fields/MinimizedField.tsx create mode 100644 src/server/public/files/upload_a6a70d84ebb65febf7900e29f52cc86d.pdf (limited to 'src') diff --git a/.vscode/settings.json b/.vscode/settings.json index 081b05b38..fc315ffaf 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -7,6 +7,7 @@ "**/.DS_Store": true, }, "editor.formatOnSave": true, + "editor.detectIndentation": false, "typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets": false, "typescript.format.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces": true -} +} \ No newline at end of file diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index bc627015c..714ab9447 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -1,19 +1,13 @@ -import { - action, - computed, - IReactionDisposer, - reaction, - runInAction, - observable -} from "mobx"; -import { library } from "@fortawesome/fontawesome-svg-core"; +import { action, computed, IReactionDisposer, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; import { Document } from "../../../fields/Document"; -import { Field, Opt, FieldWaiting } from "../../../fields/Field"; +import { Field, FieldWaiting, Opt } from "../../../fields/Field"; import { Key } from "../../../fields/Key"; import { KeyStore } from "../../../fields/KeyStore"; import { ListField } from "../../../fields/ListField"; +import { BooleanField } from "../../../fields/BooleanField"; import { TextField } from "../../../fields/TextField"; +import { ServerUtils } from "../../../server/ServerUtil"; import { Utils } from "../../../Utils"; import { Documents } from "../../documents/Documents"; import { DocumentManager } from "../../util/DocumentManager"; @@ -21,34 +15,28 @@ import { DragManager } from "../../util/DragManager"; import { SelectionManager } from "../../util/SelectionManager"; import { Transform } from "../../util/Transform"; import { CollectionDockingView } from "../collections/CollectionDockingView"; -import { - CollectionView, - CollectionViewType -} from "../collections/CollectionView"; +import { CollectionView, CollectionViewType } from "../collections/CollectionView"; import { ContextMenu } from "../ContextMenu"; import { DocumentContentsView } from "./DocumentContentsView"; import "./DocumentView.scss"; import React = require("react"); -import { ServerUtils } from "../../../server/ServerUtil"; -import { DocumentDecorations } from "../DocumentDecorations"; -import { MinimizedField } from "../../../fields/MinimizedField"; export interface DocumentViewProps { - ContainingCollectionView: Opt; - Document: Document; - AddDocument?: (doc: Document, allowDuplicates: boolean) => boolean; - RemoveDocument?: (doc: Document) => boolean; - ScreenToLocalTransform: () => Transform; - isTopMost: boolean; - ContentScaling: () => number; - PanelWidth: () => number; - PanelHeight: () => number; - focus: (doc: Document) => void; - SelectOnLoad: boolean; + ContainingCollectionView: Opt; + Document: Document; + AddDocument?: (doc: Document, allowDuplicates: boolean) => boolean; + RemoveDocument?: (doc: Document) => boolean; + ScreenToLocalTransform: () => Transform; + isTopMost: boolean; + ContentScaling: () => number; + PanelWidth: () => number; + PanelHeight: () => number; + focus: (doc: Document) => void; + SelectOnLoad: boolean; } export interface JsxArgs extends DocumentViewProps { - Keys: { [name: string]: Key }; - Fields: { [name: string]: Field }; + Keys: { [name: string]: Key }; + Fields: { [name: string]: Field }; } /* @@ -67,448 +55,448 @@ Example usage of this function: } */ export function FakeJsxArgs(keys: string[], fields: string[] = []): JsxArgs { - let Keys: { [name: string]: any } = {}; - let Fields: { [name: string]: any } = {}; - for (const key of keys) { - let fn = () => { }; - Object.defineProperty(fn, "name", { value: key + "Key" }); - Keys[key] = fn; - } - for (const field of fields) { - let fn = () => { }; - Object.defineProperty(fn, "name", { value: field }); - Fields[field] = fn; - } - let args: JsxArgs = { - Document: function Document() { }, - DocumentView: function DocumentView() { }, - Keys, - Fields - } as any; - return args; + let Keys: { [name: string]: any } = {}; + let Fields: { [name: string]: any } = {}; + for (const key of keys) { + let fn = () => { }; + Object.defineProperty(fn, "name", { value: key + "Key" }); + Keys[key] = fn; + } + for (const field of fields) { + let fn = () => { }; + Object.defineProperty(fn, "name", { value: field }); + Fields[field] = fn; + } + let args: JsxArgs = { + Document: function Document() { }, + DocumentView: function DocumentView() { }, + Keys, + Fields + } as any; + return args; } export interface JsxBindings { - Document: Document; - isSelected: () => boolean; - select: (isCtrlPressed: boolean) => void; - isTopMost: boolean; - SelectOnLoad: boolean; - [prop: string]: any; + Document: Document; + isSelected: () => boolean; + select: (isCtrlPressed: boolean) => void; + isTopMost: boolean; + SelectOnLoad: boolean; + [prop: string]: any; } @observer export class DocumentView extends React.Component { - private _mainCont = React.createRef(); - private _downX: number = 0; - private _downY: number = 0; + private _mainCont = React.createRef(); + private _downX: number = 0; + private _downY: number = 0; - private _reactionDisposer: Opt; - @computed get active(): boolean { - return ( - SelectionManager.IsSelected(this) || - !this.props.ContainingCollectionView || - this.props.ContainingCollectionView.active() - ); - } - @computed get topMost(): boolean { - return ( - !this.props.ContainingCollectionView || - this.props.ContainingCollectionView.collectionViewType == - CollectionViewType.Docking - ); - } - @computed get layout(): string { - return this.props.Document.GetText( - KeyStore.Layout, - "

    Error loading layout data

    " - ); - } - @computed get layoutKeys(): Key[] { - return this.props.Document.GetData( - KeyStore.LayoutKeys, - ListField, - new Array() - ); - } - @computed get layoutFields(): Key[] { - return this.props.Document.GetData( - KeyStore.LayoutFields, - ListField, - new Array() - ); - } - screenRect = (): ClientRect | DOMRect => - this._mainCont.current - ? this._mainCont.current.getBoundingClientRect() - : new DOMRect(); - onPointerDown = (e: React.PointerEvent): void => { - this._downX = e.clientX; - this._downY = e.clientY; - if (e.shiftKey && e.buttons === 2) { - if (this.props.isTopMost) { - this.startDragging(e.pageX, e.pageY, e.altKey || e.ctrlKey); - } else - CollectionDockingView.Instance.StartOtherDrag([this.props.Document], e); - e.stopPropagation(); - } else { - if (this.active && !e.isDefaultPrevented()) { - e.stopPropagation(); - document.removeEventListener("pointermove", this.onPointerMove); - document.addEventListener("pointermove", this.onPointerMove); - document.removeEventListener("pointerup", this.onPointerUp); - document.addEventListener("pointerup", this.onPointerUp); - } + private _reactionDisposer: Opt; + @computed get active(): boolean { + return ( + SelectionManager.IsSelected(this) || + !this.props.ContainingCollectionView || + this.props.ContainingCollectionView.active() + ); + } + @computed get topMost(): boolean { + return ( + !this.props.ContainingCollectionView || + this.props.ContainingCollectionView.collectionViewType == + CollectionViewType.Docking + ); } - }; + @computed get layout(): string { + return this.props.Document.GetText( + KeyStore.Layout, + "

    Error loading layout data

    " + ); + } + @computed get layoutKeys(): Key[] { + return this.props.Document.GetData( + KeyStore.LayoutKeys, + ListField, + new Array() + ); + } + @computed get layoutFields(): Key[] { + return this.props.Document.GetData( + KeyStore.LayoutFields, + ListField, + new Array() + ); + } + screenRect = (): ClientRect | DOMRect => + this._mainCont.current + ? this._mainCont.current.getBoundingClientRect() + : new DOMRect(); + onPointerDown = (e: React.PointerEvent): void => { + this._downX = e.clientX; + this._downY = e.clientY; + if (e.shiftKey && e.buttons === 2) { + if (this.props.isTopMost) { + this.startDragging(e.pageX, e.pageY, e.altKey || e.ctrlKey); + } else + CollectionDockingView.Instance.StartOtherDrag([this.props.Document], e); + e.stopPropagation(); + } else { + if (this.active && !e.isDefaultPrevented()) { + e.stopPropagation(); + document.removeEventListener("pointermove", this.onPointerMove); + document.addEventListener("pointermove", this.onPointerMove); + document.removeEventListener("pointerup", this.onPointerUp); + document.addEventListener("pointerup", this.onPointerUp); + } + } + }; - private dropDisposer?: DragManager.DragDropDisposer; + private dropDisposer?: DragManager.DragDropDisposer; - componentDidMount() { - if (this._mainCont.current) { - this.dropDisposer = DragManager.MakeDropTarget(this._mainCont.current, { - handlers: { drop: this.drop.bind(this) } - }); + componentDidMount() { + if (this._mainCont.current) { + this.dropDisposer = DragManager.MakeDropTarget(this._mainCont.current, { + handlers: { drop: this.drop.bind(this) } + }); + } + runInAction(() => DocumentManager.Instance.DocumentViews.push(this)); + this._reactionDisposer = reaction( + () => + this.props.ContainingCollectionView && + this.props.ContainingCollectionView.SelectedDocs.slice(), + () => { + if ( + this.props.ContainingCollectionView && + this.props.ContainingCollectionView.SelectedDocs.indexOf( + this.props.Document.Id + ) != -1 + ) + SelectionManager.SelectDoc(this, true); + } + ); } - runInAction(() => DocumentManager.Instance.DocumentViews.push(this)); - this._reactionDisposer = reaction( - () => - this.props.ContainingCollectionView && - this.props.ContainingCollectionView.SelectedDocs.slice(), - () => { - if ( - this.props.ContainingCollectionView && - this.props.ContainingCollectionView.SelectedDocs.indexOf( - this.props.Document.Id - ) != -1 - ) - SelectionManager.SelectDoc(this, true); - } - ); - } - componentDidUpdate() { - if (this.dropDisposer) { - this.dropDisposer(); - } - if (this._mainCont.current) { - this.dropDisposer = DragManager.MakeDropTarget(this._mainCont.current, { - handlers: { drop: this.drop.bind(this) } - }); + componentDidUpdate() { + if (this.dropDisposer) { + this.dropDisposer(); + } + if (this._mainCont.current) { + this.dropDisposer = DragManager.MakeDropTarget(this._mainCont.current, { + handlers: { drop: this.drop.bind(this) } + }); + } } - } - componentWillUnmount() { - if (this.dropDisposer) { - this.dropDisposer(); + componentWillUnmount() { + if (this.dropDisposer) { + this.dropDisposer(); + } + runInAction(() => + DocumentManager.Instance.DocumentViews.splice( + DocumentManager.Instance.DocumentViews.indexOf(this), + 1 + ) + ); + if (this._reactionDisposer) { + this._reactionDisposer(); + } } - runInAction(() => - DocumentManager.Instance.DocumentViews.splice( - DocumentManager.Instance.DocumentViews.indexOf(this), - 1 - ) - ); - if (this._reactionDisposer) { - this._reactionDisposer(); + + startDragging(x: number, y: number, dropAliasOfDraggedDoc: boolean) { + if (this._mainCont.current) { + const [left, top] = this.props + .ScreenToLocalTransform() + .inverse() + .transformPoint(0, 0); + let dragData = new DragManager.DocumentDragData([this.props.Document]); + dragData.aliasOnDrop = dropAliasOfDraggedDoc; + dragData.xOffset = x - left; + dragData.yOffset = y - top; + dragData.removeDocument = (dropCollectionView: CollectionView) => { + if ( + this.props.RemoveDocument && + this.props.ContainingCollectionView !== dropCollectionView + ) { + this.props.RemoveDocument(this.props.Document); + } + }; + DragManager.StartDocumentDrag([this._mainCont.current], dragData, { + handlers: { + dragComplete: action(() => { }) + }, + hideSource: !dropAliasOfDraggedDoc + }); + } } - } - startDragging(x: number, y: number, dropAliasOfDraggedDoc: boolean) { - if (this._mainCont.current) { - const [left, top] = this.props - .ScreenToLocalTransform() - .inverse() - .transformPoint(0, 0); - let dragData = new DragManager.DocumentDragData([this.props.Document]); - dragData.aliasOnDrop = dropAliasOfDraggedDoc; - dragData.xOffset = x - left; - dragData.yOffset = y - top; - dragData.removeDocument = (dropCollectionView: CollectionView) => { + onPointerMove = (e: PointerEvent): void => { + if (e.cancelBubble) { + return; + } if ( - this.props.RemoveDocument && - this.props.ContainingCollectionView !== dropCollectionView + Math.abs(this._downX - e.clientX) > 3 || + Math.abs(this._downY - e.clientY) > 3 ) { - this.props.RemoveDocument(this.props.Document); + document.removeEventListener("pointermove", this.onPointerMove); + document.removeEventListener("pointerup", this.onPointerUp); + if (!this.topMost || e.buttons == 2 || e.altKey) { + this.startDragging(e.x, e.y, e.ctrlKey || e.altKey); + } } - }; - DragManager.StartDocumentDrag([this._mainCont.current], dragData, { - handlers: { - dragComplete: action(() => { }) - }, - hideSource: !dropAliasOfDraggedDoc - }); - } - } - - onPointerMove = (e: PointerEvent): void => { - if (e.cancelBubble) { - return; - } - if ( - Math.abs(this._downX - e.clientX) > 3 || - Math.abs(this._downY - e.clientY) > 3 - ) { - document.removeEventListener("pointermove", this.onPointerMove); - document.removeEventListener("pointerup", this.onPointerUp); - if (!this.topMost || e.buttons == 2 || e.altKey) { - this.startDragging(e.x, e.y, e.ctrlKey || e.altKey); - } - } - e.stopPropagation(); - e.preventDefault(); - }; - onPointerUp = (e: PointerEvent): void => { - document.removeEventListener("pointermove", this.onPointerMove); - document.removeEventListener("pointerup", this.onPointerUp); - e.stopPropagation(); - if ( - Math.abs(e.clientX - this._downX) < 4 && - Math.abs(e.clientY - this._downY) < 4 - ) { - SelectionManager.SelectDoc(this, e.ctrlKey); - } - }; - stopPropogation = (e: React.SyntheticEvent) => { - e.stopPropagation(); - }; + e.stopPropagation(); + e.preventDefault(); + }; + onPointerUp = (e: PointerEvent): void => { + document.removeEventListener("pointermove", this.onPointerMove); + document.removeEventListener("pointerup", this.onPointerUp); + e.stopPropagation(); + if ( + Math.abs(e.clientX - this._downX) < 4 && + Math.abs(e.clientY - this._downY) < 4 + ) { + SelectionManager.SelectDoc(this, e.ctrlKey); + } + }; + stopPropogation = (e: React.SyntheticEvent) => { + e.stopPropagation(); + }; - deleteClicked = (): void => { - if (this.props.RemoveDocument) { - this.props.RemoveDocument(this.props.Document); - } - }; + deleteClicked = (): void => { + if (this.props.RemoveDocument) { + this.props.RemoveDocument(this.props.Document); + } + }; - fieldsClicked = (e: React.MouseEvent): void => { - if (this.props.AddDocument) { - this.props.AddDocument( - Documents.KVPDocument(this.props.Document, { width: 300, height: 300 }), - false - ); - } - }; - fullScreenClicked = (e: React.MouseEvent): void => { - CollectionDockingView.Instance.OpenFullScreen(this.props.Document); - ContextMenu.Instance.clearItems(); - ContextMenu.Instance.addItem({ - description: "Close Full Screen", - event: this.closeFullScreenClicked - }); - ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); - }; + fieldsClicked = (e: React.MouseEvent): void => { + if (this.props.AddDocument) { + this.props.AddDocument( + Documents.KVPDocument(this.props.Document, { width: 300, height: 300 }), + false + ); + } + }; + fullScreenClicked = (e: React.MouseEvent): void => { + CollectionDockingView.Instance.OpenFullScreen(this.props.Document); + ContextMenu.Instance.clearItems(); + ContextMenu.Instance.addItem({ + description: "Close Full Screen", + event: this.closeFullScreenClicked + }); + ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); + }; - closeFullScreenClicked = (e: React.MouseEvent): void => { - CollectionDockingView.Instance.CloseFullScreen(); - ContextMenu.Instance.clearItems(); - ContextMenu.Instance.addItem({ - description: "Full Screen", - event: this.fullScreenClicked - }); - ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); - }; + closeFullScreenClicked = (e: React.MouseEvent): void => { + CollectionDockingView.Instance.CloseFullScreen(); + ContextMenu.Instance.clearItems(); + ContextMenu.Instance.addItem({ + description: "Full Screen", + event: this.fullScreenClicked + }); + ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); + }; - @action - public minimize = (): void => { - this.props.Document.SetData( - KeyStore.Minimized, - true as boolean, - MinimizedField - ); - SelectionManager.DeselectAll(); - }; + @action + public minimize = (): void => { + this.props.Document.SetData( + KeyStore.Minimized, + true as boolean, + BooleanField + ); + SelectionManager.DeselectAll(); + }; - @action - drop = (e: Event, de: DragManager.DropEvent) => { - if (de.data instanceof DragManager.LinkDragData) { - let sourceDoc: Document = de.data.linkSourceDocumentView.props.Document; - let destDoc: Document = this.props.Document; - if (this.props.isTopMost) { - return; - } - let linkDoc: Document = new Document(); + @action + drop = (e: Event, de: DragManager.DropEvent) => { + if (de.data instanceof DragManager.LinkDragData) { + let sourceDoc: Document = de.data.linkSourceDocumentView.props.Document; + let destDoc: Document = this.props.Document; + if (this.props.isTopMost) { + return; + } + let linkDoc: Document = new Document(); - destDoc.GetTAsync(KeyStore.Prototype, Document).then(protoDest => - sourceDoc.GetTAsync(KeyStore.Prototype, Document).then(protoSrc => - runInAction(() => { - linkDoc.Set(KeyStore.Title, new TextField("New Link")); - linkDoc.Set(KeyStore.LinkDescription, new TextField("")); - linkDoc.Set(KeyStore.LinkTags, new TextField("Default")); + destDoc.GetTAsync(KeyStore.Prototype, Document).then(protoDest => + sourceDoc.GetTAsync(KeyStore.Prototype, Document).then(protoSrc => + runInAction(() => { + linkDoc.Set(KeyStore.Title, new TextField("New Link")); + linkDoc.Set(KeyStore.LinkDescription, new TextField("")); + linkDoc.Set(KeyStore.LinkTags, new TextField("Default")); - let dstTarg = protoDest ? protoDest : destDoc; - let srcTarg = protoSrc ? protoSrc : sourceDoc; - linkDoc.Set(KeyStore.LinkedToDocs, dstTarg); - linkDoc.Set(KeyStore.LinkedFromDocs, srcTarg); - dstTarg.GetOrCreateAsync( - KeyStore.LinkedFromDocs, - ListField, - field => { - (field as ListField).Data.push(linkDoc); - } - ); - srcTarg.GetOrCreateAsync( - KeyStore.LinkedToDocs, - ListField, - field => { - (field as ListField).Data.push(linkDoc); - } + let dstTarg = protoDest ? protoDest : destDoc; + let srcTarg = protoSrc ? protoSrc : sourceDoc; + linkDoc.Set(KeyStore.LinkedToDocs, dstTarg); + linkDoc.Set(KeyStore.LinkedFromDocs, srcTarg); + dstTarg.GetOrCreateAsync( + KeyStore.LinkedFromDocs, + ListField, + field => { + (field as ListField).Data.push(linkDoc); + } + ); + srcTarg.GetOrCreateAsync( + KeyStore.LinkedToDocs, + ListField, + field => { + (field as ListField).Data.push(linkDoc); + } + ); + }) + ) ); - }) - ) - ); - e.stopPropagation(); - } - }; + e.stopPropagation(); + } + }; - onDrop = (e: React.DragEvent) => { - if (e.isDefaultPrevented()) { - return; - } - let text = e.dataTransfer.getData("text/plain"); - if (text && text.startsWith(" { + if (e.isDefaultPrevented()) { + return; + } + let text = e.dataTransfer.getData("text/plain"); + if (text && text.startsWith(" { - e.stopPropagation(); - let moved = - Math.abs(this._downX - e.clientX) > 3 || - Math.abs(this._downY - e.clientY) > 3; - if (moved || e.isDefaultPrevented()) { - e.preventDefault(); - return; - } - e.preventDefault(); + @action + onContextMenu = (e: React.MouseEvent): void => { + e.stopPropagation(); + let moved = + Math.abs(this._downX - e.clientX) > 3 || + Math.abs(this._downY - e.clientY) > 3; + if (moved || e.isDefaultPrevented()) { + e.preventDefault(); + return; + } + e.preventDefault(); - if (!this.isMinimized()) { - ContextMenu.Instance.addItem({ - description: "Minimize", - event: this.minimize - }); - } - ContextMenu.Instance.addItem({ - description: "Full Screen", - event: this.fullScreenClicked - }); - ContextMenu.Instance.addItem({ - description: "Fields", - event: this.fieldsClicked - }); - ContextMenu.Instance.addItem({ - description: "Center", - event: () => this.props.focus(this.props.Document) - }); - ContextMenu.Instance.addItem({ - description: "Open Right", - event: () => - CollectionDockingView.Instance.AddRightSplit(this.props.Document) - }); - ContextMenu.Instance.addItem({ - description: "Copy URL", - event: () => { - Utils.CopyText(ServerUtils.prepend("/doc/" + this.props.Document.Id)); - } - }); - ContextMenu.Instance.addItem({ - description: "Copy ID", - event: () => { - Utils.CopyText(this.props.Document.Id); - } - }); - //ContextMenu.Instance.addItem({ description: "Docking", event: () => this.props.Document.SetNumber(KeyStore.ViewType, CollectionViewType.Docking) }) - ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); - if (!this.topMost) { - // DocumentViews should stop propagation of this event - e.stopPropagation(); - } + if (!this.isMinimized()) { + ContextMenu.Instance.addItem({ + description: "Minimize", + event: this.minimize + }); + } + ContextMenu.Instance.addItem({ + description: "Full Screen", + event: this.fullScreenClicked + }); + ContextMenu.Instance.addItem({ + description: "Fields", + event: this.fieldsClicked + }); + ContextMenu.Instance.addItem({ + description: "Center", + event: () => this.props.focus(this.props.Document) + }); + ContextMenu.Instance.addItem({ + description: "Open Right", + event: () => + CollectionDockingView.Instance.AddRightSplit(this.props.Document) + }); + ContextMenu.Instance.addItem({ + description: "Copy URL", + event: () => { + Utils.CopyText(ServerUtils.prepend("/doc/" + this.props.Document.Id)); + } + }); + ContextMenu.Instance.addItem({ + description: "Copy ID", + event: () => { + Utils.CopyText(this.props.Document.Id); + } + }); + //ContextMenu.Instance.addItem({ description: "Docking", event: () => this.props.Document.SetNumber(KeyStore.ViewType, CollectionViewType.Docking) }) + ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); + if (!this.topMost) { + // DocumentViews should stop propagation of this event + e.stopPropagation(); + } - ContextMenu.Instance.addItem({ - description: "Delete", - event: this.deleteClicked - }); - ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); - SelectionManager.SelectDoc(this, e.ctrlKey); - }; + ContextMenu.Instance.addItem({ + description: "Delete", + event: this.deleteClicked + }); + ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); + SelectionManager.SelectDoc(this, e.ctrlKey); + }; - isMinimized = () => { - let field = this.props.Document.GetT(KeyStore.Minimized, MinimizedField); - if (field && field !== FieldWaiting) { - return field.Data; - } - }; + isMinimized = () => { + let field = this.props.Document.GetT(KeyStore.Minimized, BooleanField); + if (field && field !== FieldWaiting) { + return field.Data; + } + }; - @action - expand = () => { - this.props.Document.SetData( - KeyStore.Minimized, - false as boolean, - MinimizedField - ); - }; + @action + expand = () => { + this.props.Document.SetData( + KeyStore.Minimized, + false as boolean, + BooleanField + ); + }; - isSelected = () => { - return SelectionManager.IsSelected(this); - }; + isSelected = () => { + return SelectionManager.IsSelected(this); + }; - select = (ctrlPressed: boolean) => { - SelectionManager.SelectDoc(this, ctrlPressed); - }; + select = (ctrlPressed: boolean) => { + SelectionManager.SelectDoc(this, ctrlPressed); + }; - render() { - if (!this.props.Document) { - return null; - } + render() { + if (!this.props.Document) { + return null; + } - var scaling = this.props.ContentScaling(); - var nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 0); - var nativeHeight = this.props.Document.GetNumber(KeyStore.NativeHeight, 0); + var scaling = this.props.ContentScaling(); + var nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 0); + var nativeHeight = this.props.Document.GetNumber(KeyStore.NativeHeight, 0); - if (this.isMinimized()) { - return ( -
    - ); - } else { - var backgroundcolor = this.props.Document.GetText( - KeyStore.BackgroundColor, - "" - ); - return ( -
    0 ? nativeWidth.toString() + "px" : "100%", - height: nativeHeight > 0 ? nativeHeight.toString() + "px" : "100%", - transformOrigin: "left top", - transform: `scale(${scaling} , ${scaling})` - }} - onDrop={this.onDrop} - onContextMenu={this.onContextMenu} - onPointerDown={this.onPointerDown} - > - -
    - ); + if (this.isMinimized()) { + return ( +
    + ); + } else { + var backgroundcolor = this.props.Document.GetText( + KeyStore.BackgroundColor, + "" + ); + return ( +
    0 ? nativeWidth.toString() + "px" : "100%", + height: nativeHeight > 0 ? nativeHeight.toString() + "px" : "100%", + transformOrigin: "left top", + transform: `scale(${scaling} , ${scaling})` + }} + onDrop={this.onDrop} + onContextMenu={this.onContextMenu} + onPointerDown={this.onPointerDown} + > + +
    + ); + } } - } } diff --git a/src/fields/BooleanField.ts b/src/fields/BooleanField.ts new file mode 100644 index 000000000..7378b30a1 --- /dev/null +++ b/src/fields/BooleanField.ts @@ -0,0 +1,25 @@ +import { BasicField } from "./BasicField"; +import { FieldId } from "./Field"; +import { Types } from "../server/Message"; + +export class BooleanField extends BasicField { + constructor(data: boolean = false as boolean, id?: FieldId, save: boolean = true as boolean) { + super(data, save, id); + } + + ToScriptString(): string { + return `new BooleanField("${this.Data}")`; + } + + Copy() { + return new BooleanField(this.Data); + } + + ToJson(): { type: Types; data: boolean; _id: string } { + return { + type: Types.Minimized, + data: this.Data, + _id: this.Id + }; + } +} diff --git a/src/fields/MinimizedField.tsx b/src/fields/MinimizedField.tsx deleted file mode 100644 index 5dfb22e6e..000000000 --- a/src/fields/MinimizedField.tsx +++ /dev/null @@ -1,29 +0,0 @@ -import { BasicField } from "./BasicField"; -import { FieldId } from "./Field"; -import { Types } from "../server/Message"; - -export class MinimizedField extends BasicField { - constructor( - data: boolean = false as boolean, - id?: FieldId, - save: boolean = true as boolean - ) { - super(data, save, id); - } - - ToScriptString(): string { - return `new MinimizedField("${this.Data}")`; - } - - Copy() { - return new MinimizedField(this.Data); - } - - ToJson(): { type: Types; data: boolean; _id: string } { - return { - type: Types.Minimized, - data: this.Data, - _id: this.Id - }; - } -} diff --git a/src/server/ServerUtil.ts b/src/server/ServerUtil.ts index f3c5e1d1f..d3409abf4 100644 --- a/src/server/ServerUtil.ts +++ b/src/server/ServerUtil.ts @@ -16,69 +16,69 @@ import { VideoField } from "../fields/VideoField"; import { InkField } from "../fields/InkField"; import { PDFField } from "../fields/PDFField"; import { TupleField } from "../fields/TupleField"; -import { MinimizedField } from "../fields/MinimizedField"; +import { BooleanField } from "../fields/BooleanField"; import { HistogramField } from "../client/northstar/dash-fields/HistogramField"; export class ServerUtils { - public static prepend(extension: string): string { - return window.location.origin + extension; - } + public static prepend(extension: string): string { + return window.location.origin + extension; + } - public static FromJson(json: any): Field { - let obj = json; - let data: any = obj.data; - let id: string = obj._id; - let type: Types = obj.type; + public static FromJson(json: any): Field { + let obj = json; + let data: any = obj.data; + let id: string = obj._id; + let type: Types = obj.type; - if (!(data !== undefined && id && type !== undefined)) { - console.log( - "how did you manage to get an object that doesn't have a data or an id?" - ); - return new TextField("Something to fill the space", Utils.GenerateGuid()); - } + if (!(data !== undefined && id && type !== undefined)) { + console.log( + "how did you manage to get an object that doesn't have a data or an id?" + ); + return new TextField("Something to fill the space", Utils.GenerateGuid()); + } - switch (type) { - case Types.Minimized: - return new MinimizedField(data, id, false); - case Types.Number: - return new NumberField(data, id, false); - case Types.Text: - return new TextField(data, id, false); - case Types.Html: - return new HtmlField(data, id, false); - case Types.Web: - return new WebField(new URL(data), id, false); - case Types.RichText: - return new RichTextField(data, id, false); - case Types.Key: - return new Key(data, id, false); - case Types.Image: - return new ImageField(new URL(data), id, false); - case Types.HistogramOp: - return HistogramField.FromJson(id, data); - case Types.PDF: - return new PDFField(new URL(data), id, false); - case Types.List: - return ListField.FromJson(id, data); - case Types.Audio: - return new AudioField(new URL(data), id, false); - case Types.Video: - return new VideoField(new URL(data), id, false); - case Types.Tuple: - return new TupleField(data, id, false); - case Types.Ink: - return InkField.FromJson(id, data); - case Types.Document: - let doc: Document = new Document(id, false); - let fields: [string, string][] = data as [string, string][]; - fields.forEach(element => { - doc._proxies.set(element[0], element[1]); - }); - return doc; - default: - throw Error( - "Error, unrecognized field type received from server. If you just created a new field type, be sure to add it here" - ); + switch (type) { + case Types.Minimized: + return new BooleanField(data, id, false); + case Types.Number: + return new NumberField(data, id, false); + case Types.Text: + return new TextField(data, id, false); + case Types.Html: + return new HtmlField(data, id, false); + case Types.Web: + return new WebField(new URL(data), id, false); + case Types.RichText: + return new RichTextField(data, id, false); + case Types.Key: + return new Key(data, id, false); + case Types.Image: + return new ImageField(new URL(data), id, false); + case Types.HistogramOp: + return HistogramField.FromJson(id, data); + case Types.PDF: + return new PDFField(new URL(data), id, false); + case Types.List: + return ListField.FromJson(id, data); + case Types.Audio: + return new AudioField(new URL(data), id, false); + case Types.Video: + return new VideoField(new URL(data), id, false); + case Types.Tuple: + return new TupleField(data, id, false); + case Types.Ink: + return InkField.FromJson(id, data); + case Types.Document: + let doc: Document = new Document(id, false); + let fields: [string, string][] = data as [string, string][]; + fields.forEach(element => { + doc._proxies.set(element[0], element[1]); + }); + return doc; + default: + throw Error( + "Error, unrecognized field type received from server. If you just created a new field type, be sure to add it here" + ); + } } - } } diff --git a/src/server/database.ts b/src/server/database.ts index a42d29aac..616251c72 100644 --- a/src/server/database.ts +++ b/src/server/database.ts @@ -1,8 +1,4 @@ -import { action, configure } from 'mobx'; import * as mongodb from 'mongodb'; -import { ObjectID } from 'mongodb'; -import { Transferable } from './Message'; -import { Utils } from '../Utils'; export class Database { public static Instance = new Database() @@ -26,9 +22,9 @@ export class Database { console.log(err.message); console.log(err.errmsg); } - if (res) { - console.log(JSON.stringify(res.result)); - } + // if (res) { + // console.log(JSON.stringify(res.result)); + // } callback() }); } diff --git a/src/server/public/files/upload_a6a70d84ebb65febf7900e29f52cc86d.pdf b/src/server/public/files/upload_a6a70d84ebb65febf7900e29f52cc86d.pdf new file mode 100644 index 000000000..dfd6ab339 Binary files /dev/null and b/src/server/public/files/upload_a6a70d84ebb65febf7900e29f52cc86d.pdf differ -- cgit v1.2.3-70-g09d2 From b78aff5115862cbfa5e704422cb738aa7fd73c64 Mon Sep 17 00:00:00 2001 From: bob Date: Thu, 4 Apr 2019 14:13:29 -0400 Subject: fixed a number of smaller issues related to linking --- src/client/northstar/dash-nodes/HistogramBox.scss | 5 + src/client/util/DragManager.ts | 533 +++++++------- src/client/util/SelectionManager.ts | 74 +- src/client/views/DocumentDecorations.scss | 61 +- src/client/views/DocumentDecorations.tsx | 81 ++- src/client/views/InkingCanvas.scss | 2 + src/client/views/Main.scss | 7 + .../views/collections/CollectionDockingView.scss | 2 +- .../views/collections/CollectionPDFView.scss | 2 + .../views/collections/CollectionVideoView.scss | 2 + .../views/collections/CollectionViewBase.tsx | 20 + .../CollectionFreeFormLinkView.tsx | 8 +- .../CollectionFreeFormLinksView.scss | 2 + .../collectionFreeForm/CollectionFreeFormView.scss | 6 +- .../collectionFreeForm/CollectionFreeFormView.tsx | 13 +- .../collectionFreeForm/MarqueeView.scss | 2 + .../collectionFreeForm/PreviewCursor.scss | 4 + .../views/nodes/CollectionFreeFormDocumentView.tsx | 4 + src/client/views/nodes/DocumentView.scss | 2 + src/client/views/nodes/PDFBox.scss | 4 + src/client/views/nodes/WebBox.scss | 2 + src/fields/Document.ts | 773 +++++++++++---------- 22 files changed, 882 insertions(+), 727 deletions(-) (limited to 'src') diff --git a/src/client/northstar/dash-nodes/HistogramBox.scss b/src/client/northstar/dash-nodes/HistogramBox.scss index b11840a65..94da36e29 100644 --- a/src/client/northstar/dash-nodes/HistogramBox.scss +++ b/src/client/northstar/dash-nodes/HistogramBox.scss @@ -1,6 +1,8 @@ .histogrambox-container { padding: 0vw; position: absolute; + top: 0; + left:0; text-align: center; width: 100%; height: 100%; @@ -8,6 +10,7 @@ } .histogrambox-xaxislabel { position:absolute; + left:0; width:100%; text-align: center; bottom:0; @@ -19,11 +22,13 @@ position:absolute; height:100%; width: 25px; + left:0; bottom:0; background: lightgray; } .histogrambox-yaxislabel-text { position:absolute; + left:0; transform-origin: left; transform: rotate(-90deg); text-align: center; diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index c0f482e18..e8f8cce7c 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -8,304 +8,307 @@ import { CollectionView } from "../views/collections/CollectionView"; import { DocumentView } from "../views/nodes/DocumentView"; export function setupDrag( - _reference: React.RefObject, - docFunc: () => Document, - removeFunc: (containingCollection: CollectionView) => void = () => {} + _reference: React.RefObject, + docFunc: () => Document, + removeFunc: (containingCollection: CollectionView) => void = () => { } ) { - let onRowMove = action( - (e: PointerEvent): void => { - e.stopPropagation(); - e.preventDefault(); + let onRowMove = action( + (e: PointerEvent): void => { + e.stopPropagation(); + e.preventDefault(); - document.removeEventListener("pointermove", onRowMove); - document.removeEventListener("pointerup", onRowUp); - var dragData = new DragManager.DocumentDragData([docFunc()]); - dragData.removeDocument = removeFunc; - DragManager.StartDocumentDrag([_reference.current!], dragData); - } - ); - let onRowUp = action( - (e: PointerEvent): void => { - document.removeEventListener("pointermove", onRowMove); - document.removeEventListener("pointerup", onRowUp); - } - ); - let onItemDown = (e: React.PointerEvent) => { - // if (this.props.isSelected() || this.props.isTopMost) { - if (e.button == 0) { - e.stopPropagation(); - if (e.shiftKey) { - CollectionDockingView.Instance.StartOtherDrag([docFunc()], e); - } else { - document.addEventListener("pointermove", onRowMove); - document.addEventListener("pointerup", onRowUp); - } - } - //} - }; - return onItemDown; + document.removeEventListener("pointermove", onRowMove); + document.removeEventListener("pointerup", onRowUp); + var dragData = new DragManager.DocumentDragData([docFunc()]); + dragData.removeDocument = removeFunc; + DragManager.StartDocumentDrag([_reference.current!], dragData); + } + ); + let onRowUp = action( + (e: PointerEvent): void => { + document.removeEventListener("pointermove", onRowMove); + document.removeEventListener("pointerup", onRowUp); + } + ); + let onItemDown = (e: React.PointerEvent) => { + // if (this.props.isSelected() || this.props.isTopMost) { + if (e.button == 0) { + e.stopPropagation(); + if (e.shiftKey) { + CollectionDockingView.Instance.StartOtherDrag([docFunc()], e); + } else { + document.addEventListener("pointermove", onRowMove); + document.addEventListener("pointerup", onRowUp); + } + } + //} + }; + return onItemDown; } export namespace DragManager { - export function Root() { - const root = document.getElementById("root"); - if (!root) { - throw new Error("No root element found"); + export function Root() { + const root = document.getElementById("root"); + if (!root) { + throw new Error("No root element found"); + } + return root; } - return root; - } - let dragDiv: HTMLDivElement; + let dragDiv: HTMLDivElement; - export enum DragButtons { - Left = 1, - Right = 2, - Both = Left | Right - } + export enum DragButtons { + Left = 1, + Right = 2, + Both = Left | Right + } - interface DragOptions { - handlers: DragHandlers; + interface DragOptions { + handlers: DragHandlers; - hideSource: boolean | (() => boolean); - } + hideSource: boolean | (() => boolean); + } - export interface DragDropDisposer { - (): void; - } + export interface DragDropDisposer { + (): void; + } - export class DragCompleteEvent {} + export class DragCompleteEvent { } - export interface DragHandlers { - dragComplete: (e: DragCompleteEvent) => void; - } + export interface DragHandlers { + dragComplete: (e: DragCompleteEvent) => void; + } - export interface DropOptions { - handlers: DropHandlers; - } - export class DropEvent { - constructor( - readonly x: number, - readonly y: number, - readonly data: { [id: string]: any } - ) {} - } + export interface DropOptions { + handlers: DropHandlers; + } + export class DropEvent { + constructor( + readonly x: number, + readonly y: number, + readonly data: { [id: string]: any } + ) { } + } - export interface DropHandlers { - drop: (e: Event, de: DropEvent) => void; - } + export interface DropHandlers { + drop: (e: Event, de: DropEvent) => void; + } - export function MakeDropTarget( - element: HTMLElement, - options: DropOptions - ): DragDropDisposer { - if ("canDrop" in element.dataset) { - throw new Error( - "Element is already droppable, can't make it droppable again" - ); + export function MakeDropTarget( + element: HTMLElement, + options: DropOptions + ): DragDropDisposer { + if ("canDrop" in element.dataset) { + throw new Error( + "Element is already droppable, can't make it droppable again" + ); + } + element.dataset["canDrop"] = "true"; + const handler = (e: Event) => { + const ce = e as CustomEvent; + options.handlers.drop(e, ce.detail); + }; + element.addEventListener("dashOnDrop", handler); + return () => { + element.removeEventListener("dashOnDrop", handler); + delete element.dataset["canDrop"]; + }; } - element.dataset["canDrop"] = "true"; - const handler = (e: Event) => { - const ce = e as CustomEvent; - options.handlers.drop(e, ce.detail); - }; - element.addEventListener("dashOnDrop", handler); - return () => { - element.removeEventListener("dashOnDrop", handler); - delete element.dataset["canDrop"]; - }; - } - export class DocumentDragData { - constructor(dragDoc: Document[]) { - this.draggedDocuments = dragDoc; - this.droppedDocuments = dragDoc; + export class DocumentDragData { + constructor(dragDoc: Document[]) { + this.draggedDocuments = dragDoc; + this.droppedDocuments = dragDoc; + } + draggedDocuments: Document[]; + droppedDocuments: Document[]; + xOffset?: number; + yOffset?: number; + aliasOnDrop?: boolean; + removeDocument?: (collectionDrop: CollectionView) => void; + [id: string]: any; } - draggedDocuments: Document[]; - droppedDocuments: Document[]; - xOffset?: number; - yOffset?: number; - aliasOnDrop?: boolean; - removeDocument?: (collectionDrop: CollectionView) => void; - [id: string]: any; - } - export function StartDocumentDrag( - eles: HTMLElement[], - dragData: DocumentDragData, - options?: DragOptions - ) { - StartDrag( - eles, - dragData, - options, - (dropData: { [id: string]: any }) => - (dropData.droppedDocuments = dragData.aliasOnDrop - ? dragData.draggedDocuments.map(d => d.CreateAlias()) - : dragData.draggedDocuments) - ); - } + export function StartDocumentDrag( + eles: HTMLElement[], + dragData: DocumentDragData, + options?: DragOptions + ) { + StartDrag( + eles, + dragData, + options, + (dropData: { [id: string]: any }) => + (dropData.droppedDocuments = dragData.aliasOnDrop + ? dragData.draggedDocuments.map(d => d.CreateAlias()) + : dragData.draggedDocuments) + ); + } - export class LinkDragData { - constructor(linkSourceDoc: DocumentView) { - this.linkSourceDocumentView = linkSourceDoc; + export class LinkDragData { + constructor(linkSourceDoc: DocumentView) { + this.linkSourceDocumentView = linkSourceDoc; + } + droppedDocuments: Document[] = []; + linkSourceDocumentView: DocumentView; + [id: string]: any; } - linkSourceDocumentView: DocumentView; - [id: string]: any; - } - export function StartLinkDrag( - ele: HTMLElement, - dragData: LinkDragData, - options?: DragOptions - ) { - StartDrag([ele], dragData, options); - } - function StartDrag( - eles: HTMLElement[], - dragData: { [id: string]: any }, - options?: DragOptions, - finishDrag?: (dropData: { [id: string]: any }) => void - ) { - if (!dragDiv) { - dragDiv = document.createElement("div"); - dragDiv.className = "dragManager-dragDiv"; - DragManager.Root().appendChild(dragDiv); + export function StartLinkDrag( + ele: HTMLElement, + dragData: LinkDragData, + options?: DragOptions + ) { + StartDrag([ele], dragData, options); } + function StartDrag( + eles: HTMLElement[], + dragData: { [id: string]: any }, + options?: DragOptions, + finishDrag?: (dropData: { [id: string]: any }) => void + ) { + if (!dragDiv) { + dragDiv = document.createElement("div"); + dragDiv.className = "dragManager-dragDiv"; + DragManager.Root().appendChild(dragDiv); + } - let scaleXs: number[] = []; - let scaleYs: number[] = []; - let xs: number[] = []; - let ys: number[] = []; + let scaleXs: number[] = []; + let scaleYs: number[] = []; + let xs: number[] = []; + let ys: number[] = []; - const docs: Document[] = - dragData instanceof DocumentDragData ? dragData.draggedDocuments : []; - let dragElements = eles.map(ele => { - const w = ele.offsetWidth, - h = ele.offsetHeight; - const rect = ele.getBoundingClientRect(); - const scaleX = rect.width / w, - scaleY = rect.height / h; - let x = rect.left, - y = rect.top; - xs.push(x); - ys.push(y); - scaleXs.push(scaleX); - scaleYs.push(scaleY); - let dragElement = ele.cloneNode(true) as HTMLElement; - dragElement.style.opacity = "0.7"; - dragElement.style.position = "absolute"; - dragElement.style.bottom = ""; - dragElement.style.left = ""; - dragElement.style.transformOrigin = "0 0"; - dragElement.style.zIndex = "1000"; - dragElement.style.transform = `translate(${x}px, ${y}px) scale(${scaleX}, ${scaleY})`; - dragElement.style.width = `${rect.width / scaleX}px`; - dragElement.style.height = `${rect.height / scaleY}px`; + const docs: Document[] = + dragData instanceof DocumentDragData ? dragData.draggedDocuments : []; + let dragElements = eles.map(ele => { + const w = ele.offsetWidth, + h = ele.offsetHeight; + const rect = ele.getBoundingClientRect(); + const scaleX = rect.width / w, + scaleY = rect.height / h; + let x = rect.left, + y = rect.top; + xs.push(x); + ys.push(y); + scaleXs.push(scaleX); + scaleYs.push(scaleY); + let dragElement = ele.cloneNode(true) as HTMLElement; + dragElement.style.opacity = "0.7"; + dragElement.style.position = "absolute"; + dragElement.style.margin = "0"; + dragElement.style.top = "0"; + dragElement.style.bottom = ""; + dragElement.style.left = "0"; + dragElement.style.transformOrigin = "0 0"; + dragElement.style.zIndex = "1000"; + dragElement.style.transform = `translate(${x}px, ${y}px) scale(${scaleX}, ${scaleY})`; + dragElement.style.width = `${rect.width / scaleX}px`; + dragElement.style.height = `${rect.height / scaleY}px`; - // bcz: PDFs don't show up if you clone them because they contain a canvas. - // however, PDF's have a thumbnail field that contains an image of their canvas. - // So we replace the pdf's canvas with the image thumbnail - if (docs.length) { - var pdfBox = dragElement.getElementsByClassName( - "pdfBox-cont" - )[0] as HTMLElement; - let thumbnail = docs[0].GetT(KeyStore.Thumbnail, ImageField); - if (pdfBox && pdfBox.childElementCount && thumbnail) { - let img = new Image(); - img!.src = thumbnail.toString(); - img!.style.position = "absolute"; - img!.style.width = `${rect.width / scaleX}px`; - img!.style.height = `${rect.height / scaleY}px`; - pdfBox.replaceChild(img!, pdfBox.children[0]); + // bcz: PDFs don't show up if you clone them because they contain a canvas. + // however, PDF's have a thumbnail field that contains an image of their canvas. + // So we replace the pdf's canvas with the image thumbnail + if (docs.length) { + var pdfBox = dragElement.getElementsByClassName( + "pdfBox-cont" + )[0] as HTMLElement; + let thumbnail = docs[0].GetT(KeyStore.Thumbnail, ImageField); + if (pdfBox && pdfBox.childElementCount && thumbnail) { + let img = new Image(); + img!.src = thumbnail.toString(); + img!.style.position = "absolute"; + img!.style.width = `${rect.width / scaleX}px`; + img!.style.height = `${rect.height / scaleY}px`; + pdfBox.replaceChild(img!, pdfBox.children[0]); + } + } + + dragDiv.appendChild(dragElement); + return dragElement; + }); + + let hideSource = false; + if (options) { + if (typeof options.hideSource === "boolean") { + hideSource = options.hideSource; + } else { + hideSource = options.hideSource(); + } } - } + eles.map(ele => (ele.hidden = hideSource)); - dragDiv.appendChild(dragElement); - return dragElement; - }); + const moveHandler = (e: PointerEvent) => { + e.stopPropagation(); + e.preventDefault(); + if (dragData instanceof DocumentDragData) + dragData.aliasOnDrop = e.ctrlKey || e.altKey; + if (e.shiftKey) { + abortDrag(); + CollectionDockingView.Instance.StartOtherDrag(docs, { + pageX: e.pageX, + pageY: e.pageY, + preventDefault: () => { }, + button: 0 + }); + } + dragElements.map( + (dragElement, i) => + (dragElement.style.transform = `translate(${(xs[i] += + e.movementX)}px, ${(ys[i] += e.movementY)}px) scale(${ + scaleXs[i] + }, ${scaleYs[i]})`) + ); + }; - let hideSource = false; - if (options) { - if (typeof options.hideSource === "boolean") { - hideSource = options.hideSource; - } else { - hideSource = options.hideSource(); - } + const abortDrag = () => { + document.removeEventListener("pointermove", moveHandler, true); + document.removeEventListener("pointerup", upHandler); + dragElements.map(dragElement => dragDiv.removeChild(dragElement)); + eles.map(ele => (ele.hidden = false)); + }; + const upHandler = (e: PointerEvent) => { + abortDrag(); + FinishDrag(eles, e, dragData, options, finishDrag); + }; + document.addEventListener("pointermove", moveHandler, true); + document.addEventListener("pointerup", upHandler); } - eles.map(ele => (ele.hidden = hideSource)); - const moveHandler = (e: PointerEvent) => { - e.stopPropagation(); - e.preventDefault(); - if (dragData instanceof DocumentDragData) - dragData.aliasOnDrop = e.ctrlKey || e.altKey; - if (e.shiftKey) { - abortDrag(); - CollectionDockingView.Instance.StartOtherDrag(docs, { - pageX: e.pageX, - pageY: e.pageY, - preventDefault: () => {}, - button: 0 + function FinishDrag( + dragEles: HTMLElement[], + e: PointerEvent, + dragData: { [index: string]: any }, + options?: DragOptions, + finishDrag?: (dragData: { [index: string]: any }) => void + ) { + let removed = dragEles.map(dragEle => { + let parent = dragEle.parentElement; + if (parent) parent.removeChild(dragEle); + return [dragEle, parent]; }); - } - dragElements.map( - (dragElement, i) => - (dragElement.style.transform = `translate(${(xs[i] += - e.movementX)}px, ${(ys[i] += e.movementY)}px) scale(${ - scaleXs[i] - }, ${scaleYs[i]})`) - ); - }; - - const abortDrag = () => { - document.removeEventListener("pointermove", moveHandler, true); - document.removeEventListener("pointerup", upHandler); - dragElements.map(dragElement => dragDiv.removeChild(dragElement)); - eles.map(ele => (ele.hidden = false)); - }; - const upHandler = (e: PointerEvent) => { - abortDrag(); - FinishDrag(eles, e, dragData, options, finishDrag); - }; - document.addEventListener("pointermove", moveHandler, true); - document.addEventListener("pointerup", upHandler); - } - - function FinishDrag( - dragEles: HTMLElement[], - e: PointerEvent, - dragData: { [index: string]: any }, - options?: DragOptions, - finishDrag?: (dragData: { [index: string]: any }) => void - ) { - let removed = dragEles.map(dragEle => { - let parent = dragEle.parentElement; - if (parent) parent.removeChild(dragEle); - return [dragEle, parent]; - }); - const target = document.elementFromPoint(e.x, e.y); - removed.map(r => { - let dragEle: HTMLElement = r[0]!; - let parent: HTMLElement | null = r[1]; - if (parent) parent.appendChild(dragEle); - }); - if (target) { - if (finishDrag) finishDrag(dragData); + const target = document.elementFromPoint(e.x, e.y); + removed.map(r => { + let dragEle: HTMLElement = r[0]!; + let parent: HTMLElement | null = r[1]; + if (parent) parent.appendChild(dragEle); + }); + if (target) { + if (finishDrag) finishDrag(dragData); - target.dispatchEvent( - new CustomEvent("dashOnDrop", { - bubbles: true, - detail: { - x: e.x, - y: e.y, - data: dragData - } - }) - ); + target.dispatchEvent( + new CustomEvent("dashOnDrop", { + bubbles: true, + detail: { + x: e.x, + y: e.y, + data: dragData + } + }) + ); - if (options) { - options.handlers.dragComplete({}); - } + if (options) { + options.handlers.dragComplete({}); + } + } + DocumentDecorations.Instance.Hidden = false; } - DocumentDecorations.Instance.Hidden = false; - } } diff --git a/src/client/util/SelectionManager.ts b/src/client/util/SelectionManager.ts index 438659108..958c14491 100644 --- a/src/client/util/SelectionManager.ts +++ b/src/client/util/SelectionManager.ts @@ -3,48 +3,46 @@ import { DocumentView } from "../views/nodes/DocumentView"; import { Document } from "../../fields/Document"; export namespace SelectionManager { - class Manager { - @observable - SelectedDocuments: Array = []; - - @action - SelectDoc(doc: DocumentView, ctrlPressed: boolean): void { - // if doc is not in SelectedDocuments, add it - if (!ctrlPressed) { - manager.SelectedDocuments = []; - } - - if (manager.SelectedDocuments.indexOf(doc) === -1) { - manager.SelectedDocuments.push(doc); - } + class Manager { + @observable + SelectedDocuments: Array = []; + + @action + SelectDoc(doc: DocumentView, ctrlPressed: boolean): void { + // if doc is not in SelectedDocuments, add it + if (!ctrlPressed) { + manager.SelectedDocuments = []; + } + + if (manager.SelectedDocuments.indexOf(doc) === -1) { + manager.SelectedDocuments.push(doc); + } + } } - } - const manager = new Manager(); + const manager = new Manager(); - export function SelectDoc(doc: DocumentView, ctrlPressed: boolean): void { - if (!doc.isMinimized()) { - manager.SelectDoc(doc, ctrlPressed); + export function SelectDoc(doc: DocumentView, ctrlPressed: boolean): void { + manager.SelectDoc(doc, ctrlPressed); } - } - - export function IsSelected(doc: DocumentView): boolean { - return manager.SelectedDocuments.indexOf(doc) !== -1; - } - - export function DeselectAll(except?: Document): void { - let found: DocumentView | undefined = undefined; - if (except) { - for (let i = 0; i < manager.SelectedDocuments.length; i++) { - let view = manager.SelectedDocuments[i]; - if (view.props.Document == except) found = view; - } + + export function IsSelected(doc: DocumentView): boolean { + return manager.SelectedDocuments.indexOf(doc) !== -1; + } + + export function DeselectAll(except?: Document): void { + let found: DocumentView | undefined = undefined; + if (except) { + for (let i = 0; i < manager.SelectedDocuments.length; i++) { + let view = manager.SelectedDocuments[i]; + if (view.props.Document == except) found = view; + } + } + manager.SelectedDocuments.length = 0; + if (found) manager.SelectedDocuments.push(found); } - manager.SelectedDocuments.length = 0; - if (found) manager.SelectedDocuments.push(found); - } - export function SelectedDocuments(): Array { - return manager.SelectedDocuments; - } + export function SelectedDocuments(): Array { + return manager.SelectedDocuments; + } } diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index befe175b5..080c9fa1e 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -2,13 +2,16 @@ #documentDecorations-container { position: absolute; + top: 0; + left:0; display: grid; z-index: 1000; grid-template-rows: 20px 8px 1fr 8px; - grid-template-columns: 8px 1fr 8px; + grid-template-columns: 8px 8px 1fr 8px; pointer-events: none; #documentDecorations-centerCont { + grid-column:3; background: none; } @@ -18,6 +21,24 @@ opacity: 0.8; } + #documentDecorations-topLeftResizer, + #documentDecorations-leftResizer, + #documentDecorations-bottomLeftResizer { + grid-column: 1 + } + + #documentDecorations-topResizer, + #documentDecorations-bottomResizer { + grid-column-start: 2; + grid-column-end: 4; + } + + #documentDecorations-bottomRightResizer, + #documentDecorations-topRightResizer, + #documentDecorations-rightResizer { + grid-column:4 + } + #documentDecorations-topLeftResizer, #documentDecorations-bottomRightResizer { cursor: nwse-resize; @@ -39,15 +60,19 @@ } .title{ background: lightblue; - grid-column-start:2; - grid-column-end: 4; + grid-column-start:3; + grid-column-end: 5; pointer-events: auto; } } .documentDecorations-minimizeButton { - background: rgb(250, 57, 9); + background:$alt-accent; + opacity: 0.8; + grid-column-start: 1; + grid-column-end: 3; pointer-events: all; + text-align: center; } .documentDecorations-background { background: lightblue; @@ -87,7 +112,8 @@ // } // } .linkFlyout { - grid-column: 1/4 + grid-column: 1/4; + margin-left: 25px; } .linkButton-empty:hover { @@ -102,6 +128,31 @@ cursor: pointer; } +.linkButton-linker { + position:absolute; + bottom:0px; + left: 0px; + height: 20px; + width: 20px; + margin-top: 10px; + margin-right: 5px; + border-radius: 50%; + opacity: 0.9; + pointer-events: auto; + color: $dark-color; + border: $dark-color 1px solid; + text-transform: uppercase; + letter-spacing: 2px; + font-size: 75%; + transition: transform 0.2s; + text-align: center; + display: flex; + justify-content: center; + align-items: center; +} +.linkButton-tray { + grid-column: 1/4; +} .linkButton-empty { height: 20px; width: 20px; diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index b74737ec9..a46087c9a 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -1,10 +1,11 @@ -import { action, computed, observable } from "mobx"; +import { action, computed, observable, trace, runInAction } from "mobx"; import { observer } from "mobx-react"; import { Key } from "../../fields/Key"; //import ContentEditable from 'react-contenteditable' import { KeyStore } from "../../fields/KeyStore"; import { ListField } from "../../fields/ListField"; import { NumberField } from "../../fields/NumberField"; +import { Document } from "../../fields/Document"; import { TextField } from "../../fields/TextField"; import { DragManager } from "../util/DragManager"; import { SelectionManager } from "../util/SelectionManager"; @@ -13,6 +14,7 @@ import './DocumentDecorations.scss'; import { DocumentView } from "./nodes/DocumentView"; import { LinkMenu } from "./nodes/LinkMenu"; import React = require("react"); +import { FieldWaiting } from "../../fields/Field"; const higflyout = require("@hig/flyout"); export const { anchorPoints } = higflyout; export const Flyout = higflyout.default; @@ -28,6 +30,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> private _linkBoxHeight = 30; private _titleHeight = 20; private _linkButton = React.createRef(); + private _linkerButton = React.createRef(); //@observable private _title: string = this._documents[0].props.Document.Title; @observable private _title: string = this._documents.length > 0 ? this._documents[0].props.Document.Title : ""; @observable private _fieldKey: Key = KeyStore.Title; @@ -174,18 +177,40 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> } } - onLinkButtonDown = (e: React.PointerEvent): void => { - // if () - // let linkMenu = new LinkMenu(SelectionManager.SelectedDocuments()[0]); - // linkMenu.Hidden = false; - console.log("down"); + onLinkerButtonDown = (e: React.PointerEvent): void => { + e.stopPropagation(); + document.removeEventListener("pointermove", this.onLinkerButtonMoved) + document.addEventListener("pointermove", this.onLinkerButtonMoved); + document.removeEventListener("pointerup", this.onLinkerButtonUp) + document.addEventListener("pointerup", this.onLinkerButtonUp); + } + onLinkerButtonUp = (e: PointerEvent): void => { + document.removeEventListener("pointermove", this.onLinkerButtonMoved) + document.removeEventListener("pointerup", this.onLinkerButtonUp) + e.stopPropagation(); + } + onLinkerButtonMoved = (e: PointerEvent): void => { + if (this._linkerButton.current != null) { + document.removeEventListener("pointermove", this.onLinkerButtonMoved) + document.removeEventListener("pointerup", this.onLinkerButtonUp) + let dragData = new DragManager.LinkDragData(SelectionManager.SelectedDocuments()[0]); + DragManager.StartLinkDrag(this._linkerButton.current, dragData, { + handlers: { + dragComplete: action(() => { }), + }, + hideSource: false + }) + } + e.stopPropagation(); + } + + onLinkButtonDown = (e: React.PointerEvent): void => { e.stopPropagation(); document.removeEventListener("pointermove", this.onLinkButtonMoved) document.addEventListener("pointermove", this.onLinkButtonMoved); document.removeEventListener("pointerup", this.onLinkButtonUp) document.addEventListener("pointerup", this.onLinkButtonUp); - } onLinkButtonUp = (e: PointerEvent): void => { @@ -194,18 +219,32 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> e.stopPropagation(); } - onLinkButtonMoved = (e: PointerEvent): void => { if (this._linkButton.current != null) { document.removeEventListener("pointermove", this.onLinkButtonMoved) - document.removeEventListener("pointerup", this.onLinkButtonUp) - let dragData = new DragManager.LinkDragData(SelectionManager.SelectedDocuments()[0]); - DragManager.StartLinkDrag(this._linkButton.current, dragData, { - handlers: { - dragComplete: action(() => { }), - }, - hideSource: false - }) + document.removeEventListener("pointerup", this.onLinkButtonUp); + + let sourceDoc = SelectionManager.SelectedDocuments()[0].props.Document; + let srcTarg = sourceDoc.GetT(KeyStore.Prototype, Document) + let draggedDocs = (srcTarg && srcTarg != FieldWaiting) ? + srcTarg.GetList(KeyStore.LinkedToDocs, [] as Document[]).map(linkDoc => + (linkDoc.GetT(KeyStore.LinkedToDocs, Document)) as Document) : []; + let draggedFromDocs = (srcTarg && srcTarg != FieldWaiting) ? + srcTarg.GetList(KeyStore.LinkedFromDocs, [] as Document[]).map(linkDoc => + (linkDoc.GetT(KeyStore.LinkedFromDocs, Document)) as Document) : []; + draggedDocs.push(...draggedFromDocs); + if (draggedDocs.length) { + let dragData = new DragManager.DocumentDragData(draggedDocs.map(d => { + let annot = d.GetT(KeyStore.AnnotationOn, Document); // bcz: ... needs to change ... the annotationOn document may not have been retrieved yet... + return annot && annot != FieldWaiting ? annot : d; + })); + DragManager.StartDocumentDrag([this._linkButton.current], dragData, { + handlers: { + dragComplete: action(() => { }), + }, + hideSource: false + }) + } } e.stopPropagation(); } @@ -298,7 +337,6 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> } getValue = (): string => { - console.log("value watched"); if (this._title === "changed" && this._documents.length > 0) { let field = this._documents[0].props.Document.Get(this._fieldKey); if (field instanceof TextField) { @@ -338,8 +376,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> linkButton = ( - + }>
    {linkCount}
    ); @@ -361,7 +398,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> top: bounds.y - this._resizeBorderWidth / 2 - this._titleHeight, opacity: this._opacity }}> -
    v
    +
    ...
    e.preventDefault()}>
    e.preventDefault()}>
    @@ -373,8 +410,8 @@ export class DocumentDecorations extends React.Component<{}, { value: string }>
    e.preventDefault()}>
    e.preventDefault()}>
    -
    {linkButton}
    - +
    {linkButton}
    +
    ) diff --git a/src/client/views/InkingCanvas.scss b/src/client/views/InkingCanvas.scss index 35c8ee942..c5a2a50cb 100644 --- a/src/client/views/InkingCanvas.scss +++ b/src/client/views/InkingCanvas.scss @@ -2,6 +2,8 @@ .inkingCanvas-paths-ink, .inkingCanvas-paths-markers, .inkingCanvas-noSelect, .inkingCanvas-canSelect { position: absolute; + top: 0; + left:0; width: 8192px; height: 8192px; cursor:"crosshair"; diff --git a/src/client/views/Main.scss b/src/client/views/Main.scss index 698a9c617..594803aab 100644 --- a/src/client/views/Main.scss +++ b/src/client/views/Main.scss @@ -7,6 +7,9 @@ body { overflow: hidden; font-family: $sans-serif; margin: 0; + position:absolute; + top: 0; + left:0; } #dash-title { @@ -158,11 +161,15 @@ button:hover { width:100%; height:100%; position:absolute; + top: 0; + left:0; } #mainContent-div { width:100%; height:100%; position:absolute; + top: 0; + left:0; } #add-options-content { display: table; diff --git a/src/client/views/collections/CollectionDockingView.scss b/src/client/views/collections/CollectionDockingView.scss index 2706c3272..583d50c5b 100644 --- a/src/client/views/collections/CollectionDockingView.scss +++ b/src/client/views/collections/CollectionDockingView.scss @@ -3,7 +3,7 @@ } .collectiondockingview-container { - position: relative; + position: absolute; top: 0; left: 0; overflow: hidden; diff --git a/src/client/views/collections/CollectionPDFView.scss b/src/client/views/collections/CollectionPDFView.scss index 0144625c1..0eca3f1cd 100644 --- a/src/client/views/collections/CollectionPDFView.scss +++ b/src/client/views/collections/CollectionPDFView.scss @@ -9,6 +9,8 @@ width: 100%; height: 100%; position: absolute; + top: 0; + left:0; } .collectionPdfView-backward { diff --git a/src/client/views/collections/CollectionVideoView.scss b/src/client/views/collections/CollectionVideoView.scss index cbb981b13..ed56ad268 100644 --- a/src/client/views/collections/CollectionVideoView.scss +++ b/src/client/views/collections/CollectionVideoView.scss @@ -3,6 +3,8 @@ width: 100%; height: 100%; position: absolute; + top: 0; + left:0; } .collectionVideoView-time{ diff --git a/src/client/views/collections/CollectionViewBase.tsx b/src/client/views/collections/CollectionViewBase.tsx index 2b0689800..daeca69e2 100644 --- a/src/client/views/collections/CollectionViewBase.tsx +++ b/src/client/views/collections/CollectionViewBase.tsx @@ -17,6 +17,8 @@ import { NumberField } from "../../../fields/NumberField"; import request = require("request"); import { ServerUtils } from "../../../server/ServerUtil"; import { Server } from "../../Server"; +import { CollectionDockingView } from "./CollectionDockingView"; +import { runReactions } from "mobx/lib/internal"; export interface CollectionViewProps { fieldKey: Key; @@ -92,6 +94,24 @@ export class CollectionViewBase extends React.Component e.stopPropagation(); return added; } + if (de.data instanceof DragManager.LinkDragData) { + let sourceDoc: Document = de.data.linkSourceDocumentView.props.Document; + if (sourceDoc) runInAction(() => { + let srcTarg = sourceDoc.GetT(KeyStore.Prototype, Document) + if (srcTarg && srcTarg != FieldWaiting) { + let linkDocs = srcTarg.GetList(KeyStore.LinkedToDocs, [] as Document[]); + linkDocs.map(linkDoc => { + let targDoc = linkDoc.GetT(KeyStore.LinkedToDocs, Document); + if (targDoc && targDoc != FieldWaiting) { + let dropdoc = targDoc.MakeDelegate(); + de.data.droppedDocuments.push(dropdoc); + this.props.addDocument(dropdoc, false); + } + }) + } + }) + return true; + } return false; } diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx index e84f0c5ad..3dfd74ec8 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx @@ -23,10 +23,10 @@ export class CollectionFreeFormLinkView extends React.Component { if (super.drop(e, de)) { - if (de.data instanceof DragManager.DocumentDragData) { - let screenX = de.x - (de.data.xOffset as number || 0); - let screenY = de.y - (de.data.yOffset as number || 0); + let droppedDocs = de.data.droppedDocuments as Document[]; + let xoff = de.data.xOffset as number || 0; + let yoff = de.data.yOffset as number || 0; + if (droppedDocs && droppedDocs.length) { + let screenX = de.x - xoff; + let screenY = de.y - yoff; const [x, y] = this.getTransform().transformPoint(screenX, screenY); - let dragDoc = de.data.draggedDocuments[0]; + let dragDoc = de.data.droppedDocuments[0]; let dragX = dragDoc.GetNumber(KeyStore.X, 0); let dragY = dragDoc.GetNumber(KeyStore.Y, 0); - de.data.draggedDocuments.map(d => { + droppedDocs.map(d => { let docX = d.GetNumber(KeyStore.X, 0); let docY = d.GetNumber(KeyStore.Y, 0); d.SetNumber(KeyStore.X, x + (docX - dragX)); diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.scss b/src/client/views/collections/collectionFreeForm/MarqueeView.scss index 1ee3b244b..0b406e722 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.scss +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.scss @@ -1,6 +1,8 @@ .marqueeView { position: absolute; + top:0; + left:0; width:100%; height:100%; } diff --git a/src/client/views/collections/collectionFreeForm/PreviewCursor.scss b/src/client/views/collections/collectionFreeForm/PreviewCursor.scss index 21210be2b..7a67c29bf 100644 --- a/src/client/views/collections/collectionFreeForm/PreviewCursor.scss +++ b/src/client/views/collections/collectionFreeForm/PreviewCursor.scss @@ -3,9 +3,13 @@ color: black; position: absolute; transform-origin: left top; + top: 0; + left:0; pointer-events: none; } .previewCursorView { + top: 0; + left:0; position: absolute; width:100%; height:100%; diff --git a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx index d52b662bd..1a0f0cbbd 100644 --- a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx +++ b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx @@ -66,8 +66,12 @@ export class CollectionFreeFormDocumentView extends React.Component } + panelWidth = () => this.props.Document.GetBoolean(KeyStore.Minimized, false) ? 10 : this.props.PanelWidth(); + panelHeight = () => this.props.Document.GetBoolean(KeyStore.Minimized, false) ? 10 : this.props.PanelHeight(); render() { return ( diff --git a/src/client/views/nodes/DocumentView.scss b/src/client/views/nodes/DocumentView.scss index 127a6b535..5126e69f9 100644 --- a/src/client/views/nodes/DocumentView.scss +++ b/src/client/views/nodes/DocumentView.scss @@ -2,6 +2,8 @@ .documentView-node { position: absolute; + top: 0; + left:0; background: $light-color; //overflow: hidden; &.minimized { diff --git a/src/client/views/nodes/PDFBox.scss b/src/client/views/nodes/PDFBox.scss index ad947afd5..830dfe6c6 100644 --- a/src/client/views/nodes/PDFBox.scss +++ b/src/client/views/nodes/PDFBox.scss @@ -1,12 +1,16 @@ .react-pdf__Page { transform-origin: left top; position: absolute; + top: 0; + left:0; } .react-pdf__Document { position: absolute; } .pdfBox-buttonTray { position:absolute; + top: 0; + left:0; z-index: 25; } .pdfBox-contentContainer { diff --git a/src/client/views/nodes/WebBox.scss b/src/client/views/nodes/WebBox.scss index a535b2638..c73bc0c47 100644 --- a/src/client/views/nodes/WebBox.scss +++ b/src/client/views/nodes/WebBox.scss @@ -2,6 +2,8 @@ .webBox-cont { padding: 0vw; position: absolute; + top: 0; + left:0; width: 100%; height: 100%; overflow: scroll; diff --git a/src/fields/Document.ts b/src/fields/Document.ts index 8e71019a4..92d03d765 100644 --- a/src/fields/Document.ts +++ b/src/fields/Document.ts @@ -9,415 +9,420 @@ import { Server } from "../client/Server"; import { Types } from "../server/Message"; import { UndoManager } from "../client/util/UndoManager"; import { HtmlField } from "./HtmlField"; +import { BooleanField } from "./BooleanField"; export class Document extends Field { - //TODO tfs: We should probably store FieldWaiting in fields when we request it from the server so that we don't set up multiple server gets for the same document and field - public fields: ObservableMap< - string, - { key: Key; field: Field } - > = new ObservableMap(); - public _proxies: ObservableMap = new ObservableMap(); - - constructor(id?: string, save: boolean = true) { - super(id); - - if (save) { - Server.UpdateField(this); + //TODO tfs: We should probably store FieldWaiting in fields when we request it from the server so that we don't set up multiple server gets for the same document and field + public fields: ObservableMap< + string, + { key: Key; field: Field } + > = new ObservableMap(); + public _proxies: ObservableMap = new ObservableMap(); + + constructor(id?: string, save: boolean = true) { + super(id); + + if (save) { + Server.UpdateField(this); + } } - } - UpdateFromServer(data: [string, string][]) { - for (const key in data) { - const element = data[key]; - this._proxies.set(element[0], element[1]); - } - } - - public Width = () => { - return this.GetNumber(KeyStore.Width, 0); - }; - public Height = () => { - return this.GetNumber( - KeyStore.Height, - this.GetNumber(KeyStore.NativeWidth, 0) - ? (this.GetNumber(KeyStore.NativeHeight, 0) / - this.GetNumber(KeyStore.NativeWidth, 0)) * - this.GetNumber(KeyStore.Width, 0) - : 0 - ); - }; - public Scale = () => { - return this.GetNumber(KeyStore.Scale, 1); - }; - - @computed - public get Title(): string { - let title = this.Get(KeyStore.Title, true); - if (title) - if (title != FieldWaiting && title instanceof TextField) - return title.Data; - else return "-waiting-"; - let parTitle = this.GetT(KeyStore.Title, TextField); - if (parTitle) - if (parTitle != FieldWaiting) return parTitle.Data + ".alias"; - else return "-waiting-.alias"; - return "-untitled-"; - } - - @computed - public get Fields() { - return this.fields; - } - - /** - * Get the field in the document associated with the given key. If the - * associated field has not yet been filled in from the server, a request - * to the server will automatically be sent, the value will be filled in - * when the request is completed, and {@link Field.ts#FieldWaiting} will be returned. - * @param key - The key of the value to get - * @param ignoreProto - If true, ignore any prototype this document - * might have and only search for the value on this immediate document. - * If false (default), search up the prototype chain, starting at this document, - * for a document that has a field associated with the given key, and return the first - * one found. - * - * @returns If the document does not have a field associated with the given key, returns `undefined`. - * If the document does have an associated field, but the field has not been fetched from the server, returns {@link Field.ts#FieldWaiting}. - * If the document does have an associated field, and the field has not been fetched from the server, returns the associated field. - */ - Get(key: Key, ignoreProto: boolean = false): FieldValue { - let field: FieldValue; - if (ignoreProto) { - if (this.fields.has(key.Id)) { - field = this.fields.get(key.Id)!.field; - } else if (this._proxies.has(key.Id)) { - Server.GetDocumentField(this, key); - /* - The field might have been instantly filled from the cache - Maybe we want to just switch back to returning the value - from Server.GetDocumentField if it's in the cache - */ - if (this.fields.has(key.Id)) { - field = this.fields.get(key.Id)!.field; - } else { - field = FieldWaiting; + UpdateFromServer(data: [string, string][]) { + for (const key in data) { + const element = data[key]; + this._proxies.set(element[0], element[1]); } - } - } else { - let doc: FieldValue = this; - while (doc && doc != FieldWaiting && field != FieldWaiting) { - let curField = doc.fields.get(key.Id); - let curProxy = doc._proxies.get(key.Id); - if (!curField || (curProxy && curField.field.Id !== curProxy)) { - if (curProxy) { - Server.GetDocumentField(doc, key); - /* + } + + public Width = () => { + return this.GetNumber(KeyStore.Width, 0); + }; + public Height = () => { + return this.GetNumber( + KeyStore.Height, + this.GetNumber(KeyStore.NativeWidth, 0) + ? (this.GetNumber(KeyStore.NativeHeight, 0) / + this.GetNumber(KeyStore.NativeWidth, 0)) * + this.GetNumber(KeyStore.Width, 0) + : 0 + ); + }; + public Scale = () => { + return this.GetNumber(KeyStore.Scale, 1); + }; + + @computed + public get Title(): string { + let title = this.Get(KeyStore.Title, true); + if (title) + if (title != FieldWaiting && title instanceof TextField) + return title.Data; + else return "-waiting-"; + let parTitle = this.GetT(KeyStore.Title, TextField); + if (parTitle) + if (parTitle != FieldWaiting) return parTitle.Data + ".alias"; + else return "-waiting-.alias"; + return "-untitled-"; + } + + @computed + public get Fields() { + return this.fields; + } + + /** + * Get the field in the document associated with the given key. If the + * associated field has not yet been filled in from the server, a request + * to the server will automatically be sent, the value will be filled in + * when the request is completed, and {@link Field.ts#FieldWaiting} will be returned. + * @param key - The key of the value to get + * @param ignoreProto - If true, ignore any prototype this document + * might have and only search for the value on this immediate document. + * If false (default), search up the prototype chain, starting at this document, + * for a document that has a field associated with the given key, and return the first + * one found. + * + * @returns If the document does not have a field associated with the given key, returns `undefined`. + * If the document does have an associated field, but the field has not been fetched from the server, returns {@link Field.ts#FieldWaiting}. + * If the document does have an associated field, and the field has not been fetched from the server, returns the associated field. + */ + Get(key: Key, ignoreProto: boolean = false): FieldValue { + let field: FieldValue; + if (ignoreProto) { + if (this.fields.has(key.Id)) { + field = this.fields.get(key.Id)!.field; + } else if (this._proxies.has(key.Id)) { + Server.GetDocumentField(this, key); + /* The field might have been instantly filled from the cache Maybe we want to just switch back to returning the value from Server.GetDocumentField if it's in the cache */ - if (this.fields.has(key.Id)) { - field = this.fields.get(key.Id)!.field; - } else { - field = FieldWaiting; + if (this.fields.has(key.Id)) { + field = this.fields.get(key.Id)!.field; + } else { + field = FieldWaiting; + } } - break; - } - if ( - doc.fields.has(KeyStore.Prototype.Id) || - doc._proxies.has(KeyStore.Prototype.Id) - ) { - doc = doc.GetPrototype(); - } else { - break; - } } else { - field = curField.field; - break; + let doc: FieldValue = this; + while (doc && doc != FieldWaiting && field != FieldWaiting) { + let curField = doc.fields.get(key.Id); + let curProxy = doc._proxies.get(key.Id); + if (!curField || (curProxy && curField.field.Id !== curProxy)) { + if (curProxy) { + Server.GetDocumentField(doc, key); + /* + The field might have been instantly filled from the cache + Maybe we want to just switch back to returning the value + from Server.GetDocumentField if it's in the cache + */ + if (this.fields.has(key.Id)) { + field = this.fields.get(key.Id)!.field; + } else { + field = FieldWaiting; + } + break; + } + if ( + doc.fields.has(KeyStore.Prototype.Id) || + doc._proxies.has(KeyStore.Prototype.Id) + ) { + doc = doc.GetPrototype(); + } else { + break; + } + } else { + field = curField.field; + break; + } + } + if (doc == FieldWaiting) field = FieldWaiting; } - } - if (doc == FieldWaiting) field = FieldWaiting; + + return field; } - return field; - } - - /** - * Tries to get the field associated with the given key, and if there is an - * associated field, calls the given callback with that field. - * @param key - The key of the value to get - * @param callback - A function that will be called with the associated field, if it exists, - * once it is fetched from the server (this may be immediately if the field has already been fetched). - * Note: The callback will not be called if there is no associated field. - * @returns `true` if the field exists on the document and `callback` will be called, and `false` otherwise - */ - GetAsync(key: Key, callback: (field: Opt) => void): void { - //TODO: This currently doesn't deal with prototypes - let field = this.fields.get(key.Id); - if (field && field.field) { - callback(field.field); - } else if (this._proxies.has(key.Id)) { - Server.GetDocumentField(this, key, callback); - } else if (this._proxies.has(KeyStore.Prototype.Id)) { - this.GetTAsync(KeyStore.Prototype, Document, proto => { - if (proto) { - proto.GetAsync(key, callback); + /** + * Tries to get the field associated with the given key, and if there is an + * associated field, calls the given callback with that field. + * @param key - The key of the value to get + * @param callback - A function that will be called with the associated field, if it exists, + * once it is fetched from the server (this may be immediately if the field has already been fetched). + * Note: The callback will not be called if there is no associated field. + * @returns `true` if the field exists on the document and `callback` will be called, and `false` otherwise + */ + GetAsync(key: Key, callback: (field: Opt) => void): void { + //TODO: This currently doesn't deal with prototypes + let field = this.fields.get(key.Id); + if (field && field.field) { + callback(field.field); + } else if (this._proxies.has(key.Id)) { + Server.GetDocumentField(this, key, callback); + } else if (this._proxies.has(KeyStore.Prototype.Id)) { + this.GetTAsync(KeyStore.Prototype, Document, proto => { + if (proto) { + proto.GetAsync(key, callback); + } else { + callback(undefined); + } + }); } else { - callback(undefined); + callback(undefined); } - }); - } else { - callback(undefined); } - } - - GetTAsync(key: Key, ctor: { new (): T }): Promise>; - GetTAsync( - key: Key, - ctor: { new (): T }, - callback: (field: Opt) => void - ): void; - GetTAsync( - key: Key, - ctor: { new (): T }, - callback?: (field: Opt) => void - ): Promise> | void { - let fn = (cb: (field: Opt) => void) => { - return this.GetAsync(key, field => { - cb(Cast(field, ctor)); - }); - }; - if (callback) { - fn(callback); - } else { - return new Promise(res => fn(res)); + + GetTAsync(key: Key, ctor: { new(): T }): Promise>; + GetTAsync( + key: Key, + ctor: { new(): T }, + callback: (field: Opt) => void + ): void; + GetTAsync( + key: Key, + ctor: { new(): T }, + callback?: (field: Opt) => void + ): Promise> | void { + let fn = (cb: (field: Opt) => void) => { + return this.GetAsync(key, field => { + cb(Cast(field, ctor)); + }); + }; + if (callback) { + fn(callback); + } else { + return new Promise(res => fn(res)); + } } - } - - /** - * Same as {@link Document#GetAsync}, except a field of the given type - * will be created if there is no field associated with the given key, - * or the field associated with the given key is not of the given type. - * @param ctor - Constructor of the field type to get. E.g., TextField, ImageField, etc. - */ - GetOrCreateAsync( - key: Key, - ctor: { new (): T }, - callback: (field: T) => void - ): void { - //This currently doesn't deal with prototypes - if (this._proxies.has(key.Id)) { - Server.GetDocumentField(this, key, field => { - if (field && field instanceof ctor) { - callback(field); + + /** + * Same as {@link Document#GetAsync}, except a field of the given type + * will be created if there is no field associated with the given key, + * or the field associated with the given key is not of the given type. + * @param ctor - Constructor of the field type to get. E.g., TextField, ImageField, etc. + */ + GetOrCreateAsync( + key: Key, + ctor: { new(): T }, + callback: (field: T) => void + ): void { + //This currently doesn't deal with prototypes + if (this._proxies.has(key.Id)) { + Server.GetDocumentField(this, key, field => { + if (field && field instanceof ctor) { + callback(field); + } else { + let newField = new ctor(); + this.Set(key, newField); + callback(newField); + } + }); } else { - let newField = new ctor(); - this.Set(key, newField); - callback(newField); + let newField = new ctor(); + this.Set(key, newField); + callback(newField); } - }); - } else { - let newField = new ctor(); - this.Set(key, newField); - callback(newField); } - } - - /** - * Same as {@link Document#Get}, except that it will additionally - * check if the field is of the given type. - * @param ctor - Constructor of the field type to get. E.g., `TextField`, `ImageField`, etc. - * @returns Same as {@link Document#Get}, except will return `undefined` - * if there is an associated field but it is of the wrong type. - */ - GetT( - key: Key, - ctor: { new (...args: any[]): T }, - ignoreProto: boolean = false - ): FieldValue { - var getfield = this.Get(key, ignoreProto); - if (getfield != FieldWaiting) { - return Cast(getfield, ctor); + + /** + * Same as {@link Document#Get}, except that it will additionally + * check if the field is of the given type. + * @param ctor - Constructor of the field type to get. E.g., `TextField`, `ImageField`, etc. + * @returns Same as {@link Document#Get}, except will return `undefined` + * if there is an associated field but it is of the wrong type. + */ + GetT( + key: Key, + ctor: { new(...args: any[]): T }, + ignoreProto: boolean = false + ): FieldValue { + var getfield = this.Get(key, ignoreProto); + if (getfield != FieldWaiting) { + return Cast(getfield, ctor); + } + return FieldWaiting; } - return FieldWaiting; - } - - GetOrCreate( - key: Key, - ctor: { new (): T }, - ignoreProto: boolean = false - ): T { - const field = this.GetT(key, ctor, ignoreProto); - if (field && field != FieldWaiting) { - return field; + + GetOrCreate( + key: Key, + ctor: { new(): T }, + ignoreProto: boolean = false + ): T { + const field = this.GetT(key, ctor, ignoreProto); + if (field && field != FieldWaiting) { + return field; + } + const newField = new ctor(); + this.Set(key, newField); + return newField; } - const newField = new ctor(); - this.Set(key, newField); - return newField; - } - - GetData( - key: Key, - ctor: { new (): U }, - defaultVal: T - ): T { - let val = this.Get(key); - let vval = val && val instanceof ctor ? val.Data : defaultVal; - return vval; - } - - GetHtml(key: Key, defaultVal: string): string { - return this.GetData(key, HtmlField, defaultVal); - } - - GetNumber(key: Key, defaultVal: number): number { - return this.GetData(key, NumberField, defaultVal); - } - - GetText(key: Key, defaultVal: string): string { - return this.GetData(key, TextField, defaultVal); - } - - GetList(key: Key, defaultVal: T[]): T[] { - return this.GetData>(key, ListField, defaultVal); - } - - @action - Set(key: Key, field: Field | undefined, setOnPrototype = false): void { - let old = this.fields.get(key.Id); - let oldField = old ? old.field : undefined; - if (setOnPrototype) { - this.SetOnPrototype(key, field); - } else { - if (field) { - this.fields.set(key.Id, { key, field }); - this._proxies.set(key.Id, field.Id); - // Server.AddDocumentField(this, key, field); - } else { - this.fields.delete(key.Id); - this._proxies.delete(key.Id); - // Server.DeleteDocumentField(this, key); - } - Server.UpdateField(this); + + GetData( + key: Key, + ctor: { new(): U }, + defaultVal: T + ): T { + let val = this.Get(key); + let vval = val && val instanceof ctor ? val.Data : defaultVal; + return vval; } - if (oldField || field) { - UndoManager.AddEvent({ - undo: () => this.Set(key, oldField, setOnPrototype), - redo: () => this.Set(key, field, setOnPrototype) - }); + + GetHtml(key: Key, defaultVal: string): string { + return this.GetData(key, HtmlField, defaultVal); } - } - - @action - SetOnPrototype(key: Key, field: Field | undefined): void { - this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { - f && f.Set(key, field); - }); - } - - @action - SetDataOnPrototype( - key: Key, - value: T, - ctor: { new (): U }, - replaceWrongType = true - ) { - this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { - f && f.SetData(key, value, ctor); - }); - } - - @action - SetData( - key: Key, - value: T, - ctor: { new (data: T): U }, - replaceWrongType = true - ) { - let field = this.Get(key, true); - if (field instanceof ctor) { - field.Data = value; - } else if (!field || replaceWrongType) { - let newField = new ctor(value); - // newField.Data = value; - this.Set(key, newField); + + GetBoolean(key: Key, defaultVal: boolean): boolean { + return this.GetData(key, BooleanField, defaultVal); } - } - - @action - SetText(key: Key, value: string, replaceWrongType = true) { - this.SetData(key, value, TextField, replaceWrongType); - } - - @action - SetNumber(key: Key, value: number, replaceWrongType = true) { - this.SetData(key, value, NumberField, replaceWrongType); - } - - GetPrototype(): FieldValue { - return this.GetT(KeyStore.Prototype, Document, true); - } - - GetAllPrototypes(): Document[] { - let protos: Document[] = []; - let doc: FieldValue = this; - while (doc && doc != FieldWaiting) { - protos.push(doc); - doc = doc.GetPrototype(); + + GetNumber(key: Key, defaultVal: number): number { + return this.GetData(key, NumberField, defaultVal); + } + + GetText(key: Key, defaultVal: string): string { + return this.GetData(key, TextField, defaultVal); + } + + GetList(key: Key, defaultVal: T[]): T[] { + return this.GetData>(key, ListField, defaultVal); + } + + @action + Set(key: Key, field: Field | undefined, setOnPrototype = false): void { + let old = this.fields.get(key.Id); + let oldField = old ? old.field : undefined; + if (setOnPrototype) { + this.SetOnPrototype(key, field); + } else { + if (field) { + this.fields.set(key.Id, { key, field }); + this._proxies.set(key.Id, field.Id); + // Server.AddDocumentField(this, key, field); + } else { + this.fields.delete(key.Id); + this._proxies.delete(key.Id); + // Server.DeleteDocumentField(this, key); + } + Server.UpdateField(this); + } + if (oldField || field) { + UndoManager.AddEvent({ + undo: () => this.Set(key, oldField, setOnPrototype), + redo: () => this.Set(key, field, setOnPrototype) + }); + } + } + + @action + SetOnPrototype(key: Key, field: Field | undefined): void { + this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { + f && f.Set(key, field); + }); + } + + @action + SetDataOnPrototype( + key: Key, + value: T, + ctor: { new(): U }, + replaceWrongType = true + ) { + this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { + f && f.SetData(key, value, ctor); + }); + } + + @action + SetData( + key: Key, + value: T, + ctor: { new(data: T): U }, + replaceWrongType = true + ) { + let field = this.Get(key, true); + if (field instanceof ctor) { + field.Data = value; + } else if (!field || replaceWrongType) { + let newField = new ctor(value); + // newField.Data = value; + this.Set(key, newField); + } + } + + @action + SetText(key: Key, value: string, replaceWrongType = true) { + this.SetData(key, value, TextField, replaceWrongType); + } + + @action + SetNumber(key: Key, value: number, replaceWrongType = true) { + this.SetData(key, value, NumberField, replaceWrongType); + } + + GetPrototype(): FieldValue { + return this.GetT(KeyStore.Prototype, Document, true); + } + + GetAllPrototypes(): Document[] { + let protos: Document[] = []; + let doc: FieldValue = this; + while (doc && doc != FieldWaiting) { + protos.push(doc); + doc = doc.GetPrototype(); + } + return protos; + } + + CreateAlias(id?: string): Document { + let alias = new Document(id); + this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { + f && alias.Set(KeyStore.Prototype, f); + }); + + return alias; + } + + MakeDelegate(id?: string): Document { + let delegate = new Document(id); + + delegate.Set(KeyStore.Prototype, this); + + return delegate; + } + + ToScriptString(): string { + return ""; + } + + TrySetValue(value: any): boolean { + throw new Error("Method not implemented."); + } + GetValue() { + return this.Title; + var title = + (this._proxies.has(KeyStore.Title.Id) ? "???" : this.Title) + + "(" + + this.Id + + ")"; + return title; + //throw new Error("Method not implemented."); + } + Copy(): Field { + throw new Error("Method not implemented."); + } + + ToJson(): { type: Types; data: [string, string][]; _id: string } { + let fields: [string, string][] = []; + this._proxies.forEach((field, key) => { + if (field) { + fields.push([key, field as string]); + } + }); + + return { + type: Types.Document, + data: fields, + _id: this.Id + }; } - return protos; - } - - CreateAlias(id?: string): Document { - let alias = new Document(id); - this.GetTAsync(KeyStore.Prototype, Document, (f: Opt) => { - f && alias.Set(KeyStore.Prototype, f); - }); - - return alias; - } - - MakeDelegate(id?: string): Document { - let delegate = new Document(id); - - delegate.Set(KeyStore.Prototype, this); - - return delegate; - } - - ToScriptString(): string { - return ""; - } - - TrySetValue(value: any): boolean { - throw new Error("Method not implemented."); - } - GetValue() { - return this.Title; - var title = - (this._proxies.has(KeyStore.Title.Id) ? "???" : this.Title) + - "(" + - this.Id + - ")"; - return title; - //throw new Error("Method not implemented."); - } - Copy(): Field { - throw new Error("Method not implemented."); - } - - ToJson(): { type: Types; data: [string, string][]; _id: string } { - let fields: [string, string][] = []; - this._proxies.forEach((field, key) => { - if (field) { - fields.push([key, field as string]); - } - }); - - return { - type: Types.Document, - data: fields, - _id: this.Id - }; - } } -- cgit v1.2.3-70-g09d2 From e70be930dc7c8ff1e999bf163bcbb511a60bae6f Mon Sep 17 00:00:00 2001 From: bob Date: Thu, 4 Apr 2019 17:46:33 -0400 Subject: added close button and fixed some async stuff. --- src/client/views/DocumentDecorations.scss | 17 +++++++--- src/client/views/DocumentDecorations.tsx | 38 +++++++++++++++++++--- .../views/collections/CollectionViewBase.tsx | 2 +- .../collectionFreeForm/CollectionFreeFormView.tsx | 9 +++-- .../collections/collectionFreeForm/MarqueeView.tsx | 1 + src/client/views/nodes/PDFBox.tsx | 10 +++--- 6 files changed, 60 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 080c9fa1e..d7137d7a2 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -7,7 +7,7 @@ display: grid; z-index: 1000; grid-template-rows: 20px 8px 1fr 8px; - grid-template-columns: 8px 8px 1fr 8px; + grid-template-columns: 8px 8px 1fr 8px 8px; pointer-events: none; #documentDecorations-centerCont { @@ -30,13 +30,14 @@ #documentDecorations-topResizer, #documentDecorations-bottomResizer { grid-column-start: 2; - grid-column-end: 4; + grid-column-end: 5; } #documentDecorations-bottomRightResizer, #documentDecorations-topRightResizer, #documentDecorations-rightResizer { - grid-column:4 + grid-column-start:5; + grid-column-end:7; } #documentDecorations-topLeftResizer, @@ -61,11 +62,19 @@ .title{ background: lightblue; grid-column-start:3; - grid-column-end: 5; + grid-column-end: 4; pointer-events: auto; } } +.documentDecorations-closeButton { + background:$alt-accent; + opacity: 0.8; + grid-column-start: 4; + grid-column-end: 6; + pointer-events: all; + text-align: center; +} .documentDecorations-minimizeButton { background:$alt-accent; opacity: 0.8; diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index a46087c9a..8bf1a42d1 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -142,6 +142,30 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> e.preventDefault(); } + onCloseDown = (e: React.PointerEvent): void => { + e.stopPropagation(); + if (e.button === 0) { + document.removeEventListener("pointermove", this.onCloseMove); + document.addEventListener("pointermove", this.onCloseMove); + document.removeEventListener("pointerup", this.onCloseUp); + document.addEventListener("pointerup", this.onCloseUp); + } + } + onCloseMove = (e: PointerEvent): void => { + e.stopPropagation(); + if (e.button === 0) { + } + } + @action + onCloseUp = (e: PointerEvent): void => { + e.stopPropagation(); + if (e.button === 0) { + SelectionManager.SelectedDocuments().map(dv => dv.props.RemoveDocument && dv.props.RemoveDocument(dv.props.Document)); + SelectionManager.DeselectAll(); + document.removeEventListener("pointermove", this.onCloseMove); + document.removeEventListener("pointerup", this.onCloseUp); + } + } onMinimizeDown = (e: React.PointerEvent): void => { e.stopPropagation(); if (e.button === 0) { @@ -219,7 +243,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> e.stopPropagation(); } - onLinkButtonMoved = (e: PointerEvent): void => { + onLinkButtonMoved = async (e: PointerEvent) => { if (this._linkButton.current != null) { document.removeEventListener("pointermove", this.onLinkButtonMoved) document.removeEventListener("pointerup", this.onLinkButtonUp); @@ -234,10 +258,13 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> (linkDoc.GetT(KeyStore.LinkedFromDocs, Document)) as Document) : []; draggedDocs.push(...draggedFromDocs); if (draggedDocs.length) { - let dragData = new DragManager.DocumentDragData(draggedDocs.map(d => { - let annot = d.GetT(KeyStore.AnnotationOn, Document); // bcz: ... needs to change ... the annotationOn document may not have been retrieved yet... - return annot && annot != FieldWaiting ? annot : d; - })); + let moddrag = [] as Document[]; + for (let i = 0; i < draggedDocs.length; i++) { + let doc = await draggedDocs[i].GetTAsync(KeyStore.AnnotationOn, Document); + if (doc) + moddrag.push(doc); + } + let dragData = new DragManager.DocumentDragData(moddrag); DragManager.StartDocumentDrag([this._linkButton.current], dragData, { handlers: { dragComplete: action(() => { }), @@ -400,6 +427,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> }}>
    ...
    +
    X
    e.preventDefault()}>
    e.preventDefault()}>
    e.preventDefault()}>
    diff --git a/src/client/views/collections/CollectionViewBase.tsx b/src/client/views/collections/CollectionViewBase.tsx index daeca69e2..9eee23a1d 100644 --- a/src/client/views/collections/CollectionViewBase.tsx +++ b/src/client/views/collections/CollectionViewBase.tsx @@ -128,6 +128,7 @@ export class CollectionViewBase extends React.Component } if (type.indexOf("pdf") !== -1) { ctor = Documents.PdfDocument; + options.nativeWidth = 600; } if (type.indexOf("html") !== -1) { if (path.includes('localhost')) { @@ -177,7 +178,6 @@ export class CollectionViewBase extends React.Component let item = e.dataTransfer.items[i]; if (item.kind === "string" && item.type.indexOf("uri") != -1) { e.dataTransfer.items[i].getAsString(action((s: string) => { - let document: Document; request.head(ServerUtils.prepend(RouteStore.corsProxy + "/" + s), (err, res, body) => { let type = res.headers["content-type"]; if (type) { diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 3484e963e..1ddb84a99 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -20,6 +20,7 @@ import React = require("react"); import v5 = require("uuid/v5"); import { CollectionFreeFormRemoteCursors } from "./CollectionFreeFormRemoteCursors"; import { PreviewCursor } from "./PreviewCursor"; +import { NumberField } from "../../../../fields/NumberField"; @observer export class CollectionFreeFormView extends CollectionViewBase { @@ -83,13 +84,17 @@ export class CollectionFreeFormView extends CollectionViewBase { let dragDoc = de.data.droppedDocuments[0]; let dragX = dragDoc.GetNumber(KeyStore.X, 0); let dragY = dragDoc.GetNumber(KeyStore.Y, 0); - droppedDocs.map(d => { + droppedDocs.map(async d => { let docX = d.GetNumber(KeyStore.X, 0); let docY = d.GetNumber(KeyStore.Y, 0); d.SetNumber(KeyStore.X, x + (docX - dragX)); d.SetNumber(KeyStore.Y, y + (docY - dragY)); - if (!d.GetNumber(KeyStore.Width, 0)) { + let docW = await d.GetTAsync(KeyStore.Width, NumberField); + let docH = await d.GetTAsync(KeyStore.Height, NumberField); + if (!docW) { d.SetNumber(KeyStore.Width, 300); + } + if (!docH) { d.SetNumber(KeyStore.Height, 300); } this.bringToFront(d); diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index e2239c8be..df150a045 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -135,6 +135,7 @@ export class MarqueeView extends React.Component this.marqueeInkDelete(inkData); // }, 100); this.cleanupInteractions(); + SelectionManager.DeselectAll(); } } @action diff --git a/src/client/views/nodes/PDFBox.tsx b/src/client/views/nodes/PDFBox.tsx index 3cb3cf782..c9fed7f66 100644 --- a/src/client/views/nodes/PDFBox.tsx +++ b/src/client/views/nodes/PDFBox.tsx @@ -1,5 +1,5 @@ import * as htmlToImage from "html-to-image"; -import { action, computed, observable, reaction, IReactionDisposer, trace, keys } from 'mobx'; +import { action, computed, IReactionDisposer, observable, reaction } from 'mobx'; import { observer } from "mobx-react"; import 'react-image-lightbox/style.css'; import Measure from "react-measure"; @@ -10,6 +10,7 @@ import { FieldWaiting, Opt } from '../../../fields/Field'; import { ImageField } from '../../../fields/ImageField'; import { KeyStore } from '../../../fields/KeyStore'; import { PDFField } from '../../../fields/PDFField'; +import { RouteStore } from "../../../server/RouteStore"; import { Utils } from '../../../Utils'; import { Annotation } from './Annotation'; import { FieldView, FieldViewProps } from './FieldView'; @@ -17,8 +18,6 @@ import "./ImageBox.scss"; import "./PDFBox.scss"; import { Sticky } from './Sticky'; //you should look at sticky and annotation, because they are used here import React = require("react") -import { RouteStore } from "../../../server/RouteStore"; -import { NumberField } from "../../../fields/NumberField"; /** ALSO LOOK AT: Annotation.tsx, Sticky.tsx * This method renders PDF and puts all kinds of functionalities such as annotation, highlighting, @@ -378,8 +377,9 @@ export class PDFBox extends React.Component { saveThumbnail = () => { setTimeout(() => { var me = this; - htmlToImage.toPng(this._mainDiv.current!, - { width: me.props.doc.GetNumber(KeyStore.NativeWidth, 0), height: me.props.doc.GetNumber(KeyStore.NativeHeight, 0), quality: 0.5 }) + let nwidth = me.props.doc.GetNumber(KeyStore.NativeWidth, 0); + let nheight = me.props.doc.GetNumber(KeyStore.NativeHeight, 0); + htmlToImage.toPng(this._mainDiv.current!, { width: nwidth, height: nheight, quality: 1 }) .then(function (dataUrl: string) { me.props.doc.SetData(KeyStore.Thumbnail, new URL(dataUrl), ImageField); me.props.doc.SetNumber(KeyStore.ThumbnailPage, me.props.doc.GetNumber(KeyStore.CurPage, -1)); -- cgit v1.2.3-70-g09d2 From 4fde212cd00bd2f8fc2fa122309af3bb71bba2fd Mon Sep 17 00:00:00 2001 From: bob Date: Thu, 4 Apr 2019 18:18:45 -0400 Subject: improved pdf bitmaps a bit, but still blurry. --- src/client/documents/Documents.ts | 2 +- src/client/views/collections/CollectionViewBase.tsx | 2 +- src/client/views/nodes/DocumentView.tsx | 2 +- src/client/views/nodes/PDFBox.tsx | 20 +++++++++++--------- 4 files changed, 14 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 0bf275df8..1f0744782 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -136,7 +136,7 @@ export namespace Documents { function GetPdfPrototype(): Document { if (!pdfProto) { pdfProto = setupPrototypeOptions(pdfProtoId, "PDF_PROTO", CollectionPDFView.LayoutString("AnnotationsKey"), - { x: 0, y: 0, nativeWidth: 600, width: 300, layoutKeys: [KeyStore.Data, KeyStore.Annotations] }); + { x: 0, y: 0, nativeWidth: 1200, width: 300, layoutKeys: [KeyStore.Data, KeyStore.Annotations] }); pdfProto.SetNumber(KeyStore.CurPage, 1); pdfProto.SetText(KeyStore.BackgroundLayout, PDFBox.LayoutString()); } diff --git a/src/client/views/collections/CollectionViewBase.tsx b/src/client/views/collections/CollectionViewBase.tsx index 9eee23a1d..458bae7ab 100644 --- a/src/client/views/collections/CollectionViewBase.tsx +++ b/src/client/views/collections/CollectionViewBase.tsx @@ -128,7 +128,7 @@ export class CollectionViewBase extends React.Component } if (type.indexOf("pdf") !== -1) { ctor = Documents.PdfDocument; - options.nativeWidth = 600; + options.nativeWidth = 1200; } if (type.indexOf("html") !== -1) { if (path.includes('localhost')) { diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 714ab9447..b9329f269 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -249,7 +249,7 @@ export class DocumentView extends React.Component { document.removeEventListener("pointermove", this.onPointerMove); document.removeEventListener("pointerup", this.onPointerUp); e.stopPropagation(); - if ( + if (!SelectionManager.IsSelected(this) && Math.abs(e.clientX - this._downX) < 4 && Math.abs(e.clientY - this._downY) < 4 ) { diff --git a/src/client/views/nodes/PDFBox.tsx b/src/client/views/nodes/PDFBox.tsx index c9fed7f66..f9f5bc8f8 100644 --- a/src/client/views/nodes/PDFBox.tsx +++ b/src/client/views/nodes/PDFBox.tsx @@ -18,6 +18,7 @@ import "./ImageBox.scss"; import "./PDFBox.scss"; import { Sticky } from './Sticky'; //you should look at sticky and annotation, because they are used here import React = require("react") +import { SelectionManager } from "../../util/SelectionManager"; /** ALSO LOOK AT: Annotation.tsx, Sticky.tsx * This method renders PDF and puts all kinds of functionalities such as annotation, highlighting, @@ -57,6 +58,8 @@ export class PDFBox extends React.Component { private _mainDiv = React.createRef() private _pdf = React.createRef(); + @observable private _renderAsSvg = true; + //very useful for keeping track of X and y position throughout the PDF Canvas private initX: number = 0; private initY: number = 0; @@ -91,9 +94,9 @@ export class PDFBox extends React.Component { componentDidMount() { this._reactionDisposer = reaction( - () => [this.curPage, this.thumbnailPage], + () => [SelectionManager.SelectedDocuments().slice()], () => { - if (this.curPage > 0 && this.thumbnailPage > 0 && this.curPage != this.thumbnailPage) { + if (this.curPage > 0 && this.thumbnailPage > 0 && this.curPage != this.thumbnailPage && !this.props.isSelected()) { this.saveThumbnail(); this._interactive = true; } @@ -375,19 +378,21 @@ export class PDFBox extends React.Component { @action saveThumbnail = () => { + this._renderAsSvg = false; setTimeout(() => { var me = this; let nwidth = me.props.doc.GetNumber(KeyStore.NativeWidth, 0); let nheight = me.props.doc.GetNumber(KeyStore.NativeHeight, 0); htmlToImage.toPng(this._mainDiv.current!, { width: nwidth, height: nheight, quality: 1 }) - .then(function (dataUrl: string) { + .then(action((dataUrl: string) => { me.props.doc.SetData(KeyStore.Thumbnail, new URL(dataUrl), ImageField); me.props.doc.SetNumber(KeyStore.ThumbnailPage, me.props.doc.GetNumber(KeyStore.CurPage, -1)); - }) + me._renderAsSvg = true; + })) .catch(function (error: any) { console.error('oops, something went wrong!', error); }); - }, 1000); + }, 250); } @action @@ -427,9 +432,6 @@ export class PDFBox extends React.Component { this.props.doc.SetNumber(KeyStore.Height, nativeHeight / nativeWidth * this.props.doc.GetNumber(KeyStore.Width, 0)); this.props.doc.SetNumber(KeyStore.NativeHeight, nativeHeight); } - if (!this.props.doc.GetT(KeyStore.Thumbnail, ImageField)) { - this.saveThumbnail(); - } } @computed @@ -439,7 +441,7 @@ export class PDFBox extends React.Component { let pdfUrl = this.props.doc.GetT(this.props.fieldKey, PDFField); let xf = this.props.doc.GetNumber(KeyStore.NativeHeight, 0) / renderHeight; return
    - + {({ measureRef }) =>
    -- cgit v1.2.3-70-g09d2