From 4788eddb018ce764c7152e4d39149ee7a7e3aa73 Mon Sep 17 00:00:00 2001 From: monikahedman Date: Wed, 17 Jul 2019 12:40:38 -0400 Subject: pushing --- src/client/views/ContextMenu.tsx | 8 ++++++++ 1 file changed, 8 insertions(+) (limited to 'src') diff --git a/src/client/views/ContextMenu.tsx b/src/client/views/ContextMenu.tsx index c163c56a0..e68e5c73f 100644 --- a/src/client/views/ContextMenu.tsx +++ b/src/client/views/ContextMenu.tsx @@ -27,12 +27,18 @@ export class ContextMenu extends React.Component { @observable private _width: number = 0; @observable private _height: number = 0; + @observable private _mouseDown: boolean = false; + constructor(props: Readonly<{}>) { super(props); ContextMenu.Instance = this; } + componentDidMount = () => { + + } + @action clearItems() { this._items = []; @@ -79,6 +85,8 @@ 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 + console.log("opening?") + this._pageX = x; this._pageY = y; -- cgit v1.2.3-70-g09d2 From 1b6e2dbab9a3d06b1ae5999324c7bd15899b75e1 Mon Sep 17 00:00:00 2001 From: monikahedman Date: Wed, 17 Jul 2019 12:51:56 -0400 Subject: changes --- src/client/views/ContextMenu.tsx | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/client/views/ContextMenu.tsx b/src/client/views/ContextMenu.tsx index e68e5c73f..0a8c98ec9 100644 --- a/src/client/views/ContextMenu.tsx +++ b/src/client/views/ContextMenu.tsx @@ -36,7 +36,12 @@ export class ContextMenu extends React.Component { } componentDidMount = () => { - + document.addEventListener("pointerdown", e => { + this._mouseDown = true; + }); + document.addEventListener("pointerup", e => { + this._mouseDown = false; + }) } @action @@ -85,14 +90,20 @@ 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 - console.log("opening?") + if (!this._mouseDown) { + this._pageX = x; + this._pageY = y; + this._searchString = ""; + this._display = true; + } - this._pageX = x; - this._pageY = y; - this._searchString = ""; + // this._pageX = x; + // this._pageY = y; + + // this._searchString = ""; - this._display = true; + // this._display = true; } @action -- cgit v1.2.3-70-g09d2 From 45d955f32f1896731bde03e885566026ae1d6d77 Mon Sep 17 00:00:00 2001 From: monikahedman Date: Wed, 17 Jul 2019 13:13:39 -0400 Subject: contexrt menu mac fixed --- src/client/views/ContextMenu.tsx | 47 ++++++++++++++++++++++++---------------- 1 file changed, 28 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/client/views/ContextMenu.tsx b/src/client/views/ContextMenu.tsx index 0a8c98ec9..0b14b68f6 100644 --- a/src/client/views/ContextMenu.tsx +++ b/src/client/views/ContextMenu.tsx @@ -1,6 +1,6 @@ import React = require("react"); import { ContextMenuItem, ContextMenuProps, OriginalMenuProps } from "./ContextMenuItem"; -import { observable, action, computed } from "mobx"; +import { observable, action, computed, runInAction } from "mobx"; import { observer } from "mobx-react"; import "./ContextMenu.scss"; import { library } from '@fortawesome/fontawesome-svg-core'; @@ -27,7 +27,9 @@ export class ContextMenu extends React.Component { @observable private _width: number = 0; @observable private _height: number = 0; - @observable private _mouseDown: boolean = false; + @observable private _mouseX: number = -1; + @observable private _mouseY: number = -1; + @observable private _shouldDisplay: boolean = false; constructor(props: Readonly<{}>) { super(props); @@ -35,12 +37,28 @@ export class ContextMenu extends React.Component { ContextMenu.Instance = this; } + @action componentDidMount = () => { document.addEventListener("pointerdown", e => { - this._mouseDown = true; + runInAction(() => { + this._mouseX = e.clientX; + this._mouseY = e.clientY; + }); }); document.addEventListener("pointerup", e => { - this._mouseDown = false; + let curX = e.clientX; + let curY = e.clientY; + if (this._mouseX !== curX || this._mouseY !== curY) { + runInAction(() => { + this._shouldDisplay = false; + }); + } + + if (this._shouldDisplay) { + runInAction(() => { + this._display = true; + }); + } }) } @@ -86,30 +104,21 @@ export class ContextMenu extends React.Component { } @action - displayMenu(x: number, y: number) { + displayMenu = (x: number, y: number) => { //maxX and maxY will change if the UI/font size changes, but will work for any amount //of items added to the menu - if (!this._mouseDown) { - this._pageX = x; - this._pageY = y; - this._searchString = ""; - this._display = true; - } - - - // this._pageX = x; - // this._pageY = y; - - // this._searchString = ""; - - // this._display = true; + this._pageX = x; + this._pageY = y; + this._searchString = ""; + this._shouldDisplay = true; } @action closeMenu = () => { this.clearItems(); this._display = false; + this._shouldDisplay = false; } @computed get filteredItems(): (OriginalMenuProps | string[])[] { -- cgit v1.2.3-70-g09d2 From 6bf6cad2fd500f9bb5b527f6950373566f1d6810 Mon Sep 17 00:00:00 2001 From: monikahedman Date: Wed, 17 Jul 2019 13:38:47 -0400 Subject: mght work --- src/client/views/ContextMenu.tsx | 27 ++++++++++++++++++++------- 1 file changed, 20 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/client/views/ContextMenu.tsx b/src/client/views/ContextMenu.tsx index 0b14b68f6..c97cbd076 100644 --- a/src/client/views/ContextMenu.tsx +++ b/src/client/views/ContextMenu.tsx @@ -1,6 +1,6 @@ import React = require("react"); import { ContextMenuItem, ContextMenuProps, OriginalMenuProps } from "./ContextMenuItem"; -import { observable, action, computed, runInAction } from "mobx"; +import { observable, action, computed, runInAction, IReactionDisposer, reaction } from "mobx"; import { observer } from "mobx-react"; import "./ContextMenu.scss"; import { library } from '@fortawesome/fontawesome-svg-core'; @@ -31,6 +31,8 @@ export class ContextMenu extends React.Component { @observable private _mouseY: number = -1; @observable private _shouldDisplay: boolean = false; + private _reactionDisposer?: IReactionDisposer; + constructor(props: Readonly<{}>) { super(props); @@ -54,12 +56,23 @@ export class ContextMenu extends React.Component { }); } - if (this._shouldDisplay) { - runInAction(() => { - this._display = true; - }); - } - }) + // if (this._shouldDisplay) { + // runInAction(() => { + // this._display = true; + // }); + // } + }); + + this._reactionDisposer = reaction( + () => this._shouldDisplay, + () => { + if (this._shouldDisplay) { + runInAction(() => { + this._display = true; + }); + } + }, + ); } @action -- cgit v1.2.3-70-g09d2 From 9d16c6d15809c7691e7f32be238a3b22cd0edcb5 Mon Sep 17 00:00:00 2001 From: monikahedman Date: Wed, 17 Jul 2019 13:45:01 -0400 Subject: does this work --- src/client/views/ContextMenu.tsx | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/client/views/ContextMenu.tsx b/src/client/views/ContextMenu.tsx index c97cbd076..1347d4197 100644 --- a/src/client/views/ContextMenu.tsx +++ b/src/client/views/ContextMenu.tsx @@ -30,6 +30,7 @@ export class ContextMenu extends React.Component { @observable private _mouseX: number = -1; @observable private _mouseY: number = -1; @observable private _shouldDisplay: boolean = false; + @observable private _mouseDown: boolean = false; private _reactionDisposer?: IReactionDisposer; @@ -43,11 +44,15 @@ export class ContextMenu extends React.Component { componentDidMount = () => { document.addEventListener("pointerdown", e => { runInAction(() => { + this._mouseDown = true; this._mouseX = e.clientX; this._mouseY = e.clientY; }); }); document.addEventListener("pointerup", e => { + runInAction(() => { + this._mouseDown = false; + }) let curX = e.clientX; let curY = e.clientY; if (this._mouseX !== curX || this._mouseY !== curY) { @@ -56,17 +61,17 @@ export class ContextMenu extends React.Component { }); } - // if (this._shouldDisplay) { - // runInAction(() => { - // this._display = true; - // }); - // } + if (this._shouldDisplay) { + runInAction(() => { + this._display = true; + }); + } }); this._reactionDisposer = reaction( () => this._shouldDisplay, () => { - if (this._shouldDisplay) { + if (this._shouldDisplay && !this._mouseDown) { runInAction(() => { this._display = true; }); -- cgit v1.2.3-70-g09d2 From b78da60d91e37889c30b4428a88c838a9dafe5ca Mon Sep 17 00:00:00 2001 From: monikahedman Date: Wed, 17 Jul 2019 15:02:33 -0400 Subject: search auto focuses --- src/client/views/ContextMenu.tsx | 2 +- src/client/views/MainView.tsx | 5 +- src/client/views/SearchBox.tsx | 182 ---------------------------------- src/client/views/search/SearchBox.tsx | 15 ++- 4 files changed, 18 insertions(+), 186 deletions(-) delete mode 100644 src/client/views/SearchBox.tsx (limited to 'src') diff --git a/src/client/views/ContextMenu.tsx b/src/client/views/ContextMenu.tsx index 1347d4197..60658b7f0 100644 --- a/src/client/views/ContextMenu.tsx +++ b/src/client/views/ContextMenu.tsx @@ -52,7 +52,7 @@ export class ContextMenu extends React.Component { document.addEventListener("pointerup", e => { runInAction(() => { this._mouseDown = false; - }) + }); let curX = e.clientX; let curY = e.clientY; if (this._mouseX !== curX || this._mouseY !== curY) { diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index ce7369220..5cb1d06cb 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -39,6 +39,8 @@ import { PreviewCursor } from './PreviewCursor'; import { FilterBox } from './search/FilterBox'; import { CollectionTreeView } from './collections/CollectionTreeView'; import { ClientUtils } from '../util/ClientUtils'; +import { SearchBox } from './search/SearchBox'; + @observer export class MainView extends React.Component { @@ -439,12 +441,11 @@ export class MainView extends React.Component { } @observable isSearchVisible = false; - @action + @action.bound toggleSearch = () => { this.isSearchVisible = !this.isSearchVisible; } - render() { return (
diff --git a/src/client/views/SearchBox.tsx b/src/client/views/SearchBox.tsx deleted file mode 100644 index 1b9be841f..000000000 --- a/src/client/views/SearchBox.tsx +++ /dev/null @@ -1,182 +0,0 @@ -import { library } from '@fortawesome/fontawesome-svg-core'; -import { faObjectGroup, faSearch } from '@fortawesome/free-solid-svg-icons'; -import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { action, observable, runInAction } from 'mobx'; -import { observer } from 'mobx-react'; -import * as React from 'react'; -import * as rp from 'request-promise'; -import { Doc } from '../../new_fields/Doc'; -import { Id } from '../../new_fields/FieldSymbols'; -import { NumCast } from '../../new_fields/Types'; -import { DocServer } from '../DocServer'; -import { Docs } from '../documents/Documents'; -import { SetupDrag } from '../util/DragManager'; -import { SearchItem } from './search/SearchItem'; -import "./SearchBox.scss"; - -library.add(faSearch); -library.add(faObjectGroup); - -@observer -export class SearchBox extends React.Component { - @observable - searchString: string = ""; - - @observable private _open: boolean = false; - @observable private _resultsOpen: boolean = false; - - @observable - private _results: Doc[] = []; - - @action.bound - onChange(e: React.ChangeEvent) { - this.searchString = e.target.value; - } - - @action - submitSearch = async () => { - let query = this.searchString; - //gets json result into a list of documents that can be used - const results = await this.getResults(query); - - runInAction(() => { - this._resultsOpen = true; - this._results = results; - }); - } - - @action - getResults = async (query: string) => { - let response = await rp.get(DocServer.prepend('/search'), { - qs: { - query - } - }); - let res: string[] = JSON.parse(response); - const fields = await DocServer.GetRefFields(res); - const docs: Doc[] = []; - for (const id of res) { - const field = fields[id]; - if (field instanceof Doc) { - docs.push(field); - } - } - return docs; - } - - @action - handleClickFilter = (e: Event): void => { - var className = (e.target as any).className; - var id = (e.target as any).id; - if (className !== "filter-button" && className !== "filter-form") { - this._open = false; - } - - } - - @action - handleClickResults = (e: Event): void => { - var className = (e.target as any).className; - var id = (e.target as any).id; - if (id !== "result") { - this._resultsOpen = false; - this._results = []; - } - - } - - componentWillMount() { - document.addEventListener('mousedown', this.handleClickFilter, false); - document.addEventListener('mousedown', this.handleClickResults, false); - } - - componentWillUnmount() { - document.removeEventListener('mousedown', this.handleClickFilter, false); - document.removeEventListener('mousedown', this.handleClickResults, false); - } - - @action - toggleFilterDisplay = () => { - this._open = !this._open; - } - - enter = (e: React.KeyboardEvent) => { - if (e.key === "Enter") { - this.submitSearch(); - } - } - - collectionRef = React.createRef(); - startDragCollection = async () => { - const results = await this.getResults(this.searchString); - const docs = results.map(doc => { - const isProto = Doc.GetT(doc, "isPrototype", "boolean", true); - if (isProto) { - return Doc.MakeDelegate(doc); - } else { - return Doc.MakeAlias(doc); - } - }); - let x = 0; - let y = 0; - for (const doc of docs) { - doc.x = x; - doc.y = y; - const size = 200; - const aspect = NumCast(doc.nativeHeight) / NumCast(doc.nativeWidth, 1); - if (aspect > 1) { - doc.height = size; - doc.width = size / aspect; - } else if (aspect > 0) { - doc.width = size; - doc.height = size * aspect; - } else { - doc.width = size; - doc.height = size; - } - doc.zoomBasis = 1; - x += 250; - if (x > 1000) { - x = 0; - y += 300; - } - } - return Docs.Create.FreeformDocument(docs, { width: 400, height: 400, panX: 175, panY: 175, backgroundColor: "grey", title: `Search Docs: "${this.searchString}"` }); - } - - // Useful queries: - // Delegates of a document: {!join from=id to=proto_i}id:{protoId} - // Documents in a collection: {!join from=data_l to=id}id:{collectionProtoId} - render() { - return ( -
-
-
- - - - - {/* */} - {/* */} -
- {this._resultsOpen ? ( -
- {this._results.map(result => )} -
- ) : null} -
- {this._open ? ( -
- -
- filter by collection, key, type of node -
- -
- ) : null} -
- ); - } -} \ No newline at end of file diff --git a/src/client/views/search/SearchBox.tsx b/src/client/views/search/SearchBox.tsx index 8399605fb..b2a44f448 100644 --- a/src/client/views/search/SearchBox.tsx +++ b/src/client/views/search/SearchBox.tsx @@ -15,6 +15,9 @@ import { Id } from '../../../new_fields/FieldSymbols'; import { SearchUtil } from '../../util/SearchUtil'; import { RouteStore } from '../../../server/RouteStore'; import { FilterBox } from './FilterBox'; +import { ReadStream } from 'fs'; +import * as $ from 'jquery'; + @observer @@ -29,6 +32,7 @@ export class SearchBox extends React.Component { @observable private _visibleElements: JSX.Element[] = []; private resultsRef = React.createRef(); + public inputRef = React.createRef(); private _isSearch: ("search" | "placeholder" | undefined)[] = []; private _numTotalResults = -1; @@ -46,6 +50,15 @@ export class SearchBox extends React.Component { this.resultsScrolled = this.resultsScrolled.bind(this); } + componentDidMount = () => { + if (this.inputRef.current) { + this.inputRef.current.focus(); + runInAction(() => { + this._searchbarOpen = true; + }); + } + } + @action getViews = async (doc: Doc) => { const results = await SearchUtil.GetViewsOfDocument(doc); @@ -321,7 +334,7 @@ export class SearchBox extends React.Component { - -- cgit v1.2.3-70-g09d2 From bb6c9fd9ac199e0eaf51170e5cb014205991108b Mon Sep 17 00:00:00 2001 From: Mohammad Amoush Date: Wed, 17 Jul 2019 16:31:36 -0400 Subject: just centering --- src/client/views/ContextMenu.tsx | 2 +- src/client/views/DocumentDecorations.scss | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/client/views/ContextMenu.tsx b/src/client/views/ContextMenu.tsx index 1347d4197..60658b7f0 100644 --- a/src/client/views/ContextMenu.tsx +++ b/src/client/views/ContextMenu.tsx @@ -52,7 +52,7 @@ export class ContextMenu extends React.Component { document.addEventListener("pointerup", e => { runInAction(() => { this._mouseDown = false; - }) + }); let curX = e.clientX; let curY = e.clientY; if (this._mouseX !== curX || this._mouseY !== curY) { diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 0b7411fca..5557bff94 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -96,6 +96,7 @@ $linkGap : 3px; grid-column-end: 4; pointer-events: auto; overflow: hidden; + text-align: center; } } -- cgit v1.2.3-70-g09d2 From 16337a910fa40a145c9906ff865b7c3a621efc41 Mon Sep 17 00:00:00 2001 From: Mohammad Amoush Date: Wed, 17 Jul 2019 17:12:31 -0400 Subject: grays --- src/client/views/DocumentDecorations.scss | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 5557bff94..23d78b39f 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -92,6 +92,7 @@ $linkGap : 3px; .title { background: $alt-accent; + opacity: 0.8; grid-column-start: 3; grid-column-end: 4; pointer-events: auto; -- cgit v1.2.3-70-g09d2 From 98d6476cc1d18617399b28fa670848f97160ffa1 Mon Sep 17 00:00:00 2001 From: monikahedman Date: Wed, 17 Jul 2019 17:59:45 -0400 Subject: smol changes --- src/client/views/DocumentDecorations.scss | 12 +++++++----- src/client/views/DocumentDecorations.tsx | 7 +++++-- 2 files changed, 12 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 23d78b39f..537444a93 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -24,13 +24,13 @@ $linkGap : 3px; .documentDecorations-resizer { pointer-events: auto; background: $alt-accent; - opacity: 0.8; + opacity: 1; } .documentDecorations-radius { pointer-events: auto; background: black; - opacity: 0.8; + opacity: 1; transform: translate(10px, 10px); grid-row: 4; } @@ -92,7 +92,7 @@ $linkGap : 3px; .title { background: $alt-accent; - opacity: 0.8; + opacity: 1; grid-column-start: 3; grid-column-end: 4; pointer-events: auto; @@ -104,17 +104,18 @@ $linkGap : 3px; .documentDecorations-closeButton { background: $alt-accent; - opacity: 0.8; + opacity: 1; grid-column-start: 4; grid-column-end: 6; pointer-events: all; text-align: center; cursor: pointer; + padding-right: 10px; } .documentDecorations-minimizeButton { background: $alt-accent; - opacity: 0.8; + opacity: 1; grid-column-start: 1; grid-column-end: 3; pointer-events: all; @@ -123,6 +124,7 @@ $linkGap : 3px; position: absolute; left: 0px; top: 0px; + padding-top: 5px; width: $MINIMIZED_ICON_SIZE; height: $MINIMIZED_ICON_SIZE; } diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index fb5104915..d8a4bd071 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -1,5 +1,5 @@ import { library } from '@fortawesome/fontawesome-svg-core'; -import { faLink, faTag } from '@fortawesome/free-solid-svg-icons'; +import { faLink, faTag, faTimes } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { action, computed, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; @@ -34,6 +34,7 @@ export const Flyout = higflyout.default; library.add(faLink); library.add(faTag); +library.add(faTimes); @observer export class DocumentDecorations extends React.Component<{}, { value: string }> { @@ -726,7 +727,9 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> {this._edtingTitle ? :
{`${this.selectionTitle}`}
} -
X
+
+ +
e.preventDefault()}>
e.preventDefault()}>
e.preventDefault()}>
-- cgit v1.2.3-70-g09d2 From f3c02a5df4c589846d47f0c435456f4c83b58484 Mon Sep 17 00:00:00 2001 From: Mohammad Amoush Date: Thu, 18 Jul 2019 14:09:43 -0400 Subject: hi --- src/client/views/DocumentDecorations.scss | 5 ++++ src/client/views/DocumentDecorations.tsx | 2 +- src/client/views/Main.scss | 38 ++++++++++++++++++------------- 3 files changed, 28 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 537444a93..3627edaae 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -223,6 +223,11 @@ $linkGap : 3px; margin-top: 3px; } +.documentdecorations-times { + margin-top: 3px; + padding-right: 3px; +} + .templating-button, .docDecs-tagButton { width: 20px; diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index d8a4bd071..3be5146f6 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -728,7 +728,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> :
{`${this.selectionTitle}`}
}
- +
e.preventDefault()}>
e.preventDefault()}>
diff --git a/src/client/views/Main.scss b/src/client/views/Main.scss index a16123476..eed2ae4fa 100644 --- a/src/client/views/Main.scss +++ b/src/client/views/Main.scss @@ -24,7 +24,7 @@ div { .jsx-parser { width: 100%; - height:100%; + height: 100%; pointer-events: none; border-radius: inherit; } @@ -119,6 +119,7 @@ button:hover { margin-bottom: 10px; } } + .toolbar-color-picker { background-color: $light-color; border-radius: 5px; @@ -128,6 +129,7 @@ button:hover { left: -3px; box-shadow: $intermediate-color 0.2vw 0.2vw 0.8vw; } + .toolbar-color-button { border-radius: 11px; width: 22px; @@ -146,7 +148,7 @@ button:hover { bottom: 22px; left: 250px; - > label { + >label { background: $dark-color; color: $light-color; display: inline-block; @@ -168,15 +170,15 @@ button:hover { transform: scale(1.15); } - > input { + >input { display: none; } - > input:not(:checked)~#add-options-content { + >input:not(:checked)~#add-options-content { display: none; } - > input:checked~label { + >input:checked~label { transform: rotate(45deg); transition: transform 0.5s; cursor: pointer; @@ -221,7 +223,7 @@ ul#add-options-list { list-style: none; padding: 5 0 0 0; - > li { + >li { display: inline-block; padding: 0; } @@ -231,7 +233,7 @@ ul#add-options-list { height: 100%; position: absolute; display: flex; - flex-direction:column; + flex-direction: column; } .mainView-libraryHandle { @@ -243,21 +245,25 @@ ul#add-options-list { position: absolute; z-index: 1; } + .svg-inline--fa { vertical-align: unset; } + .mainView-workspace { - height:200px; - position:relative; - display:flex; + height: 200px; + position: relative; + display: flex; } + .mainView-library { - height:75%; - position:relative; - display:flex; + height: 75%; + position: relative; + display: flex; } + .mainView-recentlyClosed { - height:25%; - position:relative; - display:flex; + height: 25%; + position: relative; + display: flex; } \ No newline at end of file -- cgit v1.2.3-70-g09d2 From c1fa702ae9e748617121f28cbe65d21cdfdc1f7d Mon Sep 17 00:00:00 2001 From: monikahedman Date: Fri, 19 Jul 2019 10:43:52 -0400 Subject: search x --- src/client/views/search/SearchBox.scss | 5 +++++ src/client/views/search/SearchBox.tsx | 7 ++++++- 2 files changed, 11 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/client/views/search/SearchBox.scss b/src/client/views/search/SearchBox.scss index 109b88ac9..481ee5789 100644 --- a/src/client/views/search/SearchBox.scss +++ b/src/client/views/search/SearchBox.scss @@ -37,6 +37,11 @@ margin-left: 2px; margin-right: 2px } + + &.searchBox-close { + color: $light-color; + max-height: 32px; + } } } diff --git a/src/client/views/search/SearchBox.tsx b/src/client/views/search/SearchBox.tsx index b2a44f448..c45c3aaee 100644 --- a/src/client/views/search/SearchBox.tsx +++ b/src/client/views/search/SearchBox.tsx @@ -4,6 +4,8 @@ import { observable, action, runInAction, flow, computed } from 'mobx'; import "./SearchBox.scss"; import "./FilterBox.scss"; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { faTimes } from '@fortawesome/free-solid-svg-icons'; +import { library } from '@fortawesome/fontawesome-svg-core'; import { SetupDrag } from '../../util/DragManager'; import { Docs } from '../../documents/Documents'; import { NumCast, Cast } from '../../../new_fields/Types'; @@ -17,8 +19,9 @@ import { RouteStore } from '../../../server/RouteStore'; import { FilterBox } from './FilterBox'; import { ReadStream } from 'fs'; import * as $ from 'jquery'; +import { MainView } from '../MainView'; - +library.add(faTimes); @observer export class SearchBox extends React.Component { @@ -242,6 +245,7 @@ export class SearchBox extends React.Component { @action.bound closeSearch = () => { + console.log("closing search") FilterBox.Instance.closeFilter(); this.closeResults(); this._searchbarOpen = false; @@ -339,6 +343,7 @@ export class SearchBox extends React.Component { style={{ width: this._searchbarOpen ? "500px" : "100px" }} /> +
Date: Fri, 19 Jul 2019 10:47:56 -0400 Subject: lets try this again --- src/client/views/search/SearchBox.tsx | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/client/views/search/SearchBox.tsx b/src/client/views/search/SearchBox.tsx index c45c3aaee..2e1017d27 100644 --- a/src/client/views/search/SearchBox.tsx +++ b/src/client/views/search/SearchBox.tsx @@ -354,5 +354,4 @@ export class SearchBox extends React.Component {
); } - } \ No newline at end of file -- cgit v1.2.3-70-g09d2 From e0709211b80f5e69384318ebe007c877cd6dbfd5 Mon Sep 17 00:00:00 2001 From: Eleanor Eng Date: Fri, 19 Jul 2019 11:38:10 -0400 Subject: mac resize fix --- src/client/views/DocumentDecorations.tsx | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 3be5146f6..bf880b9c3 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -63,6 +63,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> @observable private _opacity = 1; @observable private _removeIcon = false; @observable public Interacting = false; + @observable private _isMoving = false; constructor(props: Readonly<{}>) { super(props); @@ -337,9 +338,14 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> document.addEventListener("pointermove", this.onRadiusMove); document.addEventListener("pointerup", this.onRadiusUp); } + if (!this._isMoving) { + let dist = Math.sqrt((e.clientX - this._radiusDown[0]) * (e.clientX - this._radiusDown[0]) + (e.clientY - this._radiusDown[1]) * (e.clientY - this._radiusDown[1])); + SelectionManager.SelectedDocuments().map(dv => dv.props.Document.borderRounding = Doc.GetProto(dv.props.Document).borderRounding = `${Math.min(100, dist)}%`); + } } onRadiusMove = (e: PointerEvent): void => { + this._isMoving = true; let dist = Math.sqrt((e.clientX - this._radiusDown[0]) * (e.clientX - this._radiusDown[0]) + (e.clientY - this._radiusDown[1]) * (e.clientY - this._radiusDown[1])); SelectionManager.SelectedDocuments().map(dv => dv.props.Document.borderRounding = Doc.GetProto(dv.props.Document).borderRounding = `${Math.min(100, dist)}%`); e.stopPropagation(); @@ -351,6 +357,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> e.preventDefault(); this._isPointerDown = false; this._resizeUndo && this._resizeUndo.end(); + this._isMoving = false; document.removeEventListener("pointermove", this.onRadiusMove); document.removeEventListener("pointerup", this.onRadiusUp); } -- cgit v1.2.3-70-g09d2 From 87b4d7ab7a28a01335dd081fc85c010a22aae5d1 Mon Sep 17 00:00:00 2001 From: Eleanor Eng Date: Fri, 19 Jul 2019 11:42:25 -0400 Subject: it's just 0 --- src/client/views/DocumentDecorations.tsx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index bf880b9c3..60dcf06cd 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -339,8 +339,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> document.addEventListener("pointerup", this.onRadiusUp); } if (!this._isMoving) { - let dist = Math.sqrt((e.clientX - this._radiusDown[0]) * (e.clientX - this._radiusDown[0]) + (e.clientY - this._radiusDown[1]) * (e.clientY - this._radiusDown[1])); - SelectionManager.SelectedDocuments().map(dv => dv.props.Document.borderRounding = Doc.GetProto(dv.props.Document).borderRounding = `${Math.min(100, dist)}%`); + SelectionManager.SelectedDocuments().map(dv => dv.props.Document.borderRounding = Doc.GetProto(dv.props.Document).borderRounding = `${Math.min(100, 0)}%`); } } -- cgit v1.2.3-70-g09d2 From 0c7a6d755c3394a027309c5469d170834e2de787 Mon Sep 17 00:00:00 2001 From: Eleanor Eng Date: Fri, 19 Jul 2019 12:31:56 -0400 Subject: gross color button is FIXED --- src/client/views/Main.scss | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/client/views/Main.scss b/src/client/views/Main.scss index eed2ae4fa..04249506a 100644 --- a/src/client/views/Main.scss +++ b/src/client/views/Main.scss @@ -140,6 +140,8 @@ button:hover { // font-size: 8px; // user-select: none; // } + margin-top: -2.55px; + margin-left: -2.55px; } // add nodes menu. Note that the + button is actually an input label, not an actual button. -- cgit v1.2.3-70-g09d2 From 0191d5dfb07b6e50e5bda4523b79ff9769159541 Mon Sep 17 00:00:00 2001 From: monikahedman Date: Fri, 19 Jul 2019 16:33:19 -0400 Subject: changed min --- src/client/views/DocumentDecorations.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 60dcf06cd..8e63ea4c3 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -339,7 +339,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> document.addEventListener("pointerup", this.onRadiusUp); } if (!this._isMoving) { - SelectionManager.SelectedDocuments().map(dv => dv.props.Document.borderRounding = Doc.GetProto(dv.props.Document).borderRounding = `${Math.min(100, 0)}%`); + SelectionManager.SelectedDocuments().map(dv => dv.props.Document.borderRounding = Doc.GetProto(dv.props.Document).borderRounding = `0%`); } } -- cgit v1.2.3-70-g09d2 From ae62e415d18b83fb1ef6b4a8f438b1d7e8d3157a Mon Sep 17 00:00:00 2001 From: HJF Bulterman Date: Fri, 9 Aug 2019 11:31:57 -0400 Subject: initial commit - individual presentation document view showing but with errors --- src/client/documents/Documents.ts | 13 +- src/client/views/MainView.tsx | 7 +- src/client/views/nodes/DocumentContentsView.tsx | 3 +- src/client/views/nodes/DocumentView.tsx | 2 +- src/client/views/nodes/FieldView.tsx | 5 + src/client/views/nodes/PresBox.tsx | 880 ++++++++++++++++++++++++ src/client/views/pdf/PDFMenu.tsx | 2 +- src/new_fields/PresField.ts | 6 + 8 files changed, 912 insertions(+), 6 deletions(-) create mode 100644 src/client/views/nodes/PresBox.tsx create mode 100644 src/new_fields/PresField.ts (limited to 'src') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index ee1b9fd0d..492aebf4a 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -40,6 +40,9 @@ import DirectoryImportBox from "../util/Import & Export/DirectoryImportBox"; import { Scripting } from "../util/Scripting"; import { ButtonBox } from "../views/nodes/ButtonBox"; import { SchemaHeaderField, RandomPastel } from "../../new_fields/SchemaHeaderField"; +import { PresBox } from "../views/nodes/PresBox"; +//import { PresBox } from "../views/nodes/PresBox"; +//import { PresField } from "../../new_fields/PresField"; var requestImageSize = require('../util/request-image-size'); var path = require('path'); @@ -60,7 +63,8 @@ export enum DocumentType { LINKDOC = "linkdoc", BUTTON = "button", TEMPLATE = "template", - EXTENSION = "extension" + EXTENSION = "extension", + PRES = "presentation" } export interface DocumentOptions { @@ -168,6 +172,10 @@ export namespace Docs { }], [DocumentType.BUTTON, { layout: { view: ButtonBox }, + }], + [DocumentType.PRES, { + layout: { view: PresBox }, + options: {} }] ]); @@ -335,6 +343,9 @@ export namespace Docs { .catch((err: any) => console.log(err)); return inst; } + export function PresDocument(initial: List = new List(), options: DocumentOptions = {}) { + return InstanceFromProto(Prototypes.get(DocumentType.PRES), initial, options); + } export function VideoDocument(url: string, options: DocumentOptions = {}) { return InstanceFromProto(Prototypes.get(DocumentType.VID), new VideoField(new URL(url)), options); diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index f5a6715e5..14cfc6792 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -58,7 +58,8 @@ export class MainView extends React.Component { private set mainContainer(doc: Opt) { if (doc) { if (!("presentationView" in doc)) { - doc.presentationView = new List([Docs.Create.TreeDocument([], { title: "Presentation" })]); + let initialDoc = Docs.Create.TreeDocument([], { title: "Presentation" }); + doc.presentationView = Docs.Create.PresDocument(new List([initialDoc])); } CurrentUserUtils.UserDocument.activeWorkspace = doc; } @@ -384,11 +385,13 @@ export class MainView extends React.Component { let addButtonDocument = action(() => Docs.Create.ButtonDocument({ width: 150, height: 50, title: "Button" })); let addImportCollectionNode = action(() => Docs.Create.DirectoryImportDocument({ title: "Directory Import", width: 400, height: 400 })); + let addPresentationNode = action(() => Docs.Create.PresDocument(new List([Docs.Create.TreeDocument([], { title: "Presentation" })]))); + let btns: [React.RefObject, IconName, string, () => Doc][] = [ [React.createRef(), "object-group", "Add Collection", addColNode], [React.createRef(), "bolt", "Add Button", addButtonDocument], // [React.createRef(), "clone", "Add Docking Frame", addDockingNode], - [React.createRef(), "cloud-upload-alt", "Import Directory", addImportCollectionNode], + [React.createRef(), "cloud-upload-alt", "Import Directory", addPresentationNode], //remove at some point in favor of addImportCollectionNode ]; if (!ClientUtils.RELEASE) btns.unshift([React.createRef(), "cat", "Add Cat Image", addImageNode]); diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index 91d4fb524..f74336cdd 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -12,6 +12,7 @@ import "./DocumentView.scss"; import { FormattedTextBox } from "./FormattedTextBox"; import { ImageBox } from "./ImageBox"; import { ButtonBox } from "./ButtonBox"; +import { PresBox } from "./PresBox"; import { IconBox } from "./IconBox"; import { KeyValueBox } from "./KeyValueBox"; import { PDFBox } from "./PDFBox"; @@ -98,7 +99,7 @@ export class DocumentContentsView extends React.Component 7) return (null); if (!this.layout && (this.props.layoutKey !== "overlayLayout" || !this.templates.length)) return (null); return (Docu subitems.push({ description: "Open Fields", event: this.fieldsClicked, icon: "layer-group" }); cm.addItem({ description: "Open...", subitems: subitems, icon: "external-link-alt" }); cm.addItem({ description: BoolCast(this.props.Document.ignoreAspect, false) || !this.props.Document.nativeWidth || !this.props.Document.nativeHeight ? "Freeze" : "Unfreeze", event: this.freezeNativeDimensions, icon: "snowflake" }); - cm.addItem({ description: "Pin to Presentation", event: () => PresentationView.Instance.PinDoc(this.props.Document), icon: "map-pin" }); + cm.addItem({ description: "Pin to Presentation", event: () => PresentationView.Instance.PinDoc(this.props.Document), icon: "map-pin" }); //change this to cm.addItem({ description: BoolCast(this.props.Document.lockedPosition) ? "Unlock Position" : "Lock Position", event: this.toggleLockPosition, icon: BoolCast(this.props.Document.lockedPosition) ? "unlock" : "lock" }); let makes: ContextMenuProps[] = []; makes.push({ description: "Make Background", event: this.makeBackground, icon: BoolCast(this.props.Document.lockedPosition) ? "unlock" : "lock" }); diff --git a/src/client/views/nodes/FieldView.tsx b/src/client/views/nodes/FieldView.tsx index ffaee8042..b1030d19d 100644 --- a/src/client/views/nodes/FieldView.tsx +++ b/src/client/views/nodes/FieldView.tsx @@ -18,6 +18,7 @@ import { ImageBox } from "./ImageBox"; import { PDFBox } from "./PDFBox"; import { VideoBox } from "./VideoBox"; import { Id } from "../../../new_fields/FieldSymbols"; +import { PresBox } from "./PresBox"; // // these properties get assigned through the render() method of the DocumentView when it creates this node. @@ -54,6 +55,7 @@ export interface FieldViewProps { export class FieldView extends React.Component { public static LayoutString(fieldType: { name: string }, fieldStr: string = "data", fieldExt: string = "") { return `<${fieldType.name} {...props} fieldKey={"${fieldStr}"} fieldExt={"${fieldExt}"} />`; + //"" } @computed @@ -75,6 +77,9 @@ export class FieldView extends React.Component { else if (field instanceof ImageField) { return ; } + // else if (field instaceof PresBox) { + // return ; + // } else if (field instanceof IconField) { return ; } diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx new file mode 100644 index 000000000..2feb32693 --- /dev/null +++ b/src/client/views/nodes/PresBox.tsx @@ -0,0 +1,880 @@ +import React = require("react"); +import { FieldViewProps, FieldView } from './FieldView'; +import { observer } from "mobx-react"; +import { observable, action, runInAction, reaction, autorun, computed } from "mobx"; +import "../presentationview/PresentationView.scss"; +import { DocumentManager } from "../../util/DocumentManager"; +import { Utils } from "../../../Utils"; +import { Doc, DocListCast, DocListCastAsync } from "../../../new_fields/Doc"; +import { listSpec } from "../../../new_fields/Schema"; +import { Cast, NumCast, FieldValue, PromiseValue, StrCast, BoolCast } from "../../../new_fields/Types"; +import { Id } from "../../../new_fields/FieldSymbols"; +import { List } from "../../../new_fields/List"; +import PresentationElement, { buttonIndex } from "../presentationview/PresentationElement"; +import { library } from '@fortawesome/fontawesome-svg-core'; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { faArrowRight, faArrowLeft, faPlay, faStop, faPlus, faTimes, faMinus, faEdit } from '@fortawesome/free-solid-svg-icons'; +import { Docs } from "../../documents/Documents"; +import { undoBatch, UndoManager } from "../../util/UndoManager"; +import PresentationViewList from "../presentationview/PresentationList"; + +library.add(faArrowLeft); +library.add(faArrowRight); +library.add(faPlay); +library.add(faStop); +library.add(faPlus); +library.add(faTimes); +library.add(faMinus); +library.add(faEdit); + + +export interface PresViewProps { + Documents: List; +} + +const expandedWidth = 400; + +@observer +export class PresBox extends React.Component { //FieldViewProps? + + @computed + private get presentationDocs() { + let source = Doc.GetProto(this.props.Document); + return DocListCast(source.data); + } + + public static LayoutString(fieldKey?: string) { return FieldView.LayoutString(PresBox, fieldKey); } + + //public static Instance: PresentationView; + public static Instance: PresBox; + + //Mapping from presentation ids to a list of doc that represent a group + @observable groupMappings: Map = new Map(); + //mapping from docs to their rendered component + @observable presElementsMappings: Map = new Map(); + //variable that holds all the docs in the presentation + @observable childrenDocs: Doc[] = []; + //variable to hold if presentation is started + @observable presStatus: boolean = false; + //back-up so that presentation stays the way it's when refreshed + @observable presGroupBackUp: Doc = new Doc(); + @observable presButtonBackUp: Doc = new Doc(); + + //Keeping track of the doc for the current presentation + @observable curPresentation: Doc = new Doc(); + //Mapping of guids to presentations. + @observable presentationsMapping: Map = new Map(); + //Mapping of presentations to guid, so that select option values can be given. + @observable presentationsKeyMapping: Map = new Map(); + //Variable to keep track of guid of the current presentation + @observable currentSelectedPresValue: string | undefined; + //A flag to keep track if title input is open, which is used in rendering. + @observable PresTitleInputOpen: boolean = false; + //Variable that holds reference to title input, so that new presentations get titles assigned. + @observable titleInputElement: HTMLInputElement | undefined; + @observable PresTitleChangeOpen: boolean = false; + + @observable opacity = 1; + @observable persistOpacity = true; + @observable labelOpacity = 0; + + //initilize class variables + constructor(props: FieldViewProps) { //FieldViewProps? + super(props); + //PresentationView.Instance = this; + PresBox.Instance = this; + } + + @action + toggle = (forcedValue: boolean | undefined) => { + if (forcedValue !== undefined) { + this.curPresentation.width = forcedValue ? expandedWidth : 0; + } else { + this.curPresentation.width = this.curPresentation.width === expandedWidth ? 0 : expandedWidth; + } + } + + //The first lifecycle function that gets called to set up the current presentation. + async componentWillMount() { + this.presentationDocs.forEach(async (doc, index: number) => { + + //For each presentation received from mainContainer, a mapping is created. + let curDoc: Doc = await doc; + let newGuid = Utils.GenerateGuid(); + this.presentationsKeyMapping.set(curDoc, newGuid); + this.presentationsMapping.set(newGuid, curDoc); + + //The Presentation at first index gets set as default start presentation + if (index === 0) { + runInAction(() => this.currentSelectedPresValue = newGuid); + runInAction(() => this.curPresentation = curDoc); + } + }); + } + + //Second lifecycle function that gets called when component mounts. It makes sure to + //get the back-up information from previous session for the current presentation. + async componentDidMount() { + let docAtZero = await this.presentationDocs[0]; + runInAction(() => this.curPresentation = docAtZero); + + this.setPresentationBackUps(); + + } + + + /** + * The function that retrieves the backUps for the current Presentation if present, + * otherwise initializes. + */ + setPresentationBackUps = async () => { + //getting both backUp documents + + let castedGroupBackUp = Cast(this.curPresentation.presGroupBackUp, Doc); + let castedButtonBackUp = Cast(this.curPresentation.presButtonBackUp, Doc); + //if instantiated before + if (castedGroupBackUp instanceof Promise) { + castedGroupBackUp.then(doc => { + let toAssign = doc ? doc : new Doc(); + this.curPresentation.presGroupBackUp = toAssign; + runInAction(() => this.presGroupBackUp = toAssign); + if (doc) { + if (toAssign[Id] === doc[Id]) { + this.retrieveGroupMappings(); + } + } + }); + + //if never instantiated a store doc yet + } else if (castedGroupBackUp instanceof Doc) { + let castedDoc: Doc = await castedGroupBackUp; + runInAction(() => this.presGroupBackUp = castedDoc); + this.retrieveGroupMappings(); + } else { + runInAction(() => { + let toAssign = new Doc(); + this.presGroupBackUp = toAssign; + this.curPresentation.presGroupBackUp = toAssign; + + }); + + } + //if instantiated before + if (castedButtonBackUp instanceof Promise) { + castedButtonBackUp.then(doc => { + let toAssign = doc ? doc : new Doc(); + this.curPresentation.presButtonBackUp = toAssign; + runInAction(() => this.presButtonBackUp = toAssign); + }); + + //if never instantiated a store doc yet + } else if (castedButtonBackUp instanceof Doc) { + let castedDoc: Doc = await castedButtonBackUp; + runInAction(() => this.presButtonBackUp = castedDoc); + + } else { + runInAction(() => { + let toAssign = new Doc(); + this.presButtonBackUp = toAssign; + this.curPresentation.presButtonBackUp = toAssign; + }); + + } + + + //storing the presentation status,ie. whether it was stopped or playing + let presStatusBackUp = BoolCast(this.curPresentation.presStatus); + runInAction(() => this.presStatus = presStatusBackUp); + } + + /** + * This is the function that is called to retrieve the groups that have been stored and + * push them to the groupMappings. + */ + retrieveGroupMappings = async () => { + let castedGroupDocs = await DocListCastAsync(this.presGroupBackUp.groupDocs); + if (castedGroupDocs !== undefined) { + castedGroupDocs.forEach(async (groupDoc: Doc, index: number) => { + let castedGrouping = await DocListCastAsync(groupDoc.grouping); + let castedKey = StrCast(groupDoc.presentIdStore, null); + if (castedGrouping) { + castedGrouping.forEach((doc: Doc) => { + doc.presentId = castedKey; + }); + } + if (castedGrouping !== undefined && castedKey !== undefined) { + this.groupMappings.set(castedKey, castedGrouping); + } + }); + } + } + + //observable means render is re-called every time variable is changed + @observable + collapsed: boolean = false; + closePresentation = action(() => this.curPresentation.width = 0); + next = async () => { + const current = NumCast(this.curPresentation.selectedDoc); + //asking to get document at current index + let docAtCurrentNext = await this.getDocAtIndex(current + 1); + if (docAtCurrentNext === undefined) { + return; + } + //asking for it's presentation id + let curNextPresId = StrCast(docAtCurrentNext.presentId); + let nextSelected = current + 1; + + //if curDoc is in a group, selection slides until last one, if not it's next one + if (this.groupMappings.has(curNextPresId)) { + let currentsArray = this.groupMappings.get(StrCast(docAtCurrentNext.presentId))!; + nextSelected = current + currentsArray.length - currentsArray.indexOf(docAtCurrentNext); + + //end of grup so go beyond + if (nextSelected === current) nextSelected = current + 1; + } + + this.gotoDocument(nextSelected, current); + + } + back = async () => { + const current = NumCast(this.curPresentation.selectedDoc); + //requesting for the doc at current index + let docAtCurrent = await this.getDocAtIndex(current); + if (docAtCurrent === undefined) { + return; + } + + //asking for its presentation id. + let curPresId = StrCast(docAtCurrent.presentId); + let prevSelected = current - 1; + let zoomOut: boolean = false; + + //checking if this presentation id is mapped to a group, if so chosing the first element in group + if (this.groupMappings.has(curPresId)) { + let currentsArray = this.groupMappings.get(StrCast(docAtCurrent.presentId))!; + prevSelected = current - currentsArray.length + (currentsArray.length - currentsArray.indexOf(docAtCurrent)) - 1; + //end of grup so go beyond + if (prevSelected === current) prevSelected = current - 1; + + //checking if any of the group members had used zooming in + currentsArray.forEach((doc: Doc) => { + //let presElem: PresentationElement | undefined = this.presElementsMappings.get(doc); + if (this.presElementsMappings.get(doc)!.selected[buttonIndex.Show]) { + zoomOut = true; + return; + } + }); + + } + + // if a group set that flag to zero or a single element + //If so making sure to zoom out, which goes back to state before zooming action + if (current > 0) { + if (zoomOut || this.presElementsMappings.get(docAtCurrent)!.selected[buttonIndex.Show]) { + let prevScale = NumCast(this.childrenDocs[prevSelected].viewScale, null); + let curScale = DocumentManager.Instance.getScaleOfDocView(this.childrenDocs[current]); + if (prevScale !== undefined) { + if (prevScale !== curScale) { + DocumentManager.Instance.zoomIntoScale(docAtCurrent, prevScale); + } + } + } + } + this.gotoDocument(prevSelected, current); + + } + + /** + * This is the method that checks for the actions that need to be performed + * after the document has been presented, which involves 3 button options: + * Hide Until Presented, Hide After Presented, Fade After Presented + */ + showAfterPresented = (index: number) => { + this.presElementsMappings.forEach((presElem: PresentationElement, key: Doc) => { + let selectedButtons: boolean[] = presElem.selected; + //the order of cases is aligned based on priority + if (selectedButtons[buttonIndex.HideTillPressed]) { + if (this.childrenDocs.indexOf(key) <= index) { + key.opacity = 1; + } + } + if (selectedButtons[buttonIndex.HideAfter]) { + if (this.childrenDocs.indexOf(key) < index) { + key.opacity = 0; + } + } + if (selectedButtons[buttonIndex.FadeAfter]) { + if (this.childrenDocs.indexOf(key) < index) { + key.opacity = 0.5; + } + } + }); + } + + /** + * This is the method that checks for the actions that need to be performed + * before the document has been presented, which involves 3 button options: + * Hide Until Presented, Hide After Presented, Fade After Presented + */ + hideIfNotPresented = (index: number) => { + this.presElementsMappings.forEach((presElem: PresentationElement, key: Doc) => { + let selectedButtons: boolean[] = presElem.selected; + + //the order of cases is aligned based on priority + + if (selectedButtons[buttonIndex.HideAfter]) { + if (this.childrenDocs.indexOf(key) >= index) { + key.opacity = 1; + } + } + if (selectedButtons[buttonIndex.FadeAfter]) { + if (this.childrenDocs.indexOf(key) >= index) { + key.opacity = 1; + } + } + if (selectedButtons[buttonIndex.HideTillPressed]) { + if (this.childrenDocs.indexOf(key) > index) { + key.opacity = 0; + } + } + }); + } + + /** + * This method makes sure that cursor navigates to the element that + * has the option open and last in the group. If not in the group, and it has + * te option open, navigates to that element. + */ + navigateToElement = async (curDoc: Doc, fromDoc: number) => { + let docToJump: Doc = curDoc; + let curDocPresId = StrCast(curDoc.presentId, null); + let willZoom: boolean = false; + + //checking if in group + if (curDocPresId !== undefined) { + if (this.groupMappings.has(curDocPresId)) { + let currentDocGroup = this.groupMappings.get(curDocPresId)!; + currentDocGroup.forEach((doc: Doc, index: number) => { + let selectedButtons: boolean[] = this.presElementsMappings.get(doc)!.selected; + if (selectedButtons[buttonIndex.Navigate]) { + docToJump = doc; + willZoom = false; + } + if (selectedButtons[buttonIndex.Show]) { + docToJump = doc; + willZoom = true; + } + }); + } + + } + //docToJump stayed same meaning, it was not in the group or was the last element in the group + if (docToJump === curDoc) { + //checking if curDoc has navigation open + let curDocButtons = this.presElementsMappings.get(curDoc)!.selected; + if (curDocButtons[buttonIndex.Navigate]) { + DocumentManager.Instance.jumpToDocument(curDoc, false); + } else if (curDocButtons[buttonIndex.Show]) { + let curScale = DocumentManager.Instance.getScaleOfDocView(this.childrenDocs[fromDoc]); + //awaiting jump so that new scale can be found, since jumping is async + await DocumentManager.Instance.jumpToDocument(curDoc, true); + let newScale = DocumentManager.Instance.getScaleOfDocView(curDoc); + curDoc.viewScale = newScale; + + //saving the scale user was on before zooming in + if (curScale !== 1) { + this.childrenDocs[fromDoc].viewScale = curScale; + } + + } + return; + } + let curScale = DocumentManager.Instance.getScaleOfDocView(this.childrenDocs[fromDoc]); + + //awaiting jump so that new scale can be found, since jumping is async + await DocumentManager.Instance.jumpToDocument(docToJump, willZoom); + let newScale = DocumentManager.Instance.getScaleOfDocView(curDoc); + curDoc.viewScale = newScale; + //saving the scale that user was on + if (curScale !== 1) { + this.childrenDocs[fromDoc].viewScale = curScale; + } + + } + + /** + * Async function that supposedly return the doc that is located at given index. + */ + getDocAtIndex = async (index: number) => { + const list = FieldValue(Cast(this.curPresentation.data, listSpec(Doc))); + if (!list) { + return undefined; + } + if (index < 0 || index >= list.length) { + return undefined; + } + + this.curPresentation.selectedDoc = index; + //awaiting async call to finish to get Doc instance + const doc = await list[index]; + return doc; + } + + /** + * The function that removes a doc from a presentation. It also makes sure to + * do necessary updates to backUps and mappings stored locally. + */ + @action + public RemoveDoc = async (index: number) => { + const value = FieldValue(Cast(this.curPresentation.data, listSpec(Doc))); + if (value) { + let removedDoc = await value.splice(index, 1)[0]; + + //removing the Presentation Element stored for it + this.presElementsMappings.delete(removedDoc); + + let removedDocPresentId = StrCast(removedDoc.presentId); + + //Removing it from local mapping of the groups + if (this.groupMappings.has(removedDocPresentId)) { + let removedDocsGroup = this.groupMappings.get(removedDocPresentId); + if (removedDocsGroup) { + removedDocsGroup.splice(removedDocsGroup.indexOf(removedDoc), 1); + if (removedDocsGroup.length === 0) { + this.groupMappings.delete(removedDocPresentId); + } + } + } + + //removing it from the backUp of selected Buttons + // let castedList = Cast(this.presButtonBackUp.selectedButtonDocs, listSpec(Doc)); + // if (castedList) { + // castedList.forEach(async (doc, indexOfDoc) => { + // let curDoc = await doc; + // let curDocId = StrCast(curDoc.docId); + // if (curDocId === removedDoc[Id]) { + // if (castedList) { + // castedList.splice(indexOfDoc, 1); + // return; + // } + // } + // }); + + // } + //removing it from the backUp of selected Buttons + + let castedList = Cast(this.presButtonBackUp.selectedButtonDocs, listSpec(Doc)); + if (castedList) { + for (let doc of castedList) { + let curDoc = await doc; + let curDocId = StrCast(curDoc.docId); + if (curDocId === removedDoc[Id]) { + castedList.splice(castedList.indexOf(curDoc), 1); + break; + + } + } + } + + //removing it from the backup of groups + let castedGroupDocs = await DocListCastAsync(this.presGroupBackUp.groupDocs); + if (castedGroupDocs) { + castedGroupDocs.forEach(async (groupDoc: Doc, index: number) => { + let castedKey = StrCast(groupDoc.presentIdStore, null); + if (castedKey === removedDocPresentId) { + let castedGrouping = await DocListCastAsync(groupDoc.grouping); + if (castedGrouping) { + castedGrouping.splice(castedGrouping.indexOf(removedDoc), 1); + if (castedGrouping.length === 0) { + castedGroupDocs!.splice(castedGroupDocs!.indexOf(groupDoc), 1); + } + } + } + + }); + + } + + + } + } + + public removeDocByRef = (doc: Doc) => { + let indexOfDoc = this.childrenDocs.indexOf(doc); + const value = FieldValue(Cast(this.curPresentation.data, listSpec(Doc))); + if (value) { + value.splice(indexOfDoc, 1)[0]; + } + //this.RemoveDoc(indexOfDoc, true); + if (indexOfDoc !== - 1) { + return true; + } + return false; + } + + //The function that is called when a document is clicked or reached through next or back. + //it'll also execute the necessary actions if presentation is playing. + @action + public gotoDocument = async (index: number, fromDoc: number) => { + const list = FieldValue(Cast(this.curPresentation.data, listSpec(Doc))); + if (!list) { + return; + } + if (index < 0 || index >= list.length) { + return; + } + this.curPresentation.selectedDoc = index; + + if (!this.presStatus) { + this.presStatus = true; + this.startPresentation(index); + } + + const doc = await list[index]; + if (this.presStatus) { + this.navigateToElement(doc, fromDoc); + this.hideIfNotPresented(index); + this.showAfterPresented(index); + } + + } + + //Function that is called to resetGroupIds, so that documents get new groupIds at + //first load, when presentation is changed. + resetGroupIds = async () => { + let castedGroupDocs = await DocListCastAsync(this.presGroupBackUp.groupDocs); + if (castedGroupDocs !== undefined) { + castedGroupDocs.forEach(async (groupDoc: Doc, index: number) => { + let castedGrouping = await DocListCastAsync(groupDoc.grouping); + if (castedGrouping) { + castedGrouping.forEach((doc: Doc) => { + doc.presentId = Utils.GenerateGuid(); + }); + } + }); + } + runInAction(() => this.groupMappings = new Map()); + } + + /** + * Adds a document to the presentation view + **/ + @undoBatch + @action + public PinDoc(doc: Doc) { + //add this new doc to props.Document + const data = Cast(this.curPresentation.data, listSpec(Doc)); + if (data) { + data.push(doc); + } else { + this.curPresentation.data = new List([doc]); + } + + this.toggle(true); + } + + //Function that sets the store of the children docs. + @action + setChildrenDocs = (docList: Doc[]) => { + this.childrenDocs = docList; + } + + //The function that is called to render the play or pause button depending on + //if presentation is running or not. + renderPlayPauseButton = () => { + if (this.presStatus) { + return ; + } else { + return ; + } + } + + //The function that starts or resets presentaton functionally, depending on status flag. + @action + startOrResetPres = () => { + if (this.presStatus) { + this.resetPresentation(); + } else { + this.presStatus = true; + this.startPresentation(0); + const current = NumCast(this.curPresentation.selectedDoc); + this.gotoDocument(0, current); + } + this.curPresentation.presStatus = this.presStatus; + } + + //The function that resets the presentation by removing every action done by it. It also + //stops the presentaton. + @action + resetPresentation = () => { + this.childrenDocs.forEach((doc: Doc) => { + doc.opacity = 1; + doc.viewScale = 1; + }); + this.curPresentation.selectedDoc = 0; + this.presStatus = false; + this.curPresentation.presStatus = this.presStatus; + if (this.childrenDocs.length === 0) { + return; + } + DocumentManager.Instance.zoomIntoScale(this.childrenDocs[0], 1); + } + + + //The function that starts the presentation, also checking if actions should be applied + //directly at start. + startPresentation = (startIndex: number) => { + let selectedButtons: boolean[]; + this.presElementsMappings.forEach((component: PresentationElement, doc: Doc) => { + selectedButtons = component.selected; + if (selectedButtons[buttonIndex.HideTillPressed]) { + if (this.childrenDocs.indexOf(doc) > startIndex) { + doc.opacity = 0; + } + + } + if (selectedButtons[buttonIndex.HideAfter]) { + if (this.childrenDocs.indexOf(doc) < startIndex) { + doc.opacity = 0; + } + } + if (selectedButtons[buttonIndex.FadeAfter]) { + if (this.childrenDocs.indexOf(doc) < startIndex) { + doc.opacity = 0.5; + } + } + + }); + + } + + /** + * The function that is called to add a new presentation to the presentationView. + * It sets up te mappings and local copies of it. Resets the groupings and presentation. + * Makes the new presentation current selected, and retrieve the back-Ups if present. + */ + @action + addNewPresentation = (presTitle: string) => { + //creating a new presentation doc + let newPresentationDoc = Docs.Create.TreeDocument([], { title: presTitle }); + let presDocs = Cast(Doc.GetProto(this.props.Document).data, listSpec(Doc)); + presDocs && presDocs.push(newPresentationDoc); + + //setting that new doc as current + this.curPresentation = newPresentationDoc; + + //storing the doc in local copies for easier access + let newGuid = Utils.GenerateGuid(); + this.presentationsMapping.set(newGuid, newPresentationDoc); + this.presentationsKeyMapping.set(newPresentationDoc, newGuid); + + //resetting the previous presentation's actions so that new presentation can be loaded. + this.resetGroupIds(); + this.resetPresentation(); + this.presElementsMappings = new Map(); + this.currentSelectedPresValue = newGuid; + this.setPresentationBackUps(); + + } + + /** + * The function that is called to change the current selected presentation. + * Changes the presentation, also resetting groupings and presentation in process. + * Plus retrieving the backUps for the newly selected presentation. + */ + @action + getSelectedPresentation = (e: React.ChangeEvent) => { + //get the guid of the selected presentation + let selectedGuid = e.target.value; + //set that as current presentation + this.curPresentation = this.presentationsMapping.get(selectedGuid)!; + + //reset current Presentations local things so that new one can be loaded + this.resetGroupIds(); + this.resetPresentation(); + this.presElementsMappings = new Map(); + this.currentSelectedPresValue = selectedGuid; + this.setPresentationBackUps(); + + + } + + /** + * The function that is called to render either select for presentations, or title inputting. + */ + renderSelectOrPresSelection = () => { + let presentationList = this.presentationDocs; + if (this.PresTitleInputOpen || this.PresTitleChangeOpen) { + return this.titleInputElement = e!} type="text" className="presentationView-title" placeholder="Enter Name!" onKeyDown={this.submitPresentationTitle} />; + } else { + return ; + } + } + + /** + * The function that is called on enter press of title input. It gives the + * new presentation the title user entered. If nothing is entered, gives a default title. + */ + @action + submitPresentationTitle = (e: React.KeyboardEvent) => { + if (e.keyCode === 13) { + let presTitle = this.titleInputElement!.value; + this.titleInputElement!.value = ""; + if (this.PresTitleInputOpen) { + if (presTitle === "") { + presTitle = "Presentation"; + } + this.PresTitleInputOpen = false; + this.addNewPresentation(presTitle); + } else if (this.PresTitleChangeOpen) { + this.PresTitleChangeOpen = false; + this.changePresentationTitle(presTitle); + } + } + } + + /** + * The function that is called to remove a presentation from all its copies, and the main Container's + * list. Sets up the next presentation as current. + */ + @action + removePresentation = async () => { + if (this.presentationsMapping.size !== 1) { + let presentationList = this.presentationDocs; + let batch = UndoManager.StartBatch("presRemoval"); + + //getting the presentation that will be removed + let removedDoc = this.presentationsMapping.get(this.currentSelectedPresValue!); + //that presentation is removed + presentationList!.splice(presentationList!.indexOf(removedDoc!), 1); + + //its mappings are removed from local copies + this.presentationsKeyMapping.delete(removedDoc!); + this.presentationsMapping.delete(this.currentSelectedPresValue!); + + //the next presentation is set as current + let remainingPresentations = this.presentationsMapping.values(); + let nextDoc = remainingPresentations.next().value; + this.curPresentation = nextDoc; + + + //Storing these for being able to undo changes + let curGuid = this.currentSelectedPresValue!; + let curPresStatus = this.presStatus; + + //resetting the groups and presentation actions so that next presentation gets loaded + this.resetGroupIds(); + this.resetPresentation(); + this.currentSelectedPresValue = this.presentationsKeyMapping.get(nextDoc)!.toString(); + this.setPresentationBackUps(); + + //Storing for undo + let currentGroups = this.groupMappings; + let curPresElemMapping = this.presElementsMappings; + + //Event to undo actions that are not related to doc directly, aka. local things + UndoManager.AddEvent({ + undo: action(() => { + this.curPresentation = removedDoc!; + this.presentationsMapping.set(curGuid, removedDoc!); + this.presentationsKeyMapping.set(removedDoc!, curGuid); + this.currentSelectedPresValue = curGuid; + + this.presStatus = curPresStatus; + this.groupMappings = currentGroups; + this.presElementsMappings = curPresElemMapping; + this.setPresentationBackUps(); + + }), + redo: action(() => { + this.curPresentation = nextDoc; + this.presStatus = false; + this.presentationsKeyMapping.delete(removedDoc!); + this.presentationsMapping.delete(curGuid); + this.currentSelectedPresValue = this.presentationsKeyMapping.get(nextDoc)!.toString(); + this.setPresentationBackUps(); + + }), + }); + + batch.end(); + } + } + + /** + * The function that is called to change title of presentation to what user entered. + */ + @undoBatch + changePresentationTitle = (newTitle: string) => { + if (newTitle === "") { + return; + } + this.curPresentation.title = newTitle; + } + + addPressElem = (keyDoc: Doc, elem: PresentationElement) => { + this.presElementsMappings.set(keyDoc, elem); + } + + + render() { + + let width = NumCast(this.curPresentation.width); + + return ( +
!this.persistOpacity && (this.opacity = 1))} onPointerLeave={action(() => !this.persistOpacity && (this.opacity = 0.4))} style={{ width: width, overflow: "hidden", opacity: this.opacity, transition: "0.7s opacity ease" }}> +
+ {this.renderSelectOrPresSelection()} + {/**this.closePresentation CLICK does not work?! Also without the*/} + + + +
+
+ + {this.renderPlayPauseButton()} + +
+ ) => { + this.persistOpacity = e.target.checked; + this.opacity = this.persistOpacity ? 1 : 0.4; + })} + checked={this.persistOpacity} + style={{ position: "absolute", bottom: 5, left: 5 }} + onPointerEnter={action(() => this.labelOpacity = 1)} + onPointerLeave={action(() => this.labelOpacity = 0)} + /> +

opacity {this.persistOpacity ? "persistent" : "on focus"}

+ this.presElementsMappings.clear()} + /> +
+ ); + } + + +} \ No newline at end of file diff --git a/src/client/views/pdf/PDFMenu.tsx b/src/client/views/pdf/PDFMenu.tsx index 27c2a8f1a..23d0c0b10 100644 --- a/src/client/views/pdf/PDFMenu.tsx +++ b/src/client/views/pdf/PDFMenu.tsx @@ -250,7 +250,7 @@ export default class PDFMenu extends React.Component { ] : [ , - , + , //change this to pin to 'new' presentation
diff --git a/src/new_fields/PresField.ts b/src/new_fields/PresField.ts new file mode 100644 index 000000000..f236a04fd --- /dev/null +++ b/src/new_fields/PresField.ts @@ -0,0 +1,6 @@ +//insert code here +import { ObjectField } from "./ObjectField"; + +export abstract class PresField extends ObjectField { + +} \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 0af800d2edf120ab2a20842ed67ea7d7616996b9 Mon Sep 17 00:00:00 2001 From: HJF Bulterman Date: Fri, 9 Aug 2019 15:37:49 -0400 Subject: working for about 85% --- src/client/views/MainView.tsx | 27 +++++++++++++++++----- .../views/collections/CollectionDockingView.tsx | 9 ++++++++ src/client/views/nodes/DocumentView.tsx | 3 ++- src/client/views/nodes/PresBox.tsx | 7 +++--- 4 files changed, 36 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 14cfc6792..cb81f9aad 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -247,7 +247,6 @@ export class MainView extends React.Component { @computed get dockingContent() { let flyoutWidth = this.flyoutWidth; let mainCont = this.mainContainer; - let castRes = mainCont ? FieldValue(Cast(mainCont.presentationView, listSpec(Doc))) : undefined; return {({ measureRef }) =>
@@ -271,7 +270,7 @@ export class MainView extends React.Component { zoomToScale={emptyFunction} getScale={returnOne} />} - {castRes ? : null} + {/* {presentationDoc ? : null} */}
}
; @@ -385,13 +384,11 @@ export class MainView extends React.Component { let addButtonDocument = action(() => Docs.Create.ButtonDocument({ width: 150, height: 50, title: "Button" })); let addImportCollectionNode = action(() => Docs.Create.DirectoryImportDocument({ title: "Directory Import", width: 400, height: 400 })); - let addPresentationNode = action(() => Docs.Create.PresDocument(new List([Docs.Create.TreeDocument([], { title: "Presentation" })]))); - let btns: [React.RefObject, IconName, string, () => Doc][] = [ [React.createRef(), "object-group", "Add Collection", addColNode], [React.createRef(), "bolt", "Add Button", addButtonDocument], // [React.createRef(), "clone", "Add Docking Frame", addDockingNode], - [React.createRef(), "cloud-upload-alt", "Import Directory", addPresentationNode], //remove at some point in favor of addImportCollectionNode + [React.createRef(), "cloud-upload-alt", "Import Directory", addImportCollectionNode], //remove at some point in favor of addImportCollectionNode ]; if (!ClientUtils.RELEASE) btns.unshift([React.createRef(), "cat", "Add Cat Image", addImageNode]); @@ -402,7 +399,7 @@ export class MainView extends React.Component {
  • -
  • +
  • {btns.map(btn => @@ -453,6 +450,24 @@ export class MainView extends React.Component { this.isSearchVisible = !this.isSearchVisible; } + togglePresentationView = () => { + let presDoc = this.presentationDoc; + if (!presDoc) { + return; + } + let isOpen = CollectionDockingView.Instance.Has(presDoc); + if (isOpen) { + CollectionDockingView.Instance.CloseRightSplit(presDoc); + } else { + CollectionDockingView.Instance.AddRightSplit(presDoc, undefined); + } + } + + private get presentationDoc() { + let mainCont = this.mainContainer; + return mainCont ? FieldValue(Cast(mainCont.presentationView, Doc)) : undefined; + } + render() { return (
    diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 1859ebee7..bd83a46a3 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -162,6 +162,14 @@ export class CollectionDockingView extends React.Component { + let docs = Cast(this.props.Document.data, listSpec(Doc)); + if (!docs) { + return false; + } + return docs.includes(document); + } + // // Creates a vertical split on the right side of the docking view, and then adds the Document to that split // @@ -525,6 +533,7 @@ export class DockedFrameRenderer extends React.Component { this.props.glContainer.layoutManager.on("activeContentItemChanged", this.onActiveContentItemChanged); this.props.glContainer.on("tab", this.onActiveContentItemChanged); this.onActiveContentItemChanged(); + // setTimeout(() => MainView.Instance.openPresentationView(), 2000); } componentWillUnmount() { diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 0ca303dde..6d4c18050 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -41,6 +41,7 @@ import { ClientUtils } from '../../util/ClientUtils'; import { EditableView } from '../EditableView'; import { faHandPointer, faHandPointRight } from '@fortawesome/free-regular-svg-icons'; import { DocumentDecorations } from '../DocumentDecorations'; +import { PresBox } from './PresBox'; const JsxParser = require('react-jsx-parser').default; //TODO Why does this need to be imported like this? library.add(fa.faTrash); @@ -553,7 +554,7 @@ export class DocumentView extends DocComponent(Docu subitems.push({ description: "Open Fields", event: this.fieldsClicked, icon: "layer-group" }); cm.addItem({ description: "Open...", subitems: subitems, icon: "external-link-alt" }); cm.addItem({ description: BoolCast(this.props.Document.ignoreAspect, false) || !this.props.Document.nativeWidth || !this.props.Document.nativeHeight ? "Freeze" : "Unfreeze", event: this.freezeNativeDimensions, icon: "snowflake" }); - cm.addItem({ description: "Pin to Presentation", event: () => PresentationView.Instance.PinDoc(this.props.Document), icon: "map-pin" }); //change this to + cm.addItem({ description: "Pin to Presentation", event: () => PresBox.Instance.PinDoc(this.props.Document), icon: "map-pin" }); //this should work, and it does! A miracle! cm.addItem({ description: BoolCast(this.props.Document.lockedPosition) ? "Unlock Position" : "Lock Position", event: this.toggleLockPosition, icon: BoolCast(this.props.Document.lockedPosition) ? "unlock" : "lock" }); let makes: ContextMenuProps[] = []; makes.push({ description: "Make Background", event: this.makeBackground, icon: BoolCast(this.props.Document.lockedPosition) ? "unlock" : "lock" }); diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index 2feb32693..8316c4469 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -32,7 +32,7 @@ export interface PresViewProps { Documents: List; } -const expandedWidth = 400; +const expandedWidth = 450; @observer export class PresBox extends React.Component { //FieldViewProps? @@ -825,10 +825,11 @@ export class PresBox extends React.Component { //FieldViewProps? render() { - let width = NumCast(this.curPresentation.width); + let width = "100%"; //NumCast(this.curPresentation.width) + console.log("The width is: " + width); return ( -
    !this.persistOpacity && (this.opacity = 1))} onPointerLeave={action(() => !this.persistOpacity && (this.opacity = 0.4))} style={{ width: width, overflow: "hidden", opacity: this.opacity, transition: "0.7s opacity ease" }}> +
    !this.persistOpacity && (this.opacity = 1))} onPointerLeave={action(() => !this.persistOpacity && (this.opacity = 0.4))} style={{ width: width, overflow: "hidden", opacity: this.opacity, transition: "0.7s opacity ease", pointerEvents: "all" }}>
    {this.renderSelectOrPresSelection()} {/**this.closePresentation CLICK does not work?! Also without the*/} -- cgit v1.2.3-70-g09d2 From d271205a94bcb2ebc524b70f8a3ff98398e69252 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Mon, 12 Aug 2019 21:39:16 -0400 Subject: exporting text to google docs almost supported --- package.json | 1 + src/client/DocServer.ts | 1 + .../apis/google_docs/GoogleApiClientUtils.ts | 85 ++++++++++ src/client/views/MainView.tsx | 11 +- src/server/Message.ts | 1 + src/server/RouteStore.ts | 3 +- src/server/apis/google/GoogleApiServerUtils.ts | 109 +++++++++++++ src/server/apis/youtube/youtubeApiSample.d.ts | 2 + src/server/apis/youtube/youtubeApiSample.js | 179 +++++++++++++++++++++ .../credentials/google_docs_credentials.json | 1 + src/server/credentials/google_docs_token.json | 1 + src/server/index.ts | 33 +++- src/server/youtubeApi/youtubeApiSample.d.ts | 2 - src/server/youtubeApi/youtubeApiSample.js | 179 --------------------- 14 files changed, 418 insertions(+), 190 deletions(-) create mode 100644 src/client/apis/google_docs/GoogleApiClientUtils.ts create mode 100644 src/server/apis/google/GoogleApiServerUtils.ts create mode 100644 src/server/apis/youtube/youtubeApiSample.d.ts create mode 100644 src/server/apis/youtube/youtubeApiSample.js create mode 100644 src/server/credentials/google_docs_credentials.json create mode 100644 src/server/credentials/google_docs_token.json delete mode 100644 src/server/youtubeApi/youtubeApiSample.d.ts delete mode 100644 src/server/youtubeApi/youtubeApiSample.js (limited to 'src') diff --git a/package.json b/package.json index d699d1e6f..326468ab9 100644 --- a/package.json +++ b/package.json @@ -69,6 +69,7 @@ "@types/express-session": "^1.15.12", "@types/express-validator": "^3.0.0", "@types/formidable": "^1.0.31", + "@types/gapi": "0.0.39", "@types/jquery": "^3.3.29", "@types/jquery-awesome-cursor": "^0.3.0", "@types/jsonwebtoken": "^8.3.2", diff --git a/src/client/DocServer.ts b/src/client/DocServer.ts index bf5168c22..47aff2bb6 100644 --- a/src/client/DocServer.ts +++ b/src/client/DocServer.ts @@ -5,6 +5,7 @@ import { Utils, emptyFunction } from '../Utils'; import { SerializationHelper } from './util/SerializationHelper'; import { RefField } from '../new_fields/RefField'; import { Id, HandleUpdate } from '../new_fields/FieldSymbols'; +import { docs_v1 } from 'googleapis'; /** * This class encapsulates the transfer and cross-client synchronization of diff --git a/src/client/apis/google_docs/GoogleApiClientUtils.ts b/src/client/apis/google_docs/GoogleApiClientUtils.ts new file mode 100644 index 000000000..42e621f6b --- /dev/null +++ b/src/client/apis/google_docs/GoogleApiClientUtils.ts @@ -0,0 +1,85 @@ +import { docs_v1 } from "googleapis"; +import { PostToServer } from "../../../Utils"; +import { RouteStore } from "../../../server/RouteStore"; + +export namespace GoogleApiClientUtils { + + export namespace Docs { + + export enum Actions { + Create = "create", + Retrieve = "retrieve" + } + + export namespace Helpers { + + export const fromRgb = (red: number, green: number, blue: number) => { + return { color: { rgbColor: { red, green, blue } } }; + }; + + } + + export const ExampleDocumentSchema = { + title: "This is a Google Doc Created From Dash Web", + body: { + content: [ + { + paragraph: { + elements: [ + { + textRun: { + content: "And this is its bold, blue text!!!", + textStyle: { + bold: true, + backgroundColor: Helpers.fromRgb(0, 0, 1) + } + } + } + ] + } + } + ] as docs_v1.Schema$StructuralElement[] + } + } as docs_v1.Schema$Document; + + /** + * After following the authentication routine, which connects this API call to the current signed in account + * and grants the appropriate permissions, this function programmatically creates an arbitrary Google Doc which + * should appear in the user's Google Doc library instantaneously. + * + * @param schema whatever subset of a docs_v1.Schema$Document is required to properly initialize your + * Google Doc. This schema defines all aspects of a Google Doc, from the title to headers / footers to the + * actual document body and its styling! + * @returns the documentId of the newly generated document, or undefined if the creation process fails. + */ + export const Create = async (schema?: docs_v1.Schema$Document): Promise => { + let path = RouteStore.googleDocs + Actions.Create; + let parameters = { requestBody: schema || ExampleDocumentSchema }; + let generatedId: string | undefined; + try { + generatedId = await PostToServer(path, parameters); + } catch (e) { + console.error(e); + generatedId = undefined; + } finally { + return generatedId; + } + }; + + let path = RouteStore.googleDocs + Actions.Retrieve; + export const Retrieve = async (documentId: string): Promise => { + let parameters = { documentId }; + let documentContents: any; + try { + documentContents = await PostToServer(path, parameters); + } catch (e) { + console.error(e); + documentContents = undefined; + } finally { + return documentContents; + } + }; + + } + +} \ No newline at end of file diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 031478477..0a987de4a 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -15,7 +15,7 @@ import { listSpec } from '../../new_fields/Schema'; import { Cast, FieldValue, NumCast, BoolCast, StrCast } from '../../new_fields/Types'; import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils'; import { RouteStore } from '../../server/RouteStore'; -import { emptyFunction, returnOne, returnTrue, Utils, returnEmptyString } from '../../Utils'; +import { emptyFunction, returnOne, returnTrue, Utils, returnEmptyString, PostToServer } from '../../Utils'; import { DocServer } from '../DocServer'; import { Docs } from '../documents/Documents'; import { SetupDrag } from '../util/DragManager'; @@ -40,6 +40,8 @@ import { CollectionTreeView } from './collections/CollectionTreeView'; import { ClientUtils } from '../util/ClientUtils'; import { SchemaHeaderField, RandomPastel } from '../../new_fields/SchemaHeaderField'; import { DictationManager } from '../util/DictationManager'; +import { docs_v1 } from 'googleapis'; +import { GoogleApiClientUtils } from '../apis/google_docs/GoogleApiClientUtils'; @observer export class MainView extends React.Component { @@ -130,6 +132,8 @@ export class MainView extends React.Component { window.removeEventListener("keydown", KeyManager.Instance.handle); window.addEventListener("keydown", KeyManager.Instance.handle); + GoogleApiClientUtils.Docs.Create().then(id => console.log(id)); + reaction(() => { let workspaces = CurrentUserUtils.UserDocument.workspaces; let recent = CurrentUserUtils.UserDocument.recentlyClosed; @@ -569,6 +573,11 @@ export class MainView extends React.Component { render() { return (
    + { + if (e.which === 13) { + GoogleApiClientUtils.Docs.Retrieve(e.currentTarget.value.trim()).then((res: any) => console.log(res)); + } + }} /> {this.dictationOverlay} {this.mainContent} diff --git a/src/server/Message.ts b/src/server/Message.ts index aaee143e8..4ec390ade 100644 --- a/src/server/Message.ts +++ b/src/server/Message.ts @@ -1,4 +1,5 @@ import { Utils } from "../Utils"; +import { google, docs_v1 } from "googleapis"; export class Message { private _name: string; diff --git a/src/server/RouteStore.ts b/src/server/RouteStore.ts index e30015e39..5d977006a 100644 --- a/src/server/RouteStore.ts +++ b/src/server/RouteStore.ts @@ -30,6 +30,7 @@ export enum RouteStore { reset = "/reset/:token", // APIS - cognitiveServices = "/cognitiveservices" + cognitiveServices = "/cognitiveservices", + googleDocs = "/googleDocs/" } \ No newline at end of file diff --git a/src/server/apis/google/GoogleApiServerUtils.ts b/src/server/apis/google/GoogleApiServerUtils.ts new file mode 100644 index 000000000..817b2b696 --- /dev/null +++ b/src/server/apis/google/GoogleApiServerUtils.ts @@ -0,0 +1,109 @@ +import { google, docs_v1 } from "googleapis"; +import { createInterface } from "readline"; +import { readFile, writeFile } from "fs"; +import { OAuth2Client } from "google-auth-library"; + +/** + * Server side authentication for Google Api queries. + */ +export namespace GoogleApiServerUtils { + + // If modifying these scopes, delete token.json. + const prefix = 'https://www.googleapis.com/auth/'; + const SCOPES = [ + 'documents.readonly', + 'documents', + 'drive', + 'drive.file', + ]; + // The file token.json stores the user's access and refresh tokens, and is + // created automatically when the authorization flow completes for the first + // time. + export const parseBuffer = (data: Buffer) => JSON.parse(data.toString()); + + export namespace Docs { + + export interface CredentialPaths { + credentials: string; + token: string; + } + + export type Endpoint = docs_v1.Docs; + + export const GetEndpoint = async (paths: CredentialPaths) => { + return new Promise((resolve, reject) => { + readFile(paths.credentials, (err, credentials) => { + if (err) { + reject(err); + return console.log('Error loading client secret file:', err); + } + return authorize(parseBuffer(credentials), paths.token).then(auth => { + resolve(google.docs({ version: "v1", auth })); + }); + }); + }); + }; + + } + + /** + * Create an OAuth2 client with the given credentials, and returns the promise resolving to the authenticated client + * @param {Object} credentials The authorization client credentials. + */ + export function authorize(credentials: any, token_path: string): Promise { + const { client_secret, client_id, redirect_uris } = credentials.installed; + const oAuth2Client = new google.auth.OAuth2( + client_id, client_secret, redirect_uris[0]); + + return new Promise((resolve, reject) => { + readFile(token_path, (err, token) => { + // Check if we have previously stored a token. + if (err) { + return getNewToken(oAuth2Client, token_path).then(resolve, reject); + } + oAuth2Client.setCredentials(parseBuffer(token)); + resolve(oAuth2Client); + }); + }); + } + + /** + * Get and store new token after prompting for user authorization, and then + * execute the given callback with the authorized OAuth2 client. + * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for. + * @param {getEventsCallback} callback The callback for the authorized client. + */ + function getNewToken(oAuth2Client: OAuth2Client, token_path: string) { + return new Promise((resolve, reject) => { + const authUrl = oAuth2Client.generateAuthUrl({ + access_type: 'offline', + scope: SCOPES.map(relative => prefix + relative), + }); + console.log('Authorize this app by visiting this url:', authUrl); + const rl = createInterface({ + input: process.stdin, + output: process.stdout, + }); + rl.question('Enter the code from that page here: ', (code) => { + rl.close(); + oAuth2Client.getToken(code, (err, token) => { + if (err || !token) { + reject(err); + return console.error('Error retrieving access token', err); + } + oAuth2Client.setCredentials(token); + // Store the token to disk for later program executions + writeFile(token_path, JSON.stringify(token), (err) => { + if (err) { + console.error(err); + reject(err); + } + console.log('Token stored to', token_path); + }); + resolve(oAuth2Client); + }); + }); + }); + } + +} \ No newline at end of file diff --git a/src/server/apis/youtube/youtubeApiSample.d.ts b/src/server/apis/youtube/youtubeApiSample.d.ts new file mode 100644 index 000000000..427f54608 --- /dev/null +++ b/src/server/apis/youtube/youtubeApiSample.d.ts @@ -0,0 +1,2 @@ +declare const YoutubeApi: any; +export = YoutubeApi; \ No newline at end of file diff --git a/src/server/apis/youtube/youtubeApiSample.js b/src/server/apis/youtube/youtubeApiSample.js new file mode 100644 index 000000000..50b3c7b38 --- /dev/null +++ b/src/server/apis/youtube/youtubeApiSample.js @@ -0,0 +1,179 @@ +const fs = require('fs'); +const readline = require('readline'); +const { google } = require('googleapis'); +const OAuth2 = google.auth.OAuth2; + + +// If modifying these scopes, delete your previously saved credentials +// at ~/.credentials/youtube-nodejs-quickstart.json +let SCOPES = ['https://www.googleapis.com/auth/youtube.readonly']; +let TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || + process.env.USERPROFILE) + '/.credentials/'; +let TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json'; + +module.exports.readApiKey = (callback) => { + fs.readFile('client_secret.json', function processClientSecrets(err, content) { + if (err) { + console.log('Error loading client secret file: ' + err); + return; + } + callback(content); + }); +} + +module.exports.authorizedGetChannel = (apiKey) => { + //this didnt get called + // Authorize a client with the loaded credentials, then call the YouTube API. + authorize(JSON.parse(apiKey), getChannel); +} + +module.exports.authorizedGetVideos = (apiKey, userInput, callBack) => { + authorize(JSON.parse(apiKey), getVideos, { userInput: userInput, callBack: callBack }); +} + +module.exports.authorizedGetVideoDetails = (apiKey, videoIds, callBack) => { + authorize(JSON.parse(apiKey), getVideoDetails, { videoIds: videoIds, callBack: callBack }); +} + + +/** + * Create an OAuth2 client with the given credentials, and then execute the + * given callback function. + * + * @param {Object} credentials The authorization client credentials. + * @param {function} callback The callback to call with the authorized client. + */ +function authorize(credentials, callback, args = {}) { + let clientSecret = credentials.installed.client_secret; + let clientId = credentials.installed.client_id; + let redirectUrl = credentials.installed.redirect_uris[0]; + let oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl); + + // Check if we have previously stored a token. + fs.readFile(TOKEN_PATH, function (err, token) { + if (err) { + getNewToken(oauth2Client, callback); + } else { + oauth2Client.credentials = JSON.parse(token); + callback(oauth2Client, args); + } + }); +} + +/** + * Get and store new token after prompting for user authorization, and then + * execute the given callback with the authorized OAuth2 client. + * + * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for. + * @param {getEventsCallback} callback The callback to call with the authorized + * client. + */ +function getNewToken(oauth2Client, callback) { + var authUrl = oauth2Client.generateAuthUrl({ + access_type: 'offline', + scope: SCOPES + }); + console.log('Authorize this app by visiting this url: ', authUrl); + var rl = readline.createInterface({ + input: process.stdin, + output: process.stdout + }); + rl.question('Enter the code from that page here: ', function (code) { + rl.close(); + oauth2Client.getToken(code, function (err, token) { + if (err) { + console.log('Error while trying to retrieve access token', err); + return; + } + oauth2Client.credentials = token; + storeToken(token); + callback(oauth2Client); + }); + }); +} + +/** + * Store token to disk be used in later program executions. + * + * @param {Object} token The token to store to disk. + */ +function storeToken(token) { + try { + fs.mkdirSync(TOKEN_DIR); + } catch (err) { + if (err.code != 'EEXIST') { + throw err; + } + } + fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => { + if (err) throw err; + console.log('Token stored to ' + TOKEN_PATH); + }); + console.log('Token stored to ' + TOKEN_PATH); +} + +/** + * Lists the names and IDs of up to 10 files. + * + * @param {google.auth.OAuth2} auth An authorized OAuth2 client. + */ +function getChannel(auth) { + var service = google.youtube('v3'); + service.channels.list({ + auth: auth, + part: 'snippet,contentDetails,statistics', + forUsername: 'GoogleDevelopers' + }, function (err, response) { + if (err) { + console.log('The API returned an error: ' + err); + return; + } + var channels = response.data.items; + if (channels.length == 0) { + console.log('No channel found.'); + } else { + console.log('This channel\'s ID is %s. Its title is \'%s\', and ' + + 'it has %s views.', + channels[0].id, + channels[0].snippet.title, + channels[0].statistics.viewCount); + } + }); +} + +function getVideos(auth, args) { + let service = google.youtube('v3'); + service.search.list({ + auth: auth, + part: 'id, snippet', + type: 'video', + q: args.userInput, + maxResults: 10 + }, function (err, response) { + if (err) { + console.log('The API returned an error: ' + err); + return; + } + let videos = response.data.items; + args.callBack(videos); + }); +} + +function getVideoDetails(auth, args) { + if (args.videoIds === undefined) { + return; + } + let service = google.youtube('v3'); + service.videos.list({ + auth: auth, + part: 'contentDetails, statistics', + id: args.videoIds + }, function (err, response) { + if (err) { + console.log('The API returned an error from details: ' + err); + return; + } + let videoDetails = response.data.items; + args.callBack(videoDetails); + }); +} \ No newline at end of file diff --git a/src/server/credentials/google_docs_credentials.json b/src/server/credentials/google_docs_credentials.json new file mode 100644 index 000000000..8d097d363 --- /dev/null +++ b/src/server/credentials/google_docs_credentials.json @@ -0,0 +1 @@ +{"installed":{"client_id":"343179513178-ud6tvmh275r2fq93u9eesrnc66t6akh9.apps.googleusercontent.com","project_id":"quickstart-1565056383187","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"w8KIFSc0MQpmUYHed4qEzn8b","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}} \ No newline at end of file diff --git a/src/server/credentials/google_docs_token.json b/src/server/credentials/google_docs_token.json new file mode 100644 index 000000000..07c02d56c --- /dev/null +++ b/src/server/credentials/google_docs_token.json @@ -0,0 +1 @@ +{"access_token":"ya29.GltjB4-x03xFpd2NY2555cxg1xlT_ajqRi78M9osOfdOF2jTIjlPkn_UZL8cUwVP0DPC8rH3vhhg8RpspFe8Vewx92shAO3RPos_uMH0CUqEiCiZlaaB5I3Jq3Mv","refresh_token":"1/teUKUqGKMLjVqs-eed0L8omI02pzSxMUYaxGc2QxBw0","scope":"https://www.googleapis.com/auth/documents https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/documents.readonly","token_type":"Bearer","expiry_date":1565654175862} \ No newline at end of file diff --git a/src/server/index.ts b/src/server/index.ts index eae018f13..9986e62d6 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -14,7 +14,6 @@ import * as mobileDetect from 'mobile-detect'; import * as passport from 'passport'; import * as path from 'path'; import * as request from 'request'; -import * as rp from 'request-promise'; import * as io from 'socket.io'; import { Socket } from 'socket.io'; import * as webpack from 'webpack'; @@ -36,19 +35,16 @@ const port = 1050; // default port to listen const serverPort = 4321; import expressFlash = require('express-flash'); import flash = require('connect-flash'); -import c = require("crypto"); import { Search } from './Search'; -import { debug } from 'util'; import _ = require('lodash'); import * as Archiver from 'archiver'; -import * as AdmZip from 'adm-zip'; -import * as YoutubeApi from './youtubeApi/youtubeApiSample.js'; +import AdmZip from 'adm-zip'; +import * as YoutubeApi from "./apis/youtube/youtubeApiSample"; import { Response } from 'express-serve-static-core'; +import { GoogleApiServerUtils } from "./apis/google/GoogleApiServerUtils"; const MongoStore = require('connect-mongo')(session); const mongoose = require('mongoose'); const probe = require("probe-image-size"); -var SolrNode = require('solr-node'); -var shell = require('shelljs'); const download = (url: string, dest: fs.PathLike) => request.get(url).pipe(fs.createWriteStream(dest)); let youtubeApiKey: string; @@ -790,6 +786,29 @@ function HandleYoutubeQuery([query, callback]: [YoutubeQueryInput, (result?: any } } +const credentials = path.join(__dirname, "./credentials/google_docs_credentials.json"); +const token = path.join(__dirname, "./credentials/google_docs_token.json"); + +app.post(RouteStore.googleDocs + ":action", (req, res) => { + let parameters = req.body; + console.log(parameters, req.params.action); + + GoogleApiServerUtils.Docs.GetEndpoint({ credentials, token }).then(endpoint => { + let results: Promise | undefined; + switch (req.params.action) { + case "create": + results = endpoint.documents.create(parameters).then(generated => generated.data.documentId); + break; + case "retrieve": + results = endpoint.documents.get(parameters).then(response => response.data); + break; + default: + results = undefined; + } + results && results.then(final => res.send(final)); + }); +}); + const suffixMap: { [type: string]: (string | [string, string | ((json: any) => any)]) } = { "number": "_n", "string": "_t", diff --git a/src/server/youtubeApi/youtubeApiSample.d.ts b/src/server/youtubeApi/youtubeApiSample.d.ts deleted file mode 100644 index 427f54608..000000000 --- a/src/server/youtubeApi/youtubeApiSample.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -declare const YoutubeApi: any; -export = YoutubeApi; \ No newline at end of file diff --git a/src/server/youtubeApi/youtubeApiSample.js b/src/server/youtubeApi/youtubeApiSample.js deleted file mode 100644 index 50b3c7b38..000000000 --- a/src/server/youtubeApi/youtubeApiSample.js +++ /dev/null @@ -1,179 +0,0 @@ -const fs = require('fs'); -const readline = require('readline'); -const { google } = require('googleapis'); -const OAuth2 = google.auth.OAuth2; - - -// If modifying these scopes, delete your previously saved credentials -// at ~/.credentials/youtube-nodejs-quickstart.json -let SCOPES = ['https://www.googleapis.com/auth/youtube.readonly']; -let TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH || - process.env.USERPROFILE) + '/.credentials/'; -let TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json'; - -module.exports.readApiKey = (callback) => { - fs.readFile('client_secret.json', function processClientSecrets(err, content) { - if (err) { - console.log('Error loading client secret file: ' + err); - return; - } - callback(content); - }); -} - -module.exports.authorizedGetChannel = (apiKey) => { - //this didnt get called - // Authorize a client with the loaded credentials, then call the YouTube API. - authorize(JSON.parse(apiKey), getChannel); -} - -module.exports.authorizedGetVideos = (apiKey, userInput, callBack) => { - authorize(JSON.parse(apiKey), getVideos, { userInput: userInput, callBack: callBack }); -} - -module.exports.authorizedGetVideoDetails = (apiKey, videoIds, callBack) => { - authorize(JSON.parse(apiKey), getVideoDetails, { videoIds: videoIds, callBack: callBack }); -} - - -/** - * Create an OAuth2 client with the given credentials, and then execute the - * given callback function. - * - * @param {Object} credentials The authorization client credentials. - * @param {function} callback The callback to call with the authorized client. - */ -function authorize(credentials, callback, args = {}) { - let clientSecret = credentials.installed.client_secret; - let clientId = credentials.installed.client_id; - let redirectUrl = credentials.installed.redirect_uris[0]; - let oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl); - - // Check if we have previously stored a token. - fs.readFile(TOKEN_PATH, function (err, token) { - if (err) { - getNewToken(oauth2Client, callback); - } else { - oauth2Client.credentials = JSON.parse(token); - callback(oauth2Client, args); - } - }); -} - -/** - * Get and store new token after prompting for user authorization, and then - * execute the given callback with the authorized OAuth2 client. - * - * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for. - * @param {getEventsCallback} callback The callback to call with the authorized - * client. - */ -function getNewToken(oauth2Client, callback) { - var authUrl = oauth2Client.generateAuthUrl({ - access_type: 'offline', - scope: SCOPES - }); - console.log('Authorize this app by visiting this url: ', authUrl); - var rl = readline.createInterface({ - input: process.stdin, - output: process.stdout - }); - rl.question('Enter the code from that page here: ', function (code) { - rl.close(); - oauth2Client.getToken(code, function (err, token) { - if (err) { - console.log('Error while trying to retrieve access token', err); - return; - } - oauth2Client.credentials = token; - storeToken(token); - callback(oauth2Client); - }); - }); -} - -/** - * Store token to disk be used in later program executions. - * - * @param {Object} token The token to store to disk. - */ -function storeToken(token) { - try { - fs.mkdirSync(TOKEN_DIR); - } catch (err) { - if (err.code != 'EEXIST') { - throw err; - } - } - fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => { - if (err) throw err; - console.log('Token stored to ' + TOKEN_PATH); - }); - console.log('Token stored to ' + TOKEN_PATH); -} - -/** - * Lists the names and IDs of up to 10 files. - * - * @param {google.auth.OAuth2} auth An authorized OAuth2 client. - */ -function getChannel(auth) { - var service = google.youtube('v3'); - service.channels.list({ - auth: auth, - part: 'snippet,contentDetails,statistics', - forUsername: 'GoogleDevelopers' - }, function (err, response) { - if (err) { - console.log('The API returned an error: ' + err); - return; - } - var channels = response.data.items; - if (channels.length == 0) { - console.log('No channel found.'); - } else { - console.log('This channel\'s ID is %s. Its title is \'%s\', and ' + - 'it has %s views.', - channels[0].id, - channels[0].snippet.title, - channels[0].statistics.viewCount); - } - }); -} - -function getVideos(auth, args) { - let service = google.youtube('v3'); - service.search.list({ - auth: auth, - part: 'id, snippet', - type: 'video', - q: args.userInput, - maxResults: 10 - }, function (err, response) { - if (err) { - console.log('The API returned an error: ' + err); - return; - } - let videos = response.data.items; - args.callBack(videos); - }); -} - -function getVideoDetails(auth, args) { - if (args.videoIds === undefined) { - return; - } - let service = google.youtube('v3'); - service.videos.list({ - auth: auth, - part: 'contentDetails, statistics', - id: args.videoIds - }, function (err, response) { - if (err) { - console.log('The API returned an error from details: ' + err); - return; - } - let videoDetails = response.data.items; - args.callBack(videoDetails); - }); -} \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 278cabf67a77edb3dd3bd9bb392550eeb08ab910 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Tue, 13 Aug 2019 02:06:32 -0400 Subject: more util functions and clean up --- .../apis/google_docs/GoogleApiClientUtils.ts | 71 +++++++++++++++++++--- src/client/views/MainView.tsx | 24 +++++--- src/server/index.ts | 1 - 3 files changed, 78 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/client/apis/google_docs/GoogleApiClientUtils.ts b/src/client/apis/google_docs/GoogleApiClientUtils.ts index 42e621f6b..71e5e1073 100644 --- a/src/client/apis/google_docs/GoogleApiClientUtils.ts +++ b/src/client/apis/google_docs/GoogleApiClientUtils.ts @@ -1,6 +1,7 @@ import { docs_v1 } from "googleapis"; import { PostToServer } from "../../../Utils"; import { RouteStore } from "../../../server/RouteStore"; +import { Opt } from "../../../new_fields/Doc"; export namespace GoogleApiClientUtils { @@ -11,33 +12,76 @@ export namespace GoogleApiClientUtils { Retrieve = "retrieve" } - export namespace Helpers { + export namespace Utils { export const fromRgb = (red: number, green: number, blue: number) => { return { color: { rgbColor: { red, green, blue } } }; }; + export const extractText = (document: docs_v1.Schema$Document, removeNewlines = false) => { + let fragments: string[] = []; + if (document.body && document.body.content) { + for (let element of document.body.content) { + if (element.paragraph && element.paragraph.elements) { + for (let inner of element.paragraph.elements) { + if (inner && inner.textRun) { + let fragment = inner.textRun.content; + fragment && fragments.push(fragment); + } + } + } + } + } + let text = fragments.join(""); + return removeNewlines ? text.ReplaceAll("\n", "") : text; + }; + } export const ExampleDocumentSchema = { title: "This is a Google Doc Created From Dash Web", body: { content: [ + { + endIndex: 1, + sectionBreak: { + sectionStyle: { + columnSeparatorStyle: "NONE", + contentDirection: "LEFT_TO_RIGHT" + } + } + }, { paragraph: { elements: [ { textRun: { - content: "And this is its bold, blue text!!!", + content: "And this is its bold, blue text!!!\n", textStyle: { bold: true, - backgroundColor: Helpers.fromRgb(0, 0, 1) + backgroundColor: Utils.fromRgb(0, 0, 1) } } } ] } - } + }, + { + paragraph: { + elements: [ + { + textRun: { + content: "And this is its bold, blue text!!!\n", + textStyle: { + bold: true, + backgroundColor: Utils.fromRgb(0, 0, 1) + } + } + } + ] + } + }, + ] as docs_v1.Schema$StructuralElement[] } } as docs_v1.Schema$Document; @@ -66,20 +110,27 @@ export namespace GoogleApiClientUtils { } }; - let path = RouteStore.googleDocs + Actions.Retrieve; - export const Retrieve = async (documentId: string): Promise => { + export const Read = async (documentId: string, removeNewlines = false): Promise> => { + return Retrieve(documentId).then(schema => { + return schema ? Utils.extractText(schema, removeNewlines) : undefined; + }); + }; + + export const Retrieve = async (documentId: string): Promise> => { + let path = RouteStore.googleDocs + Actions.Retrieve; let parameters = { documentId }; - let documentContents: any; + let schema: Opt; try { - documentContents = await PostToServer(path, parameters); + schema = await PostToServer(path, parameters); } catch (e) { console.error(e); - documentContents = undefined; + schema = undefined; } finally { - return documentContents; + return schema; } }; + } } \ No newline at end of file diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 0a987de4a..3a5285a66 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -87,6 +87,11 @@ export class MainView extends React.Component { if (!("presentationView" in doc)) { doc.presentationView = new List([Docs.Create.TreeDocument([], { title: "Presentation" })]); } + if (!("googleDocId" in doc)) { + GoogleApiClientUtils.Docs.Create().then(id => { + id && (doc.googleDocId = id); + }); + } CurrentUserUtils.UserDocument.activeWorkspace = doc; } } @@ -132,8 +137,6 @@ export class MainView extends React.Component { window.removeEventListener("keydown", KeyManager.Instance.handle); window.addEventListener("keydown", KeyManager.Instance.handle); - GoogleApiClientUtils.Docs.Create().then(id => console.log(id)); - reaction(() => { let workspaces = CurrentUserUtils.UserDocument.workspaces; let recent = CurrentUserUtils.UserDocument.recentlyClosed; @@ -151,6 +154,18 @@ export class MainView extends React.Component { }, { fireImmediately: true }); } + componentDidMount() { + reaction(() => this.mainContainer, () => { + let main = this.mainContainer, googleDocId; + if (main && (googleDocId = StrCast(main.googleDocId))) { + GoogleApiClientUtils.Docs.Read(googleDocId, true).then(text => { + text && Utils.CopyText(text); + console.log(text); + }); + } + }); + } + componentWillUnMount() { window.removeEventListener("keydown", KeyManager.Instance.handle); window.removeEventListener("pointerdown", this.globalPointerDown); @@ -573,11 +588,6 @@ export class MainView extends React.Component { render() { return (
    - { - if (e.which === 13) { - GoogleApiClientUtils.Docs.Retrieve(e.currentTarget.value.trim()).then((res: any) => console.log(res)); - } - }} /> {this.dictationOverlay} {this.mainContent} diff --git a/src/server/index.ts b/src/server/index.ts index 9986e62d6..4ccb61681 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -791,7 +791,6 @@ const token = path.join(__dirname, "./credentials/google_docs_token.json"); app.post(RouteStore.googleDocs + ":action", (req, res) => { let parameters = req.body; - console.log(parameters, req.params.action); GoogleApiServerUtils.Docs.GetEndpoint({ credentials, token }).then(endpoint => { let results: Promise | undefined; -- cgit v1.2.3-70-g09d2 From 2ed0c3e1203794ddaa0b17ed908432582d0198d1 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Tue, 13 Aug 2019 02:11:38 -0400 Subject: reading options --- src/client/apis/google_docs/GoogleApiClientUtils.ts | 11 ++++++++--- src/client/views/MainView.tsx | 6 +++--- 2 files changed, 11 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/client/apis/google_docs/GoogleApiClientUtils.ts b/src/client/apis/google_docs/GoogleApiClientUtils.ts index 71e5e1073..5e974b2e7 100644 --- a/src/client/apis/google_docs/GoogleApiClientUtils.ts +++ b/src/client/apis/google_docs/GoogleApiClientUtils.ts @@ -110,9 +110,14 @@ export namespace GoogleApiClientUtils { } }; - export const Read = async (documentId: string, removeNewlines = false): Promise> => { - return Retrieve(documentId).then(schema => { - return schema ? Utils.extractText(schema, removeNewlines) : undefined; + export interface ReadOptions { + documentId: string; + removeNewlines?: boolean; + } + + export const Read = async (options: ReadOptions): Promise> => { + return Retrieve(options.documentId).then(schema => { + return schema ? Utils.extractText(schema, options.removeNewlines) : undefined; }); }; diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 3a5285a66..705eacc0c 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -156,9 +156,9 @@ export class MainView extends React.Component { componentDidMount() { reaction(() => this.mainContainer, () => { - let main = this.mainContainer, googleDocId; - if (main && (googleDocId = StrCast(main.googleDocId))) { - GoogleApiClientUtils.Docs.Read(googleDocId, true).then(text => { + let main = this.mainContainer, documentId; + if (main && (documentId = StrCast(main.googleDocId))) { + GoogleApiClientUtils.Docs.Read({ documentId }).then(text => { text && Utils.CopyText(text); console.log(text); }); -- cgit v1.2.3-70-g09d2 From 2b829d1028a61869858ecd48e2f1801819e17488 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Tue, 13 Aug 2019 22:15:47 -0400 Subject: robust google doc export api and cleanup --- .../apis/google_docs/GoogleApiClientUtils.ts | 185 ++++++++++++--------- src/client/views/MainView.tsx | 11 +- src/client/views/nodes/FormattedTextBox.tsx | 24 ++- src/new_fields/RichTextField.ts | 13 ++ src/server/index.ts | 25 ++- 5 files changed, 162 insertions(+), 96 deletions(-) (limited to 'src') diff --git a/src/client/apis/google_docs/GoogleApiClientUtils.ts b/src/client/apis/google_docs/GoogleApiClientUtils.ts index 5e974b2e7..dda36f05a 100644 --- a/src/client/apis/google_docs/GoogleApiClientUtils.ts +++ b/src/client/apis/google_docs/GoogleApiClientUtils.ts @@ -1,7 +1,8 @@ import { docs_v1 } from "googleapis"; import { PostToServer } from "../../../Utils"; import { RouteStore } from "../../../server/RouteStore"; -import { Opt } from "../../../new_fields/Doc"; +import { Opt, Doc } from "../../../new_fields/Doc"; +import { isArray } from "util"; export namespace GoogleApiClientUtils { @@ -9,15 +10,12 @@ export namespace GoogleApiClientUtils { export enum Actions { Create = "create", - Retrieve = "retrieve" + Retrieve = "retrieve", + Update = "update" } export namespace Utils { - export const fromRgb = (red: number, green: number, blue: number) => { - return { color: { rgbColor: { red, green, blue } } }; - }; - export const extractText = (document: docs_v1.Schema$Document, removeNewlines = false) => { let fragments: string[] = []; if (document.body && document.body.content) { @@ -36,55 +34,36 @@ export namespace GoogleApiClientUtils { return removeNewlines ? text.ReplaceAll("\n", "") : text; }; - } - - export const ExampleDocumentSchema = { - title: "This is a Google Doc Created From Dash Web", - body: { - content: [ - { - endIndex: 1, - sectionBreak: { - sectionStyle: { - columnSeparatorStyle: "NONE", - contentDirection: "LEFT_TO_RIGHT" + export const EndOf = (schema: docs_v1.Schema$Document): Opt => { + if (schema.body && schema.body.content) { + let paragraphs = schema.body.content.filter(el => el.paragraph); + if (paragraphs.length) { + let target = paragraphs[paragraphs.length - 1]; + if (target.paragraph && target.paragraph.elements) { + length = target.paragraph.elements.length; + if (length) { + let final = target.paragraph.elements[length - 1]; + return final.endIndex ? final.endIndex - 1 : undefined; } } - }, - { - paragraph: { - elements: [ - { - textRun: { - content: "And this is its bold, blue text!!!\n", - textStyle: { - bold: true, - backgroundColor: Utils.fromRgb(0, 0, 1) - } - } - } - ] - } - }, - { - paragraph: { - elements: [ - { - textRun: { - content: "And this is its bold, blue text!!!\n", - textStyle: { - bold: true, - backgroundColor: Utils.fromRgb(0, 0, 1) - } - } - } - ] - } - }, + } + } + }; - ] as docs_v1.Schema$StructuralElement[] - } - } as docs_v1.Schema$Document; + } + + export interface ReadOptions { + documentId: string; + removeNewlines?: boolean; + } + + export interface WriteOptions { + documentId?: string; + title?: string; + content: string | string[]; + index?: number; + store?: { receiver: Doc, key: string }; + } /** * After following the authentication routine, which connects this API call to the current signed in account @@ -96,45 +75,95 @@ export namespace GoogleApiClientUtils { * actual document body and its styling! * @returns the documentId of the newly generated document, or undefined if the creation process fails. */ - export const Create = async (schema?: docs_v1.Schema$Document): Promise => { + const Create = async (title?: string): Promise => { let path = RouteStore.googleDocs + Actions.Create; - let parameters = { requestBody: schema || ExampleDocumentSchema }; - let generatedId: string | undefined; + let parameters = { + requestBody: { + title: title || `Dash Export (${new Date().toDateString()})` + } + }; try { - generatedId = await PostToServer(path, parameters); - } catch (e) { - console.error(e); - generatedId = undefined; - } finally { - return generatedId; + let schema: docs_v1.Schema$Document = await PostToServer(path, parameters); + return schema.documentId; + } catch { + return undefined; } }; - export interface ReadOptions { - documentId: string; - removeNewlines?: boolean; - } + const Retrieve = async (documentId: string): Promise => { + let path = RouteStore.googleDocs + Actions.Retrieve; + let parameters = { + documentId + }; + try { + let schema: docs_v1.Schema$Document = await PostToServer(path, parameters); + return schema; + } catch { + return undefined; + } + }; + + const Update = async (documentId: string, requests: docs_v1.Schema$Request[]): Promise => { + let path = RouteStore.googleDocs + Actions.Update; + let parameters = { + documentId, + requestBody: { + requests + } + }; + try { + let replies: docs_v1.Schema$BatchUpdateDocumentResponse = await PostToServer(path, parameters); + console.log(replies); + return replies; + } catch { + return undefined; + } + }; - export const Read = async (options: ReadOptions): Promise> => { + export const Read = async (options: ReadOptions): Promise => { return Retrieve(options.documentId).then(schema => { return schema ? Utils.extractText(schema, options.removeNewlines) : undefined; }); }; - export const Retrieve = async (documentId: string): Promise> => { - let path = RouteStore.googleDocs + Actions.Retrieve; - let parameters = { documentId }; - let schema: Opt; - try { - schema = await PostToServer(path, parameters); - } catch (e) { - console.error(e); - schema = undefined; - } finally { - return schema; - } + export const ReadLines = async (options: ReadOptions) => { + return Retrieve(options.documentId).then(schema => { + if (!schema) { + return undefined; + } + let lines = Utils.extractText(schema).split("\n"); + return options.removeNewlines ? lines.filter(line => line.length) : lines; + }); }; + export const Write = async (options: WriteOptions): Promise => { + let target = options.documentId; + if (!target) { + if (!(target = await Create(options.title))) { + return undefined; + } + } + let index = options.index; + if (!index) { + let schema = await Retrieve(target); + if (!schema || !(index = Utils.EndOf(schema))) { + return undefined; + } + } + let text = options.content; + let request = { + insertText: { + text: isArray(text) ? text.join("\n") : text, + location: { index } + } + }; + return Update(target, [request]).then(res => { + if (res && options.store) { + options.store.receiver[options.store.key] = res.documentId; + } + return res; + }); + }; } diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 705eacc0c..7b15e9624 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -87,11 +87,6 @@ export class MainView extends React.Component { if (!("presentationView" in doc)) { doc.presentationView = new List([Docs.Create.TreeDocument([], { title: "Presentation" })]); } - if (!("googleDocId" in doc)) { - GoogleApiClientUtils.Docs.Create().then(id => { - id && (doc.googleDocId = id); - }); - } CurrentUserUtils.UserDocument.activeWorkspace = doc; } } @@ -158,9 +153,9 @@ export class MainView extends React.Component { reaction(() => this.mainContainer, () => { let main = this.mainContainer, documentId; if (main && (documentId = StrCast(main.googleDocId))) { - GoogleApiClientUtils.Docs.Read({ documentId }).then(text => { - text && Utils.CopyText(text); - console.log(text); + let options = { documentId, removeNewlines: true }; + GoogleApiClientUtils.Docs.ReadLines(options).then(lines => { + console.log(lines); }); } }); diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 44b5d2c21..8c2af7c9e 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -1,5 +1,5 @@ import { library } from '@fortawesome/fontawesome-svg-core'; -import { faEdit, faSmile, faTextHeight } from '@fortawesome/free-solid-svg-icons'; +import { faEdit, faSmile, faTextHeight, faUpload } from '@fortawesome/free-solid-svg-icons'; import { action, IReactionDisposer, observable, reaction, runInAction, computed, Lambda, trace } from "mobx"; import { observer } from "mobx-react"; import { baseKeymap } from "prosemirror-commands"; @@ -38,9 +38,10 @@ import { For } from 'babel-types'; import { DateField } from '../../../new_fields/DateField'; import { Utils } from '../../../Utils'; import { MainOverlayTextBox } from '../MainOverlayTextBox'; +import { GoogleApiClientUtils } from '../../apis/google_docs/GoogleApiClientUtils'; library.add(faEdit); -library.add(faSmile, faTextHeight); +library.add(faSmile, faTextHeight, faUpload); // FormattedTextBox: Displays an editable plain text node that maps to a specified Key of a Document // @@ -58,6 +59,8 @@ const richTextSchema = createSchema({ documentText: "string" }); +const googleDocKey = "googleDocId"; + type RichTextDocument = makeInterface<[typeof richTextSchema]>; const RichTextDocument = makeInterface(richTextSchema); @@ -661,7 +664,24 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe event: action(() => Doc.GetProto(this.props.Document).autoHeight = !BoolCast(this.props.Document.autoHeight)), icon: "expand-arrows-alt" }); ContextMenu.Instance.addItem({ description: "Text Funcs...", subitems: subitems, icon: "text-height" }); + if (!(googleDocKey in Doc.GetProto(this.props.Document))) { + ContextMenu.Instance.addItem({ description: "Export to Google Doc...", event: this.exportToGoogleDoc, icon: "upload" }); + } } + + exportToGoogleDoc = () => { + let dataDoc = Doc.GetProto(this.props.Document); + let data = Cast(dataDoc.data, RichTextField); + let content: string | undefined; + if (data && (content = data.plainText())) { + GoogleApiClientUtils.Docs.Write({ + title: StrCast(dataDoc.title), + store: { receiver: dataDoc, key: googleDocKey }, + content + }); + } + } + render() { let self = this; let style = this.props.isOverlay ? "scroll" : "hidden"; diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts index 89799b2af..dc66813e0 100644 --- a/src/new_fields/RichTextField.ts +++ b/src/new_fields/RichTextField.ts @@ -9,6 +9,7 @@ import { scriptingGlobal } from "../client/util/Scripting"; export class RichTextField extends ObjectField { @serializable(true) readonly Data: string; + private Extractor = /,\"text\":\"([^\"\}]*)\"\}/g; constructor(data: string) { super(); @@ -22,4 +23,16 @@ export class RichTextField extends ObjectField { [ToScriptString]() { return `new RichTextField("${this.Data}")`; } + + plainText = () => { + let contents = ""; + let matches: RegExpExecArray | null; + let considering = this.Data; + while ((matches = this.Extractor.exec(considering)) !== null) { + contents += matches[1]; + considering = considering.substring(matches.index + matches[0].length); + this.Extractor.lastIndex = 0; + } + return contents.length ? contents : undefined; + } } \ No newline at end of file diff --git a/src/server/index.ts b/src/server/index.ts index 4ccb61681..abaa29658 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -42,6 +42,7 @@ import AdmZip from 'adm-zip'; import * as YoutubeApi from "./apis/youtube/youtubeApiSample"; import { Response } from 'express-serve-static-core'; import { GoogleApiServerUtils } from "./apis/google/GoogleApiServerUtils"; +import { GaxiosResponse } from 'gaxios'; const MongoStore = require('connect-mongo')(session); const mongoose = require('mongoose'); const probe = require("probe-image-size"); @@ -170,6 +171,13 @@ const read_text_file = (relativePath: string) => { }); }; +const write_text_file = (relativePath: string, contents: any) => { + let target = path.join(__dirname, relativePath); + return new Promise((resolve, reject) => { + fs.writeFile(target, contents, (err) => err ? reject(err) : resolve()); + }); +}; + app.get("/version", (req, res) => { exec('"C:\\Program Files\\Git\\bin\\git.exe" rev-parse HEAD', (err, stdout, stderr) => { if (err) { @@ -790,21 +798,22 @@ const credentials = path.join(__dirname, "./credentials/google_docs_credentials. const token = path.join(__dirname, "./credentials/google_docs_token.json"); app.post(RouteStore.googleDocs + ":action", (req, res) => { - let parameters = req.body; - GoogleApiServerUtils.Docs.GetEndpoint({ credentials, token }).then(endpoint => { - let results: Promise | undefined; + let results: Promise | undefined; + let documents = endpoint.documents; + let parameters = req.body; switch (req.params.action) { case "create": - results = endpoint.documents.create(parameters).then(generated => generated.data.documentId); + results = documents.create(parameters); break; case "retrieve": - results = endpoint.documents.get(parameters).then(response => response.data); + results = documents.get(parameters); + break; + case "update": + results = documents.batchUpdate(parameters); break; - default: - results = undefined; } - results && results.then(final => res.send(final)); + !results ? res.send(undefined) : results.then(response => res.send(response.data)); }); }); -- cgit v1.2.3-70-g09d2 From dc766185075b5861686c68a704a8e49213eacbc6 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Wed, 14 Aug 2019 01:00:29 -0400 Subject: cleanup and streamlined / robust type requirements --- .../apis/google_docs/GoogleApiClientUtils.ts | 88 +++++++++++----------- src/client/views/MainView.tsx | 12 --- src/client/views/nodes/FormattedTextBox.tsx | 20 ++--- src/new_fields/RichTextField.ts | 2 +- 4 files changed, 58 insertions(+), 64 deletions(-) (limited to 'src') diff --git a/src/client/apis/google_docs/GoogleApiClientUtils.ts b/src/client/apis/google_docs/GoogleApiClientUtils.ts index dda36f05a..f4fb87e0b 100644 --- a/src/client/apis/google_docs/GoogleApiClientUtils.ts +++ b/src/client/apis/google_docs/GoogleApiClientUtils.ts @@ -17,32 +17,32 @@ export namespace GoogleApiClientUtils { export namespace Utils { export const extractText = (document: docs_v1.Schema$Document, removeNewlines = false) => { - let fragments: string[] = []; + const fragments: string[] = []; if (document.body && document.body.content) { - for (let element of document.body.content) { + for (const element of document.body.content) { if (element.paragraph && element.paragraph.elements) { - for (let inner of element.paragraph.elements) { + for (const inner of element.paragraph.elements) { if (inner && inner.textRun) { - let fragment = inner.textRun.content; + const fragment = inner.textRun.content; fragment && fragments.push(fragment); } } } } } - let text = fragments.join(""); + const text = fragments.join(""); return removeNewlines ? text.ReplaceAll("\n", "") : text; }; export const EndOf = (schema: docs_v1.Schema$Document): Opt => { if (schema.body && schema.body.content) { - let paragraphs = schema.body.content.filter(el => el.paragraph); + const paragraphs = schema.body.content.filter(el => el.paragraph); if (paragraphs.length) { - let target = paragraphs[paragraphs.length - 1]; + const target = paragraphs[paragraphs.length - 1]; if (target.paragraph && target.paragraph.elements) { length = target.paragraph.elements.length; if (length) { - let final = target.paragraph.elements[length - 1]; + const final = target.paragraph.elements[length - 1]; return final.endIndex ? final.endIndex - 1 : undefined; } } @@ -52,17 +52,25 @@ export namespace GoogleApiClientUtils { } + export type IdHandler = (id: DocumentId) => any; + export interface CreateOptions { + handler: IdHandler; + // if excluded, will use a default title annotated with the current date + title?: string; + } + export interface ReadOptions { documentId: string; + // if exluded, will preserve newlines removeNewlines?: boolean; } + export type DocumentId = string; export interface WriteOptions { - documentId?: string; - title?: string; content: string | string[]; + reference: DocumentId | CreateOptions; + // if excluded, will compute the last index of the document and append the content there index?: number; - store?: { receiver: Doc, key: string }; } /** @@ -70,33 +78,36 @@ export namespace GoogleApiClientUtils { * and grants the appropriate permissions, this function programmatically creates an arbitrary Google Doc which * should appear in the user's Google Doc library instantaneously. * - * @param schema whatever subset of a docs_v1.Schema$Document is required to properly initialize your - * Google Doc. This schema defines all aspects of a Google Doc, from the title to headers / footers to the - * actual document body and its styling! + * @param options the title to assign to the new document, and the information necessary + * to store the new documentId returned from the creation process * @returns the documentId of the newly generated document, or undefined if the creation process fails. */ - const Create = async (title?: string): Promise => { - let path = RouteStore.googleDocs + Actions.Create; - let parameters = { + const Create = async (options: CreateOptions): Promise => { + const path = RouteStore.googleDocs + Actions.Create; + const parameters = { requestBody: { - title: title || `Dash Export (${new Date().toDateString()})` + title: options.title || `Dash Export (${new Date().toDateString()})` } }; try { - let schema: docs_v1.Schema$Document = await PostToServer(path, parameters); - return schema.documentId; + const schema: docs_v1.Schema$Document = await PostToServer(path, parameters); + const generatedId = schema.documentId; + if (generatedId) { + options.handler(generatedId); + return generatedId; + } } catch { return undefined; } }; const Retrieve = async (documentId: string): Promise => { - let path = RouteStore.googleDocs + Actions.Retrieve; - let parameters = { + const path = RouteStore.googleDocs + Actions.Retrieve; + const parameters = { documentId }; try { - let schema: docs_v1.Schema$Document = await PostToServer(path, parameters); + const schema: docs_v1.Schema$Document = await PostToServer(path, parameters); return schema; } catch { return undefined; @@ -104,16 +115,15 @@ export namespace GoogleApiClientUtils { }; const Update = async (documentId: string, requests: docs_v1.Schema$Request[]): Promise => { - let path = RouteStore.googleDocs + Actions.Update; - let parameters = { + const path = RouteStore.googleDocs + Actions.Update; + const parameters = { documentId, requestBody: { requests } }; try { - let replies: docs_v1.Schema$BatchUpdateDocumentResponse = await PostToServer(path, parameters); - console.log(replies); + const replies: docs_v1.Schema$BatchUpdateDocumentResponse = await PostToServer(path, parameters); return replies; } catch { return undefined; @@ -131,38 +141,32 @@ export namespace GoogleApiClientUtils { if (!schema) { return undefined; } - let lines = Utils.extractText(schema).split("\n"); + const lines = Utils.extractText(schema).split("\n"); return options.removeNewlines ? lines.filter(line => line.length) : lines; }); }; export const Write = async (options: WriteOptions): Promise => { - let target = options.documentId; - if (!target) { - if (!(target = await Create(options.title))) { - return undefined; - } + let documentId: string | undefined; + const ref = options.reference; + if (!(documentId = typeof ref === "string" ? ref : await Create(ref))) { + return undefined; } let index = options.index; if (!index) { - let schema = await Retrieve(target); + let schema = await Retrieve(documentId); if (!schema || !(index = Utils.EndOf(schema))) { return undefined; } } - let text = options.content; - let request = { + const text = options.content; + const request = { insertText: { text: isArray(text) ? text.join("\n") : text, location: { index } } }; - return Update(target, [request]).then(res => { - if (res && options.store) { - options.store.receiver[options.store.key] = res.documentId; - } - return res; - }); + return Update(documentId, [request]); }; } diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 7b15e9624..77f0e3d60 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -149,18 +149,6 @@ export class MainView extends React.Component { }, { fireImmediately: true }); } - componentDidMount() { - reaction(() => this.mainContainer, () => { - let main = this.mainContainer, documentId; - if (main && (documentId = StrCast(main.googleDocId))) { - let options = { documentId, removeNewlines: true }; - GoogleApiClientUtils.Docs.ReadLines(options).then(lines => { - console.log(lines); - }); - } - }); - } - componentWillUnMount() { window.removeEventListener("keydown", KeyManager.Instance.handle); window.removeEventListener("pointerdown", this.globalPointerDown); diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 8c2af7c9e..50ec27259 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -670,16 +670,18 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe } exportToGoogleDoc = () => { - let dataDoc = Doc.GetProto(this.props.Document); - let data = Cast(dataDoc.data, RichTextField); - let content: string | undefined; - if (data && (content = data.plainText())) { - GoogleApiClientUtils.Docs.Write({ - title: StrCast(dataDoc.title), - store: { receiver: dataDoc, key: googleDocKey }, - content - }); + const dataDoc = Doc.GetProto(this.props.Document); + const data = Cast(dataDoc.data, RichTextField); + if (!data) { + return; } + GoogleApiClientUtils.Docs.Write({ + reference: { + title: StrCast(dataDoc.title), + handler: id => dataDoc[googleDocKey] = id + }, + content: data.plainText() + }); } render() { diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts index dc66813e0..3e8803a34 100644 --- a/src/new_fields/RichTextField.ts +++ b/src/new_fields/RichTextField.ts @@ -33,6 +33,6 @@ export class RichTextField extends ObjectField { considering = considering.substring(matches.index + matches[0].length); this.Extractor.lastIndex = 0; } - return contents.length ? contents : undefined; + return contents; } } \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 48fcec82fa384ec260a02965f9f78c2e41256dd9 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Wed, 14 Aug 2019 03:41:11 -0400 Subject: clean up and regex improvement --- .../apis/google_docs/GoogleApiClientUtils.ts | 111 ++++++++++++--------- src/client/views/nodes/FormattedTextBox.tsx | 15 ++- src/new_fields/RichTextField.ts | 4 +- src/server/index.ts | 35 ++++--- 4 files changed, 99 insertions(+), 66 deletions(-) (limited to 'src') diff --git a/src/client/apis/google_docs/GoogleApiClientUtils.ts b/src/client/apis/google_docs/GoogleApiClientUtils.ts index f4fb87e0b..c6c7d7bd4 100644 --- a/src/client/apis/google_docs/GoogleApiClientUtils.ts +++ b/src/client/apis/google_docs/GoogleApiClientUtils.ts @@ -1,7 +1,7 @@ import { docs_v1 } from "googleapis"; import { PostToServer } from "../../../Utils"; import { RouteStore } from "../../../server/RouteStore"; -import { Opt, Doc } from "../../../new_fields/Doc"; +import { Opt } from "../../../new_fields/Doc"; import { isArray } from "util"; export namespace GoogleApiClientUtils { @@ -14,9 +14,42 @@ export namespace GoogleApiClientUtils { Update = "update" } + export type DocumentId = string; + export type Reference = DocumentId | CreateOptions; + export type TextContent = string | string[]; + export type IdHandler = (id: DocumentId) => any; + + export type CreationResult = Opt; + export type RetrievalResult = Opt; + export type UpdateResult = Opt; + export type ReadLinesResult = Opt; + export type ReadResult = Opt; + + export interface CreateOptions { + handler: IdHandler; // callback to process the documentId of the newly created Google Doc + title?: string; // if excluded, will use a default title annotated with the current date + } + + export interface RetrieveOptions { + documentId: DocumentId; + } + + export type ReadOptions = RetrieveOptions & { removeNewlines?: boolean }; + + export interface WriteOptions { + content: TextContent; + reference: Reference; + index?: number; // if excluded, will compute the last index of the document and append the content there + } + + export interface UpdateOptions { + documentId: DocumentId; + requests: docs_v1.Schema$Request[]; + } + export namespace Utils { - export const extractText = (document: docs_v1.Schema$Document, removeNewlines = false) => { + export const extractText = (document: docs_v1.Schema$Document, removeNewlines = false): string => { const fragments: string[] = []; if (document.body && document.body.content) { for (const element of document.body.content) { @@ -34,7 +67,7 @@ export namespace GoogleApiClientUtils { return removeNewlines ? text.ReplaceAll("\n", "") : text; }; - export const EndOf = (schema: docs_v1.Schema$Document): Opt => { + export const endOf = (schema: docs_v1.Schema$Document): number | undefined => { if (schema.body && schema.body.content) { const paragraphs = schema.body.content.filter(el => el.paragraph); if (paragraphs.length) { @@ -50,27 +83,8 @@ export namespace GoogleApiClientUtils { } }; - } + export const initialize = async (reference: Reference) => typeof reference === "string" ? reference : create(reference); - export type IdHandler = (id: DocumentId) => any; - export interface CreateOptions { - handler: IdHandler; - // if excluded, will use a default title annotated with the current date - title?: string; - } - - export interface ReadOptions { - documentId: string; - // if exluded, will preserve newlines - removeNewlines?: boolean; - } - - export type DocumentId = string; - export interface WriteOptions { - content: string | string[]; - reference: DocumentId | CreateOptions; - // if excluded, will compute the last index of the document and append the content there - index?: number; } /** @@ -82,7 +96,7 @@ export namespace GoogleApiClientUtils { * to store the new documentId returned from the creation process * @returns the documentId of the newly generated document, or undefined if the creation process fails. */ - const Create = async (options: CreateOptions): Promise => { + export const create = async (options: CreateOptions): Promise => { const path = RouteStore.googleDocs + Actions.Create; const parameters = { requestBody: { @@ -101,43 +115,40 @@ export namespace GoogleApiClientUtils { } }; - const Retrieve = async (documentId: string): Promise => { + export const retrieve = async (options: RetrieveOptions): Promise => { const path = RouteStore.googleDocs + Actions.Retrieve; - const parameters = { - documentId - }; try { - const schema: docs_v1.Schema$Document = await PostToServer(path, parameters); + const schema: RetrievalResult = await PostToServer(path, options); return schema; } catch { return undefined; } }; - const Update = async (documentId: string, requests: docs_v1.Schema$Request[]): Promise => { + export const update = async (options: UpdateOptions): Promise => { const path = RouteStore.googleDocs + Actions.Update; const parameters = { - documentId, + documentId: options.documentId, requestBody: { - requests + requests: options.requests } }; try { - const replies: docs_v1.Schema$BatchUpdateDocumentResponse = await PostToServer(path, parameters); + const replies: UpdateResult = await PostToServer(path, parameters); return replies; } catch { return undefined; } }; - export const Read = async (options: ReadOptions): Promise => { - return Retrieve(options.documentId).then(schema => { + export const read = async (options: ReadOptions): Promise => { + return retrieve(options).then(schema => { return schema ? Utils.extractText(schema, options.removeNewlines) : undefined; }); }; - export const ReadLines = async (options: ReadOptions) => { - return Retrieve(options.documentId).then(schema => { + export const readLines = async (options: ReadOptions): Promise => { + return retrieve(options).then(schema => { if (!schema) { return undefined; } @@ -146,27 +157,29 @@ export namespace GoogleApiClientUtils { }); }; - export const Write = async (options: WriteOptions): Promise => { - let documentId: string | undefined; - const ref = options.reference; - if (!(documentId = typeof ref === "string" ? ref : await Create(ref))) { + export const write = async (options: WriteOptions): Promise => { + const documentId = await Utils.initialize(options.reference); + if (!documentId) { return undefined; } let index = options.index; if (!index) { - let schema = await Retrieve(documentId); - if (!schema || !(index = Utils.EndOf(schema))) { + let schema = await retrieve({ documentId }); + if (!schema || !(index = Utils.endOf(schema))) { return undefined; } } const text = options.content; - const request = { - insertText: { - text: isArray(text) ? text.join("\n") : text, - location: { index } - } + const updateOptions = { + documentId, + requests: [{ + insertText: { + text: isArray(text) ? text.join("\n") : text, + location: { index } + } + }] }; - return Update(documentId, [request]); + return update(updateOptions); }; } diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 50ec27259..46aed9b2d 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -288,6 +288,19 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe } } + componentWillMount() { + this.pollExportedCounterpart(); + } + + pollExportedCounterpart = async () => { + let dataDoc = Doc.GetProto(this.props.Document); + let documentId = StrCast(dataDoc[googleDocKey]); + if (documentId) { + let contents = await GoogleApiClientUtils.Docs.read({ documentId }); + contents ? console.log(contents) : delete dataDoc[googleDocKey]; + } + } + componentDidMount() { const config = { schema, @@ -675,7 +688,7 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe if (!data) { return; } - GoogleApiClientUtils.Docs.Write({ + GoogleApiClientUtils.Docs.write({ reference: { title: StrCast(dataDoc.title), handler: id => dataDoc[googleDocKey] = id diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts index 3e8803a34..4f782816c 100644 --- a/src/new_fields/RichTextField.ts +++ b/src/new_fields/RichTextField.ts @@ -9,7 +9,7 @@ import { scriptingGlobal } from "../client/util/Scripting"; export class RichTextField extends ObjectField { @serializable(true) readonly Data: string; - private Extractor = /,\"text\":\"([^\"\}]*)\"\}/g; + private Extractor = /,\"text\":\"([^\}]*)\"\}/g; constructor(data: string) { super(); @@ -33,6 +33,6 @@ export class RichTextField extends ObjectField { considering = considering.substring(matches.index + matches[0].length); this.Extractor.lastIndex = 0; } - return contents; + return contents.ReplaceAll("\\", ""); } } \ No newline at end of file diff --git a/src/server/index.ts b/src/server/index.ts index abaa29658..ef1829f30 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -43,6 +43,8 @@ import * as YoutubeApi from "./apis/youtube/youtubeApiSample"; import { Response } from 'express-serve-static-core'; import { GoogleApiServerUtils } from "./apis/google/GoogleApiServerUtils"; import { GaxiosResponse } from 'gaxios'; +import { Opt } from '../new_fields/Doc'; +import { docs_v1 } from 'googleapis'; const MongoStore = require('connect-mongo')(session); const mongoose = require('mongoose'); const probe = require("probe-image-size"); @@ -797,23 +799,28 @@ function HandleYoutubeQuery([query, callback]: [YoutubeQueryInput, (result?: any const credentials = path.join(__dirname, "./credentials/google_docs_credentials.json"); const token = path.join(__dirname, "./credentials/google_docs_token.json"); +type ApiResponse = Promise; +type ApiHandler = (endpoint: docs_v1.Resource$Documents, parameters: any) => ApiResponse; +type Action = "create" | "retrieve" | "update"; + +const EndpointHandlerMap = new Map([ + ["create", (api, params) => api.create(params)], + ["retrieve", (api, params) => api.get(params)], + ["update", (api, params) => api.batchUpdate(params)], +]); + app.post(RouteStore.googleDocs + ":action", (req, res) => { GoogleApiServerUtils.Docs.GetEndpoint({ credentials, token }).then(endpoint => { - let results: Promise | undefined; - let documents = endpoint.documents; - let parameters = req.body; - switch (req.params.action) { - case "create": - results = documents.create(parameters); - break; - case "retrieve": - results = documents.get(parameters); - break; - case "update": - results = documents.batchUpdate(parameters); - break; + let handler = EndpointHandlerMap.get(req.params.action); + if (handler) { + let execute = handler(endpoint.documents, req.body).then( + response => res.send(response.data), + rejection => res.send(rejection) + ); + execute.catch(exception => res.send(exception)); + return; } - !results ? res.send(undefined) : results.then(response => res.send(response.data)); + res.send(undefined); }); }); -- cgit v1.2.3-70-g09d2 From 9ea032b9ab14ba17511b1014044dba0236e93837 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Wed, 14 Aug 2019 10:48:23 -0400 Subject: refactored plain text parsing and setting --- src/client/views/nodes/FormattedTextBox.tsx | 13 +++++--- src/new_fields/RichTextField.ts | 50 ++++++++++++++++++++++------- 2 files changed, 48 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 46aed9b2d..5ba2aa0cf 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -12,7 +12,7 @@ import { EditorView } from "prosemirror-view"; import { Doc, Opt, DocListCast } from "../../../new_fields/Doc"; import { Id, Copy } from '../../../new_fields/FieldSymbols'; import { List } from '../../../new_fields/List'; -import { RichTextField } from "../../../new_fields/RichTextField"; +import { RichTextField, ToPlainText, FromPlainText } from "../../../new_fields/RichTextField"; import { createSchema, listSpec, makeInterface } from "../../../new_fields/Schema"; import { BoolCast, Cast, NumCast, StrCast, DateCast } from "../../../new_fields/Types"; import { DocServer } from "../../DocServer"; @@ -296,8 +296,13 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe let dataDoc = Doc.GetProto(this.props.Document); let documentId = StrCast(dataDoc[googleDocKey]); if (documentId) { - let contents = await GoogleApiClientUtils.Docs.read({ documentId }); - contents ? console.log(contents) : delete dataDoc[googleDocKey]; + let exportState = await GoogleApiClientUtils.Docs.read({ documentId }); + if (exportState) { + let data = Cast(dataDoc.data, RichTextField); + data && data[FromPlainText](exportState); + } else { + delete dataDoc[googleDocKey]; + } } } @@ -693,7 +698,7 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe title: StrCast(dataDoc.title), handler: id => dataDoc[googleDocKey] = id }, - content: data.plainText() + content: data[ToPlainText]() }); } diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts index 4f782816c..9d8a1cecb 100644 --- a/src/new_fields/RichTextField.ts +++ b/src/new_fields/RichTextField.ts @@ -4,12 +4,14 @@ import { Deserializable } from "../client/util/SerializationHelper"; import { Copy, ToScriptString } from "./FieldSymbols"; import { scriptingGlobal } from "../client/util/Scripting"; +export const ToPlainText = Symbol("PlainText"); +export const FromPlainText = Symbol("PlainText"); + @scriptingGlobal @Deserializable("RichTextField") export class RichTextField extends ObjectField { @serializable(true) - readonly Data: string; - private Extractor = /,\"text\":\"([^\}]*)\"\}/g; + Data: string; constructor(data: string) { super(); @@ -24,15 +26,41 @@ export class RichTextField extends ObjectField { return `new RichTextField("${this.Data}")`; } - plainText = () => { - let contents = ""; - let matches: RegExpExecArray | null; - let considering = this.Data; - while ((matches = this.Extractor.exec(considering)) !== null) { - contents += matches[1]; - considering = considering.substring(matches.index + matches[0].length); - this.Extractor.lastIndex = 0; + [ToPlainText]() { + let content = JSON.parse(this.Data).doc.content; + let paragraphs = content.filter((item: any) => item.type === "paragraph"); + let output = ""; + for (let i = 0; i < paragraphs.length; i++) { + let paragraph = paragraphs[i]; + if (paragraph.content) { + output += paragraph.content.map((block: any) => block.text).join(""); + } else { + output += i > 0 && paragraphs[i - 1].content ? "\n\n" : "\n"; + } } - return contents.ReplaceAll("\\", ""); + return output; + } + + [FromPlainText](plainText: string) { + let elements = plainText.split("\n"); + let parsed = JSON.parse(this.Data); + parsed.doc.content = elements.map(text => { + let paragraph: any = { type: "paragraph" }; + if (text.length) { + paragraph.content = [{ + type: "text", + marks: [], + text + }]; + } + return paragraph; + }); + parsed.selection = { + type: "text", + anchor: 0, + head: 0 + }; + this.Data = JSON.stringify(parsed); } + } \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 1b9ee607e0c34f82ef39da494329d24623debd18 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Wed, 14 Aug 2019 10:58:26 -0400 Subject: changed selection --- src/new_fields/RichTextField.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts index 9d8a1cecb..f0284b1b8 100644 --- a/src/new_fields/RichTextField.ts +++ b/src/new_fields/RichTextField.ts @@ -57,8 +57,8 @@ export class RichTextField extends ObjectField { }); parsed.selection = { type: "text", - anchor: 0, - head: 0 + anchor: plainText.length, + head: plainText.length }; this.Data = JSON.stringify(parsed); } -- cgit v1.2.3-70-g09d2 From 13d2be7f66c01ee9f09cb65f567eb3da760df670 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Wed, 14 Aug 2019 15:18:13 -0400 Subject: semi-synchronous editing between dash notes and google docs --- package.json | 2 + .../apis/google_docs/GoogleApiClientUtils.ts | 40 ++++++++++++++------ src/client/views/nodes/FormattedTextBox.tsx | 44 ++++++++++++++-------- src/new_fields/RichTextField.ts | 25 +++++++----- 4 files changed, 76 insertions(+), 35 deletions(-) (limited to 'src') diff --git a/package.json b/package.json index 326468ab9..7a629d813 100644 --- a/package.json +++ b/package.json @@ -63,6 +63,7 @@ "@types/cookie-parser": "^1.4.1", "@types/cookie-session": "^2.0.36", "@types/d3-format": "^1.3.1", + "@types/diff": "^4.0.2", "@types/dotenv": "^6.1.1", "@types/express": "^4.16.1", "@types/express-flash": "0.0.0", @@ -127,6 +128,7 @@ "cookie-session": "^2.0.0-beta.3", "crypto-browserify": "^3.11.0", "d3-format": "^1.3.2", + "diff": "^4.0.1", "dotenv": "^8.0.0", "express": "^4.16.4", "express-flash": "0.0.2", diff --git a/src/client/apis/google_docs/GoogleApiClientUtils.ts b/src/client/apis/google_docs/GoogleApiClientUtils.ts index c6c7d7bd4..c1cbba31f 100644 --- a/src/client/apis/google_docs/GoogleApiClientUtils.ts +++ b/src/client/apis/google_docs/GoogleApiClientUtils.ts @@ -14,6 +14,11 @@ export namespace GoogleApiClientUtils { Update = "update" } + export enum WriteMode { + Insert, + Replace + } + export type DocumentId = string; export type Reference = DocumentId | CreateOptions; export type TextContent = string | string[]; @@ -37,6 +42,7 @@ export namespace GoogleApiClientUtils { export type ReadOptions = RetrieveOptions & { removeNewlines?: boolean }; export interface WriteOptions { + mode: WriteMode; content: TextContent; reference: Reference; index?: number; // if excluded, will compute the last index of the document and append the content there @@ -158,28 +164,40 @@ export namespace GoogleApiClientUtils { }; export const write = async (options: WriteOptions): Promise => { + const requests: docs_v1.Schema$Request[] = []; const documentId = await Utils.initialize(options.reference); if (!documentId) { return undefined; } let index = options.index; - if (!index) { + const mode = options.mode; + if (!(index && mode === WriteMode.Insert)) { let schema = await retrieve({ documentId }); if (!schema || !(index = Utils.endOf(schema))) { return undefined; } } - const text = options.content; - const updateOptions = { - documentId, - requests: [{ - insertText: { - text: isArray(text) ? text.join("\n") : text, - location: { index } + if (mode === WriteMode.Replace) { + requests.push({ + deleteContentRange: { + range: { + startIndex: 1, + endIndex: index + } } - }] - }; - return update(updateOptions); + }); + index = 1; + } + const text = options.content; + requests.push({ + insertText: { + text: isArray(text) ? text.join("\n") : text, + location: { index } + } + }); + let replies = await update({ documentId, requests }); + console.log(replies); + return replies; }; } diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 5ba2aa0cf..ad29ce775 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -12,7 +12,7 @@ import { EditorView } from "prosemirror-view"; import { Doc, Opt, DocListCast } from "../../../new_fields/Doc"; import { Id, Copy } from '../../../new_fields/FieldSymbols'; import { List } from '../../../new_fields/List'; -import { RichTextField, ToPlainText, FromPlainText } from "../../../new_fields/RichTextField"; +import { RichTextField, ToGoogleDocText, FromGoogleDocText } from "../../../new_fields/RichTextField"; import { createSchema, listSpec, makeInterface } from "../../../new_fields/Schema"; import { BoolCast, Cast, NumCast, StrCast, DateCast } from "../../../new_fields/Types"; import { DocServer } from "../../DocServer"; @@ -39,6 +39,7 @@ import { DateField } from '../../../new_fields/DateField'; import { Utils } from '../../../Utils'; import { MainOverlayTextBox } from '../MainOverlayTextBox'; import { GoogleApiClientUtils } from '../../apis/google_docs/GoogleApiClientUtils'; +import * as diff from "diff"; library.add(faEdit); library.add(faSmile, faTextHeight, faUpload); @@ -299,7 +300,9 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe let exportState = await GoogleApiClientUtils.Docs.read({ documentId }); if (exportState) { let data = Cast(dataDoc.data, RichTextField); - data && data[FromPlainText](exportState); + if (data) { + dataDoc.data = new RichTextField(data[FromGoogleDocText](exportState)); + } } else { delete dataDoc[googleDocKey]; } @@ -629,6 +632,7 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe this._undoTyping.end(); this._undoTyping = undefined; } + this.updateGoogleDoc(); } public _undoTyping?: UndoManager.Batch; onKeyPress = (e: React.KeyboardEvent) => { @@ -683,23 +687,33 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe }); ContextMenu.Instance.addItem({ description: "Text Funcs...", subitems: subitems, icon: "text-height" }); if (!(googleDocKey in Doc.GetProto(this.props.Document))) { - ContextMenu.Instance.addItem({ description: "Export to Google Doc...", event: this.exportToGoogleDoc, icon: "upload" }); + ContextMenu.Instance.addItem({ + description: "Export to Google Doc...", + event: this.updateGoogleDoc, + icon: "upload" + }); } } - exportToGoogleDoc = () => { - const dataDoc = Doc.GetProto(this.props.Document); - const data = Cast(dataDoc.data, RichTextField); - if (!data) { - return; + updateGoogleDoc = () => { + let modes = GoogleApiClientUtils.Docs.WriteMode; + let mode = modes.Replace; + let reference: Opt = Cast(this.dataDoc[googleDocKey], "string"); + if (!reference) { + mode = modes.Insert; + reference = { + title: StrCast(this.dataDoc.title), + handler: id => this.dataDoc[googleDocKey] = id + }; + } + const data = Cast(this.dataDoc.data, RichTextField); + if (data) { + GoogleApiClientUtils.Docs.write({ + mode, + content: data[ToGoogleDocText](), + reference + }); } - GoogleApiClientUtils.Docs.write({ - reference: { - title: StrCast(dataDoc.title), - handler: id => dataDoc[googleDocKey] = id - }, - content: data[ToPlainText]() - }); } render() { diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts index f0284b1b8..92b19b921 100644 --- a/src/new_fields/RichTextField.ts +++ b/src/new_fields/RichTextField.ts @@ -4,14 +4,14 @@ import { Deserializable } from "../client/util/SerializationHelper"; import { Copy, ToScriptString } from "./FieldSymbols"; import { scriptingGlobal } from "../client/util/Scripting"; -export const ToPlainText = Symbol("PlainText"); -export const FromPlainText = Symbol("PlainText"); +export const ToGoogleDocText = Symbol("PlainText"); +export const FromGoogleDocText = Symbol("PlainText"); @scriptingGlobal @Deserializable("RichTextField") export class RichTextField extends ObjectField { @serializable(true) - Data: string; + readonly Data: string; constructor(data: string) { super(); @@ -26,24 +26,28 @@ export class RichTextField extends ObjectField { return `new RichTextField("${this.Data}")`; } - [ToPlainText]() { + [ToGoogleDocText]() { let content = JSON.parse(this.Data).doc.content; let paragraphs = content.filter((item: any) => item.type === "paragraph"); let output = ""; for (let i = 0; i < paragraphs.length; i++) { let paragraph = paragraphs[i]; + let addNewLine = i > 0 ? paragraphs[i - 1].content : false; if (paragraph.content) { output += paragraph.content.map((block: any) => block.text).join(""); } else { - output += i > 0 && paragraphs[i - 1].content ? "\n\n" : "\n"; + output += "\n"; } + addNewLine && (output += "\n"); } return output; } - [FromPlainText](plainText: string) { + [FromGoogleDocText](plainText: string) { let elements = plainText.split("\n"); + !elements[elements.length - 1].length && elements.pop(); let parsed = JSON.parse(this.Data); + let blankCount = 0; parsed.doc.content = elements.map(text => { let paragraph: any = { type: "paragraph" }; if (text.length) { @@ -52,15 +56,18 @@ export class RichTextField extends ObjectField { marks: [], text }]; + } else { + blankCount++; } return paragraph; }); + let selection = plainText.length + 2 * blankCount; parsed.selection = { type: "text", - anchor: plainText.length, - head: plainText.length + anchor: selection, + head: selection }; - this.Data = JSON.stringify(parsed); + return JSON.stringify(parsed); } } \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 4f338a06345c6a002c9bebc9ad0c9c1fe910eebd Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Wed, 14 Aug 2019 16:15:56 -0400 Subject: clean up and edge cases --- src/client/apis/google_docs/GoogleApiClientUtils.ts | 15 +++++++++++---- src/new_fields/RichTextField.ts | 10 +++------- 2 files changed, 14 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/client/apis/google_docs/GoogleApiClientUtils.ts b/src/client/apis/google_docs/GoogleApiClientUtils.ts index c1cbba31f..9d78b632d 100644 --- a/src/client/apis/google_docs/GoogleApiClientUtils.ts +++ b/src/client/apis/google_docs/GoogleApiClientUtils.ts @@ -178,7 +178,7 @@ export namespace GoogleApiClientUtils { } } if (mode === WriteMode.Replace) { - requests.push({ + index > 1 && requests.push({ deleteContentRange: { range: { startIndex: 1, @@ -189,14 +189,21 @@ export namespace GoogleApiClientUtils { index = 1; } const text = options.content; - requests.push({ + text.length && requests.push({ insertText: { text: isArray(text) ? text.join("\n") : text, location: { index } } }); - let replies = await update({ documentId, requests }); - console.log(replies); + if (!requests.length) { + return undefined; + } + let replies: any = await update({ documentId, requests }); + let errors = "errors"; + if (errors in replies) { + console.log("Write operation failed:"); + console.log(replies[errors].map((error: any) => error.message)); + } return replies; }; diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts index 92b19b921..bd24bad1a 100644 --- a/src/new_fields/RichTextField.ts +++ b/src/new_fields/RichTextField.ts @@ -36,7 +36,7 @@ export class RichTextField extends ObjectField { if (paragraph.content) { output += paragraph.content.map((block: any) => block.text).join(""); } else { - output += "\n"; + output += i === 0 ? "" : "\n"; } addNewLine && (output += "\n"); } @@ -47,7 +47,6 @@ export class RichTextField extends ObjectField { let elements = plainText.split("\n"); !elements[elements.length - 1].length && elements.pop(); let parsed = JSON.parse(this.Data); - let blankCount = 0; parsed.doc.content = elements.map(text => { let paragraph: any = { type: "paragraph" }; if (text.length) { @@ -56,16 +55,13 @@ export class RichTextField extends ObjectField { marks: [], text }]; - } else { - blankCount++; } return paragraph; }); - let selection = plainText.length + 2 * blankCount; parsed.selection = { type: "text", - anchor: selection, - head: selection + anchor: 1, + head: 1 }; return JSON.stringify(parsed); } -- cgit v1.2.3-70-g09d2 From 819ca614b022417776580251cb0fdc419ea47ddd Mon Sep 17 00:00:00 2001 From: monikahedman Date: Thu, 15 Aug 2019 15:33:16 -0400 Subject: url editable again --- src/client/views/nodes/WebBox.tsx | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx index ff5297783..dc30dbed3 100644 --- a/src/client/views/nodes/WebBox.tsx +++ b/src/client/views/nodes/WebBox.tsx @@ -17,6 +17,7 @@ import { RefField } from "../../../new_fields/RefField"; import { ObjectField } from "../../../new_fields/ObjectField"; import { updateSourceFile } from "typescript"; import { KeyValueBox } from "./KeyValueBox"; +import { setReactionScheduler } from "mobx/lib/internal"; @observer export class WebBox extends React.Component { @@ -38,11 +39,16 @@ export class WebBox extends React.Component { this.props.Document.height = NumCast(this.props.Document.width) / youtubeaspect; } } + + this.setURL(); } @action onURLChange = (e: React.ChangeEvent) => { + console.log("changing") + console.log(e.target.value) this.url = e.target.value; + console.log(this.url) } @action @@ -50,8 +56,13 @@ export class WebBox extends React.Component { const script = KeyValueBox.CompileKVPScript(`new WebField("${this.url}")`); if (!script) return; KeyValueBox.ApplyKVPScript(this.props.Document, "data", script); - let mod = document.getElementById("webpage-input"); - if (mod) mod.style.display = "none"; + } + + @action + setURL() { + let urlField: FieldResult = Cast(this.props.Document.data, WebField) + if (urlField) this.url = urlField.url.toString(); + else this.url = ""; } @computed @@ -86,7 +97,7 @@ export class WebBox extends React.Component {
    Date: Thu, 15 Aug 2019 15:39:39 -0400 Subject: things workin --- src/client/views/nodes/WebBox.tsx | 7 ------- 1 file changed, 7 deletions(-) (limited to 'src') diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx index dc30dbed3..9a177ca54 100644 --- a/src/client/views/nodes/WebBox.tsx +++ b/src/client/views/nodes/WebBox.tsx @@ -65,13 +65,6 @@ export class WebBox extends React.Component { else this.url = ""; } - @computed - get getURL() { - let urlField: FieldResult = Cast(this.props.Document.data, WebField) - if (urlField) return urlField.url.toString(); - return ""; - } - onValueKeyDown = async (e: React.KeyboardEvent) => { if (e.key === "Enter") { e.stopPropagation(); -- cgit v1.2.3-70-g09d2 From 1c1d4d4865b5dd90489cdde4c8f3dfceba60496b Mon Sep 17 00:00:00 2001 From: monikahedman Date: Thu, 15 Aug 2019 16:14:17 -0400 Subject: done! --- src/client/views/nodes/WebBox.tsx | 8 -------- 1 file changed, 8 deletions(-) (limited to 'src') diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx index 9a177ca54..91170e99a 100644 --- a/src/client/views/nodes/WebBox.tsx +++ b/src/client/views/nodes/WebBox.tsx @@ -45,10 +45,7 @@ export class WebBox extends React.Component { @action onURLChange = (e: React.ChangeEvent) => { - console.log("changing") - console.log(e.target.value) this.url = e.target.value; - console.log(this.url) } @action @@ -93,7 +90,6 @@ export class WebBox extends React.Component { value={this.url} onChange={this.onURLChange} onKeyDown={this.onValueKeyDown} - // onPointerDown={this.openViewSpecs} />
    }
    {paths.length > 1 ? this.dots(paths) : (null)}
    Date: Thu, 15 Aug 2019 22:32:15 -0400 Subject: cleaned up on closing contextMenu --- src/client/views/ContextMenu.tsx | 58 ++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 32 deletions(-) (limited to 'src') diff --git a/src/client/views/ContextMenu.tsx b/src/client/views/ContextMenu.tsx index 39192c382..760736501 100644 --- a/src/client/views/ContextMenu.tsx +++ b/src/client/views/ContextMenu.tsx @@ -41,42 +41,36 @@ export class ContextMenu extends React.Component { } @action - componentDidMount = () => { - document.addEventListener("pointerdown", e => { - runInAction(() => { - this._mouseDown = true; - this._mouseX = e.clientX; - this._mouseY = e.clientY; - }); - }); - document.addEventListener("pointerup", e => { - runInAction(() => { - this._mouseDown = false; - }); - let curX = e.clientX; - let curY = e.clientY; - if (this._mouseX !== curX || this._mouseY !== curY) { - runInAction(() => { - this._shouldDisplay = false; - }); - } + onPointerDown = (e: PointerEvent) => { + this._mouseDown = true; + this._mouseX = e.clientX; + this._mouseY = e.clientY; + } + @action + onPointerUp = (e: PointerEvent) => { + this._mouseDown = false; + let curX = e.clientX; + let curY = e.clientY; + if (this._mouseX !== curX || this._mouseY !== curY) { + this._shouldDisplay = false; + } - if (this._shouldDisplay) { - runInAction(() => { - this._display = true; - }); - } - }); + this._shouldDisplay && (this._display = true); + } + componentWillUnmount() { + document.removeEventListener("pointerdown", this.onPointerDown); + document.removeEventListener("pointerup", this.onPointerUp); + this._reactionDisposer && this._reactionDisposer(); + } + + @action + componentDidMount = () => { + document.addEventListener("pointerdown", this.onPointerDown); + document.addEventListener("pointerup", this.onPointerUp); this._reactionDisposer = reaction( () => this._shouldDisplay, - () => { - if (this._shouldDisplay && !this._mouseDown) { - runInAction(() => { - this._display = true; - }); - } - }, + () => this._shouldDisplay && !this._mouseDown && runInAction(() => this._display = true) ); } -- cgit v1.2.3-70-g09d2 From 46386fd73a06e52d606f891c812a9af0598eec79 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 15 Aug 2019 22:36:11 -0400 Subject: fixed getViewport() --- src/server/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/server/index.ts b/src/server/index.ts index 7a425b60a..eae018f13 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -436,7 +436,7 @@ function LoadPage(file: string, pageNumber: number, res: Response) { console.log(pageNumber); pdf.getPage(pageNumber).then((page: Pdfjs.PDFPageProxy) => { console.log("reading " + page); - let viewport = page.getViewport({ scale: 1 }); + let viewport = page.getViewport(1); let canvasAndContext = factory.create(viewport.width, viewport.height); let renderContext = { canvasContext: canvasAndContext.context, -- cgit v1.2.3-70-g09d2 From a7307ca3dc46782cc9e4cae4daa9b30911ace1dd Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 15 Aug 2019 23:19:33 -0400 Subject: tweaks for borderRounding in edge cases --- src/client/views/DocumentDecorations.tsx | 3 ++- src/client/views/nodes/FormattedTextBox.scss | 4 ++-- src/client/views/nodes/FormattedTextBox.tsx | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 9d877e5d6..d24762443 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -349,7 +349,8 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> document.addEventListener("pointerup", this.onRadiusUp); } if (!this._isMoving) { - SelectionManager.SelectedDocuments().map(dv => dv.props.Document.borderRounding = Doc.GetProto(dv.props.Document).borderRounding = `0%`); + SelectionManager.SelectedDocuments().map(dv => dv.props.Document.layout instanceof Doc ? dv.props.Document.layout : dv.props.Document.isTemplate ? dv.props.Document : Doc.GetProto(dv.props.Document)). + map(d => d.borderRounding = "0%"); } } diff --git a/src/client/views/nodes/FormattedTextBox.scss b/src/client/views/nodes/FormattedTextBox.scss index 247f7d1ea..d86aab09c 100644 --- a/src/client/views/nodes/FormattedTextBox.scss +++ b/src/client/views/nodes/FormattedTextBox.scss @@ -33,8 +33,8 @@ } .formattedTextBox-inner-rounded { - height: calc(100% - 25px); - width: calc(100% - 40px); + height: calc(90%); + width: calc(85%); position: absolute; overflow: auto; top: 15; diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 516e36d5b..330bd135d 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -616,7 +616,7 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe let dh = NumCast(this.props.Document.height, 0); let sh = scrBounds.height; const ChromeHeight = MainOverlayTextBox.Instance.ChromeHeight; - this.props.Document.height = (nh ? dh / nh * sh : sh) + (ChromeHeight ? ChromeHeight() : 0); + this.props.Document.height = Math.max(10, (nh ? dh / nh * sh : sh) + (ChromeHeight ? ChromeHeight() : 0)); this.dataDoc.nativeHeight = nh ? sh : undefined; } } -- cgit v1.2.3-70-g09d2 From 022db05fd859f1bbaf2b160940ce4fdcf74e5e81 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 15 Aug 2019 23:30:58 -0400 Subject: fixes for rounded text boxes. --- src/client/views/nodes/FormattedTextBox.scss | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/client/views/nodes/FormattedTextBox.scss b/src/client/views/nodes/FormattedTextBox.scss index d86aab09c..1b537cc52 100644 --- a/src/client/views/nodes/FormattedTextBox.scss +++ b/src/client/views/nodes/FormattedTextBox.scss @@ -33,12 +33,12 @@ } .formattedTextBox-inner-rounded { - height: calc(90%); - width: calc(85%); + height: 70%; + width: 85%; position: absolute; overflow: auto; - top: 15; - left: 20; + top: 15%; + left: 10%; } .formattedTextBox-inner-rounded div, -- cgit v1.2.3-70-g09d2 From 7fe3c2124fc08b722b417695c9d2c74b459e5c49 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 15 Aug 2019 23:40:38 -0400 Subject: tweaks --- src/client/util/TooltipTextMenu.tsx | 39 +++++++++++++++---------------------- 1 file changed, 16 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/client/util/TooltipTextMenu.tsx b/src/client/util/TooltipTextMenu.tsx index 450931b76..4672dd246 100644 --- a/src/client/util/TooltipTextMenu.tsx +++ b/src/client/util/TooltipTextMenu.tsx @@ -1,32 +1,25 @@ -import { action, observable, observe } from "mobx"; -import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { faTag, faPlus, faCloudUploadAlt } from '@fortawesome/free-solid-svg-icons'; -import { Dropdown, MenuItem, icons, } from "prosemirror-menu"; //no import css -import { EditorState, NodeSelection, TextSelection, Transaction } from "prosemirror-state"; -import { EditorView } from "prosemirror-view"; -import { schema } from "./RichTextSchema"; -import { Schema, NodeType, MarkType, Mark, ResolvedPos } from "prosemirror-model"; -import { Node as ProsNode } from "prosemirror-model"; -import "./TooltipTextMenu.scss"; -const { toggleMark, setBlockType } = require("prosemirror-commands"); import { library } from '@fortawesome/fontawesome-svg-core'; -import { wrapInList, liftListItem, bulletList, } from 'prosemirror-schema-list'; import { faListUl } from '@fortawesome/free-solid-svg-icons'; -import { FieldViewProps } from "../views/nodes/FieldView"; -const { openPrompt, TextField } = require("./ProsemirrorCopy/prompt.js"); -import { DragManager } from "./DragManager"; -import { Doc, Opt, Field } from "../../new_fields/Doc"; +import { action, observable } from "mobx"; +import { Dropdown, icons, MenuItem } from "prosemirror-menu"; //no import css +import { Mark, MarkType, Node as ProsNode, NodeType, ResolvedPos, Schema } from "prosemirror-model"; +import { liftListItem, wrapInList } from 'prosemirror-schema-list'; +import { EditorState, NodeSelection, TextSelection } from "prosemirror-state"; +import { EditorView } from "prosemirror-view"; +import { Doc, Field, Opt } from "../../new_fields/Doc"; +import { Id } from "../../new_fields/FieldSymbols"; +import { Utils } from "../../Utils"; import { DocServer } from "../DocServer"; import { CollectionDockingView } from "../views/collections/CollectionDockingView"; +import { FieldViewProps } from "../views/nodes/FieldView"; +import { FormattedTextBoxProps } from "../views/nodes/FormattedTextBox"; import { DocumentManager } from "./DocumentManager"; -import { Id } from "../../new_fields/FieldSymbols"; -import { FormattedTextBoxProps, FormattedTextBox } from "../views/nodes/FormattedTextBox"; -import { typeAlias } from "babel-types"; -import React, { Children } from "react"; -import ReactDOM from "react-dom"; -import { Utils } from "../../Utils"; +import { DragManager } from "./DragManager"; import { LinkManager } from "./LinkManager"; -import { bool } from "prop-types"; +import { schema } from "./RichTextSchema"; +import "./TooltipTextMenu.scss"; +const { toggleMark, setBlockType } = require("prosemirror-commands"); +const { openPrompt, TextField } = require("./ProsemirrorCopy/prompt.js"); //appears above a selection of text in a RichTextBox to give user options such as Bold, Italics, etc. export class TooltipTextMenu { -- cgit v1.2.3-70-g09d2 From 5997cb7c03438c4c051f20ec2ea6cffe0cdf1e0b Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 15 Aug 2019 23:42:05 -0400 Subject: tweaks --- src/client/util/RichTextSchema.tsx | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/client/util/RichTextSchema.tsx b/src/client/util/RichTextSchema.tsx index 8a15c212d..6d2abfaa2 100644 --- a/src/client/util/RichTextSchema.tsx +++ b/src/client/util/RichTextSchema.tsx @@ -1,12 +1,6 @@ -import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { Schema, NodeSpec, MarkSpec, DOMOutputSpecArray, NodeType, Slice, Mark, Node } from "prosemirror-model"; -import { joinUp, lift, setBlockType, toggleMark, wrapIn, selectNodeForward, deleteSelection } from 'prosemirror-commands'; -import { redo, undo } from 'prosemirror-history'; -import { orderedList, bulletList, listItem, } from 'prosemirror-schema-list'; -import { EditorState, Transaction, NodeSelection, TextSelection, Selection, } from "prosemirror-state"; -import { EditorView, } from "prosemirror-view"; -import { View } from '@react-pdf/renderer'; -import { TooltipTextMenu } from './TooltipTextMenu'; +import { DOMOutputSpecArray, MarkSpec, Node, NodeSpec, Schema, Slice } from "prosemirror-model"; +import { bulletList, listItem, orderedList } from 'prosemirror-schema-list'; +import { TextSelection } from "prosemirror-state"; const pDOM: DOMOutputSpecArray = ["p", 0], blockquoteDOM: DOMOutputSpecArray = ["blockquote", 0], hrDOM: DOMOutputSpecArray = ["hr"], preDOM: DOMOutputSpecArray = ["pre", ["code", 0]], brDOM: DOMOutputSpecArray = ["br"], ulDOM: DOMOutputSpecArray = ["ul", 0]; -- cgit v1.2.3-70-g09d2 From ca42398e6c636c0e0b4ad8165c63d6ec4934abfe Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 15 Aug 2019 23:43:16 -0400 Subject: tweaks --- src/client/views/MainView.tsx | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 6e240817c..84fdf13a1 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -1,29 +1,33 @@ import { IconName, library } from '@fortawesome/fontawesome-svg-core'; -import { faArrowDown, faCloudUploadAlt, faArrowUp, faClone, faCheck, faPlay, faPause, faCaretUp, faLongArrowAltRight, faCommentAlt, faCut, faExclamation, faFilePdf, faFilm, faFont, faGlobeAsia, faPortrait, faMusic, faObjectGroup, faPenNib, faRedoAlt, faTable, faThumbtack, faTree, faUndoAlt, faCat, faBolt } from '@fortawesome/free-solid-svg-icons'; +import { faArrowDown, faArrowUp, faBolt, faCaretUp, faCat, faCheck, faClone, faCloudUploadAlt, faCommentAlt, faCut, faExclamation, faFilePdf, faFilm, faFont, faGlobeAsia, faLongArrowAltRight, faMusic, faObjectGroup, faPause, faPenNib, faPlay, faPortrait, faRedoAlt, faTable, faThumbtack, faTree, faUndoAlt } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { action, computed, configure, observable, runInAction, reaction, trace, autorun } from 'mobx'; +import { action, computed, configure, observable, reaction, runInAction } from 'mobx'; import { observer } from 'mobx-react'; import "normalize.css"; import * as React from 'react'; import { SketchPicker } from 'react-color'; import Measure from 'react-measure'; -import { Doc, DocListCast, Opt, HeightSym } from '../../new_fields/Doc'; +import { Doc, DocListCast, HeightSym, Opt } from '../../new_fields/Doc'; import { Id } from '../../new_fields/FieldSymbols'; import { InkTool } from '../../new_fields/InkField'; import { List } from '../../new_fields/List'; import { listSpec } from '../../new_fields/Schema'; -import { Cast, FieldValue, NumCast, BoolCast, StrCast } from '../../new_fields/Types'; +import { SchemaHeaderField } from '../../new_fields/SchemaHeaderField'; +import { BoolCast, Cast, FieldValue, StrCast } from '../../new_fields/Types'; import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils'; import { RouteStore } from '../../server/RouteStore'; -import { emptyFunction, returnOne, returnTrue, Utils, returnEmptyString } from '../../Utils'; +import { emptyFunction, returnEmptyString, returnOne, returnTrue, Utils } from '../../Utils'; import { DocServer } from '../DocServer'; import { Docs } from '../documents/Documents'; +import { ClientUtils } from '../util/ClientUtils'; +import { DictationManager } from '../util/DictationManager'; import { SetupDrag } from '../util/DragManager'; import { HistoryUtil } from '../util/History'; import { Transform } from '../util/Transform'; import { UndoManager } from '../util/UndoManager'; import { CollectionBaseView } from './collections/CollectionBaseView'; import { CollectionDockingView } from './collections/CollectionDockingView'; +import { CollectionTreeView } from './collections/CollectionTreeView'; import { ContextMenu } from './ContextMenu'; import { DocumentDecorations } from './DocumentDecorations'; import KeyManager from './GlobalKeyHandler'; @@ -36,13 +40,6 @@ import PDFMenu from './pdf/PDFMenu'; import { PresentationView } from './presentationview/PresentationView'; import { PreviewCursor } from './PreviewCursor'; import { FilterBox } from './search/FilterBox'; -import { CollectionTreeView } from './collections/CollectionTreeView'; -import { ClientUtils } from '../util/ClientUtils'; -import { SearchBox } from './search/SearchBox'; -import { SchemaHeaderField, RandomPastel } from '../../new_fields/SchemaHeaderField'; -import { DictationManager } from '../util/DictationManager'; -import * as $ from 'jquery'; -import { KeyValueBox } from './nodes/KeyValueBox'; @observer export class MainView extends React.Component { -- cgit v1.2.3-70-g09d2 From 797ed4ee343a52738e8619cf336e5f94f64c69c4 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Thu, 15 Aug 2019 23:44:45 -0400 Subject: tweaks --- src/client/views/nodes/WebBox.tsx | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx index 302b45a9a..9b66b2431 100644 --- a/src/client/views/nodes/WebBox.tsx +++ b/src/client/views/nodes/WebBox.tsx @@ -1,23 +1,18 @@ +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { action, observable } from "mobx"; import { observer } from "mobx-react"; +import { FieldResult } from "../../../new_fields/Doc"; import { HtmlField } from "../../../new_fields/HtmlField"; +import { InkTool } from "../../../new_fields/InkField"; +import { Cast, NumCast } from "../../../new_fields/Types"; import { WebField } from "../../../new_fields/URLField"; +import { Utils } from "../../../Utils"; import { DocumentDecorations } from "../DocumentDecorations"; import { InkingControl } from "../InkingControl"; import { FieldView, FieldViewProps } from './FieldView'; +import { KeyValueBox } from "./KeyValueBox"; import "./WebBox.scss"; import React = require("react"); -import { InkTool } from "../../../new_fields/InkField"; -import { Cast, FieldValue, NumCast, StrCast } from "../../../new_fields/Types"; -import { Utils } from "../../../Utils"; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { observable, action, computed } from "mobx"; -import { listSpec } from "../../../new_fields/Schema"; -import { Field, FieldResult } from "../../../new_fields/Doc"; -import { RefField } from "../../../new_fields/RefField"; -import { ObjectField } from "../../../new_fields/ObjectField"; -import { updateSourceFile } from "typescript"; -import { KeyValueBox } from "./KeyValueBox"; -import { setReactionScheduler } from "mobx/lib/internal"; @observer export class WebBox extends React.Component { -- cgit v1.2.3-70-g09d2 From 6592660b944d745b7368f478cd9f5d9e778537ed Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Thu, 15 Aug 2019 23:52:39 -0400 Subject: simplified text testing --- src/new_fields/RichTextField.ts | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts index bd24bad1a..8963682c3 100644 --- a/src/new_fields/RichTextField.ts +++ b/src/new_fields/RichTextField.ts @@ -27,6 +27,9 @@ export class RichTextField extends ObjectField { } [ToGoogleDocText]() { + let state = JSON.parse(this.Data); + let text = state.doc.textBetween(0, state.doc.content.size, "\n\n"); + console.log(text); let content = JSON.parse(this.Data).doc.content; let paragraphs = content.filter((item: any) => item.type === "paragraph"); let output = ""; -- cgit v1.2.3-70-g09d2 From b45bda9a9ab289e9566b764323f517efa5e249f5 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Fri, 16 Aug 2019 08:55:08 -0400 Subject: added all closed documents to Recently Closed --- src/client/views/DocumentDecorations.tsx | 8 ++++++-- src/server/authentication/models/current_user_utils.ts | 2 -- 2 files changed, 6 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index d24762443..aae7f0d3f 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -215,10 +215,14 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> } @undoBatch @action - onCloseUp = (e: PointerEvent): void => { + onCloseUp = async (e: PointerEvent) => { e.stopPropagation(); if (e.button === 0) { - SelectionManager.SelectedDocuments().map(dv => dv.props.removeDocument && dv.props.removeDocument(dv.props.Document)); + const recent = await Cast(CurrentUserUtils.UserDocument.recentlyClosed, Doc); + SelectionManager.SelectedDocuments().map(dv => { + recent && Doc.AddDocToList(recent, "data", dv.props.Document, undefined, true, true); + dv.props.removeDocument && dv.props.removeDocument(dv.props.Document); + }); SelectionManager.DeselectAll(); document.removeEventListener("pointermove", this.onCloseMove); document.removeEventListener("pointerup", this.onCloseUp); diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 91d7ba87d..f36f5b73d 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -41,8 +41,6 @@ export class CurrentUserUtils { doc.boxShadow = "0 0"; doc.excludeFromLibrary = true; doc.optionalRightCollection = Docs.Create.StackingDocument([], { title: "New mobile uploads" }); - // doc.library = Docs.Create.TreeDocument([doc], { title: `Library: ${CurrentUserUtils.email}` }); - // (doc.library as Doc).excludeFromLibrary = true; return doc; } -- cgit v1.2.3-70-g09d2 From 842b4c4870ea304843d7e9b25c1b9d2af3e78dd1 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Fri, 16 Aug 2019 09:08:42 -0400 Subject: added lastOpened timestamp --- src/client/views/collections/CollectionBaseView.tsx | 2 ++ src/client/views/collections/CollectionDockingView.tsx | 2 ++ 2 files changed, 4 insertions(+) (limited to 'src') diff --git a/src/client/views/collections/CollectionBaseView.tsx b/src/client/views/collections/CollectionBaseView.tsx index 4a296493a..b6ed6aaa0 100644 --- a/src/client/views/collections/CollectionBaseView.tsx +++ b/src/client/views/collections/CollectionBaseView.tsx @@ -11,6 +11,7 @@ import { SelectionManager } from '../../util/SelectionManager'; import { ContextMenu } from '../ContextMenu'; import { FieldViewProps } from '../nodes/FieldView'; import './CollectionBaseView.scss'; +import { DateField } from '../../../new_fields/DateField'; export enum CollectionViewType { Invalid, @@ -113,6 +114,7 @@ export class CollectionBaseView extends React.Component { } else { Doc.GetProto(targetDataDoc)[targetField] = new List([doc]); } + Doc.GetProto(doc).lastOpened = new DateField; return true; } diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 7332a490a..b9cab428d 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -28,6 +28,7 @@ import { library } from '@fortawesome/fontawesome-svg-core'; import { faFile, faUnlockAlt } from '@fortawesome/free-solid-svg-icons'; import { CurrentUserUtils } from '../../../server/authentication/models/current_user_utils'; import { Docs } from '../../documents/Documents'; +import { DateField } from '../../../new_fields/DateField'; library.add(faFile); @observer @@ -204,6 +205,7 @@ export class CollectionDockingView extends React.Component { + document.lastOpened = new DateField; let docs = Cast(this.props.Document.data, listSpec(Doc)); if (docs) { docs.push(document); -- cgit v1.2.3-70-g09d2 From 0e4241b9f39ef14761d9dc4d469c37ee5a8831c7 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Fri, 16 Aug 2019 09:14:41 -0400 Subject: from last --- src/client/views/collections/CollectionDockingView.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index b9cab428d..a8e723379 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -205,7 +205,7 @@ export class CollectionDockingView extends React.Component { - document.lastOpened = new DateField; + Doc.GetProto(document).lastOpened = new DateField; let docs = Cast(this.props.Document.data, listSpec(Doc)); if (docs) { docs.push(document); -- cgit v1.2.3-70-g09d2 From 50e41fc0ce81c715f362be79aa2c12633f0c3ebf Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Fri, 16 Aug 2019 09:30:49 -0400 Subject: fixed pivot viewer & fit contents --- .../collectionFreeForm/CollectionFreeFormView.tsx | 73 ++++++++++------------ 1 file changed, 32 insertions(+), 41 deletions(-) (limited to 'src') diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index ed7d9a02e..6320cb3d5 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -77,7 +77,6 @@ export namespace PivotView { let collection = target.Document; const field = StrCast(collection.pivotField) || "title"; const width = NumCast(collection.pivotWidth) || 200; - const groups = new Map, Doc[]>(); for (const doc of target.childDocs) { @@ -90,14 +89,11 @@ export namespace PivotView { } else { groups.set(val, [doc]); } - } let minSize = Infinity; - groups.forEach((val, key) => { - minSize = Math.min(minSize, val.length); - }); + groups.forEach((val, key) => minSize = Math.min(minSize, val.length)); const numCols = NumCast(collection.pivotNumColumns) || Math.ceil(Math.sqrt(minSize)); const fontSize = NumCast(collection.pivotFontSize); @@ -134,42 +130,36 @@ export namespace PivotView { }); let elements = target.viewDefsToJSX(groupNames); - let curPage = FieldValue(target.Document.curPage, -1); - - let docViews = target.childDocs.filter(doc => doc instanceof Doc).reduce((prev, doc) => { - var page = NumCast(doc.page, -1); - if ((Math.abs(Math.round(page) - Math.round(curPage)) < 3) || page === -1) { - let minim = BoolCast(doc.isMinimized); - if (minim === undefined || !minim) { - let defaultPosition = (): ViewDefBounds => { - return { - x: NumCast(doc.x), - y: NumCast(doc.y), - z: NumCast(doc.z), - width: NumCast(doc.width), - height: NumCast(doc.height) - }; + let docViews = target.childDocs.reduce((prev, doc) => { + let minim = BoolCast(doc.isMinimized); + if (minim === undefined || !minim) { + let defaultPosition = (): ViewDefBounds => { + return { + x: NumCast(doc.x), + y: NumCast(doc.y), + z: NumCast(doc.z), + width: NumCast(doc.width), + height: NumCast(doc.height) }; - const pos = docMap.get(doc) || defaultPosition(); - prev.push({ - ele: ( - ), - bounds: { - x: pos.x, - y: pos.y, - z: pos.z, - width: NumCast(pos.width), - height: NumCast(pos.height) - } - }); - } + }; + const pos = docMap.get(doc) || defaultPosition(); + prev.push({ + ele: , + bounds: { + x: pos.x, + y: pos.y, + z: pos.z, + width: NumCast(pos.width), + height: NumCast(pos.height) + } + }); } return prev; }, elements); @@ -728,6 +718,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { @computed.struct get elements() { + if (this.Document.usePivotLayout) return PivotView.elements(this); let curPage = FieldValue(this.Document.curPage, -1); const initScript = this.Document.arrangeInit; const script = this.Document.arrangeScript; @@ -771,7 +762,7 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { @computed.struct get views() { - let source = this.Document.usePivotLayout === true ? PivotView.elements(this) : this.elements; + let source = this.elements; return source.filter(ele => ele.bounds && !ele.bounds.z).map(ele => ele.ele); } @computed.struct -- cgit v1.2.3-70-g09d2 From db08a4948e5943b39f3e16e076f37808eb9ef940 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Fri, 16 Aug 2019 09:48:06 -0400 Subject: fixed height of stacking views --- src/client/views/collections/CollectionStackingView.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index 4add7774e..288c38730 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -95,7 +95,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { if (this.isStackingView && BoolCast(this.props.Document.autoHeight)) { let sectionsList = Array.from(this.Sections.size ? this.Sections.values() : [this.filteredChildren]); return this.props.ContentScaling() * sectionsList.reduce((maxHght, s) => Math.max(maxHght, - 50 + s.reduce((height, d, i) => height + this.childDocHeight(d) + (i === s.length - 1 ? this.yMargin : this.gridGap), this.yMargin) + (this.Sections.size ? 50 : 0) + s.reduce((height, d, i) => height + this.childDocHeight(d) + (i === s.length - 1 ? this.yMargin : this.gridGap), this.yMargin) ), 0); } return -1; -- cgit v1.2.3-70-g09d2 From 07482c3bf435748140addfd4fd338fc668657798 Mon Sep 17 00:00:00 2001 From: HJF Bulterman Date: Fri, 16 Aug 2019 14:50:11 -0400 Subject: initial commit, mostly functional pending circular import issue --- src/client/views/MainView.tsx | 8 ++++++-- src/client/views/nodes/DocumentView.tsx | 2 +- src/client/views/nodes/PresBox.tsx | 1 - src/new_fields/ListSpec.ts | 0 .../buxton/source/.Bill_Notes_NewO.docx.icloud | Bin 0 -> 172 bytes .../buxton/source/.Bill_Notes_OLPC.docx.icloud | Bin 0 -> 172 bytes src/scraping/buxton/source/Bill_Notes_NewO.docx | Bin 2150143 -> 0 bytes src/scraping/buxton/source/Bill_Notes_OLPC.docx | Bin 6721592 -> 0 bytes 8 files changed, 7 insertions(+), 4 deletions(-) create mode 100644 src/new_fields/ListSpec.ts create mode 100644 src/scraping/buxton/source/.Bill_Notes_NewO.docx.icloud create mode 100644 src/scraping/buxton/source/.Bill_Notes_OLPC.docx.icloud delete mode 100644 src/scraping/buxton/source/Bill_Notes_NewO.docx delete mode 100644 src/scraping/buxton/source/Bill_Notes_OLPC.docx (limited to 'src') diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index cb81f9aad..de312318b 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -8,10 +8,10 @@ import * as React from 'react'; import { SketchPicker } from 'react-color'; import Measure from 'react-measure'; import { Doc, DocListCast, Opt, HeightSym } from '../../new_fields/Doc'; +import { listSpec } from "../../new_fields/Schema"; import { Id } from '../../new_fields/FieldSymbols'; import { InkTool } from '../../new_fields/InkField'; import { List } from '../../new_fields/List'; -import { listSpec } from '../../new_fields/Schema'; import { Cast, FieldValue, NumCast, BoolCast, StrCast } from '../../new_fields/Types'; import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils'; import { RouteStore } from '../../server/RouteStore'; @@ -93,6 +93,7 @@ export class MainView extends React.Component { componentWillUnMount() { window.removeEventListener("keydown", KeyManager.Instance.handle); + //close presentation } constructor(props: Readonly<{}>) { @@ -457,7 +458,10 @@ export class MainView extends React.Component { } let isOpen = CollectionDockingView.Instance.Has(presDoc); if (isOpen) { - CollectionDockingView.Instance.CloseRightSplit(presDoc); + return; + // CollectionDockingView.Instance.CloseRightSplit(presDoc); + //why?? It's throwing an error that seems impossible to fix. + //ToDo: } else { CollectionDockingView.Instance.AddRightSplit(presDoc, undefined); } diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 6d4c18050..228efdc87 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -554,7 +554,7 @@ export class DocumentView extends DocComponent(Docu subitems.push({ description: "Open Fields", event: this.fieldsClicked, icon: "layer-group" }); cm.addItem({ description: "Open...", subitems: subitems, icon: "external-link-alt" }); cm.addItem({ description: BoolCast(this.props.Document.ignoreAspect, false) || !this.props.Document.nativeWidth || !this.props.Document.nativeHeight ? "Freeze" : "Unfreeze", event: this.freezeNativeDimensions, icon: "snowflake" }); - cm.addItem({ description: "Pin to Presentation", event: () => PresBox.Instance.PinDoc(this.props.Document), icon: "map-pin" }); //this should work, and it does! A miracle! + cm.addItem({ description: "Pin to Presentation", event: () => PresBox.Instance.PinDoc(this.props.Document), icon: "map-pin" }); //I think this should work... and it does! A miracle! cm.addItem({ description: BoolCast(this.props.Document.lockedPosition) ? "Unlock Position" : "Lock Position", event: this.toggleLockPosition, icon: BoolCast(this.props.Document.lockedPosition) ? "unlock" : "lock" }); let makes: ContextMenuProps[] = []; makes.push({ description: "Make Background", event: this.makeBackground, icon: BoolCast(this.props.Document.lockedPosition) ? "unlock" : "lock" }); diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index 8316c4469..1bd2ad3c9 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -826,7 +826,6 @@ export class PresBox extends React.Component { //FieldViewProps? render() { let width = "100%"; //NumCast(this.curPresentation.width) - console.log("The width is: " + width); return (
    !this.persistOpacity && (this.opacity = 1))} onPointerLeave={action(() => !this.persistOpacity && (this.opacity = 0.4))} style={{ width: width, overflow: "hidden", opacity: this.opacity, transition: "0.7s opacity ease", pointerEvents: "all" }}> diff --git a/src/new_fields/ListSpec.ts b/src/new_fields/ListSpec.ts new file mode 100644 index 000000000..e69de29bb diff --git a/src/scraping/buxton/source/.Bill_Notes_NewO.docx.icloud b/src/scraping/buxton/source/.Bill_Notes_NewO.docx.icloud new file mode 100644 index 000000000..f71886d8c Binary files /dev/null and b/src/scraping/buxton/source/.Bill_Notes_NewO.docx.icloud differ diff --git a/src/scraping/buxton/source/.Bill_Notes_OLPC.docx.icloud b/src/scraping/buxton/source/.Bill_Notes_OLPC.docx.icloud new file mode 100644 index 000000000..30ddb3091 Binary files /dev/null and b/src/scraping/buxton/source/.Bill_Notes_OLPC.docx.icloud differ diff --git a/src/scraping/buxton/source/Bill_Notes_NewO.docx b/src/scraping/buxton/source/Bill_Notes_NewO.docx deleted file mode 100644 index 2f4a04e81..000000000 Binary files a/src/scraping/buxton/source/Bill_Notes_NewO.docx and /dev/null differ diff --git a/src/scraping/buxton/source/Bill_Notes_OLPC.docx b/src/scraping/buxton/source/Bill_Notes_OLPC.docx deleted file mode 100644 index 7a636e2d6..000000000 Binary files a/src/scraping/buxton/source/Bill_Notes_OLPC.docx and /dev/null differ -- cgit v1.2.3-70-g09d2 From b76c680013e98a4a8eb67a7371accf61cb8ef1aa Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Fri, 16 Aug 2019 16:01:34 -0400 Subject: linter errors fixed --- src/client/views/collections/CollectionStackingView.tsx | 2 +- src/client/views/nodes/DocumentView.tsx | 2 +- src/client/views/nodes/FormattedTextBox.tsx | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index 288c38730..2e4f6aff5 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -63,7 +63,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { setTimeout(() => this.props.Document.sectionHeaders = new List(), 0); return new Map(); } - const sectionHeaders = this.sectionHeaders!; + const sectionHeaders = this.sectionHeaders; let fields = new Map(sectionHeaders.map(sh => [sh, []] as [SchemaHeaderField, []])); this.filteredChildren.map(d => { let sectionValue = (d[this.sectionFilter] ? d[this.sectionFilter] : `NO ${this.sectionFilter.toUpperCase()} VALUE`) as object; diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 188a306ec..6bc8c4487 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -699,7 +699,7 @@ export class DocumentView extends DocComponent(Docu onPointerLeave = (e: React.PointerEvent): void => { Doc.UnBrushDoc(this.props.Document); }; isSelected = () => SelectionManager.IsSelected(this); - @action select = (ctrlPressed: boolean) => { SelectionManager.SelectDoc(this, ctrlPressed); } + @action select = (ctrlPressed: boolean) => { SelectionManager.SelectDoc(this, ctrlPressed); }; @computed get nativeWidth() { return this.Document.nativeWidth || 0; } @computed get nativeHeight() { return this.Document.nativeHeight || 0; } @computed get onClickHandler() { return this.props.onClick ? this.props.onClick : this.Document.onClick; } diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 9d6c6861e..f7890e5a6 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -167,7 +167,7 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe FormattedTextBox._toolTipTextMenu && (FormattedTextBox._toolTipTextMenu.HackToFixTextSelectionGlitch = false); if (state.selection.empty && FormattedTextBox._toolTipTextMenu) { const marks = tx.storedMarks; - console.log(marks) + console.log(marks); if (marks) { FormattedTextBox._toolTipTextMenu.mark_key_pressed(marks); } } this._applyingChange = true; -- cgit v1.2.3-70-g09d2 From b037aa89fb564812f880994453ce002054a0ad82 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Fri, 16 Aug 2019 16:52:49 -0400 Subject: fixed rounded borders --- src/client/views/nodes/DocumentView.tsx | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 6bc8c4487..6f5235c4a 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -747,6 +747,8 @@ export class DocumentView extends DocComponent(Docu } let showTextTitle = showTitle && StrCast(this.layoutDoc.layout).startsWith("(Docu color: foregroundColor, outlineColor: ["transparent", "maroon", "maroon"][brushDegree], outlineStyle: ["none", "dashed", "solid"][brushDegree], - outlineWidth: brushDegree && !StrCast(Doc.GetProto(this.props.Document).borderRounding) ? - `${brushDegree * this.props.ScreenToLocalTransform().Scale}px` : "0px", - marginLeft: brushDegree && StrCast(Doc.GetProto(this.props.Document).borderRounding) ? - `${-brushDegree * this.props.ScreenToLocalTransform().Scale}px` : undefined, - marginTop: brushDegree && StrCast(Doc.GetProto(this.props.Document).borderRounding) ? - `${-brushDegree * this.props.ScreenToLocalTransform().Scale}px` : undefined, - border: brushDegree && StrCast(Doc.GetProto(this.props.Document).borderRounding) ? - `${["none", "dashed", "solid"][brushDegree]} ${["transparent", "maroon", "maroon"][brushDegree]} ${this.props.ScreenToLocalTransform().Scale}px` : undefined, + outlineWidth: brushDegree && !borderRounding ? `${localScale}px` : "0px", + border: brushDegree && borderRounding ? `${["none", "dashed", "solid"][brushDegree]} ${["transparent", "maroon", "maroon"][brushDegree]} ${localScale}px` : undefined, borderRadius: "inherit", background: backgroundColor, width: nativeWidth, -- cgit v1.2.3-70-g09d2 From 697ee484fc9d5db6cf61397451869b563e97206e Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 19 Aug 2019 12:11:47 -0400 Subject: fixed imports to make presentation compile. --- src/client/documents/DocumentTypes.ts | 22 +++++++++++ src/client/documents/Documents.ts | 46 ++-------------------- src/client/util/DictationManager.ts | 3 +- src/client/views/GlobalKeyHandler.ts | 2 - .../views/collections/CollectionDockingView.tsx | 2 +- .../views/collections/CollectionStackingView.tsx | 2 +- src/client/views/collections/CollectionSubView.tsx | 3 +- .../views/collections/CollectionTreeView.tsx | 3 +- .../views/collections/CollectionViewChromes.tsx | 2 - .../collectionFreeForm/CollectionFreeFormView.tsx | 3 +- src/client/views/nodes/LinkMenuItem.tsx | 2 +- src/client/views/nodes/PresBox.tsx | 2 +- src/client/views/pdf/Page.tsx | 6 +-- src/client/views/search/FilterBox.tsx | 2 +- src/client/views/search/IconButton.tsx | 2 +- src/client/views/search/SearchBox.tsx | 1 - src/client/views/search/SearchItem.tsx | 2 +- src/new_fields/Doc.ts | 6 +-- 18 files changed, 46 insertions(+), 65 deletions(-) create mode 100644 src/client/documents/DocumentTypes.ts (limited to 'src') diff --git a/src/client/documents/DocumentTypes.ts b/src/client/documents/DocumentTypes.ts new file mode 100644 index 000000000..1578e49fe --- /dev/null +++ b/src/client/documents/DocumentTypes.ts @@ -0,0 +1,22 @@ +export enum DocumentType { + NONE = "none", + TEXT = "text", + HIST = "histogram", + IMG = "image", + WEB = "web", + COL = "collection", + KVP = "kvp", + VID = "video", + AUDIO = "audio", + PDF = "pdf", + ICON = "icon", + IMPORT = "import", + LINK = "link", + LINKDOC = "linkdoc", + BUTTON = "button", + TEMPLATE = "template", + EXTENSION = "extension", + YOUTUBE = "youtube", + DRAGBOX = "dragbox", + PRES = "presentation", +} \ No newline at end of file diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 8444f0d72..c551fd2a3 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -1,25 +1,3 @@ -export enum DocumentType { - NONE = "none", - TEXT = "text", - HIST = "histogram", - IMG = "image", - WEB = "web", - COL = "collection", - KVP = "kvp", - VID = "video", - AUDIO = "audio", - PDF = "pdf", - ICON = "icon", - IMPORT = "import", - LINK = "link", - LINKDOC = "linkdoc", - BUTTON = "button", - TEMPLATE = "template", - EXTENSION = "extension", - YOUTUBE = "youtube", - DRAGBOX = "dragbox", -} - import { HistogramField } from "../northstar/dash-fields/HistogramField"; import { HistogramBox } from "../northstar/dash-nodes/HistogramBox"; import { HistogramOperation } from "../northstar/operations/HistogramOperation"; @@ -64,32 +42,14 @@ import { ButtonBox } from "../views/nodes/ButtonBox"; import { DragBox } from "../views/nodes/DragBox"; import { SchemaHeaderField, RandomPastel } from "../../new_fields/SchemaHeaderField"; import { PresBox } from "../views/nodes/PresBox"; +import { ComputedField } from "../../new_fields/ScriptField"; +import { ProxyField } from "../../new_fields/Proxy"; +import { DocumentType } from "./DocumentTypes"; //import { PresBox } from "../views/nodes/PresBox"; //import { PresField } from "../../new_fields/PresField"; var requestImageSize = require('../util/request-image-size'); var path = require('path'); -export enum DocumentType { - NONE = "none", - TEXT = "text", - HIST = "histogram", - IMG = "image", - WEB = "web", - COL = "collection", - KVP = "kvp", - VID = "video", - AUDIO = "audio", - PDF = "pdf", - ICON = "icon", - IMPORT = "import", - LINK = "link", - LINKDOC = "linkdoc", - BUTTON = "button", - TEMPLATE = "template", - EXTENSION = "extension", - PRES = "presentation" -} - export interface DocumentOptions { x?: number; y?: number; diff --git a/src/client/util/DictationManager.ts b/src/client/util/DictationManager.ts index 9c61fe125..b00846756 100644 --- a/src/client/util/DictationManager.ts +++ b/src/client/util/DictationManager.ts @@ -2,9 +2,10 @@ import { SelectionManager } from "./SelectionManager"; import { DocumentView } from "../views/nodes/DocumentView"; import { UndoManager } from "./UndoManager"; import * as interpreter from "words-to-numbers"; +import { DocumentType } from "../documents/DocumentTypes"; import { Doc } from "../../new_fields/Doc"; import { List } from "../../new_fields/List"; -import { Docs, DocumentType } from "../documents/Documents"; +import { Docs } from "../documents/Documents"; import { CollectionViewType } from "../views/collections/CollectionBaseView"; import { Cast, CastCtor } from "../../new_fields/Types"; import { listSpec } from "../../new_fields/Schema"; diff --git a/src/client/views/GlobalKeyHandler.ts b/src/client/views/GlobalKeyHandler.ts index 833bacedb..8a7295c65 100644 --- a/src/client/views/GlobalKeyHandler.ts +++ b/src/client/views/GlobalKeyHandler.ts @@ -196,8 +196,6 @@ export default class KeyManager { async printClipboard() { let text: string = await navigator.clipboard.readText(); - console.log(text) - console.log(document.activeElement) } private ctrl_shift = action((keyname: string) => { diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 929cbf584..3fcc61b76 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -578,7 +578,7 @@ export class DockedFrameRenderer extends React.Component { } ScreenToLocalTransform = () => { - if (this._mainCont && this._mainCont!.children) { + if (this._mainCont && this._mainCont.children) { let { scale, translateX, translateY } = Utils.GetScreenTransform(this._mainCont.children[0].firstChild as HTMLElement); scale = Utils.GetScreenTransform(this._mainCont).scale; return CollectionDockingView.Instance.props.ScreenToLocalTransform().translate(-translateX, -translateY).scale(1 / this.contentScaling() / scale); diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index 2e4f6aff5..8e7fe9a82 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -11,7 +11,7 @@ import { listSpec } from "../../../new_fields/Schema"; import { SchemaHeaderField } from "../../../new_fields/SchemaHeaderField"; import { BoolCast, Cast, NumCast, StrCast, ScriptCast } from "../../../new_fields/Types"; import { emptyFunction, Utils, numberRange } from "../../../Utils"; -import { DocumentType } from "../../documents/Documents"; +import { DocumentType } from "../../documents/DocumentTypes"; import { DragManager } from "../../util/DragManager"; import { Transform } from "../../util/Transform"; import { undoBatch } from "../../util/UndoManager"; diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index 077f3f941..d192721a7 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -11,7 +11,8 @@ import { CurrentUserUtils } from "../../../server/authentication/models/current_ import { RouteStore } from "../../../server/RouteStore"; import { Utils } from "../../../Utils"; import { DocServer } from "../../DocServer"; -import { Docs, DocumentOptions, DocumentType } from "../../documents/Documents"; +import { DocumentType } from "../../documents/DocumentTypes"; +import { Docs, DocumentOptions } from "../../documents/Documents"; import { DragManager } from "../../util/DragManager"; import { undoBatch, UndoManager } from "../../util/UndoManager"; import { DocComponent } from "../DocComponent"; diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index 4b1fca18a..7424cc186 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -9,7 +9,8 @@ import { List } from '../../../new_fields/List'; import { Document, listSpec } from '../../../new_fields/Schema'; import { BoolCast, Cast, NumCast, StrCast } from '../../../new_fields/Types'; import { emptyFunction, Utils } from '../../../Utils'; -import { Docs, DocUtils, DocumentType } from '../../documents/Documents'; +import { Docs, DocUtils } from '../../documents/Documents'; +import { DocumentType } from "../../documents/DocumentTypes"; import { DocumentManager } from '../../util/DocumentManager'; import { DragManager, dropActionType, SetupDrag } from "../../util/DragManager"; import { SelectionManager } from '../../util/SelectionManager'; diff --git a/src/client/views/collections/CollectionViewChromes.tsx b/src/client/views/collections/CollectionViewChromes.tsx index 6ea718330..b92bcc7cb 100644 --- a/src/client/views/collections/CollectionViewChromes.tsx +++ b/src/client/views/collections/CollectionViewChromes.tsx @@ -173,8 +173,6 @@ export class CollectionViewBaseChrome extends React.Component i[1]).filter(i => i.length > 0).join(" && ") + ")"; let yearOffset = this._dateWithinValue[1] === 'y' ? 1 : 0; let monthOffset = this._dateWithinValue[1] === 'm' ? parseInt(this._dateWithinValue[0]) : 0; diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 6320cb3d5..dbe5272dc 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -36,7 +36,8 @@ import { CollectionFreeFormRemoteCursors } from "./CollectionFreeFormRemoteCurso import "./CollectionFreeFormView.scss"; import { MarqueeView } from "./MarqueeView"; import React = require("react"); -import { DocumentType, Docs } from "../../../documents/Documents"; +import { Docs } from "../../../documents/Documents"; +import { DocumentType } from "../../../documents/DocumentTypes"; library.add(faEye as any, faTable, faPaintBrush, faExpandArrowsAlt, faCompressArrowsAlt, faCompass, faUpload, faBraille, faChalkboard); diff --git a/src/client/views/nodes/LinkMenuItem.tsx b/src/client/views/nodes/LinkMenuItem.tsx index a119eb39b..90b335933 100644 --- a/src/client/views/nodes/LinkMenuItem.tsx +++ b/src/client/views/nodes/LinkMenuItem.tsx @@ -52,7 +52,7 @@ export class LinkMenuItem extends React.Component { } if (this.props.destinationDoc === self.props.linkDoc.anchor2 && targetContext) { - DocumentManager.Instance.jumpToDocument(jumpToDoc, e.altKey, false, async document => dockingFunc(document), undefined, targetContext!); + DocumentManager.Instance.jumpToDocument(jumpToDoc, e.altKey, false, async document => dockingFunc(document), undefined, targetContext); } else if (this.props.destinationDoc === self.props.linkDoc.anchor1 && sourceContext) { DocumentManager.Instance.jumpToDocument(jumpToDoc, e.altKey, false, document => dockingFunc(sourceContext!)); diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index 1bd2ad3c9..91c141540 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -752,7 +752,7 @@ export class PresBox extends React.Component { //FieldViewProps? //getting the presentation that will be removed let removedDoc = this.presentationsMapping.get(this.currentSelectedPresValue!); //that presentation is removed - presentationList!.splice(presentationList!.indexOf(removedDoc!), 1); + presentationList!.splice(presentationList.indexOf(removedDoc!), 1); //its mappings are removed from local copies this.presentationsKeyMapping.delete(removedDoc!); diff --git a/src/client/views/pdf/Page.tsx b/src/client/views/pdf/Page.tsx index 7ca9d2d7d..5194ab71c 100644 --- a/src/client/views/pdf/Page.tsx +++ b/src/client/views/pdf/Page.tsx @@ -19,8 +19,8 @@ interface IPageProps { numPages: number; page: number; pageLoaded: (page: Pdfjs.PDFPageViewport) => void; - fieldExtensionDoc: Doc, - Document: Doc, + fieldExtensionDoc: Doc; + Document: Doc; renderAnnotations: (annotations: Doc[], removeOld: boolean) => void; sendAnnotations: (annotations: HTMLDivElement[], page: number) => void; createAnnotation: (div: HTMLDivElement, page: number) => void; @@ -112,7 +112,7 @@ export default class Page extends React.Component { if (!BoolCast(annotationDoc.linkedToDoc)) { let annotations = await DocListCastAsync(annotationDoc.annotations); annotations && annotations.forEach(anno => anno.target = targetDoc); - DocUtils.MakeLink(annotationDoc, targetDoc, dragData.targetContext, `Annotation from ${StrCast(this.props.Document.title)}`) + DocUtils.MakeLink(annotationDoc, targetDoc, dragData.targetContext, `Annotation from ${StrCast(this.props.Document.title)}`); } } }, diff --git a/src/client/views/search/FilterBox.tsx b/src/client/views/search/FilterBox.tsx index 3e8582d61..c13d1d276 100644 --- a/src/client/views/search/FilterBox.tsx +++ b/src/client/views/search/FilterBox.tsx @@ -6,7 +6,7 @@ import { faTimes, faCheckCircle, faObjectGroup } from '@fortawesome/free-solid-s import { library } from '@fortawesome/fontawesome-svg-core'; import { Doc } from '../../../new_fields/Doc'; import { Id } from '../../../new_fields/FieldSymbols'; -import { DocumentType } from '../../documents/Documents'; +import { DocumentType } from "../../documents/DocumentTypes"; import { Cast, StrCast } from '../../../new_fields/Types'; import * as _ from "lodash"; import { IconBar } from './IconBar'; diff --git a/src/client/views/search/IconButton.tsx b/src/client/views/search/IconButton.tsx index 5d23f6eeb..d2cfe7fad 100644 --- a/src/client/views/search/IconButton.tsx +++ b/src/client/views/search/IconButton.tsx @@ -6,7 +6,7 @@ import "./IconButton.scss"; import { faSearch, faFilePdf, faFilm, faImage, faObjectGroup, faStickyNote, faMusic, faLink, faChartBar, faGlobeAsia, faBan, faVideo, faCaretDown } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { library, icon } from '@fortawesome/fontawesome-svg-core'; -import { DocumentType } from '../../documents/Documents'; +import { DocumentType } from "../../documents/DocumentTypes"; import '../globalCssVariables.scss'; import * as _ from "lodash"; import { IconBar } from './IconBar'; diff --git a/src/client/views/search/SearchBox.tsx b/src/client/views/search/SearchBox.tsx index 4dc409e77..2ad69daca 100644 --- a/src/client/views/search/SearchBox.tsx +++ b/src/client/views/search/SearchBox.tsx @@ -245,7 +245,6 @@ export class SearchBox extends React.Component { @action.bound closeSearch = () => { - console.log("closing search") FilterBox.Instance.closeFilter(); this.closeResults(); this._searchbarOpen = false; diff --git a/src/client/views/search/SearchItem.tsx b/src/client/views/search/SearchItem.tsx index 8201aa374..4bb2ed55b 100644 --- a/src/client/views/search/SearchItem.tsx +++ b/src/client/views/search/SearchItem.tsx @@ -11,7 +11,7 @@ import { RichTextField } from "../../../new_fields/RichTextField"; import { Cast, NumCast, StrCast } from "../../../new_fields/Types"; import { emptyFunction, returnEmptyString, returnFalse, returnOne, Utils } from "../../../Utils"; import { DocServer } from "../../DocServer"; -import { DocumentType } from "../../documents/Documents"; +import { DocumentType } from "../../documents/DocumentTypes"; import { DocumentManager } from "../../util/DocumentManager"; import { DragManager, SetupDrag } from "../../util/DragManager"; import { LinkManager } from "../../util/LinkManager"; diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index d634cf57f..a8b616565 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -10,10 +10,10 @@ import { RefField, FieldId } from "./RefField"; import { ToScriptString, SelfProxy, Parent, OnUpdate, Self, HandleUpdate, Update, Id, Copy } from "./FieldSymbols"; import { scriptingGlobal, CompileScript, Scripting } from "../client/util/Scripting"; import { List } from "./List"; -import { DocumentType } from "../client/documents/Documents"; +import { DocumentType } from "../client/documents/DocumentTypes"; import { ComputedField, ScriptField } from "./ScriptField"; import { PrefetchProxy, ProxyField } from "./Proxy"; -import { CurrentUserUtils } from "../server/authentication/models/current_user_utils"; +//import { CurrentUserUtils } from "../server/authentication/models/current_user_utils"; export namespace Field { export function toKeyValueString(doc: Doc, key: string): string { @@ -154,7 +154,7 @@ export class Doc extends RefField { public async [HandleUpdate](diff: any) { const set = diff.$set; - const sameAuthor = this.author === CurrentUserUtils.email; + const sameAuthor = this.author === "foo@bar.com";//CurrentUserUtils.email; if (set) { for (const key in set) { if (!key.startsWith("fields.")) { -- cgit v1.2.3-70-g09d2 From 7ea6b44b10e1bf23287ba33e0081cacbfc595780 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Mon, 19 Aug 2019 14:58:02 -0400 Subject: seemed to fix syncing with remote google doc --- src/client/views/DocumentDecorations.tsx | 14 ++++++++ src/client/views/nodes/FormattedTextBox.tsx | 41 ++++++++++++++--------- src/new_fields/RichTextField.ts | 52 +++++++++++++---------------- 3 files changed, 63 insertions(+), 44 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 6616d5d58..963722fe3 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -1,5 +1,6 @@ import { library } from '@fortawesome/fontawesome-svg-core'; import { faLink, faTag } from '@fortawesome/free-solid-svg-icons'; +import * as fa from '@fortawesome/free-brands-svg-icons'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { action, computed, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; @@ -36,6 +37,7 @@ export const Flyout = higflyout.default; library.add(faLink); library.add(faTag); +library.add(fa.faGoogleDrive as any); @observer export class DocumentDecorations extends React.Component<{}, { value: string }> { @@ -618,6 +620,17 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> ); } + considerGoogleDoc = () => { + let thisDoc = SelectionManager.SelectedDocuments()[0].props.Document; + let canEmbed = thisDoc.data && thisDoc.data instanceof RichTextField; + if (!canEmbed) return (null); + return ( +
    + +
    + ); + } + considerTooltip = () => { let thisDoc = SelectionManager.SelectedDocuments()[0].props.Document; let isTextDoc = thisDoc.data && thisDoc.data instanceof RichTextField; @@ -768,6 +781,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }>
    {this.metadataMenu} {this.considerEmbed()} + {this.considerGoogleDoc()} {/* {this.considerTooltip()} */}
    diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index ad29ce775..bc057bb5f 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -60,7 +60,7 @@ const richTextSchema = createSchema({ documentText: "string" }); -const googleDocKey = "googleDocId"; +const googleDocId = "googleDocId"; type RichTextDocument = makeInterface<[typeof richTextSchema]>; const RichTextDocument = makeInterface(richTextSchema); @@ -84,6 +84,7 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe private _proxyReactionDisposer: Opt; private dropDisposer?: DragManager.DragDropDisposer; public get CurrentDiv(): HTMLDivElement { return this._ref.current!; } + private isOpening = false; @observable _entered = false; @observable public static InputBoxOverlay?: FormattedTextBox = undefined; @@ -295,17 +296,19 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe pollExportedCounterpart = async () => { let dataDoc = Doc.GetProto(this.props.Document); - let documentId = StrCast(dataDoc[googleDocKey]); + let documentId = StrCast(dataDoc[googleDocId]); if (documentId) { let exportState = await GoogleApiClientUtils.Docs.read({ documentId }); if (exportState) { let data = Cast(dataDoc.data, RichTextField); if (data) { + this.isOpening = true; dataDoc.data = new RichTextField(data[FromGoogleDocText](exportState)); } } else { - delete dataDoc[googleDocKey]; + delete dataDoc[googleDocId]; } + this.tryUpdateHeight(); } } @@ -346,9 +349,18 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe const field = this.dataDoc ? Cast(this.dataDoc[this.props.fieldKey], RichTextField) : undefined; return field ? field.Data : `{"doc":{"type":"doc","content":[]},"selection":{"type":"text","anchor":0,"head":0}}`; }, - field2 => { - this._editorView && !this._applyingChange && - this._editorView.updateState(EditorState.fromJSON(config, JSON.parse(field2))); + incomingValue => { + if (this._editorView && !this._applyingChange) { + let updatedState = JSON.parse(incomingValue); + this._editorView.updateState(EditorState.fromJSON(config, updatedState)); + // manually sets cursor selection at the end of the text on focus + if (this.isOpening) { + this.isOpening = false; + let end = this._editorView.state.doc.content.size - 1; + updatedState.selection = { type: "text", anchor: end, head: end }; + this._editorView.updateState(EditorState.fromJSON(config, updatedState)); + } + } } ); @@ -686,7 +698,7 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe event: action(() => Doc.GetProto(this.props.Document).autoHeight = !BoolCast(this.props.Document.autoHeight)), icon: "expand-arrows-alt" }); ContextMenu.Instance.addItem({ description: "Text Funcs...", subitems: subitems, icon: "text-height" }); - if (!(googleDocKey in Doc.GetProto(this.props.Document))) { + if (!(googleDocId in Doc.GetProto(this.props.Document))) { ContextMenu.Instance.addItem({ description: "Export to Google Doc...", event: this.updateGoogleDoc, @@ -698,21 +710,18 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe updateGoogleDoc = () => { let modes = GoogleApiClientUtils.Docs.WriteMode; let mode = modes.Replace; - let reference: Opt = Cast(this.dataDoc[googleDocKey], "string"); + let reference: Opt = Cast(this.dataDoc[googleDocId], "string"); if (!reference) { mode = modes.Insert; reference = { title: StrCast(this.dataDoc.title), - handler: id => this.dataDoc[googleDocKey] = id + handler: id => this.dataDoc[googleDocId] = id }; } - const data = Cast(this.dataDoc.data, RichTextField); - if (data) { - GoogleApiClientUtils.Docs.write({ - mode, - content: data[ToGoogleDocText](), - reference - }); + if (this._editorView) { + let data = Cast(this.dataDoc.data, RichTextField); + let content = data ? data[ToGoogleDocText]() : this._editorView.state.doc.textContent; + GoogleApiClientUtils.Docs.write({ reference, content, mode }); } } diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts index 8963682c3..ec08293e9 100644 --- a/src/new_fields/RichTextField.ts +++ b/src/new_fields/RichTextField.ts @@ -6,6 +6,8 @@ import { scriptingGlobal } from "../client/util/Scripting"; export const ToGoogleDocText = Symbol("PlainText"); export const FromGoogleDocText = Symbol("PlainText"); +const delimiter = "\n"; +const joiner = ""; @scriptingGlobal @Deserializable("RichTextField") @@ -27,45 +29,39 @@ export class RichTextField extends ObjectField { } [ToGoogleDocText]() { - let state = JSON.parse(this.Data); - let text = state.doc.textBetween(0, state.doc.content.size, "\n\n"); - console.log(text); + // Because we're working with plain text, just concatenate all paragraphs let content = JSON.parse(this.Data).doc.content; let paragraphs = content.filter((item: any) => item.type === "paragraph"); - let output = ""; - for (let i = 0; i < paragraphs.length; i++) { - let paragraph = paragraphs[i]; - let addNewLine = i > 0 ? paragraphs[i - 1].content : false; - if (paragraph.content) { - output += paragraph.content.map((block: any) => block.text).join(""); - } else { - output += i === 0 ? "" : "\n"; - } - addNewLine && (output += "\n"); - } - return output; + + // Functions to flatten ProseMirror paragraph objects (and their components) to plain text + // While this function already exists in state.doc.textBeteen(), it doesn't account for newlines + let blockText = (block: any) => block.text; + let concatenateParagraph = (p: any) => (p.content ? p.content.map(blockText).join(joiner) : "") + delimiter; + + // Concatentate paragraphs and string the result together. Trim the last newline, an artifact. + let textParagraphs = paragraphs.map(concatenateParagraph); + return textParagraphs.join(joiner).trimEnd(delimiter); } [FromGoogleDocText](plainText: string) { - let elements = plainText.split("\n"); + // Remap the text, creating blocks split on newlines + let elements = plainText.split(delimiter); + + // Google Docs adds in an extra carriage return automatically, so this counteracts it !elements[elements.length - 1].length && elements.pop(); + + // Preserve the current state, but re-write the content to be the blocks let parsed = JSON.parse(this.Data); parsed.doc.content = elements.map(text => { let paragraph: any = { type: "paragraph" }; - if (text.length) { - paragraph.content = [{ - type: "text", - marks: [], - text - }]; - } + text.length && (paragraph.content = [{ type: "text", marks: [], text }]); // An empty paragraph gets treated as a line break return paragraph; }); - parsed.selection = { - type: "text", - anchor: 1, - head: 1 - }; + + // If the new content is shorter than the previous content and selection is unchanged, may throw an out of bounds exception, so we reset it + parsed.selection = { type: "text", anchor: 1, head: 1 }; + + // Export the ProseMirror-compatible state object we've jsut built return JSON.stringify(parsed); } -- cgit v1.2.3-70-g09d2 From 0e4729a8d634c67a3575761784b840a28694ba7a Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 19 Aug 2019 15:55:36 -0400 Subject: fixed treeview dragging. got rid of extra stuff from presentationview --- src/client/documents/Documents.ts | 2 +- src/client/views/MainView.tsx | 62 +- .../views/collections/CollectionDockingView.tsx | 27 +- .../views/collections/CollectionSchemaCells.tsx | 2 + .../views/collections/CollectionSchemaView.tsx | 4 + src/client/views/collections/CollectionSubView.tsx | 2 +- .../views/collections/CollectionTreeView.tsx | 18 +- .../CollectionFreeFormRemoteCursors.tsx | 2 +- .../collectionFreeForm/CollectionFreeFormView.tsx | 2 + src/client/views/nodes/DocumentView.tsx | 6 +- src/client/views/nodes/FieldView.tsx | 1 + src/client/views/nodes/KeyValuePair.tsx | 1 + src/client/views/nodes/LinkMenu.tsx | 3 - src/client/views/nodes/PresBox.tsx | 249 +----- src/client/views/pdf/Annotation.tsx | 6 +- src/client/views/pdf/PDFViewer.tsx | 1 + .../views/presentationview/PresentationElement.tsx | 3 +- .../views/presentationview/PresentationList.tsx | 5 +- .../views/presentationview/PresentationView.scss | 4 +- .../views/presentationview/PresentationView.tsx | 994 --------------------- src/client/views/search/SearchItem.tsx | 1 + src/new_fields/Doc.ts | 55 +- src/new_fields/util.ts | 3 +- .../authentication/models/current_user_utils.ts | 23 +- 24 files changed, 172 insertions(+), 1304 deletions(-) delete mode 100644 src/client/views/presentationview/PresentationView.tsx (limited to 'src') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index c551fd2a3..47df17329 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -290,7 +290,7 @@ export namespace Docs { const { omit: protoProps, extract: delegateProps } = OmitKeys(options, delegateKeys); if (!("author" in protoProps)) { - protoProps.author = CurrentUserUtils.email; + protoProps.author = Doc.CurrentUserEmail; } if (!("creationDate" in protoProps)) { diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 7119a4fc3..7b7a5542d 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -12,7 +12,6 @@ import { List } from '../../new_fields/List'; import { Id } from '../../new_fields/FieldSymbols'; import { InkTool } from '../../new_fields/InkField'; import { listSpec } from '../../new_fields/Schema'; -import { SchemaHeaderField } from '../../new_fields/SchemaHeaderField'; import { BoolCast, Cast, FieldValue, StrCast } from '../../new_fields/Types'; import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils'; import { RouteStore } from '../../server/RouteStore'; @@ -24,7 +23,7 @@ import { DictationManager } from '../util/DictationManager'; import { SetupDrag } from '../util/DragManager'; import { HistoryUtil } from '../util/History'; import { Transform } from '../util/Transform'; -import { UndoManager } from '../util/UndoManager'; +import { UndoManager, undoBatch } from '../util/UndoManager'; import { CollectionBaseView } from './collections/CollectionBaseView'; import { CollectionDockingView } from './collections/CollectionDockingView'; import { CollectionTreeView } from './collections/CollectionTreeView'; @@ -37,15 +36,16 @@ import { MainOverlayTextBox } from './MainOverlayTextBox'; import { DocumentView } from './nodes/DocumentView'; import { OverlayView } from './OverlayView'; import PDFMenu from './pdf/PDFMenu'; -import { PresentationView } from './presentationview/PresentationView'; import { PreviewCursor } from './PreviewCursor'; import { FilterBox } from './search/FilterBox'; +import { DocumentManager } from '../util/DocumentManager'; +import PresModeMenu from './presentationview/PresentationModeMenu'; +import { PresBox } from './nodes/PresBox'; @observer export class MainView extends React.Component { public static Instance: MainView; @observable addMenuToggle = React.createRef(); - @observable private _workspacesShown: boolean = false; @observable public pwidth: number = 0; @observable public pheight: number = 0; @@ -82,10 +82,6 @@ export class MainView extends React.Component { public isPointerDown = false; private set mainContainer(doc: Opt) { if (doc) { - if (!("presentationView" in doc)) { - let initialDoc = Docs.Create.TreeDocument([], { title: "Presentation" }); - doc.presentationView = Docs.Create.PresDocument(new List([initialDoc])); - } CurrentUserUtils.UserDocument.activeWorkspace = doc; } } @@ -322,6 +318,7 @@ export class MainView extends React.Component { DataDoc={undefined} addDocument={undefined} addDocTab={emptyFunction} + pinToPres={emptyFunction} onClick={undefined} removeDocument={undefined} ScreenToLocalTransform={Transform.Identity} @@ -339,7 +336,6 @@ export class MainView extends React.Component { zoomToScale={emptyFunction} getScale={returnOne} />} - {/* {presentationDoc ? : null} */}
    } ; @@ -386,6 +382,7 @@ export class MainView extends React.Component { DataDoc={undefined} addDocument={undefined} addDocTab={this.addDocTabFunc} + pinToPres={emptyFunction} removeDocument={undefined} onClick={undefined} ScreenToLocalTransform={Transform.Identity} @@ -443,26 +440,24 @@ export class MainView extends React.Component { let imgurl = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg"; - // let addDockingNode = action(() => Docs.Create.StandardCollectionDockingDocument([{ doc: addColNode(), initialWidth: 200 }], { width: 200, height: 200, title: "a nested docking freeform collection" })); - let addSchemaNode = action(() => Docs.Create.SchemaDocument([new SchemaHeaderField("title", "#f1efeb")], [], { width: 200, height: 200, title: "a schema collection" })); - //let addTreeNode = action(() => Docs.TreeDocument([CurrentUserUtils.UserDocument], { width: 250, height: 400, title: "Library:" + CurrentUserUtils.email, dropAction: "alias" })); - // let addTreeNode = action(() => Docs.TreeDocument(this._northstarSchemas, { width: 250, height: 400, title: "northstar schemas", dropAction: "copy" })); let addColNode = action(() => Docs.Create.FreeformDocument([], { width: this.pwidth * .7, height: this.pheight, title: "a freeform collection" })); + let addPresNode = action(() => Doc.UserDoc().curPresentation = Docs.Create.PresDocument(new List(), { width: 200, height: 500, title: "a presentation trail" })); let addWebNode = action(() => Docs.Create.WebDocument("https://en.wikipedia.org/wiki/Hedgehog", { width: 300, height: 300, title: "New Webpage" })); let addDragboxNode = action(() => Docs.Create.DragboxDocument({ width: 40, height: 40, title: "drag collection" })); let addImageNode = action(() => Docs.Create.ImageDocument(imgurl, { width: 200, title: "an image of a cat" })); let addButtonDocument = action(() => Docs.Create.ButtonDocument({ width: 150, height: 50, title: "Button" })); let addImportCollectionNode = action(() => Docs.Create.DirectoryImportDocument({ title: "Directory Import", width: 400, height: 400 })); - let youtubeurl = "https://www.youtube.com/embed/TqcApsGRzWw"; - let addYoutubeSearcher = action(() => Docs.Create.YoutubeDocument(youtubeurl, { width: 600, height: 600, title: "youtube search" })); + // let youtubeurl = "https://www.youtube.com/embed/TqcApsGRzWw"; + // let addYoutubeSearcher = action(() => Docs.Create.YoutubeDocument(youtubeurl, { width: 600, height: 600, title: "youtube search" })); let btns: [React.RefObject, IconName, string, () => Doc][] = [ [React.createRef(), "object-group", "Add Collection", addColNode], + [React.createRef(), "table", "Add Presentation Trail", addPresNode], [React.createRef(), "globe-asia", "Add Website", addWebNode], [React.createRef(), "bolt", "Add Button", addButtonDocument], // [React.createRef(), "clone", "Add Docking Frame", addDockingNode], [React.createRef(), "cloud-upload-alt", "Import Directory", addImportCollectionNode], //remove at some point in favor of addImportCollectionNode - [React.createRef(), "play", "Add Youtube Searcher", addYoutubeSearcher], + //[React.createRef(), "play", "Add Youtube Searcher", addYoutubeSearcher], [React.createRef(), "file", "Add Document Dragger", addDragboxNode] ]; if (!ClientUtils.RELEASE) btns.unshift([React.createRef(), "cat", "Add Cat Image", addImageNode]); @@ -489,7 +484,7 @@ export class MainView extends React.Component {
    • -
    • +
    • {btns.map(btn => @@ -543,30 +538,20 @@ export class MainView extends React.Component { @observable isSearchVisible = false; @action.bound toggleSearch = () => { - // console.log("search toggling") this.isSearchVisible = !this.isSearchVisible; } togglePresentationView = () => { - let presDoc = this.presentationDoc; - if (!presDoc) { - return; - } - let isOpen = CollectionDockingView.Instance.Has(presDoc); - if (isOpen) { - return; - // CollectionDockingView.Instance.CloseRightSplit(presDoc); - //why?? It's throwing an error that seems impossible to fix. - //ToDo: - } else { - CollectionDockingView.Instance.AddRightSplit(presDoc, undefined); + if (CurrentUserUtils.UserDocument.curPresentation) { + let isOpen = DocumentManager.Instance.getDocumentView(CurrentUserUtils.UserDocument.curPresentation as Doc); + if (isOpen) { + CollectionDockingView.Instance.CloseRightSplit(CurrentUserUtils.UserDocument.curPresentation as Doc); + } else { + CollectionDockingView.Instance.AddRightSplit(CurrentUserUtils.UserDocument.curPresentation as Doc, undefined); + } } } - private get presentationDoc() { - let mainCont = this.mainContainer; - return mainCont ? FieldValue(Cast(mainCont.presentationView, Doc)) : undefined; - } private get dictationOverlay() { let display = this.dictationOverlayVisible; let success = this.dictationSuccess; @@ -592,12 +577,21 @@ export class MainView extends React.Component { ); } + @computed get miniPresentation() { + let next = () => PresBox.CurrentPresentation.next(); + let back = () => PresBox.CurrentPresentation.back(); + let startOrResetPres = () => PresBox.CurrentPresentation.startOrResetPres(); + let closePresMode = action(() => {PresBox.CurrentPresentation.presMode = false; this.addDocTabFunc(PresBox.CurrentPresentation.props.Document)}); + return !PresBox.CurrentPresentation || !PresBox.CurrentPresentation.presMode ? (null) : + } + render() { return (
      {this.dictationOverlay} {this.mainContent} + {this.miniPresentation} {this.nodesMenu()} diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 3fcc61b76..47dfeb169 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -29,6 +29,8 @@ import { faFile, faUnlockAlt } from '@fortawesome/free-solid-svg-icons'; import { CurrentUserUtils } from '../../../server/authentication/models/current_user_utils'; import { Docs } from '../../documents/Documents'; import { DateField } from '../../../new_fields/DateField'; +import { List } from '../../../new_fields/List'; +import { DocumentType } from '../../documents/DocumentTypes'; library.add(faFile); @observer @@ -543,11 +545,31 @@ export class DockedFrameRenderer extends React.Component { })); } + /** + * Adds a document to the presentation view + **/ + @undoBatch + @action + public PinDoc(doc: Doc) { + if (doc.type === DocumentType.PRES) { + MainView.Instance.toggleMiniPresentation() + } + //add this new doc to props.Document + let curPres = Cast(CurrentUserUtils.UserDocument.curPresentation, Doc) as Doc; + if (curPres) { + const data = Cast(curPres.data, listSpec(Doc)); + if (data) { + data.push(doc); + } else { + curPres.data = new List([doc]); + } + } + } + componentDidMount() { this.props.glContainer.layoutManager.on("activeContentItemChanged", this.onActiveContentItemChanged); this.props.glContainer.on("tab", this.onActiveContentItemChanged); this.onActiveContentItemChanged(); - // setTimeout(() => MainView.Instance.openPresentationView(), 2000); } componentWillUnmount() { @@ -592,6 +614,8 @@ export class DockedFrameRenderer extends React.Component { MainView.Instance.openWorkspace(doc); } else if (location === "onRight") { CollectionDockingView.Instance.AddRightSplit(doc, dataDoc); + } else if (location === "close") { + CollectionDockingView.Instance.CloseRightSplit(doc); } else { CollectionDockingView.Instance.AddTab(this._stack, doc, dataDoc); } @@ -618,6 +642,7 @@ export class DockedFrameRenderer extends React.Component { focus={emptyFunction} backgroundColor={returnEmptyString} addDocTab={this.addDocTab} + pinToPres={this.PinDoc} ContainingCollectionView={undefined} zoomToScale={emptyFunction} getScale={returnOne} />; diff --git a/src/client/views/collections/CollectionSchemaCells.tsx b/src/client/views/collections/CollectionSchemaCells.tsx index 7e3061354..551b485e7 100644 --- a/src/client/views/collections/CollectionSchemaCells.tsx +++ b/src/client/views/collections/CollectionSchemaCells.tsx @@ -40,6 +40,7 @@ export interface CellProps { fieldKey: string; renderDepth: number; addDocTab: (document: Doc, dataDoc: Doc | undefined, where: string) => void; + pinToPres: (document: Doc) => void; moveDocument: (document: Doc, targetCollection: Doc, addDocument: (document: Doc) => boolean) => boolean; isFocused: boolean; changeFocusedCellByIndex: (row: number, col: number) => void; @@ -160,6 +161,7 @@ export class CollectionSchemaCell extends React.Component { PanelHeight: returnZero, PanelWidth: returnZero, addDocTab: this.props.addDocTab, + pinToPres: this.props.pinToPres, ContentScaling: returnOne }; diff --git a/src/client/views/collections/CollectionSchemaView.tsx b/src/client/views/collections/CollectionSchemaView.tsx index 4537dcc85..221908dd2 100644 --- a/src/client/views/collections/CollectionSchemaView.tsx +++ b/src/client/views/collections/CollectionSchemaView.tsx @@ -251,6 +251,7 @@ export interface SchemaTableProps { active: () => boolean; onDrop: (e: React.DragEvent, options: DocumentOptions, completed?: (() => void) | undefined) => void; addDocTab: (document: Doc, dataDoc: Doc | undefined, where: string) => void; + pinToPres: (document: Doc) => void; isSelected: () => boolean; isFocused: (document: Doc) => boolean; setFocused: (document: Doc) => void; @@ -377,6 +378,7 @@ export class SchemaTable extends React.Component { fieldKey: this.props.fieldKey, renderDepth: this.props.renderDepth, addDocTab: this.props.addDocTab, + pinToPres: this.props.pinToPres, moveDocument: this.props.moveDocument, setIsEditing: this.setCellIsEditing, isEditable: isEditable, @@ -907,6 +909,7 @@ interface CollectionSchemaPreviewProps { active: () => boolean; whenActiveChanged: (isActive: boolean) => void; addDocTab: (document: Doc, dataDoc: Doc | undefined, where: string) => void; + pinToPres: (document: Doc) => void; setPreviewScript: (script: string) => void; previewScript?: string; } @@ -997,6 +1000,7 @@ export class CollectionSchemaPreview extends React.Component(schemaCtor: (doc: Doc) => T) { let ind; let doc = this.props.Document; let id = CurrentUserUtils.id; - let email = CurrentUserUtils.email; + let email = Doc.CurrentUserEmail; let pos = { x: position[0], y: position[1] }; if (id && email) { const proto = Doc.GetProto(doc); diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index 7424cc186..6b9cd57b3 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -39,6 +39,7 @@ export interface TreeViewProps { moveDocument: DragManager.MoveFunction; dropAction: "alias" | "copy" | undefined; addDocTab: (doc: Doc, dataDoc: Doc | undefined, where: string) => void; + pinToPres: (document: Doc) => void; panelWidth: () => number; panelHeight: () => number; addDocument: (doc: Doc, relativeTo?: Doc, before?: boolean) => boolean; @@ -259,10 +260,10 @@ class TreeView extends React.Component { if (contents instanceof Doc || Cast(contents, listSpec(Doc))) { let remDoc = (doc: Doc) => this.remove(doc, key); - let addDoc = (doc: Doc, addBefore?: Doc, before?: boolean) => Doc.AddDocToList(this.dataDoc, key, doc, addBefore, before); + let addDoc = (doc: Doc, addBefore?: Doc, before?: boolean) => Doc.AddDocToList(this.dataDoc, key, doc, addBefore, before, !BoolCast(this.props.document.stackingHeadersSortDescending)); contentElement = TreeView.GetChildElements(contents instanceof Doc ? [contents] : DocListCast(contents), this.props.treeViewId, doc, undefined, key, addDoc, remDoc, this.move, - this.props.dropAction, this.props.addDocTab, this.props.ScreenToLocalTransform, this.props.outerXf, this.props.active, this.props.panelWidth, this.props.renderDepth); + this.props.dropAction, this.props.addDocTab, this.props.pinToPres, this.props.ScreenToLocalTransform, this.props.outerXf, this.props.active, this.props.panelWidth, this.props.renderDepth); } else { contentElement = { const expandKey = this.treeViewExpandedView === this.fieldKey ? this.fieldKey : this.treeViewExpandedView === "links" ? "links" : undefined; if (expandKey !== undefined) { let remDoc = (doc: Doc) => this.remove(doc, expandKey); - let addDoc = (doc: Doc, addBefore?: Doc, before?: boolean) => Doc.AddDocToList(this.dataDoc, expandKey, doc, addBefore, before); + let addDoc = (doc: Doc, addBefore?: Doc, before?: boolean) => Doc.AddDocToList(this.dataDoc, expandKey, doc, addBefore, before, !BoolCast(this.props.document.stackingHeadersSortDescending)); let docs = expandKey === "links" ? this.childLinks : this.childDocs; return
        {!docs ? (null) : TreeView.GetChildElements(docs as Doc[], this.props.treeViewId, this.props.document.layout as Doc, this.resolvedDataDoc, expandKey, addDoc, remDoc, this.move, - this.props.dropAction, this.props.addDocTab, this.props.ScreenToLocalTransform, + this.props.dropAction, this.props.addDocTab, this.props.pinToPres, this.props.ScreenToLocalTransform, this.props.outerXf, this.props.active, this.props.panelWidth, this.props.renderDepth)}
      ; } else if (this.treeViewExpandedView === "fields") { @@ -319,6 +320,7 @@ class TreeView extends React.Component { active={this.props.active} whenActiveChanged={emptyFunction as any} addDocTab={this.props.addDocTab} + pinToPres={this.props.pinToPres} setPreviewScript={emptyFunction}>
      ; @@ -395,6 +397,7 @@ class TreeView extends React.Component { move: DragManager.MoveFunction, dropAction: dropActionType, addDocTab: (doc: Doc, dataDoc: Doc | undefined, where: string) => void, + pinToPres: (document: Doc) => void, screenToLocalXf: () => Transform, outerXf: () => { translateX: number, translateY: number }, active: () => boolean, @@ -471,6 +474,7 @@ class TreeView extends React.Component { moveDocument={move} dropAction={dropAction} addDocTab={addDocTab} + pinToPres={pinToPres} ScreenToLocalTransform={screenToLocalXf} outerXf={outerXf} parentKey={key} @@ -554,7 +558,7 @@ export class CollectionTreeView extends CollectionSubView(Document) { render() { Doc.UpdateDocumentExtensionForField(this.props.DataDoc ? this.props.DataDoc : this.props.Document, this.props.fieldKey); let dropAction = StrCast(this.props.Document.dropAction) as dropActionType; - let addDoc = (doc: Doc, relativeTo?: Doc, before?: boolean) => Doc.AddDocToList(this.props.Document, this.props.fieldKey, doc, relativeTo, before); + let addDoc = (doc: Doc, relativeTo?: Doc, before?: boolean) => Doc.AddDocToList(this.props.Document, this.props.fieldKey, doc, relativeTo, before, !BoolCast(this.props.Document.stackingHeadersSortDescending)); let moveDoc = (d: Doc, target: Doc, addDoc: (doc: Doc) => boolean) => this.props.moveDocument(d, target, addDoc); return !this.childDocs ? (null) : (
      ([Templates.Title.Layout]) }); TreeView.loadId = doc[Id]; - Doc.AddDocToList(this.props.Document, this.props.fieldKey, doc, this.childDocs.length ? this.childDocs[0] : undefined, true); + Doc.AddDocToList(this.props.Document, this.props.fieldKey, doc, this.childDocs.length ? this.childDocs[0] : undefined, true, !BoolCast(this.props.Document.stackingHeadersSortDescending)); }} /> {this.props.Document.workspaceLibrary ? this.renderNotifsButton : (null)} {this.props.Document.allowClear ? this.renderClearButton : (null)}
        { TreeView.GetChildElements(this.childDocs, this.props.Document[Id], this.props.Document, this.props.DataDoc, this.props.fieldKey, addDoc, this.remove, - moveDoc, dropAction, this.props.addDocTab, this.props.ScreenToLocalTransform, this.outerXf, this.props.active, this.props.PanelWidth, this.props.renderDepth) + moveDoc, dropAction, this.props.addDocTab, this.props.pinToPres, this.props.ScreenToLocalTransform, this.outerXf, this.props.active, this.props.PanelWidth, this.props.renderDepth) }
      diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx index 3193f5624..b8148852d 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx @@ -55,7 +55,7 @@ export class CollectionFreeFormRemoteCursors extends React.Component void; bringToFront: (doc: Doc, sendToBack?: boolean) => void; addDocTab: (doc: Doc, dataDoc: Doc | undefined, where: string) => void; + pinToPres: (document: Doc) => void; collapseToPoint?: (scrpt: number[], expandedDocs: Doc[] | undefined) => void; zoomToScale: (scale: number) => void; backgroundColor: (doc: Doc) => string | undefined; @@ -614,7 +614,7 @@ export class DocumentView extends DocComponent(Docu let analyzers: ContextMenuProps[] = existingAnalyze && "subitems" in existingAnalyze ? existingAnalyze.subitems : []; analyzers.push({ description: "Transcribe Speech", event: this.listen, icon: "microphone" }); !existingAnalyze && cm.addItem({ description: "Analyzers...", subitems: analyzers, icon: "hand-point-right" }); - cm.addItem({ description: "Pin to Presentation", event: () => PresBox.Instance.PinDoc(this.props.Document), icon: "map-pin" }); //I think this should work... and it does! A miracle! + cm.addItem({ description: "Pin to Presentation", event: () => this.props.pinToPres(this.props.Document), icon: "map-pin" }); //I think this should work... and it does! A miracle! cm.addItem({ description: "Add Repl", icon: "laptop-code", event: () => OverlayView.Instance.addWindow(, { x: 300, y: 100, width: 200, height: 200, title: "Scripting REPL" }) }); cm.addItem({ description: "Download document", icon: "download", event: () => { @@ -661,7 +661,7 @@ export class DocumentView extends DocComponent(Docu try { let stuff = await rp.get(Utils.prepend(RouteStore.getUsers)); const users: User[] = JSON.parse(stuff); - usersMenu = users.filter(({ email }) => email !== CurrentUserUtils.email).map(({ email, userDocumentId }) => ({ + usersMenu = users.filter(({ email }) => email !== Doc.CurrentUserEmail).map(({ email, userDocumentId }) => ({ description: email, event: async () => { const userDocument = await Cast(DocServer.GetRefField(userDocumentId), Doc); if (!userDocument) { diff --git a/src/client/views/nodes/FieldView.tsx b/src/client/views/nodes/FieldView.tsx index cae975f30..f0f1b3b73 100644 --- a/src/client/views/nodes/FieldView.tsx +++ b/src/client/views/nodes/FieldView.tsx @@ -39,6 +39,7 @@ export interface FieldViewProps { selectOnLoad: boolean; addDocument?: (document: Doc, allowDuplicates?: boolean) => boolean; addDocTab: (document: Doc, dataDoc: Doc | undefined, where: string) => void; + pinToPres: (document: Doc) => void; removeDocument?: (document: Doc) => boolean; moveDocument?: (document: Doc, targetCollection: Doc, addDocument: (document: Doc) => boolean) => boolean; ScreenToLocalTransform: () => Transform; diff --git a/src/client/views/nodes/KeyValuePair.tsx b/src/client/views/nodes/KeyValuePair.tsx index 534a42efc..8001b24a7 100644 --- a/src/client/views/nodes/KeyValuePair.tsx +++ b/src/client/views/nodes/KeyValuePair.tsx @@ -68,6 +68,7 @@ export class KeyValuePair extends React.Component { PanelWidth: returnZero, PanelHeight: returnZero, addDocTab: returnZero, + pinToPres: returnZero, ContentScaling: returnOne }; let contents = ; diff --git a/src/client/views/nodes/LinkMenu.tsx b/src/client/views/nodes/LinkMenu.tsx index 1a4af04f8..1908889e9 100644 --- a/src/client/views/nodes/LinkMenu.tsx +++ b/src/client/views/nodes/LinkMenu.tsx @@ -12,9 +12,6 @@ import { library } from "@fortawesome/fontawesome-svg-core"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; library.add(faTrash); -import { Cast, FieldValue, StrCast } from "../../../new_fields/Types"; -import { Id } from "../../../new_fields/FieldSymbols"; -import { DocumentType } from "../../documents/Documents"; interface Props { docView: DocumentView; diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index 91c141540..cc042e008 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -1,22 +1,22 @@ import React = require("react"); -import { FieldViewProps, FieldView } from './FieldView'; +import { library } from '@fortawesome/fontawesome-svg-core'; +import { faArrowLeft, faArrowRight, faEdit, faMinus, faPlay, faPlus, faStop, faTimes } from '@fortawesome/free-solid-svg-icons'; +import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { action, computed, observable, runInAction } from "mobx"; import { observer } from "mobx-react"; -import { observable, action, runInAction, reaction, autorun, computed } from "mobx"; -import "../presentationview/PresentationView.scss"; -import { DocumentManager } from "../../util/DocumentManager"; -import { Utils } from "../../../Utils"; import { Doc, DocListCast, DocListCastAsync } from "../../../new_fields/Doc"; -import { listSpec } from "../../../new_fields/Schema"; -import { Cast, NumCast, FieldValue, PromiseValue, StrCast, BoolCast } from "../../../new_fields/Types"; import { Id } from "../../../new_fields/FieldSymbols"; import { List } from "../../../new_fields/List"; +import { listSpec } from "../../../new_fields/Schema"; +import { BoolCast, Cast, FieldValue, NumCast, StrCast } from "../../../new_fields/Types"; +import { Utils } from "../../../Utils"; +import { DocumentManager } from "../../util/DocumentManager"; +import { undoBatch } from "../../util/UndoManager"; import PresentationElement, { buttonIndex } from "../presentationview/PresentationElement"; -import { library } from '@fortawesome/fontawesome-svg-core'; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { faArrowRight, faArrowLeft, faPlay, faStop, faPlus, faTimes, faMinus, faEdit } from '@fortawesome/free-solid-svg-icons'; -import { Docs } from "../../documents/Documents"; -import { undoBatch, UndoManager } from "../../util/UndoManager"; import PresentationViewList from "../presentationview/PresentationList"; +import "../presentationview/PresentationView.scss"; +import { FieldView, FieldViewProps } from './FieldView'; +import { ContextMenu } from "../ContextMenu"; library.add(faArrowLeft); library.add(faArrowRight); @@ -37,17 +37,14 @@ const expandedWidth = 450; @observer export class PresBox extends React.Component { //FieldViewProps? - @computed - private get presentationDocs() { - let source = Doc.GetProto(this.props.Document); - return DocListCast(source.data); - } public static LayoutString(fieldKey?: string) { return FieldView.LayoutString(PresBox, fieldKey); } - //public static Instance: PresentationView; public static Instance: PresBox; + //Keeping track of the doc for the current presentation -- bcz: keeping a list of current presentations shouldn't be needed. Let users create them, store them, as they see fit. + @computed get curPresentation() { return this.props.Document; } + //Mapping from presentation ids to a list of doc that represent a group @observable groupMappings: Map = new Map(); //mapping from docs to their rendered component @@ -59,9 +56,6 @@ export class PresBox extends React.Component { //FieldViewProps? //back-up so that presentation stays the way it's when refreshed @observable presGroupBackUp: Doc = new Doc(); @observable presButtonBackUp: Doc = new Doc(); - - //Keeping track of the doc for the current presentation - @observable curPresentation: Doc = new Doc(); //Mapping of guids to presentations. @observable presentationsMapping: Map = new Map(); //Mapping of presentations to guid, so that select option values can be given. @@ -77,12 +71,14 @@ export class PresBox extends React.Component { //FieldViewProps? @observable opacity = 1; @observable persistOpacity = true; @observable labelOpacity = 0; + @observable presMode = false; + + @observable public static CurrentPresentation: PresBox; //initilize class variables - constructor(props: FieldViewProps) { //FieldViewProps? + constructor(props: FieldViewProps) { super(props); - //PresentationView.Instance = this; - PresBox.Instance = this; + runInAction(() => PresBox.CurrentPresentation = this); } @action @@ -94,32 +90,10 @@ export class PresBox extends React.Component { //FieldViewProps? } } - //The first lifecycle function that gets called to set up the current presentation. - async componentWillMount() { - this.presentationDocs.forEach(async (doc, index: number) => { - - //For each presentation received from mainContainer, a mapping is created. - let curDoc: Doc = await doc; - let newGuid = Utils.GenerateGuid(); - this.presentationsKeyMapping.set(curDoc, newGuid); - this.presentationsMapping.set(newGuid, curDoc); - - //The Presentation at first index gets set as default start presentation - if (index === 0) { - runInAction(() => this.currentSelectedPresValue = newGuid); - runInAction(() => this.curPresentation = curDoc); - } - }); - } - - //Second lifecycle function that gets called when component mounts. It makes sure to + //Second lifecycle function that gets called when component mounts. It makes sure toS //get the back-up information from previous session for the current presentation. async componentDidMount() { - let docAtZero = await this.presentationDocs[0]; - runInAction(() => this.curPresentation = docAtZero); - this.setPresentationBackUps(); - } @@ -212,7 +186,6 @@ export class PresBox extends React.Component { //FieldViewProps? //observable means render is re-called every time variable is changed @observable collapsed: boolean = false; - closePresentation = action(() => this.curPresentation.width = 0); next = async () => { const current = NumCast(this.curPresentation.selectedDoc); //asking to get document at current index @@ -556,23 +529,6 @@ export class PresBox extends React.Component { //FieldViewProps? runInAction(() => this.groupMappings = new Map()); } - /** - * Adds a document to the presentation view - **/ - @undoBatch - @action - public PinDoc(doc: Doc) { - //add this new doc to props.Document - const data = Cast(this.curPresentation.data, listSpec(Doc)); - if (data) { - data.push(doc); - } else { - this.curPresentation.data = new List([doc]); - } - - this.toggle(true); - } - //Function that sets the store of the children docs. @action setChildrenDocs = (docList: Doc[]) => { @@ -648,72 +604,15 @@ export class PresBox extends React.Component { //FieldViewProps? } - /** - * The function that is called to add a new presentation to the presentationView. - * It sets up te mappings and local copies of it. Resets the groupings and presentation. - * Makes the new presentation current selected, and retrieve the back-Ups if present. - */ - @action - addNewPresentation = (presTitle: string) => { - //creating a new presentation doc - let newPresentationDoc = Docs.Create.TreeDocument([], { title: presTitle }); - let presDocs = Cast(Doc.GetProto(this.props.Document).data, listSpec(Doc)); - presDocs && presDocs.push(newPresentationDoc); - - //setting that new doc as current - this.curPresentation = newPresentationDoc; - - //storing the doc in local copies for easier access - let newGuid = Utils.GenerateGuid(); - this.presentationsMapping.set(newGuid, newPresentationDoc); - this.presentationsKeyMapping.set(newPresentationDoc, newGuid); - - //resetting the previous presentation's actions so that new presentation can be loaded. - this.resetGroupIds(); - this.resetPresentation(); - this.presElementsMappings = new Map(); - this.currentSelectedPresValue = newGuid; - this.setPresentationBackUps(); - - } - - /** - * The function that is called to change the current selected presentation. - * Changes the presentation, also resetting groupings and presentation in process. - * Plus retrieving the backUps for the newly selected presentation. - */ - @action - getSelectedPresentation = (e: React.ChangeEvent) => { - //get the guid of the selected presentation - let selectedGuid = e.target.value; - //set that as current presentation - this.curPresentation = this.presentationsMapping.get(selectedGuid)!; - - //reset current Presentations local things so that new one can be loaded - this.resetGroupIds(); - this.resetPresentation(); - this.presElementsMappings = new Map(); - this.currentSelectedPresValue = selectedGuid; - this.setPresentationBackUps(); - - - } /** * The function that is called to render either select for presentations, or title inputting. */ renderSelectOrPresSelection = () => { - let presentationList = this.presentationDocs; if (this.PresTitleInputOpen || this.PresTitleChangeOpen) { return this.titleInputElement = e!} type="text" className="presentationView-title" placeholder="Enter Name!" onKeyDown={this.submitPresentationTitle} />; } else { - return ; + return (null); } } @@ -726,87 +625,12 @@ export class PresBox extends React.Component { //FieldViewProps? if (e.keyCode === 13) { let presTitle = this.titleInputElement!.value; this.titleInputElement!.value = ""; - if (this.PresTitleInputOpen) { - if (presTitle === "") { - presTitle = "Presentation"; - } - this.PresTitleInputOpen = false; - this.addNewPresentation(presTitle); - } else if (this.PresTitleChangeOpen) { + if (this.PresTitleChangeOpen) { this.PresTitleChangeOpen = false; this.changePresentationTitle(presTitle); } } } - - /** - * The function that is called to remove a presentation from all its copies, and the main Container's - * list. Sets up the next presentation as current. - */ - @action - removePresentation = async () => { - if (this.presentationsMapping.size !== 1) { - let presentationList = this.presentationDocs; - let batch = UndoManager.StartBatch("presRemoval"); - - //getting the presentation that will be removed - let removedDoc = this.presentationsMapping.get(this.currentSelectedPresValue!); - //that presentation is removed - presentationList!.splice(presentationList.indexOf(removedDoc!), 1); - - //its mappings are removed from local copies - this.presentationsKeyMapping.delete(removedDoc!); - this.presentationsMapping.delete(this.currentSelectedPresValue!); - - //the next presentation is set as current - let remainingPresentations = this.presentationsMapping.values(); - let nextDoc = remainingPresentations.next().value; - this.curPresentation = nextDoc; - - - //Storing these for being able to undo changes - let curGuid = this.currentSelectedPresValue!; - let curPresStatus = this.presStatus; - - //resetting the groups and presentation actions so that next presentation gets loaded - this.resetGroupIds(); - this.resetPresentation(); - this.currentSelectedPresValue = this.presentationsKeyMapping.get(nextDoc)!.toString(); - this.setPresentationBackUps(); - - //Storing for undo - let currentGroups = this.groupMappings; - let curPresElemMapping = this.presElementsMappings; - - //Event to undo actions that are not related to doc directly, aka. local things - UndoManager.AddEvent({ - undo: action(() => { - this.curPresentation = removedDoc!; - this.presentationsMapping.set(curGuid, removedDoc!); - this.presentationsKeyMapping.set(removedDoc!, curGuid); - this.currentSelectedPresValue = curGuid; - - this.presStatus = curPresStatus; - this.groupMappings = currentGroups; - this.presElementsMappings = curPresElemMapping; - this.setPresentationBackUps(); - - }), - redo: action(() => { - this.curPresentation = nextDoc; - this.presStatus = false; - this.presentationsKeyMapping.delete(removedDoc!); - this.presentationsMapping.delete(curGuid); - this.currentSelectedPresValue = this.presentationsKeyMapping.get(nextDoc)!.toString(); - this.setPresentationBackUps(); - - }), - }); - - batch.end(); - } - } - /** * The function that is called to change title of presentation to what user entered. */ @@ -822,26 +646,23 @@ export class PresBox extends React.Component { //FieldViewProps? this.presElementsMappings.set(keyDoc, elem); } + specificContextMenu = (e: React.MouseEvent): void => { + ContextMenu.Instance.addItem({ description: "Make Current Presentation", event: action(() => Doc.UserDoc().curPresentation = this.props.Document), icon: "asterisk" }); + ContextMenu.Instance.addItem({ + description: "Toggle Minimized Mode", event: action(() => { + this.presMode = !this.presMode; + if (this.presMode) this.props.addDocTab && this.props.addDocTab(this.props.Document, this.props.DataDoc, "close"); + }), icon: "asterisk" + }); + } render() { let width = "100%"; //NumCast(this.curPresentation.width) - return ( -
      !this.persistOpacity && (this.opacity = 1))} onPointerLeave={action(() => !this.persistOpacity && (this.opacity = 0.4))} style={{ width: width, overflow: "hidden", opacity: this.opacity, transition: "0.7s opacity ease", pointerEvents: "all" }}> -
      - {this.renderSelectOrPresSelection()} - {/**this.closePresentation CLICK does not work?! Also without the*/} - - - -
      +
      !this.persistOpacity && (this.opacity = 1))} onContextMenu={this.specificContextMenu} + onPointerLeave={action(() => !this.persistOpacity && (this.opacity = 0.4))} + style={{ width: width, opacity: this.opacity, }}>
      {this.renderPlayPauseButton()} diff --git a/src/client/views/pdf/Annotation.tsx b/src/client/views/pdf/Annotation.tsx index 7ba7b6d14..6f77a0a5b 100644 --- a/src/client/views/pdf/Annotation.tsx +++ b/src/client/views/pdf/Annotation.tsx @@ -6,10 +6,10 @@ import { Id } from "../../../new_fields/FieldSymbols"; import { List } from "../../../new_fields/List"; import { Cast, FieldValue, NumCast, StrCast } from "../../../new_fields/Types"; import { DocumentManager } from "../../util/DocumentManager"; -import { PresentationView } from "../presentationview/PresentationView"; import PDFMenu from "./PDFMenu"; import "./Annotation.scss"; import { scale } from "./PDFViewer"; +import { PresBox } from "../nodes/PresBox"; interface IAnnotationProps { anno: Doc; @@ -18,6 +18,7 @@ interface IAnnotationProps { fieldExtensionDoc: Doc; scrollTo?: (n: number) => void; addDocTab: (document: Doc, dataDoc: Doc | undefined, where: string) => void; + pinToPres: (document: Doc) => void; } export default class Annotation extends React.Component { @@ -37,6 +38,7 @@ interface IRegionAnnotationProps { fieldExtensionDoc: Doc; scrollTo?: (n: number) => void; addDocTab: (document: Doc, dataDoc: Doc | undefined, where: string) => void; + pinToPres: (document: Doc) => void; document: Doc; } @@ -81,7 +83,7 @@ class RegionAnnotation extends React.Component { pinToPres = () => { let group = FieldValue(Cast(this.props.document.group, Doc)); - group && PresentationView.Instance.PinDoc(group); + group && this.props.pinToPres(group); } @action diff --git a/src/client/views/pdf/PDFViewer.tsx b/src/client/views/pdf/PDFViewer.tsx index 08674720d..258e218f0 100644 --- a/src/client/views/pdf/PDFViewer.tsx +++ b/src/client/views/pdf/PDFViewer.tsx @@ -36,6 +36,7 @@ interface IViewerProps { active: () => boolean; setPanY?: (n: number) => void; addDocTab: (document: Doc, dataDoc: Doc | undefined, where: string) => void; + pinToPres: (document: Doc) => void; addDocument?: (doc: Doc, allowDuplicates?: boolean) => boolean; } diff --git a/src/client/views/presentationview/PresentationElement.tsx b/src/client/views/presentationview/PresentationElement.tsx index d98b66324..912970a50 100644 --- a/src/client/views/presentationview/PresentationElement.tsx +++ b/src/client/views/presentationview/PresentationElement.tsx @@ -15,7 +15,7 @@ import { SelectionManager } from "../../util/SelectionManager"; import { ContextMenu } from "../ContextMenu"; import { Transform } from "../../util/Transform"; import { DocumentView } from "../nodes/DocumentView"; -import { DocumentType } from "../../documents/Documents"; +import { DocumentType } from "../../documents/DocumentTypes"; import React = require("react"); @@ -839,6 +839,7 @@ export default class PresentationElement extends React.Component 350} PanelHeight={() => 90} diff --git a/src/client/views/presentationview/PresentationList.tsx b/src/client/views/presentationview/PresentationList.tsx index e853c4070..288ade042 100644 --- a/src/client/views/presentationview/PresentationList.tsx +++ b/src/client/views/presentationview/PresentationList.tsx @@ -6,10 +6,7 @@ import { Utils } from "../../../Utils"; import { Doc, DocListCast, DocListCastAsync } from "../../../new_fields/Doc"; import { NumCast, StrCast } from "../../../new_fields/Types"; import { Id } from "../../../new_fields/FieldSymbols"; -import PresentationElement, { buttonIndex } from "./PresentationElement"; -import "../../../new_fields/Doc"; - - +import PresentationElement from "./PresentationElement"; interface PresListProps { diff --git a/src/client/views/presentationview/PresentationView.scss b/src/client/views/presentationview/PresentationView.scss index 65b09c833..4f5858f20 100644 --- a/src/client/views/presentationview/PresentationView.scss +++ b/src/client/views/presentationview/PresentationView.scss @@ -7,7 +7,9 @@ top: 0; bottom: 0; letter-spacing: 2px; - + overflow: hidden; + transition: 0.7s opacity ease; + pointer-events: all; } .presentationView-item { diff --git a/src/client/views/presentationview/PresentationView.tsx b/src/client/views/presentationview/PresentationView.tsx deleted file mode 100644 index bea70f00b..000000000 --- a/src/client/views/presentationview/PresentationView.tsx +++ /dev/null @@ -1,994 +0,0 @@ -import { observer } from "mobx-react"; -import React = require("react"); -import { observable, action, runInAction, reaction, autorun } from "mobx"; -import "./PresentationView.scss"; -import { DocumentManager } from "../../util/DocumentManager"; -import { Utils } from "../../../Utils"; -import { Doc, DocListCast, DocListCastAsync, WidthSym } from "../../../new_fields/Doc"; -import { listSpec } from "../../../new_fields/Schema"; -import { Cast, NumCast, FieldValue, PromiseValue, StrCast, BoolCast } from "../../../new_fields/Types"; -import { Id } from "../../../new_fields/FieldSymbols"; -import { List } from "../../../new_fields/List"; -import PresentationElement, { buttonIndex } from "./PresentationElement"; -import { library } from '@fortawesome/fontawesome-svg-core'; -import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { faArrowRight, faArrowLeft, faPlay, faStop, faPlus, faTimes, faMinus, faEdit, faEye } from '@fortawesome/free-solid-svg-icons'; -import { Docs } from "../../documents/Documents"; -import { undoBatch, UndoManager } from "../../util/UndoManager"; -import PresentationViewList from "./PresentationList"; -import PresModeMenu from "./PresentationModeMenu"; -import { CollectionDockingView } from "../collections/CollectionDockingView"; - -library.add(faArrowLeft); -library.add(faArrowRight); -library.add(faPlay); -library.add(faStop); -library.add(faPlus); -library.add(faTimes); -library.add(faMinus); -library.add(faEdit); -library.add(faEye); - - -export interface PresViewProps { - Documents: List; -} - -const expandedWidth = 400; -const presMinWidth = 300; - -@observer -export class PresentationView extends React.Component { - public static Instance: PresentationView; - - //Mapping from presentation ids to a list of doc that represent a group - @observable groupMappings: Map = new Map(); - //mapping from docs to their rendered component - @observable presElementsMappings: Map = new Map(); - //variable that holds all the docs in the presentation - @observable childrenDocs: Doc[] = []; - //variable to hold if presentation is started - @observable presStatus: boolean = false; - //back-up so that presentation stays the way it's when refreshed - @observable presGroupBackUp: Doc = new Doc(); - @observable presButtonBackUp: Doc = new Doc(); - - //Keeping track of the doc for the current presentation - @observable curPresentation: Doc = new Doc(); - //Mapping of guids to presentations. - @observable presentationsMapping: Map = new Map(); - //Mapping of presentations to guid, so that select option values can be given. - @observable presentationsKeyMapping: Map = new Map(); - //Variable to keep track of guid of the current presentation - @observable currentSelectedPresValue: string | undefined; - //A flag to keep track if title input is open, which is used in rendering. - @observable PresTitleInputOpen: boolean = false; - //Variable that holds reference to title input, so that new presentations get titles assigned. - @observable titleInputElement: HTMLInputElement | undefined; - @observable PresTitleChangeOpen: boolean = false; - @observable presMode: boolean = false; - - - @observable opacity = 1; - @observable persistOpacity = true; - @observable labelOpacity = 0; - - //initilize class variables - constructor(props: PresViewProps) { - super(props); - PresentationView.Instance = this; - } - - @action - toggle = (forcedValue: boolean | undefined) => { - if (forcedValue !== undefined) { - this.curPresentation.width = forcedValue ? expandedWidth : 0; - } else { - this.curPresentation.width = this.curPresentation.width === expandedWidth ? 0 : expandedWidth; - } - } - - //The first lifecycle function that gets called to set up the current presentation. - async componentWillMount() { - - this.props.Documents.forEach(async (doc, index: number) => { - - //For each presentation received from mainContainer, a mapping is created. - let curDoc: Doc = await doc; - let newGuid = Utils.GenerateGuid(); - this.presentationsKeyMapping.set(curDoc, newGuid); - this.presentationsMapping.set(newGuid, curDoc); - - //The Presentation at first index gets set as default start presentation - if (index === 0) { - runInAction(() => this.currentSelectedPresValue = newGuid); - runInAction(() => this.curPresentation = curDoc); - } - }); - } - - //Second lifecycle function that gets called when component mounts. It makes sure to - //get the back-up information from previous session for the current presentation. - async componentDidMount() { - let docAtZero = await this.props.Documents[0]; - runInAction(() => this.curPresentation = docAtZero); - - this.setPresentationBackUps(); - - } - - - /** - * The function that retrieves the backUps for the current Presentation if present, - * otherwise initializes. - */ - setPresentationBackUps = async () => { - //getting both backUp documents - - let castedGroupBackUp = Cast(this.curPresentation.presGroupBackUp, Doc); - let castedButtonBackUp = Cast(this.curPresentation.presButtonBackUp, Doc); - //if instantiated before - if (castedGroupBackUp instanceof Promise) { - castedGroupBackUp.then(doc => { - let toAssign = doc ? doc : new Doc(); - this.curPresentation.presGroupBackUp = toAssign; - runInAction(() => this.presGroupBackUp = toAssign); - if (doc) { - if (toAssign[Id] === doc[Id]) { - this.retrieveGroupMappings(); - } - } - }); - - //if never instantiated a store doc yet - } else if (castedGroupBackUp instanceof Doc) { - let castedDoc: Doc = await castedGroupBackUp; - runInAction(() => this.presGroupBackUp = castedDoc); - this.retrieveGroupMappings(); - } else { - runInAction(() => { - let toAssign = new Doc(); - this.presGroupBackUp = toAssign; - this.curPresentation.presGroupBackUp = toAssign; - - }); - - } - //if instantiated before - if (castedButtonBackUp instanceof Promise) { - castedButtonBackUp.then(doc => { - let toAssign = doc ? doc : new Doc(); - this.curPresentation.presButtonBackUp = toAssign; - runInAction(() => this.presButtonBackUp = toAssign); - }); - - //if never instantiated a store doc yet - } else if (castedButtonBackUp instanceof Doc) { - let castedDoc: Doc = await castedButtonBackUp; - runInAction(() => this.presButtonBackUp = castedDoc); - - } else { - runInAction(() => { - let toAssign = new Doc(); - this.presButtonBackUp = toAssign; - this.curPresentation.presButtonBackUp = toAssign; - }); - - } - - - //storing the presentation status,ie. whether it was stopped or playing - let presStatusBackUp = BoolCast(this.curPresentation.presStatus); - runInAction(() => this.presStatus = presStatusBackUp); - } - - /** - * This is the function that is called to retrieve the groups that have been stored and - * push them to the groupMappings. - */ - retrieveGroupMappings = async () => { - let castedGroupDocs = await DocListCastAsync(this.presGroupBackUp.groupDocs); - if (castedGroupDocs !== undefined) { - castedGroupDocs.forEach(async (groupDoc: Doc, index: number) => { - let castedGrouping = await DocListCastAsync(groupDoc.grouping); - let castedKey = StrCast(groupDoc.presentIdStore, null); - if (castedGrouping) { - castedGrouping.forEach((doc: Doc) => { - doc.presentId = castedKey; - }); - } - if (castedGrouping !== undefined && castedKey !== undefined) { - this.groupMappings.set(castedKey, castedGrouping); - } - }); - } - } - - //observable means render is re-called every time variable is changed - @observable - collapsed: boolean = false; - closePresentation = action(() => this.curPresentation.width = 0); - next = async () => { - const current = NumCast(this.curPresentation.selectedDoc); - //asking to get document at current index - let docAtCurrentNext = await this.getDocAtIndex(current + 1); - if (docAtCurrentNext === undefined) { - return; - } - //asking for it's presentation id - let curNextPresId = StrCast(docAtCurrentNext.presentId); - let nextSelected = current + 1; - - //if curDoc is in a group, selection slides until last one, if not it's next one - if (this.groupMappings.has(curNextPresId)) { - let currentsArray = this.groupMappings.get(StrCast(docAtCurrentNext.presentId))!; - nextSelected = current + currentsArray.length - currentsArray.indexOf(docAtCurrentNext); - - //end of grup so go beyond - if (nextSelected === current) nextSelected = current + 1; - } - - this.gotoDocument(nextSelected, current); - - } - back = async () => { - const current = NumCast(this.curPresentation.selectedDoc); - //requesting for the doc at current index - let docAtCurrent = await this.getDocAtIndex(current); - if (docAtCurrent === undefined) { - return; - } - - //asking for its presentation id. - let curPresId = StrCast(docAtCurrent.presentId); - let prevSelected = current - 1; - let zoomOut: boolean = false; - - //checking if this presentation id is mapped to a group, if so chosing the first element in group - if (this.groupMappings.has(curPresId)) { - let currentsArray = this.groupMappings.get(StrCast(docAtCurrent.presentId))!; - prevSelected = current - currentsArray.length + (currentsArray.length - currentsArray.indexOf(docAtCurrent)) - 1; - //end of grup so go beyond - if (prevSelected === current) prevSelected = current - 1; - - //checking if any of the group members had used zooming in - currentsArray.forEach((doc: Doc) => { - //let presElem: PresentationElement | undefined = this.presElementsMappings.get(doc); - if (this.presElementsMappings.get(doc)!.selected[buttonIndex.Show]) { - zoomOut = true; - return; - } - }); - - } - - // if a group set that flag to zero or a single element - //If so making sure to zoom out, which goes back to state before zooming action - if (current > 0) { - if (zoomOut || this.presElementsMappings.get(docAtCurrent)!.selected[buttonIndex.Show]) { - let prevScale = NumCast(this.childrenDocs[prevSelected].viewScale, null); - let curScale = DocumentManager.Instance.getScaleOfDocView(this.childrenDocs[current]); - if (prevScale !== undefined) { - if (prevScale !== curScale) { - DocumentManager.Instance.zoomIntoScale(docAtCurrent, prevScale); - } - } - } - } - this.gotoDocument(prevSelected, current); - - } - - /** - * This is the method that checks for the actions that need to be performed - * after the document has been presented, which involves 3 button options: - * Hide Until Presented, Hide After Presented, Fade After Presented - */ - showAfterPresented = (index: number) => { - this.presElementsMappings.forEach((presElem: PresentationElement, key: Doc) => { - let selectedButtons: boolean[] = presElem.selected; - //the order of cases is aligned based on priority - if (selectedButtons[buttonIndex.HideTillPressed]) { - if (this.childrenDocs.indexOf(key) <= index) { - key.opacity = 1; - } - } - if (selectedButtons[buttonIndex.HideAfter]) { - if (this.childrenDocs.indexOf(key) < index) { - key.opacity = 0; - } - } - if (selectedButtons[buttonIndex.FadeAfter]) { - if (this.childrenDocs.indexOf(key) < index) { - key.opacity = 0.5; - } - } - }); - } - - /** - * This is the method that checks for the actions that need to be performed - * before the document has been presented, which involves 3 button options: - * Hide Until Presented, Hide After Presented, Fade After Presented - */ - hideIfNotPresented = (index: number) => { - this.presElementsMappings.forEach((presElem: PresentationElement, key: Doc) => { - let selectedButtons: boolean[] = presElem.selected; - - //the order of cases is aligned based on priority - - if (selectedButtons[buttonIndex.HideAfter]) { - if (this.childrenDocs.indexOf(key) >= index) { - key.opacity = 1; - } - } - if (selectedButtons[buttonIndex.FadeAfter]) { - if (this.childrenDocs.indexOf(key) >= index) { - key.opacity = 1; - } - } - if (selectedButtons[buttonIndex.HideTillPressed]) { - if (this.childrenDocs.indexOf(key) > index) { - key.opacity = 0; - } - } - }); - } - - /** - * This method makes sure that cursor navigates to the element that - * has the option open and last in the group. If not in the group, and it has - * te option open, navigates to that element. - */ - navigateToElement = async (curDoc: Doc, fromDoc: number) => { - let docToJump: Doc = curDoc; - let curDocPresId = StrCast(curDoc.presentId, null); - let willZoom: boolean = false; - - //checking if in group - if (curDocPresId !== undefined) { - if (this.groupMappings.has(curDocPresId)) { - let currentDocGroup = this.groupMappings.get(curDocPresId)!; - currentDocGroup.forEach((doc: Doc, index: number) => { - let selectedButtons: boolean[] = this.presElementsMappings.get(doc)!.selected; - if (selectedButtons[buttonIndex.Navigate]) { - docToJump = doc; - willZoom = false; - } - if (selectedButtons[buttonIndex.Show]) { - docToJump = doc; - willZoom = true; - } - }); - } - - } - //docToJump stayed same meaning, it was not in the group or was the last element in the group - if (docToJump === curDoc) { - //checking if curDoc has navigation open - let curDocButtons = this.presElementsMappings.get(curDoc)!.selected; - if (curDocButtons[buttonIndex.Navigate]) { - this.jumpToTabOrRight(curDocButtons, curDoc); - } else if (curDocButtons[buttonIndex.Show]) { - let curScale = DocumentManager.Instance.getScaleOfDocView(this.childrenDocs[fromDoc]); - if (curDocButtons[buttonIndex.OpenRight]) { - //awaiting jump so that new scale can be found, since jumping is async - await DocumentManager.Instance.jumpToDocument(curDoc, true); - } else { - await DocumentManager.Instance.jumpToDocument(curDoc, true, undefined, doc => CollectionDockingView.Instance.AddTab(undefined, doc, undefined)); - } - - let newScale = DocumentManager.Instance.getScaleOfDocView(curDoc); - curDoc.viewScale = newScale; - - //saving the scale user was on before zooming in - if (curScale !== 1) { - this.childrenDocs[fromDoc].viewScale = curScale; - } - - } - return; - } - let curScale = DocumentManager.Instance.getScaleOfDocView(this.childrenDocs[fromDoc]); - let curDocButtons = this.presElementsMappings.get(docToJump)!.selected; - - - if (curDocButtons[buttonIndex.OpenRight]) { - //awaiting jump so that new scale can be found, since jumping is async - await DocumentManager.Instance.jumpToDocument(docToJump, willZoom); - } else { - await DocumentManager.Instance.jumpToDocument(docToJump, willZoom, undefined, doc => CollectionDockingView.Instance.AddTab(undefined, doc, undefined)); - } - let newScale = DocumentManager.Instance.getScaleOfDocView(curDoc); - curDoc.viewScale = newScale; - //saving the scale that user was on - if (curScale !== 1) { - this.childrenDocs[fromDoc].viewScale = curScale; - } - - } - - /** - * This function checks if right option is clicked on a presentation element, if not it does open it as a tab - * with help of CollectionDockingView. - */ - jumpToTabOrRight = (curDocButtons: boolean[], curDoc: Doc) => { - if (curDocButtons[buttonIndex.OpenRight]) { - DocumentManager.Instance.jumpToDocument(curDoc, false); - } else { - DocumentManager.Instance.jumpToDocument(curDoc, false, undefined, doc => CollectionDockingView.Instance.AddTab(undefined, doc, undefined)); - } - } - - /** - * Async function that supposedly return the doc that is located at given index. - */ - getDocAtIndex = async (index: number) => { - const list = FieldValue(Cast(this.curPresentation.data, listSpec(Doc))); - if (!list) { - return undefined; - } - if (index < 0 || index >= list.length) { - return undefined; - } - - this.curPresentation.selectedDoc = index; - //awaiting async call to finish to get Doc instance - const doc = await list[index]; - return doc; - } - - /** - * The function that removes a doc from a presentation. It also makes sure to - * do necessary updates to backUps and mappings stored locally. - */ - @action - public RemoveDoc = async (index: number) => { - const value = FieldValue(Cast(this.curPresentation.data, listSpec(Doc))); - if (value) { - let removedDoc = await value.splice(index, 1)[0]; - - //removing the Presentation Element stored for it - this.presElementsMappings.delete(removedDoc); - - let removedDocPresentId = StrCast(removedDoc.presentId); - - //Removing it from local mapping of the groups - if (this.groupMappings.has(removedDocPresentId)) { - let removedDocsGroup = this.groupMappings.get(removedDocPresentId); - if (removedDocsGroup) { - removedDocsGroup.splice(removedDocsGroup.indexOf(removedDoc), 1); - if (removedDocsGroup.length === 0) { - this.groupMappings.delete(removedDocPresentId); - } - } - } - - - let castedList = Cast(this.presButtonBackUp.selectedButtonDocs, listSpec(Doc)); - if (castedList) { - for (let doc of castedList) { - let curDoc = await doc; - let curDocId = StrCast(curDoc.docId); - if (curDocId === removedDoc[Id]) { - castedList.splice(castedList.indexOf(curDoc), 1); - break; - - } - } - } - - //removing it from the backup of groups - let castedGroupDocs = await DocListCastAsync(this.presGroupBackUp.groupDocs); - if (castedGroupDocs) { - castedGroupDocs.forEach(async (groupDoc: Doc, index: number) => { - let castedKey = StrCast(groupDoc.presentIdStore, null); - if (castedKey === removedDocPresentId) { - let castedGrouping = await DocListCastAsync(groupDoc.grouping); - if (castedGrouping) { - castedGrouping.splice(castedGrouping.indexOf(removedDoc), 1); - if (castedGrouping.length === 0) { - castedGroupDocs!.splice(castedGroupDocs!.indexOf(groupDoc), 1); - } - } - } - - }); - - } - - - } - } - - /** - * An alternative remove method that removes a doc from presentation by its actual - * reference. - */ - public removeDocByRef = (doc: Doc) => { - let indexOfDoc = this.childrenDocs.indexOf(doc); - const value = FieldValue(Cast(this.curPresentation.data, listSpec(Doc))); - if (value) { - value.splice(indexOfDoc, 1)[0]; - } - if (indexOfDoc !== - 1) { - return true; - } - return false; - } - - //The function that is called when a document is clicked or reached through next or back. - //it'll also execute the necessary actions if presentation is playing. - @action - public gotoDocument = async (index: number, fromDoc: number) => { - const list = FieldValue(Cast(this.curPresentation.data, listSpec(Doc))); - if (!list) { - return; - } - if (index < 0 || index >= list.length) { - return; - } - this.curPresentation.selectedDoc = index; - - if (!this.presStatus) { - this.presStatus = true; - this.startPresentation(index); - } - - const doc = await list[index]; - if (this.presStatus) { - this.navigateToElement(doc, fromDoc); - this.hideIfNotPresented(index); - this.showAfterPresented(index); - } - - } - - //Function that is called to resetGroupIds, so that documents get new groupIds at - //first load, when presentation is changed. - resetGroupIds = async () => { - let castedGroupDocs = await DocListCastAsync(this.presGroupBackUp.groupDocs); - if (castedGroupDocs !== undefined) { - castedGroupDocs.forEach(async (groupDoc: Doc, index: number) => { - let castedGrouping = await DocListCastAsync(groupDoc.grouping); - if (castedGrouping) { - castedGrouping.forEach((doc: Doc) => { - doc.presentId = Utils.GenerateGuid(); - }); - } - }); - } - runInAction(() => this.groupMappings = new Map()); - } - - /** - * Adds a document to the presentation view - **/ - @undoBatch - @action - public PinDoc(doc: Doc) { - //add this new doc to props.Document - const data = Cast(this.curPresentation.data, listSpec(Doc)); - if (data) { - data.push(doc); - } else { - this.curPresentation.data = new List([doc]); - } - - this.toggle(true); - } - - //Function that sets the store of the children docs. - @action - setChildrenDocs = (docList: Doc[]) => { - this.childrenDocs = docList; - } - - //The function that is called to render the play or pause button depending on - //if presentation is running or not. - renderPlayPauseButton = () => { - if (this.presStatus) { - return ; - } else { - return ; - } - } - - //The function that starts or resets presentaton functionally, depending on status flag. - @action - startOrResetPres = async () => { - if (this.presStatus) { - this.resetPresentation(); - } else { - this.presStatus = true; - let startIndex = await this.findStartDocument(); - this.startPresentation(startIndex); - const current = NumCast(this.curPresentation.selectedDoc); - this.gotoDocument(startIndex, current); - } - this.curPresentation.presStatus = this.presStatus; - } - - /** - * This method is called to find the start document of presentation. So - * that when user presses on play, the correct presentation element will be - * selected. - */ - findStartDocument = async () => { - let docAtZero = await this.getDocAtIndex(0); - if (docAtZero === undefined) { - return 0; - } - let docAtZeroPresId = StrCast(docAtZero.presentId); - - if (this.groupMappings.has(docAtZeroPresId)) { - let group = this.groupMappings.get(docAtZeroPresId)!; - let lastDoc = group[group.length - 1]; - return this.childrenDocs.indexOf(lastDoc); - } else { - return 0; - } - } - - //The function that resets the presentation by removing every action done by it. It also - //stops the presentaton. - @action - resetPresentation = () => { - this.childrenDocs.forEach((doc: Doc) => { - doc.opacity = 1; - doc.viewScale = 1; - }); - this.curPresentation.selectedDoc = 0; - this.presStatus = false; - this.curPresentation.presStatus = this.presStatus; - if (this.childrenDocs.length === 0) { - return; - } - DocumentManager.Instance.zoomIntoScale(this.childrenDocs[0], 1); - } - - - //The function that starts the presentation, also checking if actions should be applied - //directly at start. - startPresentation = (startIndex: number) => { - let selectedButtons: boolean[]; - this.presElementsMappings.forEach((component: PresentationElement, doc: Doc) => { - selectedButtons = component.selected; - if (selectedButtons[buttonIndex.HideTillPressed]) { - if (this.childrenDocs.indexOf(doc) > startIndex) { - doc.opacity = 0; - } - - } - if (selectedButtons[buttonIndex.HideAfter]) { - if (this.childrenDocs.indexOf(doc) < startIndex) { - doc.opacity = 0; - } - } - if (selectedButtons[buttonIndex.FadeAfter]) { - if (this.childrenDocs.indexOf(doc) < startIndex) { - doc.opacity = 0.5; - } - } - - }); - - } - - /** - * The function that is called to add a new presentation to the presentationView. - * It sets up te mappings and local copies of it. Resets the groupings and presentation. - * Makes the new presentation current selected, and retrieve the back-Ups if present. - */ - @action - addNewPresentation = (presTitle: string) => { - //creating a new presentation doc - let newPresentationDoc = Docs.Create.TreeDocument([], { title: presTitle }); - this.props.Documents.push(newPresentationDoc); - - //setting that new doc as current - this.curPresentation = newPresentationDoc; - - //storing the doc in local copies for easier access - let newGuid = Utils.GenerateGuid(); - this.presentationsMapping.set(newGuid, newPresentationDoc); - this.presentationsKeyMapping.set(newPresentationDoc, newGuid); - - //resetting the previous presentation's actions so that new presentation can be loaded. - this.resetGroupIds(); - this.resetPresentation(); - this.presElementsMappings = new Map(); - this.currentSelectedPresValue = newGuid; - this.setPresentationBackUps(); - - } - - /** - * The function that is called to change the current selected presentation. - * Changes the presentation, also resetting groupings and presentation in process. - * Plus retrieving the backUps for the newly selected presentation. - */ - @action - getSelectedPresentation = (e: React.ChangeEvent) => { - //get the guid of the selected presentation - let selectedGuid = e.target.value; - //set that as current presentation - this.curPresentation = this.presentationsMapping.get(selectedGuid)!; - - //reset current Presentations local things so that new one can be loaded - this.resetGroupIds(); - this.resetPresentation(); - this.presElementsMappings = new Map(); - this.currentSelectedPresValue = selectedGuid; - this.setPresentationBackUps(); - - - } - - /** - * The function that is called to render either select for presentations, or title inputting. - */ - renderSelectOrPresSelection = () => { - let presentationList = DocListCast(this.props.Documents); - if (this.PresTitleInputOpen || this.PresTitleChangeOpen) { - return this.titleInputElement = e!} type="text" className="presentationView-title" placeholder="Enter Name!" onKeyDown={this.submitPresentationTitle} />; - } else { - return ; - } - } - - /** - * The function that is called on enter press of title input. It gives the - * new presentation the title user entered. If nothing is entered, gives a default title. - */ - @action - submitPresentationTitle = (e: React.KeyboardEvent) => { - if (e.keyCode === 13) { - let presTitle = this.titleInputElement!.value; - this.titleInputElement!.value = ""; - if (this.PresTitleInputOpen) { - if (presTitle === "") { - presTitle = "Presentation"; - } - this.PresTitleInputOpen = false; - this.addNewPresentation(presTitle); - } else if (this.PresTitleChangeOpen) { - this.PresTitleChangeOpen = false; - this.changePresentationTitle(presTitle); - } - } - } - - /** - * The function that is called to remove a presentation from all its copies, and the main Container's - * list. Sets up the next presentation as current. - */ - @action - removePresentation = async () => { - if (this.presentationsMapping.size !== 1) { - let presentationList = Cast(this.props.Documents, listSpec(Doc)); - let batch = UndoManager.StartBatch("presRemoval"); - - //getting the presentation that will be removed - let removedDoc = this.presentationsMapping.get(this.currentSelectedPresValue!); - //that presentation is removed - presentationList!.splice(presentationList!.indexOf(removedDoc!), 1); - - //its mappings are removed from local copies - this.presentationsKeyMapping.delete(removedDoc!); - this.presentationsMapping.delete(this.currentSelectedPresValue!); - - //the next presentation is set as current - let remainingPresentations = this.presentationsMapping.values(); - let nextDoc = remainingPresentations.next().value; - this.curPresentation = nextDoc; - - - //Storing these for being able to undo changes - let curGuid = this.currentSelectedPresValue!; - let curPresStatus = this.presStatus; - - //resetting the groups and presentation actions so that next presentation gets loaded - this.resetGroupIds(); - this.resetPresentation(); - this.currentSelectedPresValue = this.presentationsKeyMapping.get(nextDoc)!.toString(); - this.setPresentationBackUps(); - - //Storing for undo - let currentGroups = this.groupMappings; - let curPresElemMapping = this.presElementsMappings; - - //Event to undo actions that are not related to doc directly, aka. local things - UndoManager.AddEvent({ - undo: action(() => { - this.curPresentation = removedDoc!; - this.presentationsMapping.set(curGuid, removedDoc!); - this.presentationsKeyMapping.set(removedDoc!, curGuid); - this.currentSelectedPresValue = curGuid; - - this.presStatus = curPresStatus; - this.groupMappings = currentGroups; - this.presElementsMappings = curPresElemMapping; - this.setPresentationBackUps(); - - }), - redo: action(() => { - this.curPresentation = nextDoc; - this.presStatus = false; - this.presentationsKeyMapping.delete(removedDoc!); - this.presentationsMapping.delete(curGuid); - this.currentSelectedPresValue = this.presentationsKeyMapping.get(nextDoc)!.toString(); - this.setPresentationBackUps(); - - }), - }); - - batch.end(); - } - } - - /** - * The function that is called to change title of presentation to what user entered. - */ - @undoBatch - changePresentationTitle = (newTitle: string) => { - if (newTitle === "") { - return; - } - this.curPresentation.title = newTitle; - } - - /** - * On pointer down element that is catched on resizer of te - * presentation view. Sets up the event listeners to change the size with - * mouse move. - */ - _downsize = 0; - onPointerDown = (e: React.PointerEvent) => { - this._downsize = e.clientX; - document.removeEventListener("pointermove", this.onPointerMove); - document.removeEventListener("pointerup", this.onPointerUp); - document.addEventListener("pointermove", this.onPointerMove); - document.addEventListener("pointerup", this.onPointerUp); - e.stopPropagation(); - e.preventDefault(); - } - /** - * Changes the size of the presentation view, with mouse move. - * Minimum size is set to 300, so that every button is visible. - */ - @action - onPointerMove = (e: PointerEvent) => { - - this.curPresentation.width = Math.max(window.innerWidth - e.clientX, presMinWidth); - } - - /** - * The method that is called on pointer up event. It checks if the button is just - * clicked so that presentation view will be closed. The way it's done is to check - * for minimal pixel change like 4, and accept it as it's just a click on top of the dragger. - */ - @action - onPointerUp = (e: PointerEvent) => { - if (Math.abs(e.clientX - this._downsize) < 4) { - let presWidth = NumCast(this.curPresentation.width); - if (presWidth - presMinWidth !== 0) { - this.curPresentation.width = 0; - } - if (presWidth === 0) { - this.curPresentation.width = presMinWidth; - } - } - document.removeEventListener("pointermove", this.onPointerMove); - document.removeEventListener("pointerup", this.onPointerUp); - } - - /** - * This function is a setter that opens up the - * presentation mode, by setting it's render flag - * to true. It also closes the presentation view. - */ - @action - openPresMode = () => { - if (!this.presMode) { - this.curPresentation.width = 0; - this.presMode = true; - } - } - - /** - * This function closes the presentation mode by setting its - * render flag to false. It also opens up the presentation view. - * By setting it to it's minimum size. - */ - @action - closePresMode = () => { - if (this.presMode) { - this.presMode = false; - this.curPresentation.width = presMinWidth; - } - - } - - /** - * Function that is called to render the presentation mode, depending on its flag. - */ - renderPresMode = () => { - if (this.presMode) { - return ; - } else { - return (null); - } - - } - - render() { - - let width = NumCast(this.curPresentation.width); - - return ( -
      -
      !this.persistOpacity && (this.opacity = 1))} onPointerLeave={action(() => !this.persistOpacity && (this.opacity = 0.4))} style={{ width: width, overflowY: "scroll", overflowX: "hidden", opacity: this.opacity, transition: "0.7s opacity ease" }}> -
      - {this.renderSelectOrPresSelection()} - - - - - -
      -
      - - {this.renderPlayPauseButton()} - -
      - - this.presElementsMappings.clear()} - /> - ) => { - this.persistOpacity = e.target.checked; - this.opacity = this.persistOpacity ? 1 : 0.4; - })} - checked={this.persistOpacity} - style={{ position: "absolute", bottom: 5, left: 5 }} - onPointerEnter={action(() => this.labelOpacity = 1)} - onPointerLeave={action(() => this.labelOpacity = 0)} - /> -

      opacity {this.persistOpacity ? "persistent" : "on focus"}

      -
      -
      - -
      - {this.renderPresMode()} - -
      - ); - } -} diff --git a/src/client/views/search/SearchItem.tsx b/src/client/views/search/SearchItem.tsx index 4bb2ed55b..41fc49c2e 100644 --- a/src/client/views/search/SearchItem.tsx +++ b/src/client/views/search/SearchItem.tsx @@ -203,6 +203,7 @@ export class SearchItem extends React.Component { removeDocument={returnFalse} ScreenToLocalTransform={Transform.Identity} addDocTab={returnFalse} + pinToPres={returnFalse} renderDepth={1} PanelWidth={returnXDimension} PanelHeight={returnYDimension} diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index a8b616565..31f1f7a12 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -1,19 +1,18 @@ -import { observable, action, runInAction, ObservableMap } from "mobx"; -import { serializable, primitive, map, alias, list, PropSchema, custom } from "serializr"; -import { autoObject, SerializationHelper, Deserializable, afterDocDeserialize } from "../client/util/SerializationHelper"; +import { observable, ObservableMap, runInAction } from "mobx"; +import { alias, map, serializable } from "serializr"; import { DocServer } from "../client/DocServer"; -import { setter, getter, getField, updateFunction, deleteProperty, makeEditable, makeReadOnly } from "./util"; -import { Cast, ToConstructor, PromiseValue, FieldValue, NumCast, BoolCast, StrCast } from "./Types"; -import { listSpec } from "./Schema"; -import { ObjectField } from "./ObjectField"; -import { RefField, FieldId } from "./RefField"; -import { ToScriptString, SelfProxy, Parent, OnUpdate, Self, HandleUpdate, Update, Id, Copy } from "./FieldSymbols"; -import { scriptingGlobal, CompileScript, Scripting } from "../client/util/Scripting"; -import { List } from "./List"; import { DocumentType } from "../client/documents/DocumentTypes"; -import { ComputedField, ScriptField } from "./ScriptField"; +import { CompileScript, Scripting, scriptingGlobal } from "../client/util/Scripting"; +import { afterDocDeserialize, autoObject, Deserializable, SerializationHelper } from "../client/util/SerializationHelper"; +import { Copy, HandleUpdate, Id, OnUpdate, Parent, Self, SelfProxy, ToScriptString, Update } from "./FieldSymbols"; +import { List } from "./List"; +import { ObjectField } from "./ObjectField"; import { PrefetchProxy, ProxyField } from "./Proxy"; -//import { CurrentUserUtils } from "../server/authentication/models/current_user_utils"; +import { FieldId, RefField } from "./RefField"; +import { listSpec } from "./Schema"; +import { ComputedField } from "./ScriptField"; +import { BoolCast, Cast, FieldValue, NumCast, PromiseValue, StrCast, ToConstructor } from "./Types"; +import { deleteProperty, getField, getter, makeEditable, makeReadOnly, setter, updateFunction } from "./util"; export namespace Field { export function toKeyValueString(doc: Doc, key: string): string { @@ -72,6 +71,7 @@ export const HeightSym = Symbol("Height"); export const UpdatingFromServer = Symbol("UpdatingFromServer"); const CachedUpdates = Symbol("Cached updates"); + function fetchProto(doc: Doc) { const proto = doc.proto; if (proto instanceof Promise) { @@ -151,10 +151,10 @@ export class Doc extends RefField { } private [CachedUpdates]: { [key: string]: () => void | Promise } = {}; - + public static CurrentUserEmail: string = ""; public async [HandleUpdate](diff: any) { const set = diff.$set; - const sameAuthor = this.author === "foo@bar.com";//CurrentUserUtils.email; + const sameAuthor = this.author === Doc.CurrentUserEmail; if (set) { for (const key in set) { if (!key.startsWith("fields.")) { @@ -327,14 +327,12 @@ export namespace Doc { return Array.from(results); } - export function AddDocToList(target: Doc, key: string, doc: Doc, relativeTo?: Doc, before?: boolean, first?: boolean, allowDuplicates?: boolean) { + export function AddDocToList(target: Doc, key: string, doc: Doc, relativeTo?: Doc, before?: boolean, first?: boolean, allowDuplicates?: boolean, reversed?: boolean) { if (target[key] === undefined) { - console.log("target key undefined"); Doc.GetProto(target)[key] = new List(); } let list = Cast(target[key], listSpec(Doc)); if (list) { - console.log("has list"); if (allowDuplicates !== true) { let pind = list.reduce((l, d, i) => d instanceof Doc && Doc.AreProtosEqual(d, doc) ? i : l, -1); if (pind !== -1) { @@ -342,15 +340,18 @@ export namespace Doc { } } if (first) { - console.log("is first"); list.splice(0, 0, doc); } else { - console.log("not first"); let ind = relativeTo ? list.indexOf(relativeTo) : -1; - if (ind === -1) list.push(doc); - else list.splice(before ? ind : ind + 1, 0, doc); - console.log("index", ind); + if (ind === -1) { + if (reversed) list.splice(0, 0, doc); + else list.push(doc); + } + else { + if (reversed) list.splice(before ? (list.length - ind) + 1 : list.length - ind, 0, doc); + else list.splice(before ? ind : ind + 1, 0, doc); + } } } return true; @@ -595,10 +596,14 @@ export namespace Doc { }); } - export class DocBrush { + + export class DocData { + @observable _user_doc: Doc = undefined!; @observable BrushedDoc: ObservableMap = new ObservableMap(); } - const manager = new DocBrush(); + const manager = new DocData(); + export function UserDoc(): Doc { return manager._user_doc; } + export function SetUserDoc(doc: Doc) { manager._user_doc = doc; } export function IsBrushed(doc: Doc) { return manager.BrushedDoc.has(doc) || manager.BrushedDoc.has(Doc.GetDataDoc(doc)); } diff --git a/src/new_fields/util.ts b/src/new_fields/util.ts index c546e2aac..04194509c 100644 --- a/src/new_fields/util.ts +++ b/src/new_fields/util.ts @@ -7,7 +7,6 @@ import { ObjectField } from "./ObjectField"; import { action } from "mobx"; import { Parent, OnUpdate, Update, Id, SelfProxy, Self } from "./FieldSymbols"; import { DocServer } from "../client/DocServer"; -import { CurrentUserUtils } from "../server/authentication/models/current_user_utils"; function _readOnlySetter(): never { throw new Error("Documents can't be modified in read-only mode"); @@ -61,7 +60,7 @@ const _setterImpl = action(function (target: any, prop: string | symbol | number } const writeMode = DocServer.getFieldWriteMode(prop as string); const fromServer = target[UpdatingFromServer]; - const sameAuthor = fromServer || (receiver.author === CurrentUserUtils.email); + const sameAuthor = fromServer || (receiver.author === Doc.CurrentUserEmail); const writeToDoc = sameAuthor || (writeMode !== DocServer.WriteMode.LiveReadonly); const writeToServer = sameAuthor || (writeMode === DocServer.WriteMode.Default); if (writeToDoc) { diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index f36f5b73d..508655605 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -10,20 +10,17 @@ import { CollectionView } from "../../../client/views/collections/CollectionView import { Doc } from "../../../new_fields/Doc"; import { List } from "../../../new_fields/List"; import { listSpec } from "../../../new_fields/Schema"; -import { Cast, FieldValue, StrCast } from "../../../new_fields/Types"; -import { RouteStore } from "../../RouteStore"; +import { Cast, StrCast } from "../../../new_fields/Types"; import { Utils } from "../../../Utils"; +import { RouteStore } from "../../RouteStore"; export class CurrentUserUtils { - private static curr_email: string; private static curr_id: string; - @observable private static user_document: Doc; //TODO tfs: these should be temporary... private static mainDocId: string | undefined; - public static get email() { return this.curr_email; } public static get id() { return this.curr_id; } - @computed public static get UserDocument() { return this.user_document; } + @computed public static get UserDocument() { return Doc.UserDoc(); } public static get MainDocId() { return this.mainDocId; } public static set MainDocId(id: string | undefined) { this.mainDocId = id; } @@ -32,7 +29,7 @@ export class CurrentUserUtils { doc.viewType = CollectionViewType.Tree; doc.dropAction = "alias"; doc.layout = CollectionView.LayoutString(); - doc.title = this.email; + doc.title = Doc.CurrentUserEmail this.updateUserDocument(doc); doc.data = new List(); doc.gridGap = 5; @@ -58,6 +55,12 @@ export class CurrentUserUtils { recentlyClosed.boxShadow = "0 0"; doc.recentlyClosed = recentlyClosed; } + if (doc.curPresentation === undefined) { + const curPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation" }); + curPresentation.excludeFromLibrary = true; + curPresentation.boxShadow = "0 0"; + doc.curPresentation = curPresentation; + } if (doc.sidebar === undefined) { const sidebar = Docs.Create.StackingDocument([doc.workspaces as Doc, doc, doc.recentlyClosed as Doc], { title: "Sidebar" }); sidebar.excludeFromLibrary = true; @@ -85,15 +88,15 @@ export class CurrentUserUtils { public static async loadUserDocument({ id, email }: { id: string, email: string }) { this.curr_id = id; - this.curr_email = email; + Doc.CurrentUserEmail = email; await rp.get(Utils.prepend(RouteStore.getUserDocumentId)).then(id => { if (id) { return DocServer.GetRefField(id).then(async field => { if (field instanceof Doc) { await this.updateUserDocument(field); - runInAction(() => this.user_document = field); + runInAction(() => Doc.SetUserDoc(field)); } else { - runInAction(() => this.user_document = this.createUserDocument(id)); + runInAction(() => Doc.SetUserDoc(this.createUserDocument(id))); } }); } else { -- cgit v1.2.3-70-g09d2 From 8225f3d2f6647b4163f7fe056af73c86f85c28d2 Mon Sep 17 00:00:00 2001 From: bob Date: Mon, 19 Aug 2019 17:00:59 -0400 Subject: cleaned up some buttons --- src/client/DocServer.ts | 2 + src/client/views/MainView.tsx | 45 +++------------------- .../views/collections/CollectionTreeView.tsx | 4 +- src/client/views/collections/CollectionView.tsx | 6 ++- src/client/views/nodes/DocumentView.tsx | 40 +++++++++++++------ 5 files changed, 43 insertions(+), 54 deletions(-) (limited to 'src') diff --git a/src/client/DocServer.ts b/src/client/DocServer.ts index bf5168c22..2cec1046b 100644 --- a/src/client/DocServer.ts +++ b/src/client/DocServer.ts @@ -33,6 +33,8 @@ export namespace DocServer { LivePlayground = 3, } + export let AclsMode = WriteMode.Default; + const fieldWriteModes: { [field: string]: WriteMode } = {}; const docsWithUpdates: { [field: string]: Set } = {}; diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 7b7a5542d..b27b91c12 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -1,5 +1,5 @@ import { IconName, library } from '@fortawesome/fontawesome-svg-core'; -import { faArrowDown, faArrowUp, faBolt, faCaretUp, faCat, faCheck, faClone, faCloudUploadAlt, faCommentAlt, faCut, faExclamation, faFilePdf, faFilm, faFont, faGlobeAsia, faLongArrowAltRight, faMusic, faObjectGroup, faPause, faPenNib, faPlay, faPortrait, faRedoAlt, faTable, faThumbtack, faTree, faUndoAlt } from '@fortawesome/free-solid-svg-icons'; +import { faArrowDown, faArrowUp, faBolt, faCaretUp, faCat, faCheck, faClone, faCloudUploadAlt, faCommentAlt, faCut, faExclamation, faFilePdf, faFilm, faFont, faGlobeAsia, faLongArrowAltRight, faMusic, faObjectGroup, faPause, faPenNib, faPlay, faPortrait, faRedoAlt, faThumbtack, faTree, faUndoAlt, faTv } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { action, computed, configure, observable, reaction, runInAction } from 'mobx'; import { observer } from 'mobx-react'; @@ -38,7 +38,6 @@ import { OverlayView } from './OverlayView'; import PDFMenu from './pdf/PDFMenu'; import { PreviewCursor } from './PreviewCursor'; import { FilterBox } from './search/FilterBox'; -import { DocumentManager } from '../util/DocumentManager'; import PresModeMenu from './presentationview/PresentationModeMenu'; import { PresBox } from './nodes/PresBox'; @@ -172,7 +171,7 @@ export class MainView extends React.Component { library.add(faCat); library.add(faFilePdf); library.add(faObjectGroup); - library.add(faTable); + library.add(faTv); library.add(faGlobeAsia); library.add(faUndoAlt); library.add(faRedoAlt); @@ -452,30 +451,15 @@ export class MainView extends React.Component { let btns: [React.RefObject, IconName, string, () => Doc][] = [ [React.createRef(), "object-group", "Add Collection", addColNode], - [React.createRef(), "table", "Add Presentation Trail", addPresNode], + [React.createRef(), "tv", "Add Presentation Trail", addPresNode], [React.createRef(), "globe-asia", "Add Website", addWebNode], [React.createRef(), "bolt", "Add Button", addButtonDocument], - // [React.createRef(), "clone", "Add Docking Frame", addDockingNode], + [React.createRef(), "file", "Add Document Dragger", addDragboxNode], [React.createRef(), "cloud-upload-alt", "Import Directory", addImportCollectionNode], //remove at some point in favor of addImportCollectionNode //[React.createRef(), "play", "Add Youtube Searcher", addYoutubeSearcher], - [React.createRef(), "file", "Add Document Dragger", addDragboxNode] ]; if (!ClientUtils.RELEASE) btns.unshift([React.createRef(), "cat", "Add Cat Image", addImageNode]); - const setWriteMode = (mode: DocServer.WriteMode) => { - console.log(DocServer.WriteMode[mode]); - const mode1 = mode; - const mode2 = mode === DocServer.WriteMode.Default ? mode : DocServer.WriteMode.Playground; - DocServer.setFieldWriteMode("x", mode1); - DocServer.setFieldWriteMode("y", mode1); - DocServer.setFieldWriteMode("width", mode1); - DocServer.setFieldWriteMode("height", mode1); - - DocServer.setFieldWriteMode("panX", mode2); - DocServer.setFieldWriteMode("panY", mode2); - DocServer.setFieldWriteMode("scale", mode2); - DocServer.setFieldWriteMode("viewType", mode2); - }; return < div id="add-nodes-menu" style={{ left: this.flyoutWidth + 20, bottom: 20 }} > @@ -484,7 +468,6 @@ export class MainView extends React.Component {
      • -
      • {btns.map(btn => @@ -493,13 +476,6 @@ export class MainView extends React.Component {
      )} -
    • - {ClientUtils.RELEASE ? [] : [ -
    • , -
    • , -
    • , -
    • - ]}
    • diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index 077f3f941..70c0632d1 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -16,7 +16,7 @@ import { DragManager } from "../../util/DragManager"; import { undoBatch, UndoManager } from "../../util/UndoManager"; import { DocComponent } from "../DocComponent"; import { FieldViewProps } from "../nodes/FieldView"; -import { FormattedTextBox } from "../nodes/FormattedTextBox"; +import { FormattedTextBox, Blank } from "../nodes/FormattedTextBox"; import { CollectionPDFView } from "./CollectionPDFView"; import { CollectionVideoView } from "./CollectionVideoView"; import { CollectionView } from "./CollectionView"; @@ -206,7 +206,17 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T) { this.props.addDocument(Docs.Create.VideoDocument(url, { ...options, title: url, width: 400, height: 315, nativeWidth: 600, nativeHeight: 472.5 })); return; } - + let matches: RegExpExecArray | null; + if ((matches = /(https:\/\/)?docs\.google\.com\/document\/d\/([^\\]+)\/edit/g.exec(text)) !== null) { + let newBox = Docs.Create.TextDocument({ ...options, width: 600, height: 400, title: "Fetching title from Google Docs..." }); + let proto = newBox.proto!; + proto.autoHeight = true; + proto.googleDocId = matches[2]; + proto.data = "Fetching contents from Google Docs..."; + proto.backgroundColor = "#eeeeff"; + this.props.addDocument(newBox); + return; + } let batch = UndoManager.StartBatch("collection view drop"); let promises: Promise[] = []; // tslint:disable-next-line:prefer-for-of diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index bc057bb5f..406c2c4a6 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -1,6 +1,6 @@ import { library } from '@fortawesome/fontawesome-svg-core'; import { faEdit, faSmile, faTextHeight, faUpload } from '@fortawesome/free-solid-svg-icons'; -import { action, IReactionDisposer, observable, reaction, runInAction, computed, Lambda, trace } from "mobx"; +import { action, IReactionDisposer, observable, reaction, runInAction, computed, Lambda, trace, untracked } from "mobx"; import { observer } from "mobx-react"; import { baseKeymap } from "prosemirror-commands"; import { history } from "prosemirror-history"; @@ -47,6 +47,8 @@ library.add(faSmile, faTextHeight, faUpload); // FormattedTextBox: Displays an editable plain text node that maps to a specified Key of a Document // +export const Blank = `{"doc":{"type":"doc","content":[]},"selection":{"type":"text","anchor":0,"head":0}}`; + export interface FormattedTextBoxProps { isOverlay?: boolean; hideOnLeave?: boolean; @@ -84,7 +86,7 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe private _proxyReactionDisposer: Opt; private dropDisposer?: DragManager.DragDropDisposer; public get CurrentDiv(): HTMLDivElement { return this._ref.current!; } - private isOpening = false; + private isGoogleDocsUpdate = false; @observable _entered = false; @observable public static InputBoxOverlay?: FormattedTextBox = undefined; @@ -290,28 +292,6 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe } } - componentWillMount() { - this.pollExportedCounterpart(); - } - - pollExportedCounterpart = async () => { - let dataDoc = Doc.GetProto(this.props.Document); - let documentId = StrCast(dataDoc[googleDocId]); - if (documentId) { - let exportState = await GoogleApiClientUtils.Docs.read({ documentId }); - if (exportState) { - let data = Cast(dataDoc.data, RichTextField); - if (data) { - this.isOpening = true; - dataDoc.data = new RichTextField(data[FromGoogleDocText](exportState)); - } - } else { - delete dataDoc[googleDocId]; - } - this.tryUpdateHeight(); - } - } - componentDidMount() { const config = { schema, @@ -347,23 +327,32 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe this._reactionDisposer = reaction( () => { const field = this.dataDoc ? Cast(this.dataDoc[this.props.fieldKey], RichTextField) : undefined; - return field ? field.Data : `{"doc":{"type":"doc","content":[]},"selection":{"type":"text","anchor":0,"head":0}}`; + return field ? field.Data : Blank; }, incomingValue => { if (this._editorView && !this._applyingChange) { let updatedState = JSON.parse(incomingValue); this._editorView.updateState(EditorState.fromJSON(config, updatedState)); // manually sets cursor selection at the end of the text on focus - if (this.isOpening) { - this.isOpening = false; + if (this.isGoogleDocsUpdate) { + this.isGoogleDocsUpdate = false; let end = this._editorView.state.doc.content.size - 1; updatedState.selection = { type: "text", anchor: end, head: end }; this._editorView.updateState(EditorState.fromJSON(config, updatedState)); } + this.tryUpdateHeight(); } } ); + reaction(() => this.props.Document.pullFromGoogleDocsTrigger, () => { + this.pullFromGoogleDoc(); + }); + + reaction(() => this.props.Document.pushToGoogleDocsTrigger, () => { + this.pushToGoogleDoc(); + }); + this._textReactionDisposer = reaction( () => this.extensionDoc, () => { @@ -391,6 +380,13 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe this.unhighlightSearchTerms(); } }, { fireImmediately: true }); + + ["pushToGoogleDocsTrigger", "pullFromGoogleDocsTrigger"].map(key => { + let doc = this.props.Document; + if (doc[key] === undefined) { + untracked(() => doc[key] = false); + } + }); } clipboardTextSerializer = (slice: Slice): string => { @@ -644,7 +640,6 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe this._undoTyping.end(); this._undoTyping = undefined; } - this.updateGoogleDoc(); } public _undoTyping?: UndoManager.Batch; onKeyPress = (e: React.KeyboardEvent) => { @@ -701,13 +696,13 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe if (!(googleDocId in Doc.GetProto(this.props.Document))) { ContextMenu.Instance.addItem({ description: "Export to Google Doc...", - event: this.updateGoogleDoc, + event: this.pushToGoogleDoc, icon: "upload" }); } } - updateGoogleDoc = () => { + pushToGoogleDoc = () => { let modes = GoogleApiClientUtils.Docs.WriteMode; let mode = modes.Replace; let reference: Opt = Cast(this.dataDoc[googleDocId], "string"); @@ -725,6 +720,25 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe } } + pullFromGoogleDoc = async () => { + let dataDoc = Doc.GetProto(this.props.Document); + let documentId = StrCast(dataDoc[googleDocId]); + if (documentId) { + let exportState = await GoogleApiClientUtils.Docs.read({ documentId }); + if (exportState && exportState.body && exportState.title) { + let data = Cast(dataDoc.data, RichTextField); + if (data) { + this.isGoogleDocsUpdate = true; + dataDoc.data = new RichTextField(data[FromGoogleDocText](exportState.body)); + dataDoc.title = exportState.title; + } + } else { + delete dataDoc[googleDocId]; + } + } + } + + render() { let self = this; let style = this.props.isOverlay ? "scroll" : "hidden"; -- cgit v1.2.3-70-g09d2 From 43ea15b087ec923e9bd54001c7bd06c5e08efdb7 Mon Sep 17 00:00:00 2001 From: Bob Zeleznik Date: Mon, 19 Aug 2019 22:02:21 -0400 Subject: presentation view fixes --- src/client/views/MainOverlayTextBox.tsx | 3 ++- src/client/views/collections/CollectionDockingView.tsx | 6 +++--- src/client/views/collections/CollectionSchemaView.tsx | 2 ++ src/client/views/collections/CollectionStackingView.tsx | 1 + src/client/views/nodes/PDFBox.tsx | 2 +- src/client/views/nodes/PresBox.tsx | 12 ++++++------ src/client/views/presentationview/PresentationView.scss | 2 +- src/client/views/search/IconBar.tsx | 1 - 8 files changed, 16 insertions(+), 13 deletions(-) (limited to 'src') diff --git a/src/client/views/MainOverlayTextBox.tsx b/src/client/views/MainOverlayTextBox.tsx index b14a1e0ea..9fe435bc5 100644 --- a/src/client/views/MainOverlayTextBox.tsx +++ b/src/client/views/MainOverlayTextBox.tsx @@ -146,7 +146,8 @@ export class MainOverlayTextBox extends React.Component onClick={undefined} isSelected={returnTrue} select={emptyFunction} renderDepth={0} selectOnLoad={true} ContainingCollectionView={undefined} whenActiveChanged={emptyFunction} active={returnTrue} ContentScaling={returnOne} - ScreenToLocalTransform={this._textXf} PanelWidth={returnZero} PanelHeight={returnZero} focus={emptyFunction} addDocTab={this.addDocTab} outer_div={(tooltip: HTMLElement) => { this._tooltip = tooltip; this.updateTooltip(); }} /> + ScreenToLocalTransform={this._textXf} PanelWidth={returnZero} PanelHeight={returnZero} focus={emptyFunction} + pinToPres={returnZero} addDocTab={this.addDocTab} outer_div={(tooltip: HTMLElement) => { this._tooltip = tooltip; this.updateTooltip(); }} />
    diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 47dfeb169..dc0cbda0b 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -551,9 +551,6 @@ export class DockedFrameRenderer extends React.Component { @undoBatch @action public PinDoc(doc: Doc) { - if (doc.type === DocumentType.PRES) { - MainView.Instance.toggleMiniPresentation() - } //add this new doc to props.Document let curPres = Cast(CurrentUserUtils.UserDocument.curPresentation, Doc) as Doc; if (curPres) { @@ -563,6 +560,9 @@ export class DockedFrameRenderer extends React.Component { } else { curPres.data = new List([doc]); } + if (!DocumentManager.Instance.getDocumentView(curPres)) { + this.addDocTab(curPres, undefined, "onRight"); + } } } diff --git a/src/client/views/collections/CollectionSchemaView.tsx b/src/client/views/collections/CollectionSchemaView.tsx index 221908dd2..4008dea51 100644 --- a/src/client/views/collections/CollectionSchemaView.tsx +++ b/src/client/views/collections/CollectionSchemaView.tsx @@ -171,6 +171,7 @@ export class CollectionSchemaView extends CollectionSubView(doc => doc) { active={this.props.active} whenActiveChanged={this.props.whenActiveChanged} addDocTab={this.props.addDocTab} + pinToPres={this.props.pinToPres} setPreviewScript={this.setPreviewScript} previewScript={this.previewScript} /> @@ -200,6 +201,7 @@ export class CollectionSchemaView extends CollectionSubView(doc => doc) { active={this.props.active} onDrop={this.onDrop} addDocTab={this.props.addDocTab} + pinToPres={this.props.pinToPres} isSelected={this.props.isSelected} isFocused={this.isFocused} setFocused={this.setFocused} diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index 8e7fe9a82..1f7ef0689 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -155,6 +155,7 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { active={this.props.active} whenActiveChanged={this.props.whenActiveChanged} addDocTab={this.props.addDocTab} + pinToPres={this.props.pinToPres} setPreviewScript={emptyFunction} previewScript={undefined}> ; diff --git a/src/client/views/nodes/PDFBox.tsx b/src/client/views/nodes/PDFBox.tsx index 6450cb826..18f82ff47 100644 --- a/src/client/views/nodes/PDFBox.tsx +++ b/src/client/views/nodes/PDFBox.tsx @@ -198,7 +198,7 @@ export class PDFBox extends DocComponent(PdfDocumen {this.settingsPanel()}
    ); diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index cc042e008..112d39c32 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -646,14 +646,13 @@ export class PresBox extends React.Component { //FieldViewProps? this.presElementsMappings.set(keyDoc, elem); } + minimize = undoBatch(action(() => { + this.presMode = true; + this.props.addDocTab && this.props.addDocTab(this.props.Document, this.props.DataDoc, "close"); + })); + specificContextMenu = (e: React.MouseEvent): void => { ContextMenu.Instance.addItem({ description: "Make Current Presentation", event: action(() => Doc.UserDoc().curPresentation = this.props.Document), icon: "asterisk" }); - ContextMenu.Instance.addItem({ - description: "Toggle Minimized Mode", event: action(() => { - this.presMode = !this.presMode; - if (this.presMode) this.props.addDocTab && this.props.addDocTab(this.props.Document, this.props.DataDoc, "close"); - }), icon: "asterisk" - }); } render() { @@ -667,6 +666,7 @@ export class PresBox extends React.Component { //FieldViewProps? {this.renderPlayPauseButton()} +
    Date: Mon, 19 Aug 2019 22:15:34 -0400 Subject: removed multi target from pdf --- src/client/views/pdf/Page.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/client/views/pdf/Page.tsx b/src/client/views/pdf/Page.tsx index 5194ab71c..0de1777e6 100644 --- a/src/client/views/pdf/Page.tsx +++ b/src/client/views/pdf/Page.tsx @@ -151,6 +151,9 @@ export default class Page extends React.Component { PDFMenu.Instance.fadeOut(true); if (e.target && (e.target as any).parentElement === this._textLayer.current) { e.stopPropagation(); + if (!e.ctrlKey) { + this.props.sendAnnotations([], -1); + } } else { // set marquee x and y positions to the spatially transformed position @@ -161,14 +164,12 @@ export default class Page extends React.Component { } this._marqueeing = true; this._marquee.current && (this._marquee.current.style.opacity = "0.2"); + this.props.sendAnnotations([], -1); } document.removeEventListener("pointermove", this.onSelectStart); document.addEventListener("pointermove", this.onSelectStart); document.removeEventListener("pointerup", this.onSelectEnd); document.addEventListener("pointerup", this.onSelectEnd); - if (!e.ctrlKey) { - this.props.sendAnnotations([], -1); - } } } -- cgit v1.2.3-70-g09d2 From 00cecb10d80bad8d717cd06ddc4bf156664b9f2d Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Mon, 19 Aug 2019 22:39:56 -0400 Subject: fixed push pull UI --- .../apis/google_docs/GoogleApiClientUtils.ts | 3 + src/client/views/DocumentDecorations.tsx | 14 ++- src/client/views/nodes/FormattedTextBox.tsx | 122 +++++++++++---------- src/new_fields/RichTextField.ts | 8 +- 4 files changed, 81 insertions(+), 66 deletions(-) (limited to 'src') diff --git a/src/client/apis/google_docs/GoogleApiClientUtils.ts b/src/client/apis/google_docs/GoogleApiClientUtils.ts index 55b4a76f8..821c52270 100644 --- a/src/client/apis/google_docs/GoogleApiClientUtils.ts +++ b/src/client/apis/google_docs/GoogleApiClientUtils.ts @@ -4,6 +4,9 @@ import { RouteStore } from "../../../server/RouteStore"; import { Opt } from "../../../new_fields/Doc"; import { isArray } from "util"; +export const Pulls = "googleDocsPullCount"; +export const Pushes = "googleDocsPushCount"; + export namespace GoogleApiClientUtils { export namespace Docs { diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 80d4ecb9b..797b43add 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -30,6 +30,7 @@ import { ObjectField } from '../../new_fields/ObjectField'; import { MetadataEntryMenu } from './MetadataEntryMenu'; import { ImageBox } from './nodes/ImageBox'; import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils'; +import { Pulls, Pushes } from '../apis/google_docs/GoogleApiClientUtils'; const higflyout = require("@hig/flyout"); export const { anchorPoints } = higflyout; export const Flyout = higflyout.default; @@ -626,7 +627,10 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> if (!canPush) return (null); return (
    -
    thisDoc.pushToGoogleDocsTrigger = !thisDoc.pushToGoogleDocsTrigger}> +
    { + DocumentDecorations.hasPushedHack = false; + thisDoc[Pushes] = NumCast(thisDoc[Pushes]) + 1; + }}>
    @@ -639,13 +643,19 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> if (!canPull) return (null); return (
    -
    thisDoc.pullFromGoogleDocsTrigger = !thisDoc.pullFromGoogleDocsTrigger}> +
    { + DocumentDecorations.hasPulledHack = false; + thisDoc[Pulls] = NumCast(thisDoc[Pulls]) + 1; + }}>
    ); } + public static hasPushedHack = false; + public static hasPulledHack = false; + considerTooltip = () => { let thisDoc = SelectionManager.SelectedDocuments()[0].props.Document; let isTextDoc = thisDoc.data && thisDoc.data instanceof RichTextField; diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 406c2c4a6..d2eb71350 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -12,7 +12,7 @@ import { EditorView } from "prosemirror-view"; import { Doc, Opt, DocListCast } from "../../../new_fields/Doc"; import { Id, Copy } from '../../../new_fields/FieldSymbols'; import { List } from '../../../new_fields/List'; -import { RichTextField, ToGoogleDocText, FromGoogleDocText } from "../../../new_fields/RichTextField"; +import { RichTextField, ToPlainText, FromPlainText } from "../../../new_fields/RichTextField"; import { createSchema, listSpec, makeInterface } from "../../../new_fields/Schema"; import { BoolCast, Cast, NumCast, StrCast, DateCast } from "../../../new_fields/Types"; import { DocServer } from "../../DocServer"; @@ -30,16 +30,14 @@ import { ContextMenu } from "../../views/ContextMenu"; import { ContextMenuProps } from '../ContextMenuItem'; import { DocComponent } from "../DocComponent"; import { InkingControl } from "../InkingControl"; -import { Templates } from '../Templates'; import { FieldView, FieldViewProps } from "./FieldView"; import "./FormattedTextBox.scss"; import React = require("react"); -import { For } from 'babel-types'; import { DateField } from '../../../new_fields/DateField'; import { Utils } from '../../../Utils'; import { MainOverlayTextBox } from '../MainOverlayTextBox'; -import { GoogleApiClientUtils } from '../../apis/google_docs/GoogleApiClientUtils'; -import * as diff from "diff"; +import { GoogleApiClientUtils, Pulls, Pushes } from '../../apis/google_docs/GoogleApiClientUtils'; +import { DocumentDecorations } from '../DocumentDecorations'; library.add(faEdit); library.add(faSmile, faTextHeight, faUpload); @@ -84,6 +82,8 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe private _searchReactionDisposer?: Lambda; private _textReactionDisposer: Opt; private _proxyReactionDisposer: Opt; + private pullReactionDisposer: Opt; + private pushReactionDisposer: Opt; private dropDisposer?: DragManager.DragDropDisposer; public get CurrentDiv(): HTMLDivElement { return this._ref.current!; } private isGoogleDocsUpdate = false; @@ -345,13 +345,25 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe } ); - reaction(() => this.props.Document.pullFromGoogleDocsTrigger, () => { - this.pullFromGoogleDoc(); - }); + this.pullReactionDisposer = reaction( + () => this.props.Document[Pulls], + () => { + if (!DocumentDecorations.hasPulledHack) { + DocumentDecorations.hasPulledHack = true; + this.pullFromGoogleDoc(); + } + } + ); - reaction(() => this.props.Document.pushToGoogleDocsTrigger, () => { - this.pushToGoogleDoc(); - }); + this.pushReactionDisposer = reaction( + () => this.props.Document[Pushes], + () => { + if (!DocumentDecorations.hasPushedHack) { + DocumentDecorations.hasPushedHack = true; + this.pushToGoogleDoc(); + } + } + ); this._textReactionDisposer = reaction( () => this.extensionDoc, @@ -380,13 +392,44 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe this.unhighlightSearchTerms(); } }, { fireImmediately: true }); + } - ["pushToGoogleDocsTrigger", "pullFromGoogleDocsTrigger"].map(key => { - let doc = this.props.Document; - if (doc[key] === undefined) { - untracked(() => doc[key] = false); - } - }); + pushToGoogleDoc = () => { + let modes = GoogleApiClientUtils.Docs.WriteMode; + let mode = modes.Replace; + let reference: Opt = Cast(this.dataDoc[googleDocId], "string"); + if (!reference) { + mode = modes.Insert; + reference = { + title: StrCast(this.dataDoc.title), + handler: id => this.dataDoc[googleDocId] = id + }; + } + if (this._editorView) { + let data = Cast(this.dataDoc.data, RichTextField); + let content = data ? data[ToPlainText]() : this._editorView.state.doc.textContent; + GoogleApiClientUtils.Docs.write({ reference, content, mode }); + } + } + + pullFromGoogleDoc = async () => { + let dataDoc = Doc.GetProto(this.props.Document); + let documentId = StrCast(dataDoc[googleDocId]); + if (documentId) { + let exportState = await GoogleApiClientUtils.Docs.read({ documentId }); + UndoManager.RunInBatch(() => { + if (exportState && exportState.body && exportState.title) { + let data = Cast(dataDoc.data, RichTextField); + if (data) { + this.isGoogleDocsUpdate = true; + dataDoc.data = new RichTextField(data[FromPlainText](exportState.body)); + dataDoc.title = exportState.title; + } + } else { + delete dataDoc[googleDocId]; + } + }, Pulls); + } } clipboardTextSerializer = (slice: Slice): string => { @@ -516,6 +559,8 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe this._reactionDisposer && this._reactionDisposer(); this._proxyReactionDisposer && this._proxyReactionDisposer(); this._textReactionDisposer && this._textReactionDisposer(); + this.pushReactionDisposer && this.pushReactionDisposer(); + this.pullReactionDisposer && this.pullReactionDisposer(); } onPointerDown = (e: React.PointerEvent): void => { @@ -693,49 +738,6 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe event: action(() => Doc.GetProto(this.props.Document).autoHeight = !BoolCast(this.props.Document.autoHeight)), icon: "expand-arrows-alt" }); ContextMenu.Instance.addItem({ description: "Text Funcs...", subitems: subitems, icon: "text-height" }); - if (!(googleDocId in Doc.GetProto(this.props.Document))) { - ContextMenu.Instance.addItem({ - description: "Export to Google Doc...", - event: this.pushToGoogleDoc, - icon: "upload" - }); - } - } - - pushToGoogleDoc = () => { - let modes = GoogleApiClientUtils.Docs.WriteMode; - let mode = modes.Replace; - let reference: Opt = Cast(this.dataDoc[googleDocId], "string"); - if (!reference) { - mode = modes.Insert; - reference = { - title: StrCast(this.dataDoc.title), - handler: id => this.dataDoc[googleDocId] = id - }; - } - if (this._editorView) { - let data = Cast(this.dataDoc.data, RichTextField); - let content = data ? data[ToGoogleDocText]() : this._editorView.state.doc.textContent; - GoogleApiClientUtils.Docs.write({ reference, content, mode }); - } - } - - pullFromGoogleDoc = async () => { - let dataDoc = Doc.GetProto(this.props.Document); - let documentId = StrCast(dataDoc[googleDocId]); - if (documentId) { - let exportState = await GoogleApiClientUtils.Docs.read({ documentId }); - if (exportState && exportState.body && exportState.title) { - let data = Cast(dataDoc.data, RichTextField); - if (data) { - this.isGoogleDocsUpdate = true; - dataDoc.data = new RichTextField(data[FromGoogleDocText](exportState.body)); - dataDoc.title = exportState.title; - } - } else { - delete dataDoc[googleDocId]; - } - } } diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts index ec08293e9..ab58329f9 100644 --- a/src/new_fields/RichTextField.ts +++ b/src/new_fields/RichTextField.ts @@ -4,8 +4,8 @@ import { Deserializable } from "../client/util/SerializationHelper"; import { Copy, ToScriptString } from "./FieldSymbols"; import { scriptingGlobal } from "../client/util/Scripting"; -export const ToGoogleDocText = Symbol("PlainText"); -export const FromGoogleDocText = Symbol("PlainText"); +export const ToPlainText = Symbol("PlainText"); +export const FromPlainText = Symbol("PlainText"); const delimiter = "\n"; const joiner = ""; @@ -28,7 +28,7 @@ export class RichTextField extends ObjectField { return `new RichTextField("${this.Data}")`; } - [ToGoogleDocText]() { + [ToPlainText]() { // Because we're working with plain text, just concatenate all paragraphs let content = JSON.parse(this.Data).doc.content; let paragraphs = content.filter((item: any) => item.type === "paragraph"); @@ -43,7 +43,7 @@ export class RichTextField extends ObjectField { return textParagraphs.join(joiner).trimEnd(delimiter); } - [FromGoogleDocText](plainText: string) { + [FromPlainText](plainText: string) { // Remap the text, creating blocks split on newlines let elements = plainText.split(delimiter); -- cgit v1.2.3-70-g09d2 From c92761206957aebdba1cc2e77f6b662ae42db847 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Tue, 20 Aug 2019 01:44:18 -0400 Subject: interactive ui --- src/client/views/DocumentDecorations.tsx | 84 +++++++++++++++++++++++------ src/client/views/nodes/FormattedTextBox.tsx | 63 +++++++++++++++------- 2 files changed, 112 insertions(+), 35 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 797b43add..1db452b45 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -1,5 +1,5 @@ -import { library } from '@fortawesome/fontawesome-svg-core'; -import { faLink, faTag, faArrowAltCircleDown, faArrowAltCircleUp } from '@fortawesome/free-solid-svg-icons'; +import { library, IconProp } from '@fortawesome/fontawesome-svg-core'; +import { faLink, faTag, faArrowAltCircleDown, faArrowAltCircleUp, faCheckCircle, faStopCircle, faCloudUploadAlt } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { action, computed, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; @@ -18,7 +18,7 @@ import { CollectionView } from "./collections/CollectionView"; import './DocumentDecorations.scss'; import { DocumentView, PositionDocument } from "./nodes/DocumentView"; import { FieldView } from "./nodes/FieldView"; -import { FormattedTextBox } from "./nodes/FormattedTextBox"; +import { FormattedTextBox, GoogleRef } from "./nodes/FormattedTextBox"; import { IconBox } from "./nodes/IconBox"; import { LinkMenu } from "./nodes/LinkMenu"; import { TemplateMenu } from "./TemplateMenu"; @@ -26,7 +26,6 @@ import { Template, Templates } from "./Templates"; import React = require("react"); import { RichTextField } from '../../new_fields/RichTextField'; import { LinkManager } from '../util/LinkManager'; -import { ObjectField } from '../../new_fields/ObjectField'; import { MetadataEntryMenu } from './MetadataEntryMenu'; import { ImageBox } from './nodes/ImageBox'; import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils'; @@ -39,6 +38,11 @@ library.add(faLink); library.add(faTag); library.add(faArrowAltCircleDown); library.add(faArrowAltCircleUp); +library.add(faStopCircle); +library.add(faCheckCircle); +library.add(faCloudUploadAlt); + +const cloud: IconProp = "cloud-upload-alt"; @observer export class DocumentDecorations extends React.Component<{}, { value: string }> { @@ -69,6 +73,52 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> @observable private _removeIcon = false; @observable public Interacting = false; + @observable public pushIcon: IconProp = "arrow-alt-circle-up"; + @observable public pullIcon: IconProp = "arrow-alt-circle-down"; + @observable public pullColor: string = "white"; + public pullColorAnimating = false; + + private pullAnimating = false; + private pushAnimating = false; + + public startPullOutcome = action((success: boolean) => { + if (this.pullAnimating) { + return; + } + this.pullAnimating = true; + this.pullIcon = success ? "check-circle" : "stop-circle"; + setTimeout(() => runInAction(() => { + this.pullIcon = "arrow-alt-circle-down"; + this.pullAnimating = false; + }), 1000); + }); + + public startPushOutcome = action((success: boolean) => { + if (this.pushAnimating) { + return; + } + this.pushAnimating = true; + this.pushIcon = success ? "check-circle" : "stop-circle"; + setTimeout(() => runInAction(() => { + this.pushIcon = "arrow-alt-circle-up"; + this.pushAnimating = false; + }), 1000); + }); + + public setPullState = (unchanged: boolean) => { + if (this.pullColorAnimating) { + return; + } + this.pullColorAnimating = true; + this.pullColor = unchanged ? "lawngreen" : "red"; + setTimeout(() => { + runInAction(() => { + this.pullColor = "white"; + this.pullColorAnimating = false; + }); + }, 2000); + } + constructor(props: Readonly<{}>) { super(props); DocumentDecorations.Instance = this; @@ -621,33 +671,37 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> ); } + private get targetDoc() { + return SelectionManager.SelectedDocuments()[0].props.Document; + } + considerGoogleDocsPush = () => { - let thisDoc = SelectionManager.SelectedDocuments()[0].props.Document; - let canPush = thisDoc.data && thisDoc.data instanceof RichTextField; + let canPush = this.targetDoc.data && this.targetDoc.data instanceof RichTextField; if (!canPush) return (null); + let published = Doc.GetProto(this.targetDoc)[GoogleRef] !== undefined; + let icon: IconProp = published ? (this.pushIcon as any) : (cloud as any); return (
    -
    { +
    { DocumentDecorations.hasPushedHack = false; - thisDoc[Pushes] = NumCast(thisDoc[Pushes]) + 1; + this.targetDoc[Pushes] = NumCast(this.targetDoc[Pushes]) + 1; }}> - +
    ); } considerGoogleDocsPull = () => { - let thisDoc = SelectionManager.SelectedDocuments()[0].props.Document; - let canPull = thisDoc.data && thisDoc.data instanceof RichTextField; - if (!canPull) return (null); + let canPull = this.targetDoc.data && this.targetDoc.data instanceof RichTextField; + if (!canPull || !Doc.GetProto(this.targetDoc)[GoogleRef]) return (null); return (
    -
    { +
    { DocumentDecorations.hasPulledHack = false; - thisDoc[Pulls] = NumCast(thisDoc[Pulls]) + 1; + this.targetDoc[Pulls] = NumCast(this.targetDoc[Pulls]) + 1; }}> - +
    ); diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index d2eb71350..33d222813 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -60,11 +60,13 @@ const richTextSchema = createSchema({ documentText: "string" }); -const googleDocId = "googleDocId"; +export const GoogleRef = "googleDocId"; type RichTextDocument = makeInterface<[typeof richTextSchema]>; const RichTextDocument = makeInterface(richTextSchema); +type PullHandler = (exportState: GoogleApiClientUtils.Docs.ReadResult, dataDoc: Doc) => void; + @observer export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTextBoxProps), RichTextDocument>(RichTextDocument) { public static LayoutString(fieldStr: string = "data") { @@ -324,6 +326,8 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe }, { fireImmediately: true }); } + this.pullFromGoogleDoc(this.checkState); + this._reactionDisposer = reaction( () => { const field = this.dataDoc ? Cast(this.dataDoc[this.props.fieldKey], RichTextField) : undefined; @@ -350,7 +354,7 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe () => { if (!DocumentDecorations.hasPulledHack) { DocumentDecorations.hasPulledHack = true; - this.pullFromGoogleDoc(); + this.pullFromGoogleDoc(this.updateState); } } ); @@ -394,44 +398,63 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe }, { fireImmediately: true }); } - pushToGoogleDoc = () => { + pushToGoogleDoc = async () => { let modes = GoogleApiClientUtils.Docs.WriteMode; let mode = modes.Replace; - let reference: Opt = Cast(this.dataDoc[googleDocId], "string"); + let reference: Opt = Cast(this.dataDoc[GoogleRef], "string"); if (!reference) { mode = modes.Insert; reference = { title: StrCast(this.dataDoc.title), - handler: id => this.dataDoc[googleDocId] = id + handler: id => this.dataDoc[GoogleRef] = id }; } if (this._editorView) { let data = Cast(this.dataDoc.data, RichTextField); let content = data ? data[ToPlainText]() : this._editorView.state.doc.textContent; - GoogleApiClientUtils.Docs.write({ reference, content, mode }); + let response = await GoogleApiClientUtils.Docs.write({ reference, content, mode }); + let pushSuccess = response !== undefined && !("errors" in response); + DocumentDecorations.Instance.startPushOutcome(pushSuccess); } } - pullFromGoogleDoc = async () => { + pullFromGoogleDoc = async (handler: PullHandler) => { let dataDoc = Doc.GetProto(this.props.Document); - let documentId = StrCast(dataDoc[googleDocId]); + let documentId = StrCast(dataDoc[GoogleRef]); if (documentId) { let exportState = await GoogleApiClientUtils.Docs.read({ documentId }); - UndoManager.RunInBatch(() => { - if (exportState && exportState.body && exportState.title) { - let data = Cast(dataDoc.data, RichTextField); - if (data) { - this.isGoogleDocsUpdate = true; - dataDoc.data = new RichTextField(data[FromPlainText](exportState.body)); - dataDoc.title = exportState.title; - } - } else { - delete dataDoc[googleDocId]; - } - }, Pulls); + UndoManager.RunInBatch(() => handler(exportState, dataDoc), Pulls); } } + updateState = (exportState: GoogleApiClientUtils.Docs.ReadResult, dataDoc: Doc) => { + let pullSuccess = false; + if (exportState !== undefined && exportState.body !== undefined && exportState.title !== undefined) { + let data = Cast(dataDoc.data, RichTextField); + if (data) { + pullSuccess = true; + this.isGoogleDocsUpdate = true; + dataDoc.data = new RichTextField(data[FromPlainText](exportState.body)); + dataDoc.title = exportState.title; + } + } else { + delete dataDoc[GoogleRef]; + } + DocumentDecorations.Instance.startPullOutcome(pullSuccess); + } + + checkState = (exportState: GoogleApiClientUtils.Docs.ReadResult, dataDoc: Doc) => { + if (exportState !== undefined && exportState.body !== undefined && exportState.title !== undefined) { + let data = Cast(dataDoc.data, RichTextField); + if (data) { + let storedPlainText = data[ToPlainText]() + "\n"; + let receivedPlainText = exportState.body; + DocumentDecorations.Instance.setPullState(storedPlainText === receivedPlainText); + } + } + } + + clipboardTextSerializer = (slice: Slice): string => { let text = "", separated = true; const from = 0, to = slice.content.size; -- cgit v1.2.3-70-g09d2 From aa0e6f5ffc30fdffc3be13a1948981b754544a01 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Tue, 20 Aug 2019 12:03:50 -0400 Subject: automation of pull push button visibility --- src/client/views/DocumentDecorations.tsx | 3 +- src/client/views/nodes/FormattedTextBox.tsx | 61 +++++++++++++++++++---------- 2 files changed, 42 insertions(+), 22 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 1db452b45..05239073b 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -694,7 +694,8 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> considerGoogleDocsPull = () => { let canPull = this.targetDoc.data && this.targetDoc.data instanceof RichTextField; - if (!canPull || !Doc.GetProto(this.targetDoc)[GoogleRef]) return (null); + let dataDoc = Doc.GetProto(this.targetDoc); + if (!canPull || !dataDoc[GoogleRef] || dataDoc.unchanged) return (null); return (
    { diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 33d222813..8a355a425 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -1,6 +1,6 @@ import { library } from '@fortawesome/fontawesome-svg-core'; import { faEdit, faSmile, faTextHeight, faUpload } from '@fortawesome/free-solid-svg-icons'; -import { action, IReactionDisposer, observable, reaction, runInAction, computed, Lambda, trace, untracked } from "mobx"; +import { action, IReactionDisposer, observable, reaction, runInAction, computed, Lambda, trace, untracked, autorun } from "mobx"; import { observer } from "mobx-react"; import { baseKeymap } from "prosemirror-commands"; import { history } from "prosemirror-history"; @@ -399,32 +399,46 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe } pushToGoogleDoc = async () => { - let modes = GoogleApiClientUtils.Docs.WriteMode; - let mode = modes.Replace; - let reference: Opt = Cast(this.dataDoc[GoogleRef], "string"); - if (!reference) { - mode = modes.Insert; - reference = { - title: StrCast(this.dataDoc.title), - handler: id => this.dataDoc[GoogleRef] = id + this.pullFromGoogleDoc(async (exportState: GoogleApiClientUtils.Docs.ReadResult, dataDoc: Doc) => { + let modes = GoogleApiClientUtils.Docs.WriteMode; + let mode = modes.Replace; + let reference: Opt = Cast(this.dataDoc[GoogleRef], "string"); + if (!reference) { + mode = modes.Insert; + reference = { + title: StrCast(this.dataDoc.title), + handler: id => this.dataDoc[GoogleRef] = id + }; + } + let redo = async () => { + if (this._editorView && reference) { + let data = Cast(this.dataDoc.data, RichTextField); + let content = data ? data[ToPlainText]() : this._editorView.state.doc.textContent; + let response = await GoogleApiClientUtils.Docs.write({ reference, content, mode }); + let pushSuccess = response !== undefined && !("errors" in response); + dataDoc.unchanged = pushSuccess; + DocumentDecorations.Instance.startPushOutcome(pushSuccess); + } }; - } - if (this._editorView) { - let data = Cast(this.dataDoc.data, RichTextField); - let content = data ? data[ToPlainText]() : this._editorView.state.doc.textContent; - let response = await GoogleApiClientUtils.Docs.write({ reference, content, mode }); - let pushSuccess = response !== undefined && !("errors" in response); - DocumentDecorations.Instance.startPushOutcome(pushSuccess); - } + let undo = () => { + let content = exportState.body; + if (reference && content) { + GoogleApiClientUtils.Docs.write({ reference, content, mode }); + } + }; + UndoManager.AddEvent({ undo, redo }); + redo(); + }); } pullFromGoogleDoc = async (handler: PullHandler) => { - let dataDoc = Doc.GetProto(this.props.Document); + let dataDoc = this.dataDoc; let documentId = StrCast(dataDoc[GoogleRef]); + let exportState: GoogleApiClientUtils.Docs.ReadResult = {}; if (documentId) { - let exportState = await GoogleApiClientUtils.Docs.read({ documentId }); - UndoManager.RunInBatch(() => handler(exportState, dataDoc), Pulls); + exportState = await GoogleApiClientUtils.Docs.read({ documentId }); } + UndoManager.RunInBatch(() => handler(exportState, dataDoc), Pulls); } updateState = (exportState: GoogleApiClientUtils.Docs.ReadResult, dataDoc: Doc) => { @@ -436,6 +450,7 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe this.isGoogleDocsUpdate = true; dataDoc.data = new RichTextField(data[FromPlainText](exportState.body)); dataDoc.title = exportState.title; + dataDoc.unchanged = true; } } else { delete dataDoc[GoogleRef]; @@ -449,7 +464,11 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe if (data) { let storedPlainText = data[ToPlainText]() + "\n"; let receivedPlainText = exportState.body; - DocumentDecorations.Instance.setPullState(storedPlainText === receivedPlainText); + let storedTitle = dataDoc.title; + let receivedTitle = exportState.title; + let unchanged = storedPlainText === receivedPlainText && storedTitle === receivedTitle; + dataDoc.unchanged = unchanged; + DocumentDecorations.Instance.setPullState(unchanged); } } } -- cgit v1.2.3-70-g09d2 From 700dfc5add1ecd9c2b1ecafcdc593ff821b7a6a6 Mon Sep 17 00:00:00 2001 From: bob Date: Tue, 20 Aug 2019 17:20:27 -0400 Subject: UI enhancements and other backend fixes for templates. --- src/client/util/DragManager.ts | 3 +- src/client/views/MetadataEntryMenu.scss | 12 +++++ src/client/views/MetadataEntryMenu.tsx | 52 +++++++++++--------- .../views/collections/CollectionStackingView.tsx | 3 +- .../CollectionStackingViewFieldColumn.tsx | 9 ++-- src/client/views/collections/CollectionSubView.tsx | 2 +- .../views/collections/CollectionTreeView.tsx | 3 ++ .../views/collections/CollectionViewChromes.scss | 1 - .../views/collections/CollectionViewChromes.tsx | 57 +++++++++++----------- .../collectionFreeForm/CollectionFreeFormView.tsx | 30 ++++++------ src/client/views/nodes/DocumentContentsView.tsx | 2 +- src/client/views/nodes/DocumentView.tsx | 25 +++++++--- src/client/views/nodes/FormattedTextBox.tsx | 12 ++--- src/client/views/nodes/ImageBox.tsx | 7 +-- src/new_fields/Doc.ts | 11 +++-- 15 files changed, 131 insertions(+), 98 deletions(-) (limited to 'src') diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index 0b6d9b5e5..894b366ef 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -9,8 +9,6 @@ import { DocumentManager } from "./DocumentManager"; import { LinkManager } from "./LinkManager"; import { SelectionManager } from "./SelectionManager"; import { SchemaHeaderField } from "../../new_fields/SchemaHeaderField"; -import { DocumentDecorations } from "../views/DocumentDecorations"; -import { NumberLiteralType } from "typescript"; export type dropActionType = "alias" | "copy" | undefined; export function SetupDrag( @@ -211,6 +209,7 @@ export namespace DragManager { dropAction: dropActionType; userDropAction: dropActionType; moveDocument?: MoveFunction; + applyAsTemplate?: boolean; [id: string]: any; } diff --git a/src/client/views/MetadataEntryMenu.scss b/src/client/views/MetadataEntryMenu.scss index bcfc9a82d..e28c4d0e0 100644 --- a/src/client/views/MetadataEntryMenu.scss +++ b/src/client/views/MetadataEntryMenu.scss @@ -1,8 +1,20 @@ .metadataEntry-outerDiv { display: flex; + flex-direction: column; width: 300px; } +.metadataEntry-keys { + max-height: 80; + overflow-y: auto; + display: flex; + flex-direction: column; +} +.metadataEntry-inputArea { + display:flex; + flex-direction: row; +} + .react-autosuggest__container { position: relative; } diff --git a/src/client/views/MetadataEntryMenu.tsx b/src/client/views/MetadataEntryMenu.tsx index 36c240dd8..4a45eede9 100644 --- a/src/client/views/MetadataEntryMenu.tsx +++ b/src/client/views/MetadataEntryMenu.tsx @@ -1,11 +1,12 @@ import * as React from 'react'; import "./MetadataEntryMenu.scss"; import { observer } from 'mobx-react'; -import { observable, action, runInAction, trace } from 'mobx'; +import { observable, action, runInAction, trace, computed, IReactionDisposer, reaction } from 'mobx'; import { KeyValueBox } from './nodes/KeyValueBox'; import { Doc, Field } from '../../new_fields/Doc'; import * as Autosuggest from 'react-autosuggest'; import { undoBatch } from '../util/UndoManager'; +import { emptyFunction } from '../../Utils'; export type DocLike = Doc | Doc[] | Promise | Promise; export interface MetadataEntryProps { @@ -18,7 +19,8 @@ export interface MetadataEntryProps { export class MetadataEntryMenu extends React.Component{ @observable private _currentKey: string = ""; @observable private _currentValue: string = ""; - @observable private suggestions: string[] = []; + @observable _allSuggestions: string[] = []; + _suggestionDispser: IReactionDisposer | undefined; private userModified = false; private autosuggestRef = React.createRef(); @@ -140,35 +142,39 @@ export class MetadataEntryMenu extends React.Component{ getSuggestionValue = (suggestion: string) => suggestion; renderSuggestion = (suggestion: string) => { - return

    {suggestion}

    ; + return (null); } + componentDidMount() { - onSuggestionFetch = async ({ value }: { value: string }) => { - const sugg = await this.getKeySuggestions(value); - runInAction(() => { - this.suggestions = sugg; - }); + this._suggestionDispser = reaction(() => this._currentKey, + () => this.getKeySuggestions(this._currentKey).then(action((s: string[]) => this._allSuggestions = s)), + { fireImmediately: true }); } - - @action - onSuggestionClear = () => { - this.suggestions = []; + componentWillUnmount() { + this._suggestionDispser && this._suggestionDispser(); } render() { return (
    - Key: - - Value: - +
    + Key: + + Value: + +
    +
    +
      + {this._allSuggestions.map(s =>
    • { this._currentKey = s; this.previewValue(); })} >{s}
    • )} +
    +
    ); } diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index 1f7ef0689..c74c60d8f 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -160,7 +160,8 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { previewScript={undefined}> ; } - getDocHeight(d: Doc) { + getDocHeight(d?: Doc) { + if (!d) return 0; let nw = NumCast(d.nativeWidth); let nh = NumCast(d.nativeHeight); if (!d.ignoreAspect && nw && nh) { diff --git a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx index 74c7ef305..cc8476548 100644 --- a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx +++ b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx @@ -78,11 +78,14 @@ export class CollectionStackingViewFieldColumn extends React.Component { - let pair = Doc.GetLayoutDataDocPair(parent.props.Document, parent.props.DataDoc, parent.props.fieldKey, d); + const pair = Doc.GetLayoutDataDocPair(parent.props.Document, parent.props.DataDoc, parent.props.fieldKey, d); + if (!pair.layout || pair.data instanceof Promise) { + return (null); + } let width = () => Math.min(d.nativeWidth && !d.ignoreAspect && !parent.props.Document.fillColumn ? d[WidthSym]() : Number.MAX_VALUE, parent.columnWidth / parent.numGroupColumns); - let height = () => parent.getDocHeight(pair.layout); + let height = () => parent.getDocHeight(pair!.layout); let dref = React.createRef(); - let dxf = () => this.getDocTransform(pair.layout, dref.current!); + let dxf = () => this.getDocTransform(pair!.layout, dref.current!); this.props.parent._docXfs.push({ dxf: dxf, width: width, height: height }); let rowSpan = Math.ceil((height() + parent.gridGap) / parent.gridGap); let style = parent.isStackingView ? { width: width(), margin: "auto", marginTop: i === 0 ? 0 : parent.gridGap, height: height() } : { gridRowEnd: `span ${rowSpan}` }; diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index cfe3fefb3..818e76619 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -113,7 +113,7 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T) { @undoBatch @action protected drop(e: Event, de: DragManager.DropEvent): boolean { - if (de.data instanceof DragManager.DocumentDragData) { + if (de.data instanceof DragManager.DocumentDragData && !de.data.applyAsTemplate) { if (de.mods === "AltKey" && de.data.draggedDocuments.length) { this.childDocs.map(doc => Doc.ApplyTemplateTo(de.data.draggedDocuments[0], doc, undefined) diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index b6a14238e..ebd385743 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -443,6 +443,9 @@ class TreeView extends React.Component { let rowWidth = () => panelWidth() - 20; return docs.map((child, i) => { let pair = Doc.GetLayoutDataDocPair(containingCollection, dataDoc, key, child); + if (!pair.layout || pair.data instanceof Promise) { + return (null); + } let indent = i === 0 ? undefined : () => { if (StrCast(docs[i - 1].layout).indexOf("CollectionView") !== -1) { diff --git a/src/client/views/collections/CollectionViewChromes.scss b/src/client/views/collections/CollectionViewChromes.scss index 595f079d1..f39bd877a 100644 --- a/src/client/views/collections/CollectionViewChromes.scss +++ b/src/client/views/collections/CollectionViewChromes.scss @@ -7,7 +7,6 @@ z-index: 9001; transition: top .5s; background: lightgrey; - padding: 10px; .collectionViewChrome { display: grid; diff --git a/src/client/views/collections/CollectionViewChromes.tsx b/src/client/views/collections/CollectionViewChromes.tsx index b92bcc7cb..25b152d4e 100644 --- a/src/client/views/collections/CollectionViewChromes.tsx +++ b/src/client/views/collections/CollectionViewChromes.tsx @@ -1,30 +1,25 @@ -import * as React from "react"; -import { CollectionView } from "./CollectionView"; -import "./CollectionViewChromes.scss"; -import { CollectionViewType } from "./CollectionBaseView"; -import { undoBatch } from "../../util/UndoManager"; -import { action, observable, runInAction, computed, IObservable, IObservableValue, reaction, autorun } from "mobx"; -import { observer } from "mobx-react"; -import { Doc, DocListCast, FieldResult } from "../../../new_fields/Doc"; -import { DocLike } from "../MetadataEntryMenu"; -import * as Autosuggest from 'react-autosuggest'; -import { EditableView } from "../EditableView"; -import { StrCast, NumCast, BoolCast, Cast } from "../../../new_fields/Types"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { action, computed, observable, runInAction } from "mobx"; +import { observer } from "mobx-react"; +import * as React from "react"; +import { Doc, DocListCast } from "../../../new_fields/Doc"; +import { Id } from "../../../new_fields/FieldSymbols"; +import { List } from "../../../new_fields/List"; +import { listSpec } from "../../../new_fields/Schema"; +import { ScriptField } from "../../../new_fields/ScriptField"; +import { BoolCast, Cast, NumCast, StrCast } from "../../../new_fields/Types"; import { Utils } from "../../../Utils"; -import KeyRestrictionRow from "./KeyRestrictionRow"; +import { DragManager } from "../../util/DragManager"; import { CompileScript } from "../../util/Scripting"; -import { ScriptField } from "../../../new_fields/ScriptField"; -import { CollectionSchemaView } from "./CollectionSchemaView"; +import { undoBatch } from "../../util/UndoManager"; +import { EditableView } from "../EditableView"; import { COLLECTION_BORDER_WIDTH } from "../globalCssVariables.scss"; -import { listSpec } from "../../../new_fields/Schema"; -import { List } from "../../../new_fields/List"; -import { Id } from "../../../new_fields/FieldSymbols"; -import { threadId } from "worker_threads"; -import { DragManager } from "../../util/DragManager"; +import { DocLike } from "../MetadataEntryMenu"; +import { CollectionViewType } from "./CollectionBaseView"; +import { CollectionView } from "./CollectionView"; +import "./CollectionViewChromes.scss"; +import KeyRestrictionRow from "./KeyRestrictionRow"; const datepicker = require('js-datepicker'); -import * as $ from 'jquery'; -import { firebasedynamiclinks } from "googleapis/build/src/apis/firebasedynamiclinks"; interface CollectionViewChromeProps { CollectionView: CollectionView; @@ -51,7 +46,6 @@ export class CollectionViewBaseChrome extends React.Component { let re: any = /(!)?\(\(\(doc\.(\w+)\s+&&\s+\(doc\.\w+\s+as\s+\w+\)\.includes\(\"(\w+)\"\)/g; @@ -91,11 +85,6 @@ export class CollectionViewBaseChrome extends React.Component { - setTimeout(() => this._picker = datepicker("#" + this._datePickerElGuid, { - disabler: (date: Date) => date > new Date(), - onSelect: (instance: any, date: Date) => runInAction(() => this._dateValue = date), - dateSelected: new Date() - }), 1000); let fields: Filter[] = []; if (this.filterValue) { @@ -306,6 +295,15 @@ export class CollectionViewBaseChrome extends React.Component { + if (node) { + this._picker = datepicker("#" + node.id, { + disabler: (date: Date) => date > new Date(), + onSelect: (instance: any, date: Date) => runInAction(() => this._dateValue = date), + dateSelected: new Date() + }); + } + } render() { let collapsed = this.props.CollectionView.props.Document.chromeStatus !== "enabled"; return ( @@ -366,7 +364,8 @@ export class CollectionViewBaseChrome extends React.Component1 year of runInAction(() => this._dateValue = e.target.value)} onPointerDown={this.openDatePicker} diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index d69ece421..3be6aa3d3 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -622,20 +622,19 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { getScale = () => this.Document.scale ? this.Document.scale : 1; - getChildDocumentViewProps(childDocLayout: Doc): DocumentViewProps { - let pair = Doc.GetLayoutDataDocPair(this.props.Document, this.props.DataDoc, this.props.fieldKey, childDocLayout); + getChildDocumentViewProps(childLayout: Doc, childData?: Doc): DocumentViewProps { return { - DataDoc: pair.data, - Document: pair.layout, + DataDoc: childData, + Document: childLayout, addDocument: this.props.addDocument, removeDocument: this.props.removeDocument, moveDocument: this.props.moveDocument, onClick: this.props.onClick, - ScreenToLocalTransform: pair.layout.z ? this.getTransformOverlay : this.getTransform, + ScreenToLocalTransform: childLayout.z ? this.getTransformOverlay : this.getTransform, renderDepth: this.props.renderDepth + 1, - selectOnLoad: pair.layout[Id] === this._selectOnLoaded, - PanelWidth: pair.layout[WidthSym], - PanelHeight: pair.layout[HeightSym], + selectOnLoad: childLayout[Id] === this._selectOnLoaded, + PanelWidth: childLayout[WidthSym], + PanelHeight: childLayout[HeightSym], ContentScaling: returnOne, ContainingCollectionView: this.props.CollectionView, focus: this.focusDocument, @@ -745,12 +744,15 @@ export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) { const pos = script ? this.getCalculatedPositions(script, { doc, index: prev.length, collection: this.Document, docs, state }) : { x: Cast(doc.x, "number"), y: Cast(doc.y, "number"), z: Cast(doc.z, "number"), width: Cast(doc.width, "number"), height: Cast(doc.height, "number") }; state = pos.state === undefined ? state : pos.state; - prev.push({ - ele: , - bounds: (pos.x !== undefined && pos.y !== undefined) ? { x: pos.x, y: pos.y, z: pos.z, width: NumCast(pos.width), height: NumCast(pos.height) } : undefined - }); + let pair = Doc.GetLayoutDataDocPair(this.props.Document, this.props.DataDoc, this.props.fieldKey, doc); + if (pair.layout && !(pair.data instanceof Promise)) { + prev.push({ + ele: , + bounds: (pos.x !== undefined && pos.y !== undefined) ? { x: pos.x, y: pos.y, z: pos.z, width: NumCast(pos.width), height: NumCast(pos.height) } : undefined + }); + } } } return prev; diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index b901bdcfb..d77662355 100644 --- a/src/client/views/nodes/DocumentContentsView.tsx +++ b/src/client/views/nodes/DocumentContentsView.tsx @@ -68,7 +68,7 @@ export class DocumentContentsView extends React.Component(Docu private _lastTap: number = 0; private _doubleTap = false; private _hitExpander = false; + private _hitTemplateDrag = false; private _mainCont = React.createRef(); private _dropDisposer?: DragManager.DragDropDisposer; _animateToIconDisposer?: IReactionDisposer; @@ -228,7 +229,7 @@ export class DocumentView extends DocComponent(Docu } get dataDoc() { - if (this.props.DataDoc === undefined && this.props.Document.layout instanceof Doc) { + if (this.props.DataDoc === undefined && (this.props.Document.layout instanceof Doc || this.props.Document instanceof Promise)) { // if there is no dataDoc (ie, we're not rendering a temlplate layout), but this document // has a template layout document, then we will render the template layout but use // this document as the data document for the layout. @@ -236,7 +237,7 @@ export class DocumentView extends DocComponent(Docu } return this.props.DataDoc !== this.props.Document ? this.props.DataDoc : undefined; } - startDragging(x: number, y: number, dropAction: dropActionType, dragSubBullets: boolean) { + startDragging(x: number, y: number, dropAction: dropActionType, dragSubBullets: boolean, applyAsTemplate?: boolean) { if (this._mainCont.current) { let allConnected = [this.props.Document, ...(dragSubBullets ? DocListCast(this.props.Document.subBulletDocs) : [])]; let alldataConnected = [this.dataDoc, ...(dragSubBullets ? DocListCast(this.props.Document.subBulletDocs) : [])]; @@ -247,6 +248,7 @@ export class DocumentView extends DocComponent(Docu dragData.xOffset = xoff; dragData.yOffset = yoff; dragData.moveDocument = this.props.moveDocument; + dragData.applyAsTemplate = applyAsTemplate; DragManager.StartDocumentDrag([this._mainCont.current], dragData, x, y, { handlers: { dragComplete: action(emptyFunction) @@ -377,15 +379,19 @@ export class DocumentView extends DocComponent(Docu } } } + + onPointerDown = (e: React.PointerEvent): void => { if (e.nativeEvent.cancelBubble) return; this._downX = e.clientX; this._downY = e.clientY; this._hitExpander = DocListCast(this.props.Document.subBulletDocs).length > 0; - // if (e.shiftKey && e.buttons === 1 && CollectionDockingView.Instance) { - // CollectionDockingView.Instance.StartOtherDrag(e, [Doc.MakeAlias(this.props.Document)], [this.dataDoc]); - // e.stopPropagation(); - // } else { + this._hitTemplateDrag = false; + for (let element = (e.target as any); element && !this._hitTemplateDrag; element = element.parentElement) { + if (element.className && element.className.toString() === "collectionViewBaseChrome-collapse") { + this._hitTemplateDrag = true; + } + } if (this.active) e.stopPropagation(); // events stop at the lowest document that is active. document.removeEventListener("pointermove", this.onPointerMove); document.addEventListener("pointermove", this.onPointerMove); @@ -399,7 +405,7 @@ export class DocumentView extends DocComponent(Docu if (!e.altKey && !this.topMost && e.buttons === 1 && !BoolCast(this.props.Document.lockedPosition)) { document.removeEventListener("pointermove", this.onPointerMove); document.removeEventListener("pointerup", this.onPointerUp); - this.startDragging(this._downX, this._downY, e.ctrlKey || e.altKey ? "alias" : undefined, this._hitExpander); + this.startDragging(this._downX, this._downY, e.ctrlKey || e.altKey ? "alias" : undefined, this._hitExpander, this._hitTemplateDrag); } } e.stopPropagation(); // doesn't actually stop propagation since all our listeners are listening to events on 'document' however it does mark the event as cancelBubble=true which we test for in the move event handlers @@ -457,6 +463,10 @@ export class DocumentView extends DocComponent(Docu DocUtils.MakeLink(annotationDoc, targetDoc, this.props.ContainingCollectionView!.props.Document, `Link from ${StrCast(annotationDoc.title)}`); } + if (de.data instanceof DragManager.DocumentDragData && de.data.applyAsTemplate) { + Doc.ApplyTemplateTo(de.data.draggedDocuments[0], this.props.Document, this.props.DataDoc); + e.stopPropagation(); + } if (de.data instanceof DragManager.LinkDragData) { let sourceDoc = de.data.linkSourceDocument; let destDoc = this.props.Document; @@ -679,7 +689,6 @@ export class DocumentView extends DocComponent(Docu cm.addItem({ description: "Share...", subitems: usersMenu, icon: "share" }); if (!ClientUtils.RELEASE) { let setWriteMode = (mode: DocServer.WriteMode) => { - console.log(DocServer.WriteMode[mode]); DocServer.AclsMode = mode; const mode1 = mode; const mode2 = mode === DocServer.WriteMode.Default ? mode : DocServer.WriteMode.Playground; diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index f7890e5a6..0e347ca67 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -167,7 +167,6 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe FormattedTextBox._toolTipTextMenu && (FormattedTextBox._toolTipTextMenu.HackToFixTextSelectionGlitch = false); if (state.selection.empty && FormattedTextBox._toolTipTextMenu) { const marks = tx.storedMarks; - console.log(marks); if (marks) { FormattedTextBox._toolTipTextMenu.mark_key_pressed(marks); } } this._applyingChange = true; @@ -296,10 +295,10 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe this._editorView.updateState(EditorState.fromJSON(config, JSON.parse(field2))) ); - this.props.isOverlay && (this._heightReactionDisposer = reaction( + this._heightReactionDisposer = reaction( () => this.props.Document[WidthSym](), () => this.tryUpdateHeight() - )); + ); this._textReactionDisposer = reaction( () => this.extensionDoc, @@ -448,8 +447,8 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe if (this.props.selectOnLoad) { if (!this.props.isOverlay) this.props.select(false); else this._editorView!.focus(); - this.tryUpdateHeight(); } + this.tryUpdateHeight(); } componentWillUnmount() { @@ -610,9 +609,10 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe @action tryUpdateHeight() { - if (this.props.Document.autoHeight && this.props.isOverlay) { + if (this.props.Document.autoHeight && this._ref.current!.scrollHeight !== 0) { + console.log("DT = " + this.props.Document.title + " " + this._ref.current!.clientHeight + " " + this._ref.current!.scrollHeight + " " + this._ref.current!.textContent) let xf = this._ref.current!.getBoundingClientRect(); - let scrBounds = this.props.ScreenToLocalTransform().transformBounds(0, 0, xf.width, xf.height); + let scrBounds = this.props.ScreenToLocalTransform().transformBounds(0, 0, xf.width, this._ref.current!.textContent === "" ? 35 : this._ref.current!.scrollHeight); let nh = this.props.Document.isTemplate ? 0 : NumCast(this.dataDoc.nativeHeight, 0); let dh = NumCast(this.props.Document.height, 0); let sh = scrBounds.height; diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index 708e00576..6fc94a140 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -89,10 +89,7 @@ export class ImageBox extends DocComponent(ImageD drop = (e: Event, de: DragManager.DropEvent) => { if (de.data instanceof DragManager.DocumentDragData) { de.data.droppedDocuments.forEach(action((drop: Doc) => { - if (de.mods === "CtrlKey") { - Doc.ApplyTemplateTo(drop, this.props.Document, this.props.DataDoc); - e.stopPropagation(); - } else if (de.mods === "AltKey" && /*this.dataDoc !== this.props.Document &&*/ drop.data instanceof ImageField) { + if (de.mods === "AltKey" && /*this.dataDoc !== this.props.Document &&*/ drop.data instanceof ImageField) { Doc.GetProto(this.dataDoc)[this.props.fieldKey] = new ImageField(drop.data.url); e.stopPropagation(); } else if (de.mods === "MetaKey") { @@ -321,7 +318,7 @@ export class ImageBox extends DocComponent(ImageD let rotation = NumCast(this.dataDoc.rotation) % 180; let realsize = rotation === 90 || rotation === 270 ? { height: size.width, width: size.height } : size; let aspect = realsize.height / realsize.width; - if (Math.abs(NumCast(layoutdoc.height) - realsize.height) > 1 || Math.abs(NumCast(layoutdoc.width) - realsize.width) > 1) { + if (layoutdoc.nativeHeight !== 0 && layoutdoc.nativeWidth !== 0 && (Math.abs(NumCast(layoutdoc.height) - realsize.height) > 1 || Math.abs(NumCast(layoutdoc.width) - realsize.width) > 1)) { setTimeout(action(() => { layoutdoc.height = layoutdoc[WidthSym]() * aspect; layoutdoc.nativeHeight = realsize.height; diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 31f1f7a12..ca05dfa45 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -446,20 +446,23 @@ export namespace Doc { if (expandedTemplateLayout instanceof Doc) { return expandedTemplateLayout; } + if (expandedTemplateLayout instanceof Promise) { + return undefined; + } let expandedLayoutFieldKey = "Layout[" + templateLayoutDoc[Id] + "]"; expandedTemplateLayout = dataDoc[expandedLayoutFieldKey]; if (expandedTemplateLayout instanceof Doc) { return expandedTemplateLayout; } if (expandedTemplateLayout === undefined) { - setTimeout(() => - dataDoc[expandedLayoutFieldKey] = Doc.MakeDelegate(templateLayoutDoc, undefined, "[" + templateLayoutDoc.title + "]"), 0); + setTimeout(() => dataDoc[expandedLayoutFieldKey] === undefined && + (dataDoc[expandedLayoutFieldKey] = Doc.MakeDelegate(templateLayoutDoc, undefined, "[" + templateLayoutDoc.title + "]")), 0); } - return templateLayoutDoc; // use the templateLayout when it's not a template or the expandedTemplate is pending. + return undefined; // use the templateLayout when it's not a template or the expandedTemplate is pending. } export function GetLayoutDataDocPair(doc: Doc, dataDoc: Doc | undefined, fieldKey: string, childDocLayout: Doc) { - let layoutDoc = childDocLayout; + let layoutDoc: Doc | undefined = childDocLayout; let resolvedDataDoc = !doc.isTemplate && dataDoc !== doc && dataDoc ? Doc.GetDataDoc(dataDoc) : undefined; if (resolvedDataDoc && Doc.WillExpandTemplateLayout(childDocLayout, resolvedDataDoc)) { Doc.UpdateDocumentExtensionForField(resolvedDataDoc, fieldKey); -- cgit v1.2.3-70-g09d2 From dc587b0fb493d869e6cd38fa94b81105da4fbaab Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Tue, 20 Aug 2019 20:03:08 -0400 Subject: finished UI --- src/client/views/DocumentDecorations.scss | 6 +- src/client/views/DocumentDecorations.tsx | 92 ++++++++++++++++++----------- src/client/views/nodes/FormattedTextBox.tsx | 3 +- src/new_fields/RichTextField.ts | 7 ++- 4 files changed, 67 insertions(+), 41 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 0b7411fca..ef7159370 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -255,4 +255,8 @@ $linkGap : 3px; input { margin-right: 10px; } -} \ No newline at end of file +} + +@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } } +@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } } +@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform: rotate(360deg); } } \ No newline at end of file diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 05239073b..7645af054 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -1,5 +1,5 @@ import { library, IconProp } from '@fortawesome/fontawesome-svg-core'; -import { faLink, faTag, faArrowAltCircleDown, faArrowAltCircleUp, faCheckCircle, faStopCircle, faCloudUploadAlt } from '@fortawesome/free-solid-svg-icons'; +import { faLink, faTag, faArrowAltCircleDown, faArrowAltCircleUp, faCheckCircle, faStopCircle, faCloudUploadAlt, faSyncAlt } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { action, computed, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; @@ -41,8 +41,10 @@ library.add(faArrowAltCircleUp); library.add(faStopCircle); library.add(faCheckCircle); library.add(faCloudUploadAlt); +library.add(faSyncAlt); const cloud: IconProp = "cloud-upload-alt"; +const fetch: IconProp = "sync-alt"; @observer export class DocumentDecorations extends React.Component<{}, { value: string }> { @@ -76,48 +78,47 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> @observable public pushIcon: IconProp = "arrow-alt-circle-up"; @observable public pullIcon: IconProp = "arrow-alt-circle-down"; @observable public pullColor: string = "white"; + @observable public isAnimatingFetch = false; public pullColorAnimating = false; private pullAnimating = false; private pushAnimating = false; public startPullOutcome = action((success: boolean) => { - if (this.pullAnimating) { - return; + if (!this.pullAnimating) { + this.pullAnimating = true; + this.pullIcon = success ? "check-circle" : "stop-circle"; + setTimeout(() => runInAction(() => { + this.pullIcon = "arrow-alt-circle-down"; + this.pullAnimating = false; + }), 1000); } - this.pullAnimating = true; - this.pullIcon = success ? "check-circle" : "stop-circle"; - setTimeout(() => runInAction(() => { - this.pullIcon = "arrow-alt-circle-down"; - this.pullAnimating = false; - }), 1000); }); public startPushOutcome = action((success: boolean) => { - if (this.pushAnimating) { - return; + if (!this.pushAnimating) { + this.pushAnimating = true; + this.pushIcon = success ? "check-circle" : "stop-circle"; + setTimeout(() => runInAction(() => { + this.pushIcon = "arrow-alt-circle-up"; + this.pushAnimating = false; + }), 1000); } - this.pushAnimating = true; - this.pushIcon = success ? "check-circle" : "stop-circle"; - setTimeout(() => runInAction(() => { - this.pushIcon = "arrow-alt-circle-up"; - this.pushAnimating = false; - }), 1000); }); - public setPullState = (unchanged: boolean) => { - if (this.pullColorAnimating) { - return; + public setPullState = action((unchanged: boolean) => { + this.isAnimatingFetch = false; + if (!this.pullColorAnimating) { + this.pullColorAnimating = true; + this.pullColor = unchanged ? "lawngreen" : "red"; + setTimeout(this.clearPullColor, 1000); } - this.pullColorAnimating = true; - this.pullColor = unchanged ? "lawngreen" : "red"; - setTimeout(() => { - runInAction(() => { - this.pullColor = "white"; - this.pullColorAnimating = false; - }); - }, 2000); - } + }); + + private clearPullColor = action(() => { + this.pullColor = "white"; + this.pullColorAnimating = false; + }); constructor(props: Readonly<{}>) { super(props); @@ -679,7 +680,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> let canPush = this.targetDoc.data && this.targetDoc.data instanceof RichTextField; if (!canPush) return (null); let published = Doc.GetProto(this.targetDoc)[GoogleRef] !== undefined; - let icon: IconProp = published ? (this.pushIcon as any) : (cloud as any); + let icon: IconProp = published ? (this.pushIcon as any) : cloud; return (
    { @@ -695,14 +696,33 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> considerGoogleDocsPull = () => { let canPull = this.targetDoc.data && this.targetDoc.data instanceof RichTextField; let dataDoc = Doc.GetProto(this.targetDoc); - if (!canPull || !dataDoc[GoogleRef] || dataDoc.unchanged) return (null); + if (!canPull || !dataDoc[GoogleRef]) return (null); + let icon = !dataDoc.unchanged ? (this.pullIcon as any) : fetch; + let animation = this.isAnimatingFetch ? "spin 0.5s linear infinite" : "none"; return (
    -
    { - DocumentDecorations.hasPulledHack = false; - this.targetDoc[Pulls] = NumCast(this.targetDoc[Pulls]) + 1; - }}> - +
    { + this.clearPullColor(); + DocumentDecorations.hasPulledHack = false; + this.targetDoc[Pulls] = NumCast(this.targetDoc[Pulls]) + 1; + dataDoc.unchanged && runInAction(() => this.isAnimatingFetch = true); + }}> +
    ); diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 8a355a425..e06be7079 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -354,7 +354,8 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe () => { if (!DocumentDecorations.hasPulledHack) { DocumentDecorations.hasPulledHack = true; - this.pullFromGoogleDoc(this.updateState); + let unchanged = this.dataDoc.unchanged; + this.pullFromGoogleDoc(unchanged ? this.checkState : this.updateState); } } ); diff --git a/src/new_fields/RichTextField.ts b/src/new_fields/RichTextField.ts index ab58329f9..cae5623e6 100644 --- a/src/new_fields/RichTextField.ts +++ b/src/new_fields/RichTextField.ts @@ -38,9 +38,10 @@ export class RichTextField extends ObjectField { let blockText = (block: any) => block.text; let concatenateParagraph = (p: any) => (p.content ? p.content.map(blockText).join(joiner) : "") + delimiter; - // Concatentate paragraphs and string the result together. Trim the last newline, an artifact. - let textParagraphs = paragraphs.map(concatenateParagraph); - return textParagraphs.join(joiner).trimEnd(delimiter); + // Concatentate paragraphs and string the result together + let textParagraphs: string[] = paragraphs.map(concatenateParagraph); + let plainText = textParagraphs.join(joiner); + return plainText.substring(0, plainText.length - 1); } [FromPlainText](plainText: string) { -- cgit v1.2.3-70-g09d2 From bd734ec84fa8fae36fceebf74da44216a0746b23 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Tue, 20 Aug 2019 21:02:05 -0400 Subject: open remote document on ctrl click --- src/client/views/DocumentDecorations.tsx | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index d5d59a8ee..3482fd043 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -1,5 +1,5 @@ import { library, IconProp } from '@fortawesome/fontawesome-svg-core'; -import { faLink, faTag, faTimes, faArrowAltCircleDown, faArrowAltCircleUp, faCheckCircle, faStopCircle, faCloudUploadAlt, faSyncAlt } from '@fortawesome/free-solid-svg-icons'; +import { faLink, faTag, faTimes, faArrowAltCircleDown, faArrowAltCircleUp, faCheckCircle, faStopCircle, faCloudUploadAlt, faSyncAlt, faShare } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { action, computed, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; @@ -43,6 +43,7 @@ library.add(faStopCircle); library.add(faCheckCircle); library.add(faCloudUploadAlt); library.add(faSyncAlt); +library.add(faShare); const cloud: IconProp = "cloud-upload-alt"; const fetch: IconProp = "sync-alt"; @@ -81,6 +82,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> @observable public pullIcon: IconProp = "arrow-alt-circle-down"; @observable public pullColor: string = "white"; @observable public isAnimatingFetch = false; + @observable public openHover = false; public pullColorAnimating = false; private pullAnimating = false; @@ -710,21 +712,29 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> let dataDoc = Doc.GetProto(this.targetDoc); if (!canPull || !dataDoc[GoogleRef]) return (null); let icon = !dataDoc.unchanged ? (this.pullIcon as any) : fetch; + icon = this.openHover ? "share" : icon; let animation = this.isAnimatingFetch ? "spin 0.5s linear infinite" : "none"; + let title = `${!dataDoc.unchanged ? "Pull from" : "Fetch"} Google Docs`; return (
    { - this.clearPullColor(); - DocumentDecorations.hasPulledHack = false; - this.targetDoc[Pulls] = NumCast(this.targetDoc[Pulls]) + 1; - dataDoc.unchanged && runInAction(() => this.isAnimatingFetch = true); + onPointerEnter={e => e.ctrlKey && runInAction(() => this.openHover = true)} + onPointerLeave={() => runInAction(() => this.openHover = false)} + onClick={e => { + if (e.ctrlKey) { + window.open(`https://docs.google.com/document/d/${dataDoc[GoogleRef]}/edit`); + } else { + this.clearPullColor(); + DocumentDecorations.hasPulledHack = false; + this.targetDoc[Pulls] = NumCast(this.targetDoc[Pulls]) + 1; + dataDoc.unchanged && runInAction(() => this.isAnimatingFetch = true); + } }}> Date: Tue, 20 Aug 2019 21:05:25 -0400 Subject: auto height set on google docs publishing --- src/client/views/DocumentDecorations.tsx | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 3482fd043..891fd7847 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -694,6 +694,9 @@ export class DocumentDecorations extends React.Component<{}, { value: string }> let canPush = this.targetDoc.data && this.targetDoc.data instanceof RichTextField; if (!canPush) return (null); let published = Doc.GetProto(this.targetDoc)[GoogleRef] !== undefined; + if (!published) { + this.targetDoc.autoHeight = true; + } let icon: IconProp = published ? (this.pushIcon as any) : cloud; return (
    -- cgit v1.2.3-70-g09d2 From 820ad7343816ee9d5881eefdbcbe8783fe903257 Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Tue, 20 Aug 2019 21:07:43 -0400 Subject: animation fix --- src/client/views/nodes/FormattedTextBox.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 2705fac14..d4cbb5116 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -1,6 +1,6 @@ import { library } from '@fortawesome/fontawesome-svg-core'; import { faEdit, faSmile, faTextHeight, faUpload } from '@fortawesome/free-solid-svg-icons'; -import { action, computed, IReactionDisposer, Lambda, observable, reaction } from "mobx"; +import { action, computed, IReactionDisposer, Lambda, observable, reaction, runInAction } from "mobx"; import { observer } from "mobx-react"; import { baseKeymap } from "prosemirror-commands"; import { history } from "prosemirror-history"; @@ -298,6 +298,7 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe } this.pullFromGoogleDoc(this.checkState); + runInAction(() => DocumentDecorations.Instance.isAnimatingFetch = true); this._reactionDisposer = reaction( () => { -- cgit v1.2.3-70-g09d2 From c0439996ec8b4858c48a7871120e19bb7c06c67d Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Tue, 20 Aug 2019 21:37:32 -0400 Subject: drag and drop google docs tweaks --- package.json | 4 +--- src/client/DocServer.ts | 1 - src/client/views/collections/CollectionSubView.tsx | 8 ++++---- src/client/views/nodes/FormattedTextBox.tsx | 1 + 4 files changed, 6 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/package.json b/package.json index e6a0a54b9..de1f3f6e6 100644 --- a/package.json +++ b/package.json @@ -63,7 +63,6 @@ "@types/cookie-parser": "^1.4.1", "@types/cookie-session": "^2.0.36", "@types/d3-format": "^1.3.1", - "@types/diff": "^4.0.2", "@types/dotenv": "^6.1.1", "@types/express": "^4.16.1", "@types/express-flash": "0.0.0", @@ -128,7 +127,6 @@ "cookie-session": "^2.0.0-beta.3", "crypto-browserify": "^3.11.0", "d3-format": "^1.3.2", - "diff": "^4.0.1", "dotenv": "^8.0.0", "express": "^4.16.4", "express-flash": "0.0.2", @@ -221,4 +219,4 @@ "xoauth2": "^1.2.0", "youtube": "^0.1.0" } -} +} \ No newline at end of file diff --git a/src/client/DocServer.ts b/src/client/DocServer.ts index 56d9147ae..2cec1046b 100644 --- a/src/client/DocServer.ts +++ b/src/client/DocServer.ts @@ -5,7 +5,6 @@ import { Utils, emptyFunction } from '../Utils'; import { SerializationHelper } from './util/SerializationHelper'; import { RefField } from '../new_fields/RefField'; import { Id, HandleUpdate } from '../new_fields/FieldSymbols'; -import { docs_v1 } from 'googleapis'; /** * This class encapsulates the transfer and cross-client synchronization of diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index 3deec22b5..5b50c545c 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -17,7 +17,7 @@ import { DragManager } from "../../util/DragManager"; import { undoBatch, UndoManager } from "../../util/UndoManager"; import { DocComponent } from "../DocComponent"; import { FieldViewProps } from "../nodes/FieldView"; -import { FormattedTextBox, Blank } from "../nodes/FormattedTextBox"; +import { FormattedTextBox, GoogleRef } from "../nodes/FormattedTextBox"; import { CollectionPDFView } from "./CollectionPDFView"; import { CollectionVideoView } from "./CollectionVideoView"; import { CollectionView } from "./CollectionView"; @@ -209,11 +209,11 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T) { } let matches: RegExpExecArray | null; if ((matches = /(https:\/\/)?docs\.google\.com\/document\/d\/([^\\]+)\/edit/g.exec(text)) !== null) { - let newBox = Docs.Create.TextDocument({ ...options, width: 600, height: 400, title: "Fetching title from Google Docs..." }); + let newBox = Docs.Create.TextDocument({ ...options, width: 400, height: 200, title: "Awaiting title from Google Docs..." }); let proto = newBox.proto!; proto.autoHeight = true; - proto.googleDocId = matches[2]; - proto.data = "Fetching contents from Google Docs..."; + proto[GoogleRef] = matches[2]; + proto.data = "Please select and then click on this document's pull button to load its contents from from Google Docs..."; proto.backgroundColor = "#eeeeff"; this.props.addDocument(newBox); return; diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index d4cbb5116..2b01fb70a 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -434,6 +434,7 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe delete dataDoc[GoogleRef]; } DocumentDecorations.Instance.startPullOutcome(pullSuccess); + this.tryUpdateHeight(); } checkState = (exportState: GoogleApiClientUtils.Docs.ReadResult, dataDoc: Doc) => { -- cgit v1.2.3-70-g09d2 From 73bb0f572e261850583b698dd819d35a6fe768ec Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Tue, 20 Aug 2019 21:42:37 -0400 Subject: cleanup --- src/client/views/MainView.tsx | 2 +- src/client/views/collections/CollectionSubView.tsx | 2 +- src/client/views/nodes/FormattedTextBox.tsx | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index e85374f6a..f28844009 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -15,7 +15,7 @@ import { listSpec } from '../../new_fields/Schema'; import { BoolCast, Cast, FieldValue, StrCast } from '../../new_fields/Types'; import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils'; import { RouteStore } from '../../server/RouteStore'; -import { emptyFunction, returnOne, returnTrue, Utils, returnEmptyString, PostToServer } from '../../Utils'; +import { emptyFunction, returnOne, returnTrue, Utils, returnEmptyString } from '../../Utils'; import { DocServer } from '../DocServer'; import { Docs } from '../documents/Documents'; import { ClientUtils } from '../util/ClientUtils'; diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index 5b50c545c..99e5ab7b3 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -213,7 +213,7 @@ export function CollectionSubView(schemaCtor: (doc: Doc) => T) { let proto = newBox.proto!; proto.autoHeight = true; proto[GoogleRef] = matches[2]; - proto.data = "Please select and then click on this document's pull button to load its contents from from Google Docs..."; + proto.data = "Please select this document and then click on its pull button to load its contents from from Google Docs..."; proto.backgroundColor = "#eeeeff"; this.props.addDocument(newBox); return; diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 2b01fb70a..606e8edb0 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -389,9 +389,9 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe }; } let redo = async () => { - if (this._editorView && reference) { - let data = Cast(this.dataDoc.data, RichTextField); - let content = data ? data[ToPlainText]() : this._editorView.state.doc.textContent; + let data = Cast(this.dataDoc.data, RichTextField); + if (this._editorView && reference && data) { + let content = data[ToPlainText](); let response = await GoogleApiClientUtils.Docs.write({ reference, content, mode }); let pushSuccess = response !== undefined && !("errors" in response); dataDoc.unchanged = pushSuccess; -- cgit v1.2.3-70-g09d2 From 9984f2f19001c07e63738947172e12da25e4498e Mon Sep 17 00:00:00 2001 From: Sam Wilkins Date: Tue, 20 Aug 2019 21:55:46 -0400 Subject: bulleted list --- src/client/util/DictationManager.ts | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/client/util/DictationManager.ts b/src/client/util/DictationManager.ts index b00846756..488a146bf 100644 --- a/src/client/util/DictationManager.ts +++ b/src/client/util/DictationManager.ts @@ -13,6 +13,7 @@ import { AudioField, ImageField } from "../../new_fields/URLField"; import { HistogramField } from "../northstar/dash-fields/HistogramField"; import { MainView } from "../views/MainView"; import { Utils } from "../../Utils"; +import { RichTextField } from "../../new_fields/RichTextField"; /** * This namespace provides a singleton instance of a manager that @@ -300,11 +301,15 @@ export namespace DictationManager { } }], - ["promote", { + ["create bulleted note", { action: (target: DocumentView) => { - console.log(target); - }, - restrictTo: [DocumentType.TEXT] + let newBox = Docs.Create.TextDocument({ width: 400, height: 200, title: "My Outline" }); + let proto = newBox.proto!; + let proseMirrorState = '"{"doc":{"type":"doc","content":[{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"type":"text","text":""}]}]}]}]},"selection":{"type":"text","anchor":1,"head":1}}"'; + proto.data = new RichTextField(proseMirrorState); + proto.backgroundColor = "#eeffff"; + target.props.addDocTab(newBox, proto, "onRight"); + } }] ]); -- cgit v1.2.3-70-g09d2 From 186cf33322b6c96386c6e9fdb823025d09c5caeb Mon Sep 17 00:00:00 2001 From: bob Date: Wed, 21 Aug 2019 11:35:18 -0400 Subject: extended treeview functionality - better indenting, state management, drag dropping. --- src/client/views/EditableView.tsx | 28 +++++--- .../views/collections/CollectionTreeView.tsx | 83 +++++++++++++--------- src/client/views/nodes/FormattedTextBox.tsx | 1 - .../authentication/models/current_user_utils.ts | 5 +- 4 files changed, 75 insertions(+), 42 deletions(-) (limited to 'src') diff --git a/src/client/views/EditableView.tsx b/src/client/views/EditableView.tsx index c3612fee9..dd5395802 100644 --- a/src/client/views/EditableView.tsx +++ b/src/client/views/EditableView.tsx @@ -3,6 +3,7 @@ import { observer } from 'mobx-react'; import { observable, action, trace } from 'mobx'; import "./EditableView.scss"; import * as Autosuggest from 'react-autosuggest'; +import { undoBatch } from '../util/UndoManager'; export interface EditableProps { /** @@ -70,14 +71,12 @@ export class EditableView extends React.Component { onKeyDown = (e: React.KeyboardEvent) => { if (e.key === "Tab") { e.stopPropagation(); + this.finalizeEdit(e.currentTarget.value, e.shiftKey); this.props.OnTab && this.props.OnTab(); } else if (e.key === "Enter") { e.stopPropagation(); if (!e.ctrlKey) { - if (this.props.SetValue(e.currentTarget.value, e.shiftKey)) { - this._editing = false; - this.props.isEditingCallback && this.props.isEditingCallback(false); - } + this.finalizeEdit(e.currentTarget.value, e.shiftKey); } else if (this.props.OnFillDown) { this.props.OnFillDown(e.currentTarget.value); this._editing = false; @@ -100,6 +99,14 @@ export class EditableView extends React.Component { e.stopPropagation(); } + @action + private finalizeEdit(value: string, shiftDown: boolean) { + if (this.props.SetValue(value, shiftDown)) { + this._editing = false; + this.props.isEditingCallback && this.props.isEditingCallback(false); + } + } + stopPropagation(e: React.SyntheticEvent) { e.stopPropagation(); } @@ -118,7 +125,7 @@ export class EditableView extends React.Component { className: "editableView-input", onKeyDown: this.onKeyDown, autoFocus: true, - onBlur: action(() => this._editing = false), + onBlur: e => this.finalizeEdit(e.currentTarget.value, false), onPointerDown: this.stopPropagation, onClick: this.stopPropagation, onPointerUp: this.stopPropagation, @@ -126,9 +133,14 @@ export class EditableView extends React.Component { onChange: this.props.autosuggestProps.onChange }} /> - : { this._editing = false; this.props.isEditingCallback && this.props.isEditingCallback(false); })} onPointerDown={this.stopPropagation} onClick={this.stopPropagation} onPointerUp={this.stopPropagation} - style={{ display: this.props.display, fontSize: this.props.fontSize }} />; + : this.finalizeEdit(e.currentTarget.value, false)} + onPointerDown={this.stopPropagation} onClick={this.stopPropagation} onPointerUp={this.stopPropagation} + style={{ display: this.props.display, fontSize: this.props.fontSize }} + />; } else { if (this.props.autosuggestProps) this.props.autosuggestProps.resetValue(); return ( diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index ebd385743..e1eb9e1a5 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -49,6 +49,8 @@ export interface TreeViewProps { treeViewId: string; parentKey: string; active: () => boolean; + showHeaderFields: () => boolean; + preventTreeViewOpen: boolean; } library.add(faTrashAlt); @@ -65,7 +67,12 @@ library.add(faArrowsAltH); library.add(faPlus, faMinus); @observer /** - * Component that takes in a document prop and a boolean whether it's collapsed or not. + * Renders a treeView of a collection of documents + * + * special fields: + * treeViewOpen : flag denoting whether the documents sub-tree (contents) is visible or hidden + * preventTreeViewOpen : ignores the treeViewOpen flag (for allowing a view to not be slaved to other views of the document) + * treeViewExpandedView : name of field whose contents are being displayed as the document's subtree */ class TreeView extends React.Component { static loadId = ""; @@ -73,7 +80,9 @@ class TreeView extends React.Component { private _treedropDisposer?: DragManager.DragDropDisposer; private _dref = React.createRef(); get defaultExpandedView() { return this.childDocs ? this.fieldKey : "fields"; } - @observable _collapsed: boolean = true; + @observable _overrideTreeViewOpen = false; // override of the treeViewOpen field allowing the display state to be independent of the document's state + @computed get treeViewOpen() { return (BoolCast(this.props.document.treeViewOpen) && !this.props.preventTreeViewOpen) || this._overrideTreeViewOpen; } + set treeViewOpen(c: boolean) { if (this.props.preventTreeViewOpen) this._overrideTreeViewOpen = c; else this.props.document.treeViewOpen = c; } @computed get treeViewExpandedView() { return StrCast(this.props.document.treeViewExpandedView, this.defaultExpandedView); } @computed get MAX_EMBED_HEIGHT() { return NumCast(this.props.document.maxEmbedHeight, 300); } @computed get dataDoc() { return this.resolvedDataDoc ? this.resolvedDataDoc : this.props.document; } @@ -146,7 +155,7 @@ class TreeView extends React.Component { let rect = this._header!.current!.getBoundingClientRect(); let bounds = this.props.ScreenToLocalTransform().transformPoint(rect.left, rect.top + rect.height / 2); let before = x[1] < bounds[1]; - let inside = x[0] > bounds[0] + 75 || (!before && !this._collapsed); + let inside = x[0] > bounds[0] + 75 || (!before && this.treeViewOpen); this._header!.current!.className = "treeViewItem-header"; if (inside) this._header!.current!.className += " treeViewItem-header-inside"; else if (before) this._header!.current!.className += " treeViewItem-header-above"; @@ -163,15 +172,15 @@ class TreeView extends React.Component { fontStyle={style} fontSize={12} GetValue={() => StrCast(this.props.document[key])} - SetValue={(value: string) => (Doc.GetProto(this.dataDoc)[key] = value) ? true : true} - OnFillDown={(value: string) => { + SetValue={undoBatch((value: string) => (Doc.GetProto(this.dataDoc)[key] = value) ? true : true)} + OnFillDown={undoBatch((value: string) => { Doc.GetProto(this.dataDoc)[key] = value; let doc = this.props.document.detailedLayout instanceof Doc ? Doc.ApplyTemplate(Doc.GetProto(this.props.document.detailedLayout)) : undefined; if (!doc) doc = Docs.Create.FreeformDocument([], { title: "", x: 0, y: 0, width: 100, height: 25, templates: new List([Templates.Title.Layout]) }); TreeView.loadId = doc[Id]; return this.props.addDocument(doc); - }} - OnTab={() => this.props.indentDocument && this.props.indentDocument()} + })} + OnTab={() => { TreeView.loadId = ""; this.props.indentDocument && this.props.indentDocument(); }} />) onWorkspaceContextMenu = (e: React.MouseEvent): void => { @@ -200,7 +209,7 @@ class TreeView extends React.Component { let rect = this._header!.current!.getBoundingClientRect(); let bounds = this.props.ScreenToLocalTransform().transformPoint(rect.left, rect.top + rect.height / 2); let before = x[1] < bounds[1]; - let inside = x[0] > bounds[0] + 75 || (!before && !this._collapsed); + let inside = x[0] > bounds[0] + 75 || (!before && this.treeViewOpen); if (de.data instanceof DragManager.LinkDragData) { let sourceDoc = de.data.linkSourceDocument; let destDoc = this.props.document; @@ -256,14 +265,14 @@ class TreeView extends React.Component { let rows: JSX.Element[] = []; for (let key of Object.keys(ids).slice().sort()) { let contents = doc[key]; - let contentElement: JSX.Element[] | JSX.Element = []; + let contentElement: (JSX.Element | null)[] | JSX.Element = []; if (contents instanceof Doc || Cast(contents, listSpec(Doc))) { let remDoc = (doc: Doc) => this.remove(doc, key); - let addDoc = (doc: Doc, addBefore?: Doc, before?: boolean) => Doc.AddDocToList(this.dataDoc, key, doc, addBefore, before, !BoolCast(this.props.document.stackingHeadersSortDescending)); + let addDoc = (doc: Doc, addBefore?: Doc, before?: boolean) => Doc.AddDocToList(this.dataDoc, key, doc, addBefore, before, !BoolCast(this.props.document.stackingHeadersSortDescending, true)); contentElement = TreeView.GetChildElements(contents instanceof Doc ? [contents] : DocListCast(contents), this.props.treeViewId, doc, undefined, key, addDoc, remDoc, this.move, - this.props.dropAction, this.props.addDocTab, this.props.pinToPres, this.props.ScreenToLocalTransform, this.props.outerXf, this.props.active, this.props.panelWidth, this.props.renderDepth); + this.props.dropAction, this.props.addDocTab, this.props.pinToPres, this.props.ScreenToLocalTransform, this.props.outerXf, this.props.active, this.props.panelWidth, this.props.renderDepth, this.props.showHeaderFields, this.props.preventTreeViewOpen); } else { contentElement = { const expandKey = this.treeViewExpandedView === this.fieldKey ? this.fieldKey : this.treeViewExpandedView === "links" ? "links" : undefined; if (expandKey !== undefined) { let remDoc = (doc: Doc) => this.remove(doc, expandKey); - let addDoc = (doc: Doc, addBefore?: Doc, before?: boolean) => Doc.AddDocToList(this.dataDoc, expandKey, doc, addBefore, before, !BoolCast(this.props.document.stackingHeadersSortDescending)); + let addDoc = (doc: Doc, addBefore?: Doc, before?: boolean) => Doc.AddDocToList(this.dataDoc, expandKey, doc, addBefore, before, !BoolCast(this.props.document.stackingHeadersSortDescending, true)); let docs = expandKey === "links" ? this.childLinks : this.childDocs; return
      {!docs ? (null) : TreeView.GetChildElements(docs as Doc[], this.props.treeViewId, this.props.document.layout as Doc, this.resolvedDataDoc, expandKey, addDoc, remDoc, this.move, this.props.dropAction, this.props.addDocTab, this.props.pinToPres, this.props.ScreenToLocalTransform, - this.props.outerXf, this.props.active, this.props.panelWidth, this.props.renderDepth)} + this.props.outerXf, this.props.active, this.props.panelWidth, this.props.renderDepth, this.props.showHeaderFields, this.props.preventTreeViewOpen)}
    ; } else if (this.treeViewExpandedView === "fields") { return
      @@ -329,8 +338,8 @@ class TreeView extends React.Component { @computed get renderBullet() { - return
      this._collapsed = !this._collapsed)} style={{ color: StrCast(this.props.document.color, "black"), opacity: 0.4 }}> - {} + return
      this.treeViewOpen = !this.treeViewOpen)} style={{ color: StrCast(this.props.document.color, "black"), opacity: 0.4 }}> + {}
      ; } /** @@ -344,13 +353,13 @@ class TreeView extends React.Component { let headerElements = ( { - if (!this._collapsed) { + if (this.treeViewOpen) { this.props.document.treeViewExpandedView = this.treeViewExpandedView === this.fieldKey ? "fields" : this.treeViewExpandedView === "fields" && this.props.document.layout ? "layout" : this.treeViewExpandedView === "layout" && this.props.document.links ? "links" : this.childDocs ? this.fieldKey : "fields"; } - this._collapsed = false; + this.treeViewOpen = true; })}> {this.treeViewExpandedView} ); @@ -368,7 +377,7 @@ class TreeView extends React.Component { }} > {this.editableView("title")}
      - {headerElements} + {this.props.showHeaderFields() ? headerElements : (null)} {openRight} ; } @@ -381,13 +390,13 @@ class TreeView extends React.Component { {this.renderTitle}
      - {this._collapsed ? (null) : this.renderContent} + {!this.treeViewOpen ? (null) : this.renderContent}
    ; } public static GetChildElements( - docs: Doc[], + docList: Doc[], treeViewId: string, containingCollection: Doc, dataDoc: Doc | undefined, @@ -402,8 +411,11 @@ class TreeView extends React.Component { outerXf: () => { translateX: number, translateY: number }, active: () => boolean, panelWidth: () => number, - renderDepth: number + renderDepth: number, + showHeaderFields: () => boolean, + preventTreeViewOpen: boolean ) { + let docs = docList.filter(child => !child.excludeFromLibrary); let viewSpecScript = Cast(containingCollection.viewSpecScript, ScriptField); if (viewSpecScript) { let script = viewSpecScript.script; @@ -418,7 +430,7 @@ class TreeView extends React.Component { }); } - let descending = BoolCast(containingCollection.stackingHeadersSortDescending); + let descending = BoolCast(containingCollection.stackingHeadersSortDescending, true); docs.slice().sort(function (a, b): 1 | -1 { let descA = descending ? b : a; let descB = descending ? a : b; @@ -448,11 +460,14 @@ class TreeView extends React.Component { } let indent = i === 0 ? undefined : () => { - if (StrCast(docs[i - 1].layout).indexOf("CollectionView") !== -1) { + if (StrCast(docs[i - 1].layout).indexOf("fieldKey") !== -1) { let fieldKeysub = StrCast(docs[i - 1].layout).split("fieldKey")[1]; let fieldKey = fieldKeysub.split("\"")[1]; - Doc.AddDocToList(docs[i - 1], fieldKey, child); - remove(child); + if (fieldKey && Cast(docs[i - 1][fieldKey], listSpec(Doc)) !== undefined) { + Doc.AddDocToList(docs[i - 1], fieldKey, child); + docs[i - 1].treeViewOpen = true; + remove(child); + } } }; let addDocument = (doc: Doc, relativeTo?: Doc, before?: boolean) => { @@ -481,7 +496,9 @@ class TreeView extends React.Component { ScreenToLocalTransform={screenToLocalXf} outerXf={outerXf} parentKey={key} - active={active} />; + active={active} + showHeaderFields={showHeaderFields} + preventTreeViewOpen={preventTreeViewOpen} />; }); } } @@ -561,7 +578,7 @@ export class CollectionTreeView extends CollectionSubView(Document) { render() { Doc.UpdateDocumentExtensionForField(this.props.DataDoc ? this.props.DataDoc : this.props.Document, this.props.fieldKey); let dropAction = StrCast(this.props.Document.dropAction) as dropActionType; - let addDoc = (doc: Doc, relativeTo?: Doc, before?: boolean) => Doc.AddDocToList(this.props.Document, this.props.fieldKey, doc, relativeTo, before, !BoolCast(this.props.Document.stackingHeadersSortDescending)); + let addDoc = (doc: Doc, relativeTo?: Doc, before?: boolean) => Doc.AddDocToList(this.props.Document, this.props.fieldKey, doc, relativeTo, before, false, false, !BoolCast(this.props.Document.stackingHeadersSortDescending, true)); let moveDoc = (d: Doc, target: Doc, addDoc: (doc: Doc) => boolean) => this.props.moveDocument(d, target, addDoc); return !this.childDocs ? (null) : (
    StrCast(this.resolvedDataDoc.title)} - SetValue={(value: string) => (Doc.GetProto(this.resolvedDataDoc).title = value) ? true : true} - OnFillDown={(value: string) => { + SetValue={undoBatch((value: string) => (Doc.GetProto(this.resolvedDataDoc).title = value) ? true : true)} + OnFillDown={undoBatch((value: string) => { Doc.GetProto(this.props.Document).title = value; let doc = this.props.Document.detailedLayout instanceof Doc ? Doc.ApplyTemplate(Doc.GetProto(this.props.Document.detailedLayout)) : undefined; if (!doc) doc = Docs.Create.FreeformDocument([], { title: "", x: 0, y: 0, width: 100, height: 25, templates: new List([Templates.Title.Layout]) }); TreeView.loadId = doc[Id]; - Doc.AddDocToList(this.props.Document, this.props.fieldKey, doc, this.childDocs.length ? this.childDocs[0] : undefined, true, !BoolCast(this.props.Document.stackingHeadersSortDescending)); - }} /> + Doc.AddDocToList(this.props.Document, this.props.fieldKey, doc, this.childDocs.length ? this.childDocs[0] : undefined, true, false, false, !BoolCast(this.props.Document.stackingHeadersSortDescending, true)); + })} /> {this.props.Document.workspaceLibrary ? this.renderNotifsButton : (null)} {this.props.Document.allowClear ? this.renderClearButton : (null)}
      { TreeView.GetChildElements(this.childDocs, this.props.Document[Id], this.props.Document, this.props.DataDoc, this.props.fieldKey, addDoc, this.remove, - moveDoc, dropAction, this.props.addDocTab, this.props.pinToPres, this.props.ScreenToLocalTransform, this.outerXf, this.props.active, this.props.PanelWidth, this.props.renderDepth) + moveDoc, dropAction, this.props.addDocTab, this.props.pinToPres, this.props.ScreenToLocalTransform, + this.outerXf, this.props.active, this.props.PanelWidth, this.props.renderDepth, () => this.props.Document.chromeStatus !== "disabled", + BoolCast(this.props.Document.preventTreeViewOpen)) }
    diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx index 606e8edb0..3f3360eff 100644 --- a/src/client/views/nodes/FormattedTextBox.tsx +++ b/src/client/views/nodes/FormattedTextBox.tsx @@ -736,7 +736,6 @@ export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTe @action tryUpdateHeight() { if (this.props.Document.autoHeight && this._ref.current!.scrollHeight !== 0) { - console.log("DT = " + this.props.Document.title + " " + this._ref.current!.clientHeight + " " + this._ref.current!.scrollHeight + " " + this._ref.current!.textContent); let xf = this._ref.current!.getBoundingClientRect(); let scrBounds = this.props.ScreenToLocalTransform().transformBounds(0, 0, xf.width, this._ref.current!.textContent === "" ? 35 : this._ref.current!.scrollHeight); let nh = this.props.Document.isTemplate ? 0 : NumCast(this.dataDoc.nativeHeight, 0); diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index 508655605..aa3da0034 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -10,7 +10,7 @@ import { CollectionView } from "../../../client/views/collections/CollectionView import { Doc } from "../../../new_fields/Doc"; import { List } from "../../../new_fields/List"; import { listSpec } from "../../../new_fields/Schema"; -import { Cast, StrCast } from "../../../new_fields/Types"; +import { Cast, StrCast, PromiseValue } from "../../../new_fields/Types"; import { Utils } from "../../../Utils"; import { RouteStore } from "../../RouteStore"; @@ -49,12 +49,14 @@ export class CurrentUserUtils { workspaces.boxShadow = "0 0"; doc.workspaces = workspaces; } + PromiseValue(Cast(doc.workspaces, Doc)).then(workspaces => workspaces && (workspaces.preventTreeViewOpen = true)); if (doc.recentlyClosed === undefined) { const recentlyClosed = Docs.Create.TreeDocument([], { title: "Recently Closed", height: 75 }); recentlyClosed.excludeFromLibrary = true; recentlyClosed.boxShadow = "0 0"; doc.recentlyClosed = recentlyClosed; } + PromiseValue(Cast(doc.recentlyClosed, Doc)).then(recent => recent && (recent.preventTreeViewOpen = true)); if (doc.curPresentation === undefined) { const curPresentation = Docs.Create.PresDocument(new List(), { title: "Presentation" }); curPresentation.excludeFromLibrary = true; @@ -73,6 +75,7 @@ export class CurrentUserUtils { } StrCast(doc.title).indexOf("@") !== -1 && (doc.title = StrCast(doc.title).split("@")[0] + "'s Library"); doc.width = 100; + doc.preventTreeViewOpen = true; } public static loadCurrentUser() { -- cgit v1.2.3-70-g09d2 From 542d272921666ad6ffbef8a028d8204e5c357791 Mon Sep 17 00:00:00 2001 From: bob Date: Wed, 21 Aug 2019 11:51:55 -0400 Subject: added pinning tree items to presentation. fixed float doc opacity when = 0 --- src/client/views/MetadataEntryMenu.tsx | 2 +- src/client/views/collections/CollectionTreeView.tsx | 3 ++- src/client/views/nodes/CollectionFreeFormDocumentView.tsx | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/client/views/MetadataEntryMenu.tsx b/src/client/views/MetadataEntryMenu.tsx index 4a45eede9..4d696e37a 100644 --- a/src/client/views/MetadataEntryMenu.tsx +++ b/src/client/views/MetadataEntryMenu.tsx @@ -172,7 +172,7 @@ export class MetadataEntryMenu extends React.Component{
      - {this._allSuggestions.map(s =>
    • { this._currentKey = s; this.previewValue(); })} >{s}
    • )} + {this._allSuggestions.sort().map(s =>
    • { this._currentKey = s; this.previewValue(); })} >{s}
    • )}
    diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx index e1eb9e1a5..472e2f256 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -186,6 +186,7 @@ class TreeView extends React.Component { onWorkspaceContextMenu = (e: React.MouseEvent): void => { if (!e.isPropagationStopped()) { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7 if (NumCast(this.props.document.viewType) !== CollectionViewType.Docking) { + ContextMenu.Instance.addItem({ description: "Pin to Presentation", event: () => this.props.pinToPres(this.props.document), icon: "tv" }); ContextMenu.Instance.addItem({ description: "Open Tab", event: () => this.props.addDocTab(this.props.document, this.resolvedDataDoc, "inTab"), icon: "folder" }); ContextMenu.Instance.addItem({ description: "Open Right", event: () => this.props.addDocTab(this.props.document, this.resolvedDataDoc, "onRight"), icon: "caret-square-right" }); if (DocumentManager.Instance.getDocumentViews(this.dataDoc).length) { @@ -415,7 +416,7 @@ class TreeView extends React.Component { showHeaderFields: () => boolean, preventTreeViewOpen: boolean ) { - let docs = docList.filter(child => !child.excludeFromLibrary); + let docs = docList.filter(child => !child.excludeFromLibrary && child.opacity !== 0); let viewSpecScript = Cast(containingCollection.viewSpecScript, ScriptField); if (viewSpecScript) { let script = viewSpecScript.script; diff --git a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx index ee596c841..7631ecc6c 100644 --- a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx +++ b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx @@ -83,7 +83,7 @@ export class CollectionFreeFormDocumentView extends DocComponent Date: Wed, 21 Aug 2019 13:37:55 -0400 Subject: tree view drop tweak --- 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 472e2f256..b61894b29 100644 --- a/src/client/views/collections/CollectionTreeView.tsx +++ b/src/client/views/collections/CollectionTreeView.tsx @@ -155,7 +155,7 @@ class TreeView extends React.Component { let rect = this._header!.current!.getBoundingClientRect(); let bounds = this.props.ScreenToLocalTransform().transformPoint(rect.left, rect.top + rect.height / 2); let before = x[1] < bounds[1]; - let inside = x[0] > bounds[0] + 75 || (!before && this.treeViewOpen); + let inside = x[0] > bounds[0] + 75; this._header!.current!.className = "treeViewItem-header"; if (inside) this._header!.current!.className += " treeViewItem-header-inside"; else if (before) this._header!.current!.className += " treeViewItem-header-above"; -- cgit v1.2.3-70-g09d2 From 3e33c2f1642195e023673cf669c4b5820fe2aeba Mon Sep 17 00:00:00 2001 From: bob Date: Wed, 21 Aug 2019 15:46:23 -0400 Subject: restructed presentationview --- src/client/views/nodes/PresBox.tsx | 279 ++-------- .../views/presentationview/PresentationElement.tsx | 611 ++------------------- .../views/presentationview/PresentationList.tsx | 47 +- .../views/presentationview/PresentationView.scss | 10 +- src/new_fields/Doc.ts | 3 + 5 files changed, 128 insertions(+), 822 deletions(-) (limited to 'src') diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index 112d39c32..cf222601f 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -12,7 +12,7 @@ import { BoolCast, Cast, FieldValue, NumCast, StrCast } from "../../../new_field import { Utils } from "../../../Utils"; import { DocumentManager } from "../../util/DocumentManager"; import { undoBatch } from "../../util/UndoManager"; -import PresentationElement, { buttonIndex } from "../presentationview/PresentationElement"; +import PresentationElement from "../presentationview/PresentationElement"; import PresentationViewList from "../presentationview/PresentationList"; import "../presentationview/PresentationView.scss"; import { FieldView, FieldViewProps } from './FieldView'; @@ -45,17 +45,12 @@ export class PresBox extends React.Component { //FieldViewProps? //Keeping track of the doc for the current presentation -- bcz: keeping a list of current presentations shouldn't be needed. Let users create them, store them, as they see fit. @computed get curPresentation() { return this.props.Document; } - //Mapping from presentation ids to a list of doc that represent a group - @observable groupMappings: Map = new Map(); //mapping from docs to their rendered component @observable presElementsMappings: Map = new Map(); //variable that holds all the docs in the presentation @observable childrenDocs: Doc[] = []; //variable to hold if presentation is started @observable presStatus: boolean = false; - //back-up so that presentation stays the way it's when refreshed - @observable presGroupBackUp: Doc = new Doc(); - @observable presButtonBackUp: Doc = new Doc(); //Mapping of guids to presentations. @observable presentationsMapping: Map = new Map(); //Mapping of presentations to guid, so that select option values can be given. @@ -102,87 +97,11 @@ export class PresBox extends React.Component { //FieldViewProps? * otherwise initializes. */ setPresentationBackUps = async () => { - //getting both backUp documents - - let castedGroupBackUp = Cast(this.curPresentation.presGroupBackUp, Doc); - let castedButtonBackUp = Cast(this.curPresentation.presButtonBackUp, Doc); - //if instantiated before - if (castedGroupBackUp instanceof Promise) { - castedGroupBackUp.then(doc => { - let toAssign = doc ? doc : new Doc(); - this.curPresentation.presGroupBackUp = toAssign; - runInAction(() => this.presGroupBackUp = toAssign); - if (doc) { - if (toAssign[Id] === doc[Id]) { - this.retrieveGroupMappings(); - } - } - }); - - //if never instantiated a store doc yet - } else if (castedGroupBackUp instanceof Doc) { - let castedDoc: Doc = await castedGroupBackUp; - runInAction(() => this.presGroupBackUp = castedDoc); - this.retrieveGroupMappings(); - } else { - runInAction(() => { - let toAssign = new Doc(); - this.presGroupBackUp = toAssign; - this.curPresentation.presGroupBackUp = toAssign; - - }); - - } - //if instantiated before - if (castedButtonBackUp instanceof Promise) { - castedButtonBackUp.then(doc => { - let toAssign = doc ? doc : new Doc(); - this.curPresentation.presButtonBackUp = toAssign; - runInAction(() => this.presButtonBackUp = toAssign); - }); - - //if never instantiated a store doc yet - } else if (castedButtonBackUp instanceof Doc) { - let castedDoc: Doc = await castedButtonBackUp; - runInAction(() => this.presButtonBackUp = castedDoc); - - } else { - runInAction(() => { - let toAssign = new Doc(); - this.presButtonBackUp = toAssign; - this.curPresentation.presButtonBackUp = toAssign; - }); - - } - - //storing the presentation status,ie. whether it was stopped or playing let presStatusBackUp = BoolCast(this.curPresentation.presStatus); runInAction(() => this.presStatus = presStatusBackUp); } - /** - * This is the function that is called to retrieve the groups that have been stored and - * push them to the groupMappings. - */ - retrieveGroupMappings = async () => { - let castedGroupDocs = await DocListCastAsync(this.presGroupBackUp.groupDocs); - if (castedGroupDocs !== undefined) { - castedGroupDocs.forEach(async (groupDoc: Doc, index: number) => { - let castedGrouping = await DocListCastAsync(groupDoc.grouping); - let castedKey = StrCast(groupDoc.presentIdStore, null); - if (castedGrouping) { - castedGrouping.forEach((doc: Doc) => { - doc.presentId = castedKey; - }); - } - if (castedGrouping !== undefined && castedKey !== undefined) { - this.groupMappings.set(castedKey, castedGrouping); - } - }); - } - } - //observable means render is re-called every time variable is changed @observable collapsed: boolean = false; @@ -193,17 +112,13 @@ export class PresBox extends React.Component { //FieldViewProps? if (docAtCurrentNext === undefined) { return; } - //asking for it's presentation id - let curNextPresId = StrCast(docAtCurrentNext.presentId); let nextSelected = current + 1; - //if curDoc is in a group, selection slides until last one, if not it's next one - if (this.groupMappings.has(curNextPresId)) { - let currentsArray = this.groupMappings.get(StrCast(docAtCurrentNext.presentId))!; - nextSelected = current + currentsArray.length - currentsArray.indexOf(docAtCurrentNext); + let presDocs = DocListCast(this.curPresentation.data); + for (; nextSelected < presDocs.length - 1; nextSelected++) { + if (!this.presElementsMappings.get(presDocs[nextSelected + 1])!.props.document.groupButton) + break; - //end of grup so go beyond - if (nextSelected === current) nextSelected = current + 1; } this.gotoDocument(nextSelected, current); @@ -219,31 +134,31 @@ export class PresBox extends React.Component { //FieldViewProps? //asking for its presentation id. let curPresId = StrCast(docAtCurrent.presentId); - let prevSelected = current - 1; + let prevSelected = current; let zoomOut: boolean = false; //checking if this presentation id is mapped to a group, if so chosing the first element in group - if (this.groupMappings.has(curPresId)) { - let currentsArray = this.groupMappings.get(StrCast(docAtCurrent.presentId))!; - prevSelected = current - currentsArray.length + (currentsArray.length - currentsArray.indexOf(docAtCurrent)) - 1; - //end of grup so go beyond - if (prevSelected === current) prevSelected = current - 1; - - //checking if any of the group members had used zooming in - currentsArray.forEach((doc: Doc) => { - //let presElem: PresentationElement | undefined = this.presElementsMappings.get(doc); - if (this.presElementsMappings.get(doc)!.selected[buttonIndex.Show]) { - zoomOut = true; - return; - } - }); - + let presDocs = DocListCast(this.curPresentation.data); + let currentsArray: Doc[] = []; + for (; prevSelected > 0 && presDocs[prevSelected].groupButton; prevSelected--) { + currentsArray.push(presDocs[prevSelected]); } + prevSelected = Math.max(0, prevSelected - 1); + + //checking if any of the group members had used zooming in + currentsArray.forEach((doc: Doc) => { + //let presElem: PresentationElement | undefined = this.presElementsMappings.get(doc); + if (this.presElementsMappings.get(doc)!.props.document.showButton) { + zoomOut = true; + return; + } + }); + // if a group set that flag to zero or a single element //If so making sure to zoom out, which goes back to state before zooming action if (current > 0) { - if (zoomOut || this.presElementsMappings.get(docAtCurrent)!.selected[buttonIndex.Show]) { + if (zoomOut || this.presElementsMappings.get(docAtCurrent)!.showButton) { let prevScale = NumCast(this.childrenDocs[prevSelected].viewScale, null); let curScale = DocumentManager.Instance.getScaleOfDocView(this.childrenDocs[current]); if (prevScale !== undefined) { @@ -264,19 +179,18 @@ export class PresBox extends React.Component { //FieldViewProps? */ showAfterPresented = (index: number) => { this.presElementsMappings.forEach((presElem: PresentationElement, key: Doc) => { - let selectedButtons: boolean[] = presElem.selected; //the order of cases is aligned based on priority - if (selectedButtons[buttonIndex.HideTillPressed]) { + if (presElem.props.document.hideTillShownButton) { if (this.childrenDocs.indexOf(key) <= index) { key.opacity = 1; } } - if (selectedButtons[buttonIndex.HideAfter]) { + if (presElem.props.document.hideAfterButton) { if (this.childrenDocs.indexOf(key) < index) { key.opacity = 0; } } - if (selectedButtons[buttonIndex.FadeAfter]) { + if (presElem.props.document.fadeButton) { if (this.childrenDocs.indexOf(key) < index) { key.opacity = 0.5; } @@ -291,21 +205,19 @@ export class PresBox extends React.Component { //FieldViewProps? */ hideIfNotPresented = (index: number) => { this.presElementsMappings.forEach((presElem: PresentationElement, key: Doc) => { - let selectedButtons: boolean[] = presElem.selected; - //the order of cases is aligned based on priority - if (selectedButtons[buttonIndex.HideAfter]) { + if (presElem.props.document.hideAfterButton) { if (this.childrenDocs.indexOf(key) >= index) { key.opacity = 1; } } - if (selectedButtons[buttonIndex.FadeAfter]) { + if (presElem.props.document.fadeButton) { if (this.childrenDocs.indexOf(key) >= index) { key.opacity = 1; } } - if (selectedButtons[buttonIndex.HideTillPressed]) { + if (presElem.props.document.hideTillShownButton) { if (this.childrenDocs.indexOf(key) > index) { key.opacity = 0; } @@ -320,34 +232,35 @@ export class PresBox extends React.Component { //FieldViewProps? */ navigateToElement = async (curDoc: Doc, fromDoc: number) => { let docToJump: Doc = curDoc; - let curDocPresId = StrCast(curDoc.presentId, null); let willZoom: boolean = false; - //checking if in group - if (curDocPresId !== undefined) { - if (this.groupMappings.has(curDocPresId)) { - let currentDocGroup = this.groupMappings.get(curDocPresId)!; - currentDocGroup.forEach((doc: Doc, index: number) => { - let selectedButtons: boolean[] = this.presElementsMappings.get(doc)!.selected; - if (selectedButtons[buttonIndex.Navigate]) { - docToJump = doc; - willZoom = false; - } - if (selectedButtons[buttonIndex.Show]) { - docToJump = doc; - willZoom = true; - } - }); - } + let presDocs = DocListCast(this.curPresentation.data); + let nextSelected = presDocs.indexOf(curDoc); + let currentDocGroups: Doc[] = []; + for (; nextSelected < presDocs.length - 1; nextSelected++) { + if (!this.presElementsMappings.get(presDocs[nextSelected + 1])!.props.document.groupButton) + break; + currentDocGroups.push(presDocs[nextSelected]); } + + currentDocGroups.forEach((doc: Doc, index: number) => { + if (this.presElementsMappings.get(doc)!.navButton) { + docToJump = doc; + willZoom = false; + } + if (this.presElementsMappings.get(doc)!.showButton) { + docToJump = doc; + willZoom = true; + } + }); + //docToJump stayed same meaning, it was not in the group or was the last element in the group if (docToJump === curDoc) { //checking if curDoc has navigation open - let curDocButtons = this.presElementsMappings.get(curDoc)!.selected; - if (curDocButtons[buttonIndex.Navigate]) { + if (this.presElementsMappings.get(curDoc)!.navButton) { DocumentManager.Instance.jumpToDocument(curDoc, false); - } else if (curDocButtons[buttonIndex.Show]) { + } else if (this.presElementsMappings.get(curDoc)!.showButton) { let curScale = DocumentManager.Instance.getScaleOfDocView(this.childrenDocs[fromDoc]); //awaiting jump so that new scale can be found, since jumping is async await DocumentManager.Instance.jumpToDocument(curDoc, true); @@ -406,69 +319,6 @@ export class PresBox extends React.Component { //FieldViewProps? //removing the Presentation Element stored for it this.presElementsMappings.delete(removedDoc); - let removedDocPresentId = StrCast(removedDoc.presentId); - - //Removing it from local mapping of the groups - if (this.groupMappings.has(removedDocPresentId)) { - let removedDocsGroup = this.groupMappings.get(removedDocPresentId); - if (removedDocsGroup) { - removedDocsGroup.splice(removedDocsGroup.indexOf(removedDoc), 1); - if (removedDocsGroup.length === 0) { - this.groupMappings.delete(removedDocPresentId); - } - } - } - - //removing it from the backUp of selected Buttons - // let castedList = Cast(this.presButtonBackUp.selectedButtonDocs, listSpec(Doc)); - // if (castedList) { - // castedList.forEach(async (doc, indexOfDoc) => { - // let curDoc = await doc; - // let curDocId = StrCast(curDoc.docId); - // if (curDocId === removedDoc[Id]) { - // if (castedList) { - // castedList.splice(indexOfDoc, 1); - // return; - // } - // } - // }); - - // } - //removing it from the backUp of selected Buttons - - let castedList = Cast(this.presButtonBackUp.selectedButtonDocs, listSpec(Doc)); - if (castedList) { - for (let doc of castedList) { - let curDoc = await doc; - let curDocId = StrCast(curDoc.docId); - if (curDocId === removedDoc[Id]) { - castedList.splice(castedList.indexOf(curDoc), 1); - break; - - } - } - } - - //removing it from the backup of groups - let castedGroupDocs = await DocListCastAsync(this.presGroupBackUp.groupDocs); - if (castedGroupDocs) { - castedGroupDocs.forEach(async (groupDoc: Doc, index: number) => { - let castedKey = StrCast(groupDoc.presentIdStore, null); - if (castedKey === removedDocPresentId) { - let castedGrouping = await DocListCastAsync(groupDoc.grouping); - if (castedGrouping) { - castedGrouping.splice(castedGrouping.indexOf(removedDoc), 1); - if (castedGrouping.length === 0) { - castedGroupDocs!.splice(castedGroupDocs!.indexOf(groupDoc), 1); - } - } - } - - }); - - } - - } } @@ -489,6 +339,7 @@ export class PresBox extends React.Component { //FieldViewProps? //it'll also execute the necessary actions if presentation is playing. @action public gotoDocument = async (index: number, fromDoc: number) => { + Doc.UnBrushAllDocs(); const list = FieldValue(Cast(this.curPresentation.data, listSpec(Doc))); if (!list) { return; @@ -509,26 +360,7 @@ export class PresBox extends React.Component { //FieldViewProps? this.hideIfNotPresented(index); this.showAfterPresented(index); } - } - - //Function that is called to resetGroupIds, so that documents get new groupIds at - //first load, when presentation is changed. - resetGroupIds = async () => { - let castedGroupDocs = await DocListCastAsync(this.presGroupBackUp.groupDocs); - if (castedGroupDocs !== undefined) { - castedGroupDocs.forEach(async (groupDoc: Doc, index: number) => { - let castedGrouping = await DocListCastAsync(groupDoc.grouping); - if (castedGrouping) { - castedGrouping.forEach((doc: Doc) => { - doc.presentId = Utils.GenerateGuid(); - }); - } - }); - } - runInAction(() => this.groupMappings = new Map()); - } - //Function that sets the store of the children docs. @action setChildrenDocs = (docList: Doc[]) => { @@ -580,21 +412,19 @@ export class PresBox extends React.Component { //FieldViewProps? //The function that starts the presentation, also checking if actions should be applied //directly at start. startPresentation = (startIndex: number) => { - let selectedButtons: boolean[]; this.presElementsMappings.forEach((component: PresentationElement, doc: Doc) => { - selectedButtons = component.selected; - if (selectedButtons[buttonIndex.HideTillPressed]) { + if (component.props.document.hideTillShownButton) { if (this.childrenDocs.indexOf(doc) > startIndex) { doc.opacity = 0; } } - if (selectedButtons[buttonIndex.HideAfter]) { + if (component.props.document.hideAfterButton) { if (this.childrenDocs.indexOf(doc) < startIndex) { doc.opacity = 0; } } - if (selectedButtons[buttonIndex.FadeAfter]) { + if (component.props.document.fadeButton) { if (this.childrenDocs.indexOf(doc) < startIndex) { doc.opacity = 0.5; } @@ -684,12 +514,9 @@ export class PresBox extends React.Component { //FieldViewProps? mainDocument={this.curPresentation} deleteDocument={this.RemoveDoc} gotoDocument={this.gotoDocument} - groupMappings={this.groupMappings} PresElementsMappings={this.presElementsMappings} setChildrenDocs={this.setChildrenDocs} presStatus={this.presStatus} - presButtonBackUp={this.presButtonBackUp} - presGroupBackUp={this.presGroupBackUp} removeDocByRef={this.removeDocByRef} clearElemMap={() => this.presElementsMappings.clear()} /> diff --git a/src/client/views/presentationview/PresentationElement.tsx b/src/client/views/presentationview/PresentationElement.tsx index 912970a50..68c5a5b8d 100644 --- a/src/client/views/presentationview/PresentationElement.tsx +++ b/src/client/views/presentationview/PresentationElement.tsx @@ -1,21 +1,19 @@ import { library } from '@fortawesome/fontawesome-svg-core'; import { faFile as fileRegular } from '@fortawesome/free-regular-svg-icons'; -import { faArrowUp, faFile as fileSolid, faFileDownload, faLocationArrow, faSearch, faArrowRight } from '@fortawesome/free-solid-svg-icons'; +import { faArrowRight, faArrowUp, faFile as fileSolid, faFileDownload, faLocationArrow, faSearch } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; -import { action, computed, observable, runInAction } from "mobx"; +import { action, computed } from "mobx"; import { observer } from "mobx-react"; import { Doc } from "../../../new_fields/Doc"; import { Id } from "../../../new_fields/FieldSymbols"; -import { List } from "../../../new_fields/List"; -import { listSpec } from "../../../new_fields/Schema"; -import { BoolCast, Cast, NumCast, StrCast } from "../../../new_fields/Types"; -import { Utils, returnFalse, emptyFunction, returnOne, returnEmptyString } from "../../../Utils"; +import { BoolCast, NumCast, StrCast } from "../../../new_fields/Types"; +import { emptyFunction, returnEmptyString, returnFalse, returnOne } from "../../../Utils"; +import { DocumentType } from "../../documents/DocumentTypes"; import { DragManager, dropActionType, SetupDrag } from "../../util/DragManager"; import { SelectionManager } from "../../util/SelectionManager"; -import { ContextMenu } from "../ContextMenu"; import { Transform } from "../../util/Transform"; +import { ContextMenu } from "../ContextMenu"; import { DocumentView } from "../nodes/DocumentView"; -import { DocumentType } from "../../documents/DocumentTypes"; import React = require("react"); @@ -33,26 +31,9 @@ interface PresentationElementProps { deleteDocument(index: number): void; gotoDocument(index: number, fromDoc: number): Promise; allListElements: Doc[]; - groupMappings: Map; presStatus: boolean; - presButtonBackUp: Doc; - presGroupBackUp: Doc; removeDocByRef(doc: Doc): boolean; PresElementsMappings: Map; - - -} - -//enum for the all kinds of buttons a doc in presentation can have -export enum buttonIndex { - Show = 0, - Navigate = 1, - HideTillPressed = 2, - FadeAfter = 3, - HideAfter = 4, - Group = 5, - OpenRight = 6 - } /** @@ -62,37 +43,33 @@ export enum buttonIndex { @observer export default class PresentationElement extends React.Component { - @observable private selectedButtons: boolean[]; private header?: HTMLDivElement | undefined; private listdropDisposer?: DragManager.DragDropDisposer; - private presElRef: React.RefObject; - private backUpDoc: Doc | undefined; - - - constructor(props: PresentationElementProps) { - super(props); - this.selectedButtons = new Array(7); - - this.presElRef = React.createRef(); - } - + private presElRef: React.RefObject = React.createRef(); componentWillUnmount() { this.listdropDisposer && this.listdropDisposer(); } + @computed get currentIndex() { return NumCast(this.props.mainDocument.selectedDoc); } - /** - * Getter to get the status of the buttons. - */ - @computed - get selected() { - return this.selectedButtons; - } + @computed get showButton() { return BoolCast(this.props.document.showButton); } + @computed get navButton() { return BoolCast(this.props.document.navButton); } + @computed get hideTillShownButton() { return BoolCast(this.props.document.hideTillShownButton); } + @computed get fadeButton() { return BoolCast(this.props.document.fadeButton); } + @computed get hideAfterButton() { return BoolCast(this.props.document.hideAfterButton); } + @computed get groupButton() { return BoolCast(this.props.document.groupButton); } + @computed get openRightButton() { return BoolCast(this.props.document.openRightButton); } + set showButton(val: boolean) { this.props.document.showButton = val; } + set navButton(val: boolean) { this.props.document.navButton = val; } + set hideTillShownButton(val: boolean) { this.props.document.hideTillShownButton = val; } + set fadeButton(val: boolean) { this.props.document.fadeButton = val; } + set hideAfterButton(val: boolean) { this.props.document.hideAfterButton = val; } + set groupButton(val: boolean) { this.props.document.groupButton = val; } + set openRightButton(val: boolean) { this.props.document.openRightButton = val; } //Lifecycle function that makes sure that button BackUp is received when mounted. async componentDidMount() { - this.receiveButtonBackUp(); if (this.presElRef.current) { this.header = this.presElRef.current; this.createListDropTarget(this.presElRef.current); @@ -107,156 +84,9 @@ export default class PresentationElement extends React.Component { - - //get the list that stores docs that keep track of buttons - let castedList = Cast(this.props.presButtonBackUp.selectedButtonDocs, listSpec(Doc)); - if (!castedList) { - this.props.presButtonBackUp.selectedButtonDocs = castedList = new List(); - } - - let foundDoc: boolean = false; - - //if this is the first time this doc mounts, push a doc for it to store - - for (let doc of castedList) { - let curDoc = await doc; - let curDocId = StrCast(curDoc.docId); - if (curDocId === this.props.document[Id]) { - let selectedButtonOfDoc = Cast(curDoc.selectedButtons, listSpec("boolean"), null); - if (selectedButtonOfDoc !== undefined) { - runInAction(() => this.selectedButtons = selectedButtonOfDoc); - foundDoc = true; - this.backUpDoc = curDoc; - break; - } - } - } - - if (!foundDoc) { - let newDoc = new Doc(); - let defaultBooleanArray: boolean[] = new Array(7); - newDoc.selectedButtons = new List(defaultBooleanArray); - newDoc.docId = this.props.document[Id]; - castedList.push(newDoc); - this.backUpDoc = newDoc; - } - - } - - /** - * The function that is called to group docs together. It tries to group a doc - * that turned grouping option with the above document. If that doc is grouped with - * other documents. Those other documents will be grouped with doc's above document as well. - */ @action - onGroupClick = (document: Doc, index: number, buttonStatus: boolean) => { - let p = this.props; - if (index >= 1) { - //checking if options was turned true - if (buttonStatus) { - //getting the id of the above-doc and the doc - let aboveGuid = StrCast(p.allListElements[index - 1].presentId, null); - let docGuid = StrCast(document.presentId, null); - //the case where above-doc is already in group - if (p.groupMappings.has(aboveGuid)) { - let aboveArray = p.groupMappings.get(aboveGuid)!; - //case where doc is already in group - if (p.groupMappings.has(docGuid)) { - let docsArray = p.groupMappings.get(docGuid)!; - docsArray.forEach((doc: Doc) => { - if (!aboveArray.includes(doc)) { - aboveArray.push(doc); - } - doc.presentId = aboveGuid; - }); - p.groupMappings.delete(docGuid); - //the case where doc was not in group - } else { - if (!aboveArray.includes(document)) { - aboveArray.push(document); - - } - - } - //the case where above-doc was not in group - } else { - let newAboveArray: Doc[] = []; - newAboveArray.push(p.allListElements[index - 1]); - - //the case where doc is in group - if (p.groupMappings.has(docGuid)) { - let docsArray = p.groupMappings.get(docGuid)!; - docsArray.forEach((doc: Doc) => { - newAboveArray.push(doc); - doc.presentId = aboveGuid; - }); - p.groupMappings.delete(docGuid); - - //the case where doc is not in a group - } else { - newAboveArray.push(document); - - } - p.groupMappings.set(aboveGuid, newAboveArray); - - } - document.presentId = aboveGuid; - - //when grouping is turned off - } else { - let curArray = p.groupMappings.get(StrCast(document.presentId, Utils.GenerateGuid()))!; - let targetIndex = curArray.indexOf(document); - let firstPart = curArray.slice(0, targetIndex); - let firstPartNewGuid = Utils.GenerateGuid(); - firstPart.forEach((doc: Doc) => doc.presentId = firstPartNewGuid); - let secondPart = curArray.slice(targetIndex); - p.groupMappings.set(StrCast(p.allListElements[index - 1].presentId, Utils.GenerateGuid()), firstPart); - p.groupMappings.set(StrCast(document.presentId, Utils.GenerateGuid()), secondPart); - - - } - - } - this.autoSaveGroupChanges(); - - } - - - /** - * This function is called at the end of each group update to update the group updates. - */ - @action - autoSaveGroupChanges = () => { - let castedList: List = new List(); - this.props.presGroupBackUp.groupDocs = castedList; - this.props.groupMappings.forEach((docArray: Doc[], id: String) => { - //create a new doc for each group - let newGroupDoc = new Doc(); - castedList.push(newGroupDoc); - //store the id of the group in the doc - newGroupDoc.presentIdStore = id.toString(); - //store the doc array which represents the group in the doc - newGroupDoc.grouping = new List(docArray); - }); - - } - - /** - * Function that is called on click to change the group status of a docus, by turning the option on/off. - */ - @action - changeGroupStatus = () => { - if (this.selectedButtons[buttonIndex.Group]) { - this.selectedButtons[buttonIndex.Group] = false; - } else { - this.selectedButtons[buttonIndex.Group] = true; - } - this.autoSaveButtonChange(buttonIndex.Group); - + onGroupClick = (e: React.MouseEvent) => { + this.groupButton = !this.groupButton; } /** @@ -266,31 +96,18 @@ export default class PresentationElement extends React.Component { e.stopPropagation(); - const current = NumCast(this.props.mainDocument.selectedDoc); - if (this.selectedButtons[buttonIndex.HideTillPressed]) { - this.selectedButtons[buttonIndex.HideTillPressed] = false; - if (this.props.index >= current) { + this.hideTillShownButton = !this.hideTillShownButton; + if (!this.hideTillShownButton) { + if (this.props.index >= this.currentIndex) { this.props.document.opacity = 1; } } else { - this.selectedButtons[buttonIndex.HideTillPressed] = true; if (this.props.presStatus) { - if (this.props.index > current) { + if (this.props.index > this.currentIndex) { this.props.document.opacity = 0; } } } - this.autoSaveButtonChange(buttonIndex.HideTillPressed); - } - - /** - * This function is called to get the updates for the changed buttons. - */ - @action - autoSaveButtonChange = async (index: buttonIndex) => { - if (this.backUpDoc) { - this.backUpDoc.selectedButtons = new List(this.selectedButtons); - } } /** @@ -301,25 +118,19 @@ export default class PresentationElement extends React.Component { e.stopPropagation(); - const current = NumCast(this.props.mainDocument.selectedDoc); - if (this.selectedButtons[buttonIndex.HideAfter]) { - this.selectedButtons[buttonIndex.HideAfter] = false; - if (this.props.index <= current) { + this.hideAfterButton = !this.hideAfterButton; + if (!this.hideAfterButton) { + if (this.props.index <= this.currentIndex) { this.props.document.opacity = 1; } } else { - if (this.selectedButtons[buttonIndex.FadeAfter]) { - this.selectedButtons[buttonIndex.FadeAfter] = false; - } - this.selectedButtons[buttonIndex.HideAfter] = true; + if (this.fadeButton) this.fadeButton = false; if (this.props.presStatus) { - if (this.props.index < current) { + if (this.props.index < this.currentIndex) { this.props.document.opacity = 0; } } } - this.autoSaveButtonChange(buttonIndex.HideAfter); - } /** @@ -330,25 +141,19 @@ export default class PresentationElement extends React.Component { e.stopPropagation(); - const current = NumCast(this.props.mainDocument.selectedDoc); - if (this.selectedButtons[buttonIndex.FadeAfter]) { - this.selectedButtons[buttonIndex.FadeAfter] = false; - if (this.props.index <= current) { + this.fadeButton = !this.fadeButton; + if (!this.fadeButton) { + if (this.props.index <= this.currentIndex) { this.props.document.opacity = 1; } } else { - if (this.selectedButtons[buttonIndex.HideAfter]) { - this.selectedButtons[buttonIndex.HideAfter] = false; - } - this.selectedButtons[buttonIndex.FadeAfter] = true; + this.hideAfterButton = false; if (this.props.presStatus) { - if (this.props.index < current) { + if (this.props.index < this.currentIndex) { this.props.document.opacity = 0.5; } } } - this.autoSaveButtonChange(buttonIndex.FadeAfter); - } /** @@ -357,22 +162,13 @@ export default class PresentationElement extends React.Component { e.stopPropagation(); - if (this.selectedButtons[buttonIndex.Navigate]) { - this.selectedButtons[buttonIndex.Navigate] = false; - - } else { - if (this.selectedButtons[buttonIndex.Show]) { - this.selectedButtons[buttonIndex.Show] = false; - } - this.selectedButtons[buttonIndex.Navigate] = true; - const current = NumCast(this.props.mainDocument.selectedDoc); - if (current === this.props.index) { + this.navButton = !this.navButton; + if (this.navButton) { + this.showButton = false; + if (this.currentIndex === this.props.index) { this.props.gotoDocument(this.props.index, this.props.index); } } - - this.autoSaveButtonChange(buttonIndex.Navigate); - } /** @@ -381,23 +177,16 @@ export default class PresentationElement extends React.Component { e.stopPropagation(); - if (this.selectedButtons[buttonIndex.Show]) { - this.selectedButtons[buttonIndex.Show] = false; - this.props.document.viewScale = 1; + this.showButton = !this.showButton; + if (!this.showButton) { + this.props.document.viewScale = 1; } else { - if (this.selectedButtons[buttonIndex.Navigate]) { - this.selectedButtons[buttonIndex.Navigate] = false; - } - this.selectedButtons[buttonIndex.Show] = true; - const current = NumCast(this.props.mainDocument.selectedDoc); - if (current === this.props.index) { + this.navButton = false; + if (this.currentIndex === this.props.index) { this.props.gotoDocument(this.props.index, this.props.index); } } - - this.autoSaveButtonChange(buttonIndex.Show); - } /** @@ -407,13 +196,8 @@ export default class PresentationElement extends React.Component { e.stopPropagation(); - if (this.selectedButtons[buttonIndex.OpenRight]) { - this.selectedButtons[buttonIndex.OpenRight] = false; - // action maybe - } else { - this.selectedButtons[buttonIndex.OpenRight] = true; - } - this.autoSaveButtonChange(buttonIndex.OpenRight); + + this.openRightButton = !this.openRightButton; } /** @@ -449,8 +233,6 @@ export default class PresentationElement extends React.Component Doc.AddDocToList(this.props.mainDocument, "data", d, this.props.document, before) || added, false) @@ -463,221 +245,13 @@ export default class PresentationElement extends React.Component { - - let x = this.ScreenToLocalListTransform(de.x, de.y); - let rect = this.header!.getBoundingClientRect(); - let bounds = this.ScreenToLocalListTransform(rect.left, rect.top + rect.height / 2); - let before = x[1] < bounds[1]; - - let droppedDocIndex = this.props.allListElements.indexOf(droppedDoc); - - let dropIndexDiff = droppedDocIndex - this.props.index; - - //checking if the position it's dropped corresponds to current location with 3 cases. - if (droppedDocIndex === this.props.index) { - return; - } - - if (dropIndexDiff === 1 && !before) { - return; - } - if (dropIndexDiff === -1 && before) { - return; - } - - let p = this.props; - let droppedDocSelectedButtons: boolean[] = await this.getSelectedButtonsOfDoc(droppedDoc); - let curDocGuid = StrCast(droppedDoc.presentId, null); - - //Splicing the doc from its current group, since it's moved - if (p.groupMappings.has(curDocGuid)) { - let groupArray = this.props.groupMappings.get(curDocGuid)!; - - if (droppedDocSelectedButtons[buttonIndex.Group]) { - let groupIndexOfDrop = groupArray.indexOf(droppedDoc); - let firstPart = groupArray.splice(0, groupIndexOfDrop); - - if (firstPart.length > 1) { - let newGroupGuid = Utils.GenerateGuid(); - firstPart.forEach((doc: Doc) => doc.presentId = newGroupGuid); - this.props.groupMappings.set(newGroupGuid, firstPart); - } - } - - groupArray.splice(groupArray.indexOf(droppedDoc), 1); - if (groupArray.length === 0) { - this.props.groupMappings.delete(curDocGuid); - } - droppedDoc.presentId = Utils.GenerateGuid(); - - //making sure to correct to groups after splicing, in case the dragged element - //had the grouping on. - let indexOfBelow = droppedDocIndex + 1; - if (indexOfBelow < this.props.allListElements.length && indexOfBelow > 1) { - let selectedButtonsOrigBelow: boolean[] = await this.getSelectedButtonsOfDoc(this.props.allListElements[indexOfBelow]); - let aboveBelowDoc: Doc = this.props.allListElements[droppedDocIndex - 1]; - let aboveBelowDocSelectedButtons: boolean[] = await this.getSelectedButtonsOfDoc(aboveBelowDoc); - let belowDoc: Doc = this.props.allListElements[indexOfBelow]; - let belowDocPresId = StrCast(belowDoc.presentId); - - if (selectedButtonsOrigBelow[buttonIndex.Group]) { - let belowDocGroup: Doc[] = this.props.groupMappings.get(belowDocPresId)!; - if (aboveBelowDocSelectedButtons[buttonIndex.Group]) { - let aboveBelowDocPresId = StrCast(aboveBelowDoc.presentId); - if (this.props.groupMappings.has(aboveBelowDocPresId)) { - let aboveBelowDocGroup: Doc[] = this.props.groupMappings.get(aboveBelowDocPresId)!; - aboveBelowDocGroup.push(...belowDocGroup); - this.props.groupMappings.delete(belowDocPresId); - belowDocGroup.forEach((doc: Doc) => doc.presentId = aboveBelowDocPresId); - - } - } else { - belowDocGroup.unshift(aboveBelowDoc); - aboveBelowDoc.presentId = belowDocPresId; - } - - - } - } - - } - - //Case, when the dropped doc had the group button clicked. - if (droppedDocSelectedButtons[buttonIndex.Group]) { - if (before) { - if (this.props.index > 0) { - let aboveDoc = this.props.allListElements[this.props.index - 1]; - let aboveDocGuid = StrCast(aboveDoc.presentId); - if (this.props.groupMappings.has(aboveDocGuid)) { - this.protectOrderAndPush(aboveDocGuid, aboveDoc, droppedDoc); - } else { - this.createNewGroup(aboveDoc, droppedDoc, aboveDocGuid); - } - } else { - let propsPresId = StrCast(this.props.document.presentId); - if (this.selectedButtons[buttonIndex.Group]) { - let propsArray = this.props.groupMappings.get(propsPresId)!; - propsArray.unshift(droppedDoc); - droppedDoc.presentId = propsPresId; - } - } - } else { - let propsDocGuid = StrCast(this.props.document.presentId); - if (this.props.groupMappings.has(propsDocGuid)) { - this.protectOrderAndPush(propsDocGuid, this.props.document, droppedDoc); - - } else { - this.createNewGroup(this.props.document, droppedDoc, propsDocGuid); - } - } - - - //if the group button of the element was not clicked. - } else { - if (before) { - if (this.props.index > 0) { - - let aboveDoc = this.props.allListElements[this.props.index - 1]; - let aboveDocGuid = StrCast(aboveDoc.presentId); - let aboveDocSelectedButtons: boolean[] = await this.getSelectedButtonsOfDoc(aboveDoc); - - - if (this.selectedButtons[buttonIndex.Group]) { - if (aboveDocSelectedButtons[buttonIndex.Group]) { - let aboveGroupArray = this.props.groupMappings.get(aboveDocGuid)!; - let propsDocPresId = StrCast(this.props.document.presentId); - - this.halveGroupArray(aboveDoc, aboveGroupArray, droppedDoc, propsDocPresId); - - } else { - let belowPresentId = StrCast(this.props.document.presentId); - let belowGroup = this.props.groupMappings.get(belowPresentId)!; - belowGroup.splice(belowGroup.indexOf(aboveDoc), 1); - belowGroup.unshift(droppedDoc); - droppedDoc.presentId = belowPresentId; - aboveDoc.presentId = Utils.GenerateGuid(); - } - - - } - } else { - let propsPresId = StrCast(this.props.document.presentId); - if (this.selectedButtons[buttonIndex.Group]) { - let propsArray = this.props.groupMappings.get(propsPresId)!; - propsArray.unshift(droppedDoc); - droppedDoc.presentId = propsPresId; - } - } - } else { - if (this.props.index < this.props.allListElements.length - 1) { - let belowDoc = this.props.allListElements[this.props.index + 1]; - let belowDocGuid = StrCast(belowDoc.presentId); - let belowDocSelectedButtons: boolean[] = await this.getSelectedButtonsOfDoc(belowDoc); - - let propsDocGuid = StrCast(this.props.document.presentId); - - if (belowDocSelectedButtons[buttonIndex.Group]) { - let belowGroupArray = this.props.groupMappings.get(belowDocGuid)!; - if (this.selectedButtons[buttonIndex.Group]) { - - let propsGroupArray = this.props.groupMappings.get(propsDocGuid)!; - - this.halveGroupArray(this.props.document, propsGroupArray, droppedDoc, belowDocGuid); - - } else { - belowGroupArray.splice(belowGroupArray.indexOf(this.props.document), 1); - this.props.document.presentId = Utils.GenerateGuid(); - belowGroupArray.unshift(droppedDoc); - droppedDoc.presentId = belowDocGuid; - } - } - - } - } - } - this.autoSaveGroupChanges(); - - } - - /** - * This method returns the selectedButtons boolean array of the passed in doc, - * retrieving it from the back-up. - */ - getSelectedButtonsOfDoc = async (paramDoc: Doc) => { - let castedList = Cast(this.props.presButtonBackUp.selectedButtonDocs, listSpec(Doc)); - let foundSelectedButtons: boolean[] = new Array(7); - - //if this is the first time this doc mounts, push a doc for it to store - for (let doc of castedList!) { - let curDoc = await doc; - let curDocId = StrCast(curDoc.docId); - if (curDocId === paramDoc[Id]) { - let selectedButtonOfDoc = Cast(curDoc.selectedButtons, listSpec("boolean"), null); - if (selectedButtonOfDoc !== undefined) { - return selectedButtonOfDoc; - } - } - } - - return foundSelectedButtons; - - } - //This is used to add dragging as an event. onPointerEnter = (e: React.PointerEvent): void => { if (e.buttons === 1 && SelectionManager.GetIsDragging()) { - let selected = NumCast(this.props.mainDocument.selectedDoc, 0); this.header!.className = "presentationView-item"; - - if (selected === this.props.index) { + if (this.currentIndex === this.props.index) { //this doc is selected this.header!.className = "presentationView-item presentationView-selected"; } @@ -688,12 +262,10 @@ export default class PresentationElement extends React.Component { //to get currently selected presentation doc - let selected = NumCast(this.props.mainDocument.selectedDoc, 0); this.header!.className = "presentationView-item"; - - if (selected === this.props.index) { + if (this.currentIndex === this.props.index) { //this doc is selected this.header!.className = "presentationView-item presentationView-selected"; @@ -729,62 +301,6 @@ export default class PresentationElement extends React.Component { return this.props.document !== target && this.props.removeDocByRef(doc) && addDoc(doc); } - - /** - * Helper method that gets called to divide a group array into two different groups - * including the targetDoc in first part. - * @param targetDoc document that is targeted as slicing point - * @param propsGroupArray the array that gets divided into 2 - * @param droppedDoc the dropped document - * @param belowDocGuid presentId of the belowGroup - */ - private halveGroupArray(targetDoc: Doc, propsGroupArray: Doc[], droppedDoc: Doc, belowDocGuid: string) { - let targetIndex = propsGroupArray.indexOf(targetDoc); - let firstPart = propsGroupArray.slice(0, targetIndex + 1); - let firstPartNewGuid = Utils.GenerateGuid(); - firstPart.forEach((doc: Doc) => doc.presentId = firstPartNewGuid); - let secondPart = propsGroupArray.slice(targetIndex + 1); - secondPart.unshift(droppedDoc); - droppedDoc.presentId = belowDocGuid; - this.props.groupMappings.set(firstPartNewGuid, firstPart); - this.props.groupMappings.set(belowDocGuid, secondPart); - } - - /** - * Helper method that creates a new group, pushing above document first, - * and dropped document second. - * @param aboveDoc the document above dropped document - * @param droppedDoc the dropped document itself - * @param aboveDocGuid above document's presentId - */ - private createNewGroup(aboveDoc: Doc, droppedDoc: Doc, aboveDocGuid: string) { - let newGroup: Doc[] = []; - newGroup.push(aboveDoc); - newGroup.push(droppedDoc); - droppedDoc.presentId = aboveDocGuid; - this.props.groupMappings.set(aboveDocGuid, newGroup); - } - - /** - * Helper method that finds the above document's group, and pushes the - * dropped document into that group, protecting the visual order of the - * presentation elements. - * @param aboveDoc the document above dropped document - * @param droppedDoc the dropped document itself - * @param aboveDocGuid above document's presentId - */ - private protectOrderAndPush(aboveDocGuid: string, aboveDoc: Doc, droppedDoc: Doc) { - let groupArray = this.props.groupMappings.get(aboveDocGuid)!; - let tempStack: Doc[] = []; - while (groupArray[groupArray.length - 1] !== aboveDoc) { - tempStack.push(groupArray.pop()!); - } - groupArray.push(droppedDoc); - droppedDoc.presentId = aboveDocGuid; - while (tempStack.length !== 0) { - groupArray.push(tempStack.pop()!); - } - } /** * This function is a getter to get if a document is in previewMode. */ @@ -872,11 +388,8 @@ export default class PresentationElement extends React.Component { p.gotoDocument(p.index, NumCast(this.props.mainDocument.selectedDoc)); e.stopPropagation(); }}> + onClick={e => { p.gotoDocument(p.index, this.currentIndex); e.stopPropagation(); }}> {`${p.index + 1}. ${title}`}

    - - - - - - - + + + + + + +
    {this.renderEmbeddedInline()} diff --git a/src/client/views/presentationview/PresentationList.tsx b/src/client/views/presentationview/PresentationList.tsx index 288ade042..930ce202e 100644 --- a/src/client/views/presentationview/PresentationList.tsx +++ b/src/client/views/presentationview/PresentationList.tsx @@ -1,24 +1,20 @@ -import { observer } from "mobx-react"; -import React = require("react"); import { action } from "mobx"; -import "./PresentationView.scss"; -import { Utils } from "../../../Utils"; -import { Doc, DocListCast, DocListCastAsync } from "../../../new_fields/Doc"; -import { NumCast, StrCast } from "../../../new_fields/Types"; +import { observer } from "mobx-react"; +import { Doc, DocListCast } from "../../../new_fields/Doc"; import { Id } from "../../../new_fields/FieldSymbols"; +import { NumCast } from "../../../new_fields/Types"; import PresentationElement from "./PresentationElement"; +import "./PresentationView.scss"; +import React = require("react"); interface PresListProps { mainDocument: Doc; deleteDocument(index: number): void; gotoDocument(index: number, fromDoc: number): Promise; - groupMappings: Map; PresElementsMappings: Map; setChildrenDocs: (docList: Doc[]) => void; presStatus: boolean; - presButtonBackUp: Doc; - presGroupBackUp: Doc; removeDocByRef(doc: Doc): boolean; clearElemMap(): void; @@ -31,35 +27,6 @@ interface PresListProps { */ export default class PresentationViewList extends React.Component { - /** - * Method that initializes presentation ids for the - * docs that is in the presentation, when presentation list - * gets re-rendered. It makes sure to not assign ids to the - * docs that are in the group, so that mapping won't be disrupted. - */ - - @action - initializeGroupIds = async (docList: Doc[]) => { - docList.forEach(async (doc: Doc, index: number) => { - let docGuid = StrCast(doc.presentId, null); - //checking if part of group - let storedGuids: string[] = []; - let castedGroupDocs = await DocListCastAsync(this.props.presGroupBackUp.groupDocs); - //making sure the docs that were in groups, which were stored, to not get new guids. - if (castedGroupDocs !== undefined) { - castedGroupDocs.forEach((doc: Doc) => { - let storedGuid = StrCast(doc.presentIdStore, null); - if (storedGuid) { - storedGuids.push(storedGuid); - } - - }); - } - if (!this.props.groupMappings.has(docGuid) && !storedGuids.includes(docGuid)) { - doc.presentId = Utils.GenerateGuid(); - } - }); - } /** * Initially every document starts with a viewScale 1, which means @@ -77,7 +44,6 @@ export default class PresentationViewList extends React.Component render() { const children = DocListCast(this.props.mainDocument.data); - this.initializeGroupIds(children); this.initializeScaleViews(children); this.props.setChildrenDocs(children); this.props.clearElemMap(); @@ -96,11 +62,8 @@ export default class PresentationViewList extends React.Component index={index} deleteDocument={this.props.deleteDocument} gotoDocument={this.props.gotoDocument} - groupMappings={this.props.groupMappings} allListElements={children} presStatus={this.props.presStatus} - presButtonBackUp={this.props.presButtonBackUp} - presGroupBackUp={this.props.presGroupBackUp} removeDocByRef={this.props.removeDocByRef} PresElementsMappings={this.props.PresElementsMappings} /> diff --git a/src/client/views/presentationview/PresentationView.scss b/src/client/views/presentationview/PresentationView.scss index b0968132b..bc1899811 100644 --- a/src/client/views/presentationview/PresentationView.scss +++ b/src/client/views/presentationview/PresentationView.scss @@ -1,6 +1,5 @@ .presentationView-cont { position: absolute; - background: white; z-index: 2; box-shadow: #AAAAAA .2vw .2vw .4vw; right: 0; @@ -49,12 +48,15 @@ .presentationView-item:hover { transition: all .1s; - background: #AAAAAA + background: #AAAAAA; + border-radius: 12px; } .presentationView-selected { background: gray; color: black; + border-radius: 12px; + box-shadow: black 2px 2px 5px; } .presentationView-heading { @@ -79,11 +81,12 @@ } .presentation-interaction { + color: gray; float: left; } .presentation-interaction-selected { - background: #505050; + color: white; float: left; } @@ -96,6 +99,7 @@ margin-right: 2.5%; margin-left: 2.5%; width: 20%; + border-radius: 5px; } .presentation-buttons { diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index ca05dfa45..e5b609966 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -621,6 +621,9 @@ export namespace Doc { manager.BrushedDoc.delete(doc); manager.BrushedDoc.delete(Doc.GetDataDoc(doc)); } + export function UnBrushAllDocs() { + manager.BrushedDoc.clear(); + } } Scripting.addGlobal(function renameAlias(doc: any, n: any) { return StrCast(doc.title).replace(/\([0-9]*\)/, "") + `(${n})`; }); Scripting.addGlobal(function getProto(doc: any) { return Doc.GetProto(doc); }); \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 43d731ef2a6b2bd3fcdb7dd26fb6a8beac8e1306 Mon Sep 17 00:00:00 2001 From: bob Date: Wed, 21 Aug 2019 16:23:38 -0400 Subject: from last with presentations and small tweaks. --- src/client/views/MetadataEntryMenu.tsx | 2 +- src/client/views/collections/CollectionStackingView.tsx | 4 ++-- src/client/views/collections/CollectionStackingViewFieldColumn.tsx | 4 ++-- src/client/views/nodes/KeyValueBox.tsx | 2 +- src/client/views/nodes/PresBox.tsx | 7 ++++--- src/client/views/presentationview/PresentationElement.tsx | 2 -- src/client/views/presentationview/PresentationView.scss | 4 ---- src/server/authentication/models/current_user_utils.ts | 2 +- 8 files changed, 11 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/client/views/MetadataEntryMenu.tsx b/src/client/views/MetadataEntryMenu.tsx index 4d696e37a..ec628c5a3 100644 --- a/src/client/views/MetadataEntryMenu.tsx +++ b/src/client/views/MetadataEntryMenu.tsx @@ -172,7 +172,7 @@ export class MetadataEntryMenu extends React.Component{
      - {this._allSuggestions.sort().map(s =>
    • { this._currentKey = s; this.previewValue(); })} >{s}
    • )} + {this._allSuggestions.slice().sort().map(s =>
    • { this._currentKey = s; this.previewValue(); })} >{s}
    • )}
    diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index c74c60d8f..be6ee1756 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -291,10 +291,10 @@ export class CollectionStackingView extends CollectionSubView(doc => doc) { let layoutDoc = Doc.expandTemplateLayout(d, this.props.DataDoc); let width = () => (d.nativeWidth && !d.ignoreAspect && !this.props.Document.fillColumn ? Math.min(d[WidthSym](), this.columnWidth) : this.columnWidth);/// (uniqueHeadings.length + 1); let height = () => this.getDocHeight(layoutDoc); - let dxf = () => this.getDocTransform(layoutDoc, dref.current!); + let dxf = () => this.getDocTransform(layoutDoc!, dref.current!); let rowSpan = Math.ceil((height() + this.gridGap) / this.gridGap); this._docXfs.push({ dxf: dxf, width: width, height: height }); - return
    + return !layoutDoc ? (null) :
    {this.getDisplayDoc(layoutDoc, d, dxf, width)}
    ; }); diff --git a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx index cc8476548..2536eff00 100644 --- a/src/client/views/collections/CollectionStackingViewFieldColumn.tsx +++ b/src/client/views/collections/CollectionStackingViewFieldColumn.tsx @@ -83,9 +83,9 @@ export class CollectionStackingViewFieldColumn extends React.Component Math.min(d.nativeWidth && !d.ignoreAspect && !parent.props.Document.fillColumn ? d[WidthSym]() : Number.MAX_VALUE, parent.columnWidth / parent.numGroupColumns); - let height = () => parent.getDocHeight(pair!.layout); + let height = () => parent.getDocHeight(pair.layout); let dref = React.createRef(); - let dxf = () => this.getDocTransform(pair!.layout, dref.current!); + let dxf = () => this.getDocTransform(pair.layout!, dref.current!); this.props.parent._docXfs.push({ dxf: dxf, width: width, height: height }); let rowSpan = Math.ceil((height() + parent.gridGap) / parent.gridGap); let style = parent.isStackingView ? { width: width(), margin: "auto", marginTop: i === 0 ? 0 : parent.gridGap, height: height() } : { gridRowEnd: `span ${rowSpan}` }; diff --git a/src/client/views/nodes/KeyValueBox.tsx b/src/client/views/nodes/KeyValueBox.tsx index 0d4b377dd..653c5c27f 100644 --- a/src/client/views/nodes/KeyValueBox.tsx +++ b/src/client/views/nodes/KeyValueBox.tsx @@ -128,7 +128,7 @@ export class KeyValueBox extends React.Component { let rows: JSX.Element[] = []; let i = 0; const self = this; - for (let key of Object.keys(ids).sort()) { + for (let key of Object.keys(ids).slice().sort()) { rows.push( { diff --git a/src/client/views/nodes/PresBox.tsx b/src/client/views/nodes/PresBox.tsx index cf222601f..e376fbddb 100644 --- a/src/client/views/nodes/PresBox.tsx +++ b/src/client/views/nodes/PresBox.tsx @@ -116,9 +116,9 @@ export class PresBox extends React.Component { //FieldViewProps? let presDocs = DocListCast(this.curPresentation.data); for (; nextSelected < presDocs.length - 1; nextSelected++) { - if (!this.presElementsMappings.get(presDocs[nextSelected + 1])!.props.document.groupButton) + if (!this.presElementsMappings.get(presDocs[nextSelected + 1])!.props.document.groupButton) { break; - + } } this.gotoDocument(nextSelected, current); @@ -239,8 +239,9 @@ export class PresBox extends React.Component { //FieldViewProps? let nextSelected = presDocs.indexOf(curDoc); let currentDocGroups: Doc[] = []; for (; nextSelected < presDocs.length - 1; nextSelected++) { - if (!this.presElementsMappings.get(presDocs[nextSelected + 1])!.props.document.groupButton) + if (!this.presElementsMappings.get(presDocs[nextSelected + 1])!.props.document.groupButton) { break; + } currentDocGroups.push(presDocs[nextSelected]); } diff --git a/src/client/views/presentationview/PresentationElement.tsx b/src/client/views/presentationview/PresentationElement.tsx index 68c5a5b8d..83413814f 100644 --- a/src/client/views/presentationview/PresentationElement.tsx +++ b/src/client/views/presentationview/PresentationElement.tsx @@ -261,8 +261,6 @@ export default class PresentationElement extends React.Component { - //to get currently selected presentation doc - this.header!.className = "presentationView-item"; if (this.currentIndex === this.props.index) { diff --git a/src/client/views/presentationview/PresentationView.scss b/src/client/views/presentationview/PresentationView.scss index bc1899811..5c40a8808 100644 --- a/src/client/views/presentationview/PresentationView.scss +++ b/src/client/views/presentationview/PresentationView.scss @@ -23,14 +23,11 @@ user-select: none; transition: all .1s; - - .documentView-node { position: absolute; z-index: 1; } - } .presentationView-item-above { @@ -73,7 +70,6 @@ display: inline-block; width: calc(100% - 200px); letter-spacing: 2px; - } .presentation-icon { diff --git a/src/server/authentication/models/current_user_utils.ts b/src/server/authentication/models/current_user_utils.ts index aa3da0034..f7ce24967 100644 --- a/src/server/authentication/models/current_user_utils.ts +++ b/src/server/authentication/models/current_user_utils.ts @@ -29,7 +29,7 @@ export class CurrentUserUtils { doc.viewType = CollectionViewType.Tree; doc.dropAction = "alias"; doc.layout = CollectionView.LayoutString(); - doc.title = Doc.CurrentUserEmail + doc.title = Doc.CurrentUserEmail; this.updateUserDocument(doc); doc.data = new List(); doc.gridGap = 5; -- cgit v1.2.3-70-g09d2