aboutsummaryrefslogtreecommitdiff
path: root/src/client/views
diff options
context:
space:
mode:
Diffstat (limited to 'src/client/views')
-rw-r--r--src/client/views/DocComponent.tsx14
-rw-r--r--src/client/views/DocumentDecorations.scss31
-rw-r--r--src/client/views/DocumentDecorations.tsx209
-rw-r--r--src/client/views/EditableView.tsx2
-rw-r--r--src/client/views/InkingCanvas.tsx56
-rw-r--r--src/client/views/InkingControl.tsx7
-rw-r--r--src/client/views/InkingStroke.scss3
-rw-r--r--src/client/views/InkingStroke.tsx10
-rw-r--r--src/client/views/Main.tsx185
-rw-r--r--src/client/views/MainOverlayTextBox.tsx17
-rw-r--r--src/client/views/PresentationView.tsx117
-rw-r--r--src/client/views/TemplateMenu.tsx16
-rw-r--r--src/client/views/Templates.tsx24
-rw-r--r--src/client/views/collections/CollectionBaseView.tsx105
-rw-r--r--src/client/views/collections/CollectionDockingView.tsx150
-rw-r--r--src/client/views/collections/CollectionPDFView.tsx21
-rw-r--r--src/client/views/collections/CollectionSchemaView.tsx169
-rw-r--r--src/client/views/collections/CollectionSubView.tsx343
-rw-r--r--src/client/views/collections/CollectionTreeView.scss10
-rw-r--r--src/client/views/collections/CollectionTreeView.tsx124
-rw-r--r--src/client/views/collections/CollectionVideoView.tsx94
-rw-r--r--src/client/views/collections/CollectionView.tsx15
-rw-r--r--src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx36
-rw-r--r--src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx70
-rw-r--r--src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx1
-rw-r--r--src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx201
-rw-r--r--src/client/views/collections/collectionFreeForm/MarqueeView.tsx99
-rw-r--r--src/client/views/nodes/AudioBox.tsx27
-rw-r--r--src/client/views/nodes/CollectionFreeFormDocumentView.tsx178
-rw-r--r--src/client/views/nodes/DocumentContentsView.tsx64
-rw-r--r--src/client/views/nodes/DocumentView.tsx216
-rw-r--r--src/client/views/nodes/FieldView.tsx68
-rw-r--r--src/client/views/nodes/FormattedTextBox.scss6
-rw-r--r--src/client/views/nodes/FormattedTextBox.tsx107
-rw-r--r--src/client/views/nodes/IconBox.scss12
-rw-r--r--src/client/views/nodes/IconBox.tsx40
-rw-r--r--src/client/views/nodes/ImageBox.scss2
-rw-r--r--src/client/views/nodes/ImageBox.tsx75
-rw-r--r--src/client/views/nodes/KeyValueBox.tsx37
-rw-r--r--src/client/views/nodes/KeyValuePair.tsx59
-rw-r--r--src/client/views/nodes/LinkBox.tsx84
-rw-r--r--src/client/views/nodes/LinkEditor.tsx16
-rw-r--r--src/client/views/nodes/LinkMenu.tsx27
-rw-r--r--src/client/views/nodes/PDFBox.tsx60
-rw-r--r--src/client/views/nodes/VideoBox.tsx69
-rw-r--r--src/client/views/nodes/WebBox.tsx23
46 files changed, 1657 insertions, 1642 deletions
diff --git a/src/client/views/DocComponent.tsx b/src/client/views/DocComponent.tsx
new file mode 100644
index 000000000..d6562492f
--- /dev/null
+++ b/src/client/views/DocComponent.tsx
@@ -0,0 +1,14 @@
+import * as React from 'react';
+import { Doc } from '../../new_fields/Doc';
+import { computed } from 'mobx';
+
+export function DocComponent<P extends { Document: Doc }, T>(schemaCtor: (doc: Doc) => T) {
+ class Component extends React.Component<P> {
+ //TODO This might be pretty inefficient if doc isn't observed, because computed doesn't cache then
+ @computed
+ get Document(): T {
+ return schemaCtor(this.props.Document);
+ }
+ }
+ return Component;
+} \ No newline at end of file
diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss
index ecddb8b06..158b02b5a 100644
--- a/src/client/views/DocumentDecorations.scss
+++ b/src/client/views/DocumentDecorations.scss
@@ -105,37 +105,6 @@ $linkGap : 3px;
opacity: 0.1;
}
-// position: absolute;
-// display: grid;
-// z-index: 1000;
-// grid-template-rows: 20px 1fr 20px 0px;
-// grid-template-columns: 20px 1fr 20px;
-// pointer-events: none;
-// #documentDecorations-centerCont {
-// background: none;
-// }
-// .documentDecorations-resizer {
-// pointer-events: auto;
-// background: lightblue;
-// opacity: 0.4;
-// }
-// #documentDecorations-topLeftResizer,
-// #documentDecorations-bottomRightResizer {
-// cursor: nwse-resize;
-// }
-// #documentDecorations-topRightResizer,
-// #documentDecorations-bottomLeftResizer {
-// cursor: nesw-resize;
-// }
-// #documentDecorations-topResizer,
-// #documentDecorations-bottomResizer {
-// cursor: ns-resize;
-// }
-// #documentDecorations-leftResizer,
-// #documentDecorations-rightResizer {
-// cursor: ew-resize;
-// }
-// }
.linkFlyout {
grid-column: 2/4;
margin-top: $linkGap;
diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx
index cc5b754f0..693d6ec55 100644
--- a/src/client/views/DocumentDecorations.tsx
+++ b/src/client/views/DocumentDecorations.tsx
@@ -1,32 +1,34 @@
import { action, computed, observable, runInAction, untracked, reaction } from "mobx";
import { observer } from "mobx-react";
-import { Key } from "../../fields/Key";
-import { KeyStore } from "../../fields/KeyStore";
-import { ListField } from "../../fields/ListField";
-import { NumberField } from "../../fields/NumberField";
-import { TextField } from "../../fields/TextField";
-import { Document } from "../../fields/Document";
import { emptyFunction, Utils } from "../../Utils";
import { DragLinksAsDocuments, DragManager } from "../util/DragManager";
import { SelectionManager } from "../util/SelectionManager";
import { undoBatch } from "../util/UndoManager";
import './DocumentDecorations.scss';
import { MainOverlayTextBox } from "./MainOverlayTextBox";
-import { DocumentView } from "./nodes/DocumentView";
+import { DocumentView, PositionDocument } from "./nodes/DocumentView";
import { LinkMenu } from "./nodes/LinkMenu";
import { TemplateMenu } from "./TemplateMenu";
import React = require("react");
import { Template, Templates } from "./Templates";
import { CompileScript } from "../util/Scripting";
import { IconBox } from "./nodes/IconBox";
-import { FieldValue, Field } from "../../fields/Field";
-import { Documents } from "../documents/Documents";
+import { Cast, FieldValue, NumCast, StrCast } from "../../new_fields/Types";
+import { Doc, FieldResult } from "../../new_fields/Doc";
+import { listSpec } from "../../new_fields/Schema";
+import { Docs } from "../documents/Documents";
+import { List } from "../../new_fields/List";
const higflyout = require("@hig/flyout");
export const { anchorPoints } = higflyout;
export const Flyout = higflyout.default;
import { faLink } from '@fortawesome/free-solid-svg-icons';
import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { MINIMIZED_ICON_SIZE } from "../views/globalCssVariables.scss";
+import { CollectionFreeFormView } from "./collections/collectionFreeForm/CollectionFreeFormView";
+import { CollectionView } from "./collections/CollectionView";
+import { createCipher } from "crypto";
+import { FieldView } from "./nodes/FieldView";
library.add(faLink);
@@ -43,44 +45,44 @@ export class DocumentDecorations extends React.Component<{}, { value: string }>
private _linkerButton = React.createRef<HTMLDivElement>();
private _downX = 0;
private _downY = 0;
+ private _iconDoc?: Doc = undefined;
@observable private _minimizedX = 0;
@observable private _minimizedY = 0;
@observable private _title: string = "";
@observable private _edtingTitle = false;
- @observable private _fieldKey: Key = KeyStore.Title;
+ @observable private _fieldKey = "title";
@observable private _hidden = false;
@observable private _opacity = 1;
- @observable private _iconifying = false;
+ @observable private _removeIcon = false;
@observable public Interacting = false;
constructor(props: Readonly<{}>) {
super(props);
DocumentDecorations.Instance = this;
this.keyinput = React.createRef();
- reaction(() => SelectionManager.SelectedDocuments().slice(), (docs) => docs.length === 0 && (this._edtingTitle = false));
+ reaction(() => SelectionManager.SelectedDocuments().slice(), docs => this._edtingTitle = false);
}
- @action titleChanged = (event: any) => { this._title = event.target.value; }
- @action titleBlur = () => { this._edtingTitle = false; }
+ @action titleChanged = (event: any) => { this._title = event.target.value; };
+ @action titleBlur = () => { this._edtingTitle = false; };
@action titleEntered = (e: any) => {
var key = e.keyCode || e.which;
// enter pressed
if (key === 13) {
var text = e.target.value;
if (text[0] === '#') {
- let command = text.slice(1, text.length);
- this._fieldKey = new Key(command);
+ this._fieldKey = text.slice(1, text.length);
this._title = this.selectionTitle;
}
else {
if (SelectionManager.SelectedDocuments().length > 0) {
- let field = SelectionManager.SelectedDocuments()[0].props.Document.Get(this._fieldKey);
- if (field instanceof NumberField) {
+ let field = SelectionManager.SelectedDocuments()[0].props.Document[this._fieldKey];
+ if (typeof field === "number") {
SelectionManager.SelectedDocuments().forEach(d =>
- d.props.Document.SetNumber(this._fieldKey, +this._title));
- } else if (field instanceof TextField || true) {
+ d.props.Document[this._fieldKey] = +this._title);
+ } else {
SelectionManager.SelectedDocuments().forEach(d =>
- d.props.Document.SetText(this._fieldKey, this._title));
+ d.props.Document[this._fieldKey] = this._title);
}
}
}
@@ -147,7 +149,6 @@ export class DocumentDecorations extends React.Component<{}, { value: string }>
let dragData = new DragManager.DocumentDragData(SelectionManager.SelectedDocuments().map(dv => dv.props.Document));
dragData.xOffset = xoff;
dragData.yOffset = yoff;
- dragData.aliasOnDrop = false;
dragData.moveDocument = SelectionManager.SelectedDocuments()[0].props.moveDocument;
this.Interacting = true;
this._hidden = true;
@@ -198,9 +199,11 @@ export class DocumentDecorations extends React.Component<{}, { value: string }>
@action
onMinimizeDown = (e: React.PointerEvent): void => {
e.stopPropagation();
+ this._iconDoc = undefined;
if (e.button === 0) {
this._downX = e.pageX;
this._downY = e.pageY;
+ this._removeIcon = false;
let selDoc = SelectionManager.SelectedDocuments()[0];
let selDocPos = selDoc.props.ScreenToLocalTransform().scale(selDoc.props.ContentScaling()).inverse().transformPoint(0, 0);
this._minimizedX = selDocPos[0] + 12;
@@ -223,41 +226,15 @@ export class DocumentDecorations extends React.Component<{}, { value: string }>
this._minimizedX = snapped ? selDocPos[0] + 4 : e.clientX;
this._minimizedY = snapped ? selDocPos[1] - 18 : e.clientY;
let selectedDocs = SelectionManager.SelectedDocuments().map(sd => sd);
- Promise.all(selectedDocs.map(async selDoc => await this.getIconDoc(selDoc))).then(minDocSet =>
- this.moveIconDocs(SelectionManager.SelectedDocuments())
- );
- this._iconifying = snapped;
- }
- }
-
- @action createIcon = (docView: DocumentView, layoutString: string): Document => {
- let doc = docView.props.Document;
- let iconDoc = Documents.IconDocument(layoutString);
- iconDoc.SetText(KeyStore.Title, "ICON" + doc.Title)
- iconDoc.SetBoolean(KeyStore.IsMinimized, false);
- iconDoc.SetNumber(KeyStore.NativeWidth, 0);
- iconDoc.SetNumber(KeyStore.NativeHeight, 0);
- iconDoc.SetNumber(KeyStore.X, doc.GetNumber(KeyStore.X, 0));
- iconDoc.SetNumber(KeyStore.Y, doc.GetNumber(KeyStore.Y, 0) - 24);
- iconDoc.Set(KeyStore.Prototype, doc);
- iconDoc.Set(KeyStore.MaximizedDoc, doc);
- doc.Set(KeyStore.MinimizedDoc, iconDoc);
- docView.props.addDocument && docView.props.addDocument(iconDoc, false);
- return iconDoc;
- }
- @action
- public getIconDoc = async (docView: DocumentView): Promise<Document | undefined> => {
- let doc = docView.props.Document;
- let iconDoc = await doc.GetTAsync(KeyStore.MinimizedDoc, Document).then(async mindoc =>
- mindoc ? mindoc :
- await doc.GetTAsync(KeyStore.BackgroundLayout, TextField).then(async field =>
- (field instanceof TextField) ? this.createIcon(docView, field.Data) :
- await doc.GetTAsync(KeyStore.Layout, TextField).then(field =>
- (field instanceof TextField) ? this.createIcon(docView, field.Data) : undefined)));
- if (SelectionManager.SelectedDocuments()[0].props.addDocument !== undefined)
- SelectionManager.SelectedDocuments()[0].props.addDocument!(iconDoc!);
- return iconDoc;
+ if (selectedDocs.length > 1) {
+ this._iconDoc = this._iconDoc ? this._iconDoc : this.createIcon(SelectionManager.SelectedDocuments(), CollectionView.LayoutString());
+ this.moveIconDoc(this._iconDoc);
+ } else {
+ this.getIconDoc(selectedDocs[0]).then(icon => icon && this.moveIconDoc(this._iconDoc = icon));
+ }
+ this._removeIcon = snapped;
+ }
}
@action
onMinimizeUp = (e: PointerEvent): void => {
@@ -266,34 +243,52 @@ export class DocumentDecorations extends React.Component<{}, { value: string }>
document.removeEventListener("pointermove", this.onMinimizeMove);
document.removeEventListener("pointerup", this.onMinimizeUp);
let selectedDocs = SelectionManager.SelectedDocuments().map(sd => sd);
- Promise.all(selectedDocs.map(async selDoc => await this.getIconDoc(selDoc))).then(minDocSet => {
- let minDocs = minDocSet.filter(minDoc => minDoc instanceof Document).map(minDoc => minDoc as Document);
- minDocs.map(minDoc => {
- minDoc.SetNumber(KeyStore.X, minDocs[0].GetNumber(KeyStore.X, 0));
- minDoc.SetNumber(KeyStore.Y, minDocs[0].GetNumber(KeyStore.Y, 0));
- minDoc.SetData(KeyStore.LinkTags, minDocs, ListField);
- if (this._iconifying && selectedDocs[0].props.removeDocument) {
- selectedDocs[0].props.removeDocument(minDoc);
- (minDoc.Get(KeyStore.MaximizedDoc, false) as Document)!.Set(KeyStore.MinimizedDoc, undefined);
- }
- });
- runInAction(() => this._minimizedX = this._minimizedY = 0);
- if (!this._iconifying) selectedDocs[0].props.toggleMinimized();
- this._iconifying = false;
- });
+ if (this._iconDoc && selectedDocs.length === 1 && this._removeIcon) {
+ selectedDocs[0].props.removeDocument && selectedDocs[0].props.removeDocument(this._iconDoc);
+ }
+ !this._removeIcon && selectedDocs.length === 1 && this.getIconDoc(selectedDocs[0]).then(icon => selectedDocs[0].props.toggleMinimized());
+ this._removeIcon = false;
}
+ runInAction(() => this._minimizedX = this._minimizedY = 0);
}
- moveIconDocs(selViews: DocumentView[], minDocSet?: FieldValue<Field>[]) {
- selViews.map(selDoc => {
- let minDoc = selDoc.props.Document.Get(KeyStore.MinimizedDoc);
- if (minDoc instanceof Document) {
- let zoom = selDoc.props.Document.GetNumber(KeyStore.ZoomBasis, 1);
- let where = (selDoc.props.ScreenToLocalTransform()).scale(selDoc.props.ContentScaling()).scale(1 / zoom).
- transformPoint(this._minimizedX - 12, this._minimizedY - 12);
- minDoc.SetNumber(KeyStore.X, where[0] + selDoc.props.Document.GetNumber(KeyStore.X, 0));
- minDoc.SetNumber(KeyStore.Y, where[1] + selDoc.props.Document.GetNumber(KeyStore.Y, 0));
- }
- });
+
+ @action createIcon = (selected: DocumentView[], layoutString: string): Doc => {
+ let doc = selected[0].props.Document;
+ let iconDoc = Docs.IconDocument(layoutString);
+ iconDoc.isButton = true;
+ iconDoc.title = selected.length > 1 ? "ICONset" : "ICON" + StrCast(doc.title);
+ iconDoc.labelField = this._fieldKey;
+ iconDoc[this._fieldKey] = selected.length > 1 ? "collection" : undefined;
+ iconDoc.isMinimized = false;
+ iconDoc.width = Number(MINIMIZED_ICON_SIZE);
+ iconDoc.height = Number(MINIMIZED_ICON_SIZE);
+ iconDoc.x = NumCast(doc.x);
+ iconDoc.y = NumCast(doc.y) - 24;
+ iconDoc.maximizedDocs = new List<Doc>(selected.map(s => s.props.Document));
+ doc.minimizedDoc = iconDoc;
+ selected[0].props.addDocument && selected[0].props.addDocument(iconDoc, false);
+ return iconDoc;
+ }
+ @action
+ public getIconDoc = async (docView: DocumentView): Promise<Doc | undefined> => {
+ let doc = docView.props.Document;
+ let iconDoc: Doc | undefined = await Cast(doc.minimizedDoc, Doc);
+ if (!iconDoc) {
+ const layout = StrCast(doc.backgroundLayout, StrCast(doc.layout, FieldView.LayoutString(DocumentView)));
+ iconDoc = this.createIcon([docView], layout);
+ }
+ if (SelectionManager.SelectedDocuments()[0].props.addDocument !== undefined) {
+ SelectionManager.SelectedDocuments()[0].props.addDocument!(iconDoc!);
+ }
+ return iconDoc;
+ }
+ moveIconDoc(iconDoc: Doc) {
+ let selView = SelectionManager.SelectedDocuments()[0];
+ let zoom = NumCast(selView.props.Document.zoomBasis, 1);
+ let where = (selView.props.ScreenToLocalTransform()).scale(selView.props.ContentScaling()).scale(1 / zoom).
+ transformPoint(this._minimizedX - 12, this._minimizedY - 12);
+ iconDoc.x = where[0] + NumCast(selView.props.Document.x);
+ iconDoc.y = where[1] + NumCast(selView.props.Document.y);
}
@action
@@ -328,7 +323,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }>
document.removeEventListener("pointermove", this.onLinkerButtonMoved);
document.removeEventListener("pointerup", this.onLinkerButtonUp);
let selDoc = SelectionManager.SelectedDocuments()[0];
- let container = selDoc.props.ContainingCollectionView ? selDoc.props.ContainingCollectionView.props.Document.GetPrototype() : undefined;
+ let container = selDoc.props.ContainingCollectionView ? selDoc.props.ContainingCollectionView.props.Document.proto : undefined;
let dragData = new DragManager.LinkDragData(selDoc.props.Document, container ? [container] : []);
DragManager.StartLinkDrag(this._linkerButton.current, dragData, e.pageX, e.pageY, {
handlers: {
@@ -417,28 +412,30 @@ export class DocumentDecorations extends React.Component<{}, { value: string }>
const rect = element.ContentDiv ? element.ContentDiv.getBoundingClientRect() : new DOMRect();
if (rect.width !== 0) {
- let doc = element.props.Document;
- let width = doc.GetNumber(KeyStore.Width, 0);
- let nwidth = doc.GetNumber(KeyStore.NativeWidth, 0);
- let nheight = doc.GetNumber(KeyStore.NativeHeight, 0);
- let height = doc.GetNumber(KeyStore.Height, nwidth ? nheight / nwidth * width : 0);
- let x = doc.GetOrCreate(KeyStore.X, NumberField);
- let y = doc.GetOrCreate(KeyStore.Y, NumberField);
+ let doc = PositionDocument(element.props.Document);
+ let width = FieldValue(doc.width, 0);
+ let nwidth = FieldValue(doc.nativeWidth, 0);
+ let nheight = FieldValue(doc.nativeHeight, 0);
+ let height = FieldValue(doc.height, nwidth ? nheight / nwidth * width : 0);
+ let x = FieldValue(doc.x, 0);
+ let y = FieldValue(doc.y, 0);
let scale = width / rect.width;
let actualdW = Math.max(width + (dW * scale), 20);
let actualdH = Math.max(height + (dH * scale), 20);
- x.Data += dX * (actualdW - width);
- y.Data += dY * (actualdH - height);
- var nativeWidth = doc.GetNumber(KeyStore.NativeWidth, 0);
- var nativeHeight = doc.GetNumber(KeyStore.NativeHeight, 0);
+ x += dX * (actualdW - width);
+ y += dY * (actualdH - height);
+ doc.x = x;
+ doc.y = y;
+ var nativeWidth = FieldValue(doc.nativeWidth, 0);
+ var nativeHeight = FieldValue(doc.nativeHeight, 0);
if (nativeWidth > 0 && nativeHeight > 0) {
if (Math.abs(dW) > Math.abs(dH)) {
actualdH = nativeHeight / nativeWidth * actualdW;
}
else actualdW = nativeWidth / nativeHeight * actualdH;
}
- doc.SetNumber(KeyStore.Width, actualdW);
- doc.SetNumber(KeyStore.Height, actualdH);
+ doc.width = actualdW;
+ doc.height = actualdH;
}
});
}
@@ -460,12 +457,12 @@ export class DocumentDecorations extends React.Component<{}, { value: string }>
@computed
get selectionTitle(): string {
if (SelectionManager.SelectedDocuments().length === 1) {
- let field = SelectionManager.SelectedDocuments()[0].props.Document.Get(this._fieldKey);
- if (field instanceof TextField) {
- return (field).GetValue();
+ let field = SelectionManager.SelectedDocuments()[0].props.Document[this._fieldKey];
+ if (typeof field === "string") {
+ return field;
}
- else if (field instanceof NumberField) {
- return (field).GetValue().toString();
+ else if (typeof field === "number") {
+ return field.toString();
}
} else if (SelectionManager.SelectedDocuments().length > 1) {
return "-multiple-";
@@ -488,21 +485,21 @@ export class DocumentDecorations extends React.Component<{}, { value: string }>
}
let minimizeIcon = (
<div className="documentDecorations-minimizeButton" onPointerDown={this.onMinimizeDown}>
- {SelectionManager.SelectedDocuments().length == 1 ? IconBox.DocumentIcon(SelectionManager.SelectedDocuments()[0].props.Document.GetText(KeyStore.Layout, "...")) : "..."}
+ {SelectionManager.SelectedDocuments().length === 1 ? IconBox.DocumentIcon(StrCast(SelectionManager.SelectedDocuments()[0].props.Document.layout, "...")) : "..."}
</div>);
let linkButton = null;
if (SelectionManager.SelectedDocuments().length > 0) {
let selFirst = SelectionManager.SelectedDocuments()[0];
- let linkToSize = selFirst.props.Document.GetData(KeyStore.LinkedToDocs, ListField, []).length;
- let linkFromSize = selFirst.props.Document.GetData(KeyStore.LinkedFromDocs, ListField, []).length;
+ let linkToSize = Cast(selFirst.props.Document.linkedToDocs, listSpec(Doc), []).length;
+ let linkFromSize = Cast(selFirst.props.Document.linkedFromDocs, listSpec(Doc), []).length;
let linkCount = linkToSize + linkFromSize;
linkButton = (<Flyout
anchorPoint={anchorPoints.RIGHT_TOP}
content={<LinkMenu docView={selFirst}
changeFlyout={this.changeFlyoutContent} />}>
<div className={"linkButton-" + (linkCount ? "nonempty" : "empty")} onPointerDown={this.onLinkButtonDown} >{linkCount}</div>
- </Flyout>);
+ </Flyout >);
}
let templates: Map<Template, boolean> = new Map();
@@ -511,7 +508,7 @@ export class DocumentDecorations extends React.Component<{}, { value: string }>
let docTemps = doc.templates;
let checked = false;
docTemps.forEach(temp => {
- if (template.Name === temp.Name) {
+ if (template.Layout === temp) {
checked = true;
}
});
diff --git a/src/client/views/EditableView.tsx b/src/client/views/EditableView.tsx
index 2f17c6c51..73467eb9d 100644
--- a/src/client/views/EditableView.tsx
+++ b/src/client/views/EditableView.tsx
@@ -60,7 +60,7 @@ export class EditableView extends React.Component<EditableProps> {
return (
<div className="editableView-container-editing" style={{ display: this.props.display, height: "auto", maxHeight: `${this.props.height}` }}
onClick={action(() => this.editing = true)} >
- {this.props.contents}
+ <span>{this.props.contents}</span>
</div>
);
}
diff --git a/src/client/views/InkingCanvas.tsx b/src/client/views/InkingCanvas.tsx
index 83836aa59..1c0d13545 100644
--- a/src/client/views/InkingCanvas.tsx
+++ b/src/client/views/InkingCanvas.tsx
@@ -1,9 +1,5 @@
import { action, computed, trace, observable, runInAction } from "mobx";
import { observer } from "mobx-react";
-import { Document } from "../../fields/Document";
-import { FieldWaiting } from "../../fields/Field";
-import { InkField, InkTool, StrokeData, StrokeMap } from "../../fields/InkField";
-import { KeyStore } from "../../fields/KeyStore";
import { Utils } from "../../Utils";
import { Transform } from "../util/Transform";
import "./InkingCanvas.scss";
@@ -11,10 +7,13 @@ import { InkingControl } from "./InkingControl";
import { InkingStroke } from "./InkingStroke";
import React = require("react");
import { undoBatch, UndoManager } from "../util/UndoManager";
+import { StrokeData, InkField, InkTool } from "../../new_fields/InkField";
+import { Doc } from "../../new_fields/Doc";
+import { Cast, PromiseValue, NumCast } from "../../new_fields/Types";
interface InkCanvasProps {
getScreenTransform: () => Transform;
- Document: Document;
+ Document: Doc;
children: () => JSX.Element[];
}
@@ -23,7 +22,7 @@ export class InkingCanvas extends React.Component<InkCanvasProps> {
maxCanvasDim = 8192 / 2; // 1/2 of the maximum canvas dimension for Chrome
@observable inkMidX: number = 0;
@observable inkMidY: number = 0;
- private previousState?: StrokeMap;
+ private previousState?: Map<string, StrokeData>;
private _currentStrokeId: string = "";
public static IntersectStrokeRect(stroke: StrokeData, selRect: { left: number, top: number, width: number, height: number }): boolean {
return stroke.pathData.reduce((inside: boolean, val) => inside ||
@@ -33,9 +32,9 @@ export class InkingCanvas extends React.Component<InkCanvasProps> {
}
componentDidMount() {
- this.props.Document.GetTAsync(KeyStore.Ink, InkField, ink => runInAction(() => {
+ PromiseValue(Cast(this.props.Document.ink, InkField)).then(ink => runInAction(() => {
if (ink) {
- let bounds = Array.from(ink.Data).reduce(([mix, max, miy, may], [id, strokeData]) =>
+ let bounds = Array.from(ink.inkData).reduce(([mix, max, miy, may], [id, strokeData]) =>
strokeData.pathData.reduce(([mix, max, miy, may], p) =>
[Math.min(mix, p.x), Math.max(max, p.x), Math.min(miy, p.y), Math.max(may, p.y)],
[mix, max, miy, may]),
@@ -47,13 +46,13 @@ export class InkingCanvas extends React.Component<InkCanvasProps> {
}
@computed
- get inkData(): StrokeMap {
- let map = this.props.Document.GetT(KeyStore.Ink, InkField);
- return !map || map === FieldWaiting ? new Map : new Map(map.Data);
+ get inkData(): Map<string, StrokeData> {
+ let map = Cast(this.props.Document.ink, InkField);
+ return !map ? new Map : new Map(map.inkData);
}
- set inkData(value: StrokeMap) {
- this.props.Document.SetDataOnPrototype(KeyStore.Ink, value, InkField);
+ set inkData(value: Map<string, StrokeData>) {
+ Doc.SetOnPrototype(this.props.Document, "ink", new InkField(value));
}
@action
@@ -78,7 +77,7 @@ export class InkingCanvas extends React.Component<InkCanvasProps> {
color: InkingControl.Instance.selectedColor,
width: InkingControl.Instance.selectedWidth,
tool: InkingControl.Instance.selectedTool,
- page: this.props.Document.GetNumber(KeyStore.CurPage, -1)
+ page: NumCast(this.props.Document.curPage, -1)
});
this.inkData = data;
}
@@ -137,26 +136,29 @@ export class InkingCanvas extends React.Component<InkCanvasProps> {
@computed
get drawnPaths() {
- let curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1);
+ let curPage = NumCast(this.props.Document.curPage, -1);
let paths = Array.from(this.inkData).reduce((paths, [id, strokeData]) => {
if (strokeData.page === -1 || strokeData.page === curPage) {
- paths.push(<InkingStroke key={id} id={id} line={strokeData.pathData}
+ paths.push(<InkingStroke key={id} id={id}
+ line={strokeData.pathData}
+ count={strokeData.pathData.length}
offsetX={this.maxCanvasDim - this.inkMidX}
offsetY={this.maxCanvasDim - this.inkMidY}
- color={strokeData.color} width={strokeData.width}
- tool={strokeData.tool} deleteCallback={this.removeLine} />);
+ color={strokeData.color}
+ width={strokeData.width}
+ tool={strokeData.tool}
+ deleteCallback={this.removeLine} />);
}
return paths;
}, [] as JSX.Element[]);
- return [
- <svg className={`inkingCanvas-paths-ink`} key="Pens"
- style={{ left: `${this.inkMidX - this.maxCanvasDim}px`, top: `${this.inkMidY - this.maxCanvasDim}px` }}>
- {paths.filter(path => path.props.tool !== InkTool.Highlighter)}
- </svg>,
- <svg className={`inkingCanvas-paths-markers`} key="Markers"
- style={{ left: `${this.inkMidX - this.maxCanvasDim}px`, top: `${this.inkMidY - this.maxCanvasDim}px` }} >
- {paths.filter(path => path.props.tool === InkTool.Highlighter)}
- </svg>];
+ return [<svg className={`inkingCanvas-paths-ink`} key="Pens"
+ style={{ left: `${this.inkMidX - this.maxCanvasDim}px`, top: `${this.inkMidY - this.maxCanvasDim}px` }} >
+ {paths.filter(path => path.props.tool !== InkTool.Highlighter)}
+ </svg>,
+ <svg className={`inkingCanvas-paths-markers`} key="Markers"
+ style={{ left: `${this.inkMidX - this.maxCanvasDim}px`, top: `${this.inkMidY - this.maxCanvasDim}px` }}>
+ {paths.filter(path => path.props.tool === InkTool.Highlighter)}
+ </svg>];
}
render() {
diff --git a/src/client/views/InkingControl.tsx b/src/client/views/InkingControl.tsx
index 9a68f0671..4b3dbd4e0 100644
--- a/src/client/views/InkingControl.tsx
+++ b/src/client/views/InkingControl.tsx
@@ -2,15 +2,14 @@ import { observable, action, computed } from "mobx";
import { CirclePicker, ColorResult } from 'react-color';
import React = require("react");
-import { InkTool } from "../../fields/InkField";
import { observer } from "mobx-react";
import "./InkingControl.scss";
import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faPen, faHighlighter, faEraser, faBan } from '@fortawesome/free-solid-svg-icons';
import { SelectionManager } from "../util/SelectionManager";
-import { KeyStore } from "../../fields/KeyStore";
-import { TextField } from "../../fields/TextField";
+import { InkTool } from "../../new_fields/InkField";
+import { Doc } from "../../new_fields/Doc";
library.add(faPen, faHighlighter, faEraser, faBan);
@@ -39,7 +38,7 @@ export class InkingControl extends React.Component {
if (SelectionManager.SelectedDocuments().length === 1) {
var sdoc = SelectionManager.SelectedDocuments()[0];
if (sdoc.props.ContainingCollectionView) {
- sdoc.props.Document.SetDataOnPrototype(KeyStore.BackgroundColor, color.hex, TextField);
+ Doc.SetOnPrototype(sdoc.props.Document, "backgroundColor", color.hex);
}
}
}
diff --git a/src/client/views/InkingStroke.scss b/src/client/views/InkingStroke.scss
new file mode 100644
index 000000000..cdbfdcff3
--- /dev/null
+++ b/src/client/views/InkingStroke.scss
@@ -0,0 +1,3 @@
+.inkingStroke-marker {
+ mix-blend-mode: multiply
+} \ No newline at end of file
diff --git a/src/client/views/InkingStroke.tsx b/src/client/views/InkingStroke.tsx
index 0f05da22c..37b1f5899 100644
--- a/src/client/views/InkingStroke.tsx
+++ b/src/client/views/InkingStroke.tsx
@@ -1,14 +1,16 @@
import { observer } from "mobx-react";
-import { observable } from "mobx";
+import { observable, trace } from "mobx";
import { InkingControl } from "./InkingControl";
-import { InkTool } from "../../fields/InkField";
import React = require("react");
+import { InkTool } from "../../new_fields/InkField";
+import "./InkingStroke.scss";
interface StrokeProps {
offsetX: number;
offsetY: number;
id: string;
+ count: number;
line: Array<{ x: number, y: number }>;
color: string;
width: string;
@@ -48,10 +50,12 @@ export class InkingStroke extends React.Component<StrokeProps> {
render() {
let pathStyle = this.createStyle();
let pathData = this.parseData(this.props.line);
+ let pathlength = this.props.count; // bcz: this is needed to force reactions to the line data changes
+ let marker = this.props.tool === InkTool.Highlighter ? "-marker" : "";
let pointerEvents: any = InkingControl.Instance.selectedTool === InkTool.Eraser ? "all" : "none";
return (
- <path d={pathData} style={{ ...pathStyle, pointerEvents: pointerEvents }} strokeLinejoin="round" strokeLinecap="round"
+ <path className={`inkingStroke${marker}`} d={pathData} style={{ ...pathStyle, pointerEvents: pointerEvents }} strokeLinejoin="round" strokeLinecap="round"
onPointerOver={this.deleteStroke} onPointerDown={this.deleteStroke} />
);
}
diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx
index 28ea902f4..c3b48d20f 100644
--- a/src/client/views/Main.tsx
+++ b/src/client/views/Main.tsx
@@ -8,16 +8,10 @@ import * as React from 'react';
import * as ReactDOM from 'react-dom';
import Measure from 'react-measure';
import * as request from 'request';
-import { Document } from '../../fields/Document';
-import { Field, FieldWaiting, Opt, FIELD_WAITING } from '../../fields/Field';
-import { KeyStore } from '../../fields/KeyStore';
-import { ListField } from '../../fields/ListField';
import { CurrentUserUtils } from '../../server/authentication/models/current_user_utils';
-import { MessageStore } from '../../server/Message';
import { RouteStore } from '../../server/RouteStore';
-import { ServerUtils } from '../../server/ServerUtil';
-import { emptyDocFunction, emptyFunction, returnTrue, Utils, returnOne, returnZero } from '../../Utils';
-import { Documents } from '../documents/Documents';
+import { emptyFunction, returnTrue, Utils, returnOne, returnZero } from '../../Utils';
+import { Docs } from '../documents/Documents';
import { ColumnAttributeModel } from '../northstar/core/attribute/AttributeModel';
import { AttributeTransformationModel } from '../northstar/core/attribute/AttributeTransformationModel';
import { Gateway, NorthstarSettings } from '../northstar/manager/Gateway';
@@ -25,12 +19,10 @@ import { AggregateFunction, Catalog } from '../northstar/model/idea/idea';
import '../northstar/model/ModelExtensions';
import { HistogramOperation } from '../northstar/operations/HistogramOperation';
import '../northstar/utils/Extensions';
-import { Server } from '../Server';
import { SetupDrag, DragManager } from '../util/DragManager';
import { Transform } from '../util/Transform';
import { UndoManager } from '../util/UndoManager';
import { PresentationView } from './PresentationView';
-import { WorkspacesMenu } from '../../server/authentication/controllers/WorkspacesMenu';
import { CollectionDockingView } from './collections/CollectionDockingView';
import { ContextMenu } from './ContextMenu';
import { DocumentDecorations } from './DocumentDecorations';
@@ -40,6 +32,11 @@ import { MainOverlayTextBox } from './MainOverlayTextBox';
import { DocumentView } from './nodes/DocumentView';
import { PreviewCursor } from './PreviewCursor';
import { SelectionManager } from '../util/SelectionManager';
+import { FieldResult, Field, Doc, Opt } from '../../new_fields/Doc';
+import { Cast, FieldValue, StrCast } from '../../new_fields/Types';
+import { DocServer } from '../DocServer';
+import { listSpec } from '../../new_fields/Schema';
+import { Id } from '../../new_fields/RefField';
@observer
@@ -49,13 +46,15 @@ export class Main extends React.Component {
@observable public pwidth: number = 0;
@observable public pheight: number = 0;
- @computed private get mainContainer(): Document | undefined | FIELD_WAITING {
- return CurrentUserUtils.UserDocument.GetT(KeyStore.ActiveWorkspace, Document);
+ @computed private get mainContainer(): Opt<Doc> {
+ return FieldValue(Cast(CurrentUserUtils.UserDocument.activeWorkspace, Doc));
}
- private set mainContainer(doc: Document | undefined | FIELD_WAITING) {
+ private set mainContainer(doc: Opt<Doc>) {
if (doc) {
- doc.GetOrCreateAsync(KeyStore.PresentationView, Document, doc => { });
- CurrentUserUtils.UserDocument.Set(KeyStore.ActiveWorkspace, doc);
+ if (!("presentationView" in doc)) {
+ doc.presentationView = new Doc();
+ }
+ CurrentUserUtils.UserDocument.activeWorkspace = doc;
}
}
@@ -89,11 +88,11 @@ export class Main extends React.Component {
this.initEventListeners();
this.initAuthenticationRouters();
- try {
- this.initializeNorthstar();
- } catch (e) {
+ // try {
+ // this.initializeNorthstar();
+ // } catch (e) {
- }
+ // }
}
componentDidMount() { window.onpopstate = this.onHistory; }
@@ -103,9 +102,8 @@ export class Main extends React.Component {
onHistory = () => {
if (window.location.pathname !== RouteStore.home) {
let pathname = window.location.pathname.split("/");
- CurrentUserUtils.MainDocId = pathname[pathname.length - 1];
- Server.GetField(CurrentUserUtils.MainDocId, action((field: Opt<Field>) => {
- if (field instanceof Document) {
+ DocServer.GetRefField(pathname[pathname.length - 1]).then(action((field: Opt<Field>) => {
+ if (field instanceof Doc) {
this.openWorkspace(field, true);
}
}));
@@ -117,9 +115,9 @@ export class Main extends React.Component {
window.addEventListener("drop", (e) => e.preventDefault(), false); // drop event handler
window.addEventListener("dragover", (e) => e.preventDefault(), false); // drag event handler
window.addEventListener("keydown", (e) => {
- if (e.key == "Escape") {
+ if (e.key === "Escape") {
DragManager.AbortDrag();
- SelectionManager.DeselectAll()
+ SelectionManager.DeselectAll();
}
}, false); // drag event handler
// click interactions for the context menu
@@ -130,60 +128,60 @@ export class Main extends React.Component {
}), true);
}
- initAuthenticationRouters = () => {
+ initAuthenticationRouters = async () => {
// Load the user's active workspace, or create a new one if initial session after signup
if (!CurrentUserUtils.MainDocId) {
- CurrentUserUtils.UserDocument.GetTAsync(KeyStore.ActiveWorkspace, Document).then(doc => {
- if (doc) {
- CurrentUserUtils.MainDocId = doc.Id;
- this.openWorkspace(doc);
- } else {
- this.createNewWorkspace();
- }
- });
+ const doc = await Cast(CurrentUserUtils.UserDocument.activeWorkspace, Doc);
+ if (doc) {
+ this.openWorkspace(doc);
+ } else {
+ this.createNewWorkspace();
+ }
} else {
- Server.GetField(CurrentUserUtils.MainDocId).then(field =>
- field instanceof Document ? this.openWorkspace(field) :
+ DocServer.GetRefField(CurrentUserUtils.MainDocId).then(field =>
+ field instanceof Doc ? this.openWorkspace(field) :
this.createNewWorkspace(CurrentUserUtils.MainDocId));
}
}
@action
- createNewWorkspace = (id?: string): void => {
- CurrentUserUtils.UserDocument.GetTAsync<ListField<Document>>(KeyStore.Workspaces, ListField).then(action((list: Opt<ListField<Document>>) => {
- if (list) {
- let freeformDoc = Documents.FreeformDocument([], { x: 0, y: 400, title: "mini collection" });
- var dockingLayout = { content: [{ type: 'row', content: [CollectionDockingView.makeDocumentConfig(freeformDoc)] }] };
- let mainDoc = Documents.DockDocument(JSON.stringify(dockingLayout), { title: `Main Container ${list.Data.length + 1}` }, id);
- list.Data.push(mainDoc);
- CurrentUserUtils.MainDocId = mainDoc.Id;
- // bcz: strangely, we need a timeout to prevent exceptions/issues initializing GoldenLayout (the rendering engine for Main Container)
- setTimeout(() => {
- this.openWorkspace(mainDoc);
- let pendingDocument = Documents.SchemaDocument([], { title: "New Mobile Uploads" });
- mainDoc.Set(KeyStore.OptionalRightCollection, pendingDocument);
- }, 0);
- }
- }));
+ createNewWorkspace = async (id?: string) => {
+ const list = Cast(CurrentUserUtils.UserDocument.data, listSpec(Doc));
+ if (list) {
+ let freeformDoc = Docs.FreeformDocument([], { x: 0, y: 400, title: `WS collection ${list.length + 1}` });
+ var dockingLayout = { content: [{ type: 'row', content: [CollectionDockingView.makeDocumentConfig(CurrentUserUtils.UserDocument, 150), CollectionDockingView.makeDocumentConfig(freeformDoc, 600)] }] };
+ let mainDoc = Docs.DockDocument([CurrentUserUtils.UserDocument, freeformDoc], JSON.stringify(dockingLayout), { title: `Workspace ${list.length + 1}` });
+ list.push(mainDoc);
+ // bcz: strangely, we need a timeout to prevent exceptions/issues initializing GoldenLayout (the rendering engine for Main Container)
+ setTimeout(() => {
+ this.openWorkspace(mainDoc);
+ let pendingDocument = Docs.SchemaDocument([], { title: "New Mobile Uploads" });
+ mainDoc.optionalRightCollection = pendingDocument;
+ }, 0);
+ }
}
@action
- openWorkspace = (doc: Document, fromHistory = false): void => {
+ openWorkspace = async (doc: Doc, fromHistory = false) => {
+ CurrentUserUtils.MainDocId = doc[Id];
this.mainContainer = doc;
- fromHistory || window.history.pushState(null, doc.Title, "/doc/" + doc.Id);
- CurrentUserUtils.UserDocument.GetTAsync(KeyStore.OptionalRightCollection, Document).then(col =>
- // if there is a pending doc, and it has new data, show it (syip: we use a timeout to prevent collection docking view from being uninitialized)
- setTimeout(() =>
- col && col.GetTAsync<ListField<Document>>(KeyStore.Data, ListField, (f: Opt<ListField<Document>>) =>
- f && f.Data.length > 0 && CollectionDockingView.Instance.AddRightSplit(col))
- , 100)
- );
+ fromHistory || window.history.pushState(null, StrCast(doc.title), "/doc/" + doc[Id]);
+ const col = await Cast(CurrentUserUtils.UserDocument.optionalRightCollection, Doc);
+ // if there is a pending doc, and it has new data, show it (syip: we use a timeout to prevent collection docking view from being uninitialized)
+ setTimeout(async () => {
+ if (col) {
+ const l = Cast(col.data, listSpec(Doc));
+ if (l && l.length > 0) {
+ CollectionDockingView.Instance.AddRightSplit(col);
+ }
+ }
+ }, 100);
}
@computed
get presentationView() {
if (this.mainContainer) {
- let presentation = this.mainContainer.GetT(KeyStore.PresentationView, Document);
+ let presentation = FieldValue(Cast(this.mainContainer.presentationView, Doc));
return presentation ? <PresentationView Document={presentation} key="presentation" /> : (null);
}
return (null);
@@ -210,9 +208,10 @@ export class Main extends React.Component {
PanelHeight={pheightFunc}
isTopMost={true}
selectOnLoad={false}
- focus={emptyDocFunction}
+ focus={emptyFunction}
parentActive={returnTrue}
whenActiveChanged={emptyFunction}
+ bringToFront={emptyFunction}
ContainingCollectionView={undefined} />}
{pcontent}
</div>
@@ -221,25 +220,26 @@ export class Main extends React.Component {
}
/* for the expandable add nodes menu. Not included with the miscbuttons because once it expands it expands the whole div with it, making canvas interactions limited. */
- @computed
- get nodesMenu() {
+ nodesMenu() {
+
let imgurl = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/1200px-Cat03.jpg";
let pdfurl = "http://www.adobe.com/support/products/enterprise/knowledgecenter/media/c27211_sample_explain.pdf";
let weburl = "https://cs.brown.edu/courses/cs166/";
let audiourl = "http://techslides.com/demos/samples/sample.mp3";
let videourl = "http://techslides.com/demos/sample-videos/small.mp4";
- let addTextNode = action(() => Documents.TextDocument({ borderRounding: -1, width: 200, height: 50, title: "a text note" }));
- let addColNode = action(() => Documents.FreeformDocument([], { width: 200, height: 200, title: "a freeform collection" }));
- let addSchemaNode = action(() => Documents.SchemaDocument([], { width: 200, height: 200, title: "a schema collection" }));
- let addTreeNode = action(() => Documents.TreeDocument(this._northstarSchemas, { width: 250, height: 400, title: "northstar schemas", copyDraggedItems: true }));
- let addVideoNode = action(() => Documents.VideoDocument(videourl, { width: 200, title: "video node" }));
- let addPDFNode = action(() => Documents.PdfDocument(pdfurl, { width: 200, height: 200, title: "a pdf doc" }));
- let addImageNode = action(() => Documents.ImageDocument(imgurl, { width: 200, title: "an image of a cat" }));
- let addWebNode = action(() => Documents.WebDocument(weburl, { width: 200, height: 200, title: "a sample web page" }));
- let addAudioNode = action(() => Documents.AudioDocument(audiourl, { width: 200, height: 200, title: "audio node" }));
+ let addTextNode = action(() => Docs.TextDocument({ borderRounding: -1, width: 200, height: 200, title: "a text note" }));
+ let addColNode = action(() => Docs.FreeformDocument([], { width: 200, height: 200, title: "a freeform collection" }));
+ let addSchemaNode = action(() => Docs.SchemaDocument([], { 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 addVideoNode = action(() => Docs.VideoDocument(videourl, { width: 200, title: "video node" }));
+ let addPDFNode = action(() => Docs.PdfDocument(pdfurl, { width: 200, height: 200, title: "a pdf doc" }));
+ let addImageNode = action(() => Docs.ImageDocument(imgurl, { width: 200, title: "an image of a cat" }));
+ let addWebNode = action(() => Docs.WebDocument(weburl, { width: 200, height: 200, title: "a sample web page" }));
+ let addAudioNode = action(() => Docs.AudioDocument(audiourl, { width: 200, height: 200, title: "audio node" }));
- let btns: [React.RefObject<HTMLDivElement>, IconName, string, () => Document][] = [
+ let btns: [React.RefObject<HTMLDivElement>, IconName, string, () => Doc][] = [
[React.createRef<HTMLDivElement>(), "font", "Add Textbox", addTextNode],
[React.createRef<HTMLDivElement>(), "image", "Add Image", addImageNode],
[React.createRef<HTMLDivElement>(), "file-pdf", "Add PDF", addPDFNode],
@@ -271,36 +271,20 @@ export class Main extends React.Component {
/* @TODO this should really be moved into a moveable toolbar component, but for now let's put it here to meet the deadline */
@computed
get miscButtons() {
- let workspacesRef = React.createRef<HTMLDivElement>();
let logoutRef = React.createRef<HTMLDivElement>();
- let toggleWorkspaces = () => runInAction(() => this._workspacesShown = !this._workspacesShown);
- let clearDatabase = action(() => Utils.Emit(Server.Socket, MessageStore.DeleteAll, {}));
return [
- <button className="clear-db-button" key="clear-db" onClick={clearDatabase}>Clear Database</button>,
+ <button className="clear-db-button" key="clear-db" onClick={DocServer.DeleteDatabase}>Clear Database</button>,
<div id="toolbar" key="toolbar">
<button className="toolbar-button round-button" title="Undo" onClick={() => UndoManager.Undo()}><FontAwesomeIcon icon="undo-alt" size="sm" /></button>
<button className="toolbar-button round-button" title="Redo" onClick={() => UndoManager.Redo()}><FontAwesomeIcon icon="redo-alt" size="sm" /></button>
<button className="toolbar-button round-button" title="Ink" onClick={() => InkingControl.Instance.toggleDisplay()}><FontAwesomeIcon icon="pen-nib" size="sm" /></button>
</div >,
- <div className="main-buttonDiv" key="workspaces" style={{ top: '34px', left: '2px', position: 'absolute' }} ref={workspacesRef}>
- <button onClick={toggleWorkspaces}>Workspaces</button></div>,
<div className="main-buttonDiv" key="logout" style={{ top: '34px', right: '1px', position: 'absolute' }} ref={logoutRef}>
- <button onClick={() => request.get(ServerUtils.prepend(RouteStore.logout), emptyFunction)}>Log Out</button></div>
+ <button onClick={() => request.get(DocServer.prepend(RouteStore.logout), emptyFunction)}>Log Out</button></div>
];
}
- @computed
- get workspaceMenu() {
- let areWorkspacesShown = () => this._workspacesShown;
- let toggleWorkspaces = () => runInAction(() => this._workspacesShown = !this._workspacesShown);
- let workspaces = CurrentUserUtils.UserDocument.GetT<ListField<Document>>(KeyStore.Workspaces, ListField);
- return (!workspaces || workspaces === FieldWaiting || this.mainContainer === FieldWaiting) ? (null) :
- <WorkspacesMenu active={this.mainContainer} open={this.openWorkspace}
- new={this.createNewWorkspace} allWorkspaces={workspaces.Data}
- isShown={areWorkspacesShown} toggle={toggleWorkspaces} />;
- }
-
render() {
return (
<div id="main-div">
@@ -308,9 +292,8 @@ export class Main extends React.Component {
{this.mainContent}
<PreviewCursor />
<ContextMenu />
- {this.nodesMenu}
+ {this.nodesMenu()}
{this.miscButtons}
- {this.workspaceMenu}
<InkingControl />
<MainOverlayTextBox />
</div>
@@ -318,17 +301,17 @@ export class Main extends React.Component {
}
// --------------- Northstar hooks ------------- /
- private _northstarSchemas: Document[] = [];
+ private _northstarSchemas: Doc[] = [];
@action SetNorthstarCatalog(ctlog: Catalog) {
CurrentUserUtils.NorthstarDBCatalog = ctlog;
if (ctlog && ctlog.schemas) {
ctlog.schemas.map(schema => {
- let schemaDocuments: Document[] = [];
+ let schemaDocuments: Doc[] = [];
let attributesToBecomeDocs = CurrentUserUtils.GetAllNorthstarColumnAttributes(schema);
Promise.all(attributesToBecomeDocs.reduce((promises, attr) => {
- promises.push(Server.GetField(attr.displayName! + ".alias").then(action((field: Opt<Field>) => {
- if (field instanceof Document) {
+ promises.push(DocServer.GetRefField(attr.displayName! + ".alias").then(action((field: Opt<Field>) => {
+ if (field instanceof Doc) {
schemaDocuments.push(field);
} else {
var atmod = new ColumnAttributeModel(attr);
@@ -336,12 +319,12 @@ export class Main extends React.Component {
new AttributeTransformationModel(atmod, AggregateFunction.None),
new AttributeTransformationModel(atmod, AggregateFunction.Count),
new AttributeTransformationModel(atmod, AggregateFunction.Count));
- schemaDocuments.push(Documents.HistogramDocument(histoOp, { width: 200, height: 200, title: attr.displayName! }, undefined, attr.displayName! + ".alias"));
+ schemaDocuments.push(Docs.HistogramDocument(histoOp, { width: 200, height: 200, title: attr.displayName! }));
}
})));
return promises;
}, [] as Promise<void>[])).finally(() =>
- this._northstarSchemas.push(Documents.TreeDocument(schemaDocuments, { width: 50, height: 100, title: schema.displayName! })));
+ this._northstarSchemas.push(Docs.TreeDocument(schemaDocuments, { width: 50, height: 100, title: schema.displayName! })));
});
}
}
@@ -353,7 +336,7 @@ export class Main extends React.Component {
}
(async () => {
- await Documents.initProtos();
+ await Docs.initProtos();
await CurrentUserUtils.loadCurrentUser();
ReactDOM.render(<Main />, document.getElementById('root'));
})();
diff --git a/src/client/views/MainOverlayTextBox.tsx b/src/client/views/MainOverlayTextBox.tsx
index 13e661b46..d32e3f21b 100644
--- a/src/client/views/MainOverlayTextBox.tsx
+++ b/src/client/views/MainOverlayTextBox.tsx
@@ -2,16 +2,15 @@ import { action, observable, trace } from 'mobx';
import { observer } from 'mobx-react';
import "normalize.css";
import * as React from 'react';
-import { Document } from '../../fields/Document';
-import { Key } from '../../fields/Key';
-import { KeyStore } from '../../fields/KeyStore';
-import { emptyDocFunction, emptyFunction, returnTrue, returnZero } from '../../Utils';
+import { emptyFunction, returnTrue, returnZero } from '../../Utils';
import '../northstar/model/ModelExtensions';
import '../northstar/utils/Extensions';
import { DragManager } from '../util/DragManager';
import { Transform } from '../util/Transform';
import "./MainOverlayTextBox.scss";
import { FormattedTextBox } from './nodes/FormattedTextBox';
+import { Doc } from '../../new_fields/Doc';
+import { NumCast } from '../../new_fields/Types';
interface MainOverlayTextBoxProps {
}
@@ -19,10 +18,10 @@ interface MainOverlayTextBoxProps {
@observer
export class MainOverlayTextBox extends React.Component<MainOverlayTextBoxProps> {
public static Instance: MainOverlayTextBox;
- @observable public TextDoc?: Document = undefined;
+ @observable public TextDoc?: Doc = undefined;
public TextScroll: number = 0;
@observable _textXf: () => Transform = () => Transform.Identity();
- private _textFieldKey: Key = KeyStore.Data;
+ private _textFieldKey: string = "data";
private _textColor: string | null = null;
private _textTargetDiv: HTMLDivElement | undefined;
private _textProxyDiv: React.RefObject<HTMLDivElement>;
@@ -34,7 +33,7 @@ export class MainOverlayTextBox extends React.Component<MainOverlayTextBoxProps>
}
@action
- SetTextDoc(textDoc?: Document, textFieldKey?: Key, div?: HTMLDivElement, tx?: () => Transform) {
+ SetTextDoc(textDoc?: Doc, textFieldKey?: string, div?: HTMLDivElement, tx?: () => Transform) {
if (this._textTargetDiv) {
this._textTargetDiv.style.color = this._textColor;
}
@@ -89,12 +88,12 @@ export class MainOverlayTextBox extends React.Component<MainOverlayTextBoxProps>
if (this.TextDoc && this._textTargetDiv) {
let textRect = this._textTargetDiv.getBoundingClientRect();
let s = this._textXf().Scale;
- return <div className="mainOverlayTextBox-textInput" style={{ transform: `translate(${textRect.x}px, ${textRect.y}px) scale(${1 / s},${1 / s})`, width: "auto", height: "auto" }} >
+ return <div className="mainOverlayTextBox-textInput" style={{ transform: `translate(${textRect.left}px, ${textRect.top}px) scale(${1 / s},${1 / s})`, width: "auto", height: "auto" }} >
<div className="mainOverlayTextBox-textInput" onPointerDown={this.textBoxDown} ref={this._textProxyDiv} onScroll={this.textScroll}
style={{ width: `${textRect.width * s}px`, height: `${textRect.height * s}px` }}>
<FormattedTextBox fieldKey={this._textFieldKey} isOverlay={true} Document={this.TextDoc} isSelected={returnTrue} select={emptyFunction} isTopMost={true}
selectOnLoad={true} ContainingCollectionView={undefined} whenActiveChanged={emptyFunction} active={returnTrue}
- ScreenToLocalTransform={this._textXf} PanelWidth={returnZero} PanelHeight={returnZero} focus={emptyDocFunction} />
+ ScreenToLocalTransform={this._textXf} PanelWidth={returnZero} PanelHeight={returnZero} focus={emptyFunction} />
</div>
</ div>;
}
diff --git a/src/client/views/PresentationView.tsx b/src/client/views/PresentationView.tsx
index 9c5297e7c..b4c12d057 100644
--- a/src/client/views/PresentationView.tsx
+++ b/src/client/views/PresentationView.tsx
@@ -1,19 +1,18 @@
import { observer } from "mobx-react";
-import { Document } from "../../fields/Document";
-import { KeyStore } from "../../fields/KeyStore";
-import { ListField } from "../../fields/ListField";
import React = require("react")
-import { TextField } from "../../fields/TextField";
import { observable, action } from "mobx";
-import { Field, FieldWaiting } from "../../fields/Field";
import "./PresentationView.scss"
-import { NumberField } from "../../fields/NumberField";
import "./Main.tsx";
import { DocumentManager } from "../util/DocumentManager";
import { Utils } from "../../Utils";
+import { Doc } from "../../new_fields/Doc";
+import { listSpec } from "../../new_fields/Schema";
+import { Cast, NumCast, FieldValue } from "../../new_fields/Types";
+import { Id } from "../../new_fields/RefField";
+import { List } from "../../new_fields/List";
export interface PresViewProps {
- Document: Document;
+ Document: Doc;
}
@@ -25,7 +24,7 @@ class PresentationViewItem extends React.Component<PresViewProps> {
//look at CollectionFreeformView.focusDocument(d)
@action
- openDoc = (doc: Document) => {
+ openDoc = (doc: Doc) => {
let docView = DocumentManager.Instance.getDocumentView(doc);
if (docView) {
docView.props.focus(docView.props.Document);
@@ -36,17 +35,17 @@ class PresentationViewItem extends React.Component<PresViewProps> {
* Removes a document from the presentation view
**/
@action
- public RemoveDoc(doc: Document) {
- const value = this.props.Document.GetData(KeyStore.Data, ListField, new Array<Document>())
+ public RemoveDoc(doc: Doc) {
+ const value = Cast(this.props.Document.data, listSpec(Doc), []);
let index = -1;
for (let i = 0; i < value.length; i++) {
- if (value[i].Id === doc.Id) {
+ if (value[i][Id] === doc[Id]) {
index = i;
break;
}
}
if (index !== -1) {
- value.splice(index, 1)
+ value.splice(index, 1);
}
}
@@ -54,46 +53,36 @@ class PresentationViewItem extends React.Component<PresViewProps> {
* Renders a single child document. It will just append a list element.
* @param document The document to render.
*/
- renderChild(document: Document) {
- let title = document.Title;
+ renderChild(document: Doc) {
+ let title = document.title;
//to get currently selected presentation doc
- let selected = this.props.Document.GetNumber(KeyStore.SelectedDoc, 0);
+ let selected = NumCast(this.props.Document.selectedDoc, 0);
- // if the title hasn't loaded, immediately return the div
- if (!title) {
- return <div className="presentationView-item" key={document.Id}></div>;
- }
// finally, if it's a normal document, then render it as such.
- else {
- const children = this.props.Document.GetT<ListField<Document>>(KeyStore.Data, ListField);
- if (children && children.Data[selected] === document) {
- //this doc is selected
- const styles = {
- background: "gray"
- }
- return <li className="presentationView-item" style={styles} key={Utils.GenerateGuid()}>
- <div className="presentationView-header" onClick={() => this.openDoc(document)}>{title}</div>
- <div className="presentation-icon" onClick={() => this.RemoveDoc(document)}>X</div></li>;
- } else {
- return <li className="presentationView-item" key={Utils.GenerateGuid()} >
- <div className="presentationView-header" onClick={() => this.openDoc(document)}>{title}</div>
- <div className="presentation-icon" onClick={() => this.RemoveDoc(document)}>X</div></li>;
- }
-
+ const children = Cast(this.props.Document.data, listSpec(Doc));
+ const styles: any = {};
+ if (children && children[selected] === document) {
+ //this doc is selected
+ styles.background = "gray";
}
+ return (
+ <li className="presentationView-item" style={styles} key={Utils.GenerateGuid()}>
+ <div className="presentationView-header" onClick={() => this.openDoc(document)}>{title}</div>
+ <div className="presentation-icon" onClick={() => this.RemoveDoc(document)}>X</div>
+ </li>
+ );
+
}
render() {
- const children = this.props.Document.GetT<ListField<Document>>(KeyStore.Data, ListField);
+ const children = Cast(this.props.Document.data, listSpec(Doc), []);
- if (children) {
- return (<div>
- {children.Data.map(value => this.renderChild(value))}
- </div>)
- } else {
- return <div></div>;
- }
+ return (
+ <div>
+ {children.map(value => this.renderChild(value))}
+ </div>
+ );
}
}
@@ -105,42 +94,40 @@ export class PresentationView extends React.Component<PresViewProps> {
//observable means render is re-called every time variable is changed
@observable
collapsed: boolean = false;
- closePresentation = action(() => this.props.Document.SetNumber(KeyStore.Width, 0));
+ closePresentation = action(() => this.props.Document.width = 0);
next = () => {
- const current = this.props.Document.GetNumber(KeyStore.SelectedDoc, 0);
- const allDocs = this.props.Document.GetT<ListField<Document>>(KeyStore.Data, ListField);
- if (allDocs && current < allDocs.Data.length + 1) {
+ const current = NumCast(this.props.Document.selectedDoc);
+ const allDocs = FieldValue(Cast(this.props.Document.data, listSpec(Doc)));
+ if (allDocs && current < allDocs.length + 1) {
//can move forwards
- this.props.Document.SetNumber(KeyStore.SelectedDoc, current + 1);
- const doc = allDocs.Data[current + 1];
+ this.props.Document.selectedDoc = current + 1;
+ const doc = allDocs[current + 1];
let docView = DocumentManager.Instance.getDocumentView(doc);
if (docView) {
docView.props.focus(docView.props.Document);
}
}
- };
+ }
back = () => {
- const current = this.props.Document.GetNumber(KeyStore.SelectedDoc, 0);
- const allDocs = this.props.Document.GetT<ListField<Document>>(KeyStore.Data, ListField);
+ const current = NumCast(this.props.Document.selectedDoc);
+ const allDocs = FieldValue(Cast(this.props.Document.data, listSpec(Doc)));
if (allDocs && current - 1 >= 0) {
//can move forwards
- this.props.Document.SetNumber(KeyStore.SelectedDoc, current - 1);
- const doc = allDocs.Data[current - 1];
+ this.props.Document.selectedDoc = current - 1;
+ const doc = allDocs[current - 1];
let docView = DocumentManager.Instance.getDocumentView(doc);
if (docView) {
docView.props.focus(docView.props.Document);
}
}
+ }
- };
-
- private ref: React.RefObject<HTMLDivElement>;
+ private ref = React.createRef<HTMLDivElement>();
//initilize class variables
constructor(props: PresViewProps) {
super(props);
- this.ref = React.createRef()
PresentationView.Instance = this;
}
@@ -148,21 +135,21 @@ export class PresentationView extends React.Component<PresViewProps> {
* Adds a document to the presentation view
**/
@action
- public PinDoc(doc: Document) {
+ public PinDoc(doc: Doc) {
//add this new doc to props.Document
- if (this.props.Document.Get(KeyStore.Data) instanceof Field) {
- const value = this.props.Document.GetData(KeyStore.Data, ListField, new Array<Document>())
- value.push(doc);
+ const data = Cast(this.props.Document.data, listSpec(Doc));
+ if (data) {
+ data.push(doc);
} else {
- this.props.Document.SetData(KeyStore.Data, [doc], ListField);
+ this.props.Document.data = new List([doc]);
}
- this.props.Document.SetNumber(KeyStore.Width, 300);
+ this.props.Document.width = 300;
}
render() {
let titleStr = this.props.Document.Title;
- let width = this.props.Document.GetNumber(KeyStore.Width, 0);
+ let width = NumCast(this.props.Document.width);
//TODO: next and back should be icons
return (
diff --git a/src/client/views/TemplateMenu.tsx b/src/client/views/TemplateMenu.tsx
index 8eb2fc6c6..f29d9c8a1 100644
--- a/src/client/views/TemplateMenu.tsx
+++ b/src/client/views/TemplateMenu.tsx
@@ -1,4 +1,4 @@
-import { observable, computed, action } from "mobx";
+import { observable, computed, action, trace } from "mobx";
import React = require("react");
import { observer } from "mobx-react";
import './DocumentDecorations.scss';
@@ -33,23 +33,24 @@ export interface TemplateMenuProps {
export class TemplateMenu extends React.Component<TemplateMenuProps> {
@observable private _hidden: boolean = true;
- @observable private _templates: Map<Template, boolean> = this.props.templates;
@action
toggleTemplate = (event: React.ChangeEvent<HTMLInputElement>, template: Template): void => {
if (event.target.checked) {
this.props.doc.addTemplate(template);
- this._templates.set(template, true);
+ this.props.templates.set(template, true);
+ this.props.templates.forEach((checked, template) => console.log("Set Checked + " + checked + " " + this.props.templates.get(template)));
} else {
this.props.doc.removeTemplate(template);
- this._templates.set(template, false);
+ this.props.templates.set(template, false);
+ this.props.templates.forEach((checked, template) => console.log("Unset Checked + " + checked + " " + this.props.templates.get(template)));
}
}
@action
componentWillReceiveProps(nextProps: TemplateMenuProps) {
- this._templates = nextProps.templates;
+ // this._templates = nextProps.templates;
}
@action
@@ -59,9 +60,8 @@ export class TemplateMenu extends React.Component<TemplateMenuProps> {
render() {
let templateMenu: Array<JSX.Element> = [];
- this._templates.forEach((checked, template) => {
- templateMenu.push(<TemplateToggle key={template.Name} template={template} checked={checked} toggle={this.toggleTemplate} />);
- });
+ this.props.templates.forEach((checked, template) =>
+ templateMenu.push(<TemplateToggle key={template.Name} template={template} checked={checked} toggle={this.toggleTemplate} />));
return (
<div className="templating-menu" >
diff --git a/src/client/views/Templates.tsx b/src/client/views/Templates.tsx
index fef69392d..5858ee014 100644
--- a/src/client/views/Templates.tsx
+++ b/src/client/views/Templates.tsx
@@ -39,20 +39,36 @@ export namespace Templates {
// export const BasicLayout = new Template("Basic layout", "{layout}");
export const OuterCaption = new Template("Outer caption", TemplatePosition.OutterBottom,
- `<div><div style="margin:auto; height:calc(100%); width:100%;">{layout}</div><div style="height:(100% + 50px); width:100%; position:absolute"><FormattedTextBox {...props} fieldKey={CaptionKey} /></div></div>`
+ `<div><div style="margin:auto; height:calc(100%); width:100%;">{layout}</div><div style="height:(100% + 50px); width:100%; position:absolute"><FormattedTextBox {...props} fieldKey={"caption"} /></div></div>`
);
export const InnerCaption = new Template("Inner caption", TemplatePosition.InnerBottom,
- `<div><div style="margin:auto; height:calc(100% - 50px); width:100%;">{layout}</div><div style="height:50px; width:100%; position:absolute"><FormattedTextBox {...props} fieldKey={CaptionKey}/></div></div>`
+ `<div><div style="margin:auto; height:calc(100% - 50px); width:100%;">{layout}</div><div style="height:50px; width:100%; position:absolute"><FormattedTextBox {...props} fieldKey={"caption"}/></div></div>`
);
export const SideCaption = new Template("Side caption", TemplatePosition.OutterRight,
- `<div><div style="margin:auto; height:100%; width:100%;">{layout}</div><div style="height:100%; width:300px; position:absolute; top: 0; right: -300px;"><FormattedTextBox {...props} fieldKey={CaptionKey}/></div> </div>`
+ `<div><div style="margin:auto; height:100%; width:100%;">{layout}</div><div style="height:100%; width:300px; position:absolute; top: 0; right: -300px;"><FormattedTextBox {...props} fieldKey={"caption"}/></div> </div>`
);
export const Title = new Template("Title", TemplatePosition.InnerTop,
- `<div><div style="height:100%; width:100%;position:absolute;">{layout}</div><div style="height:25px; width:100%; position:absolute; top: 0; background-color: rgba(0, 0, 0, .4); color: white; padding:2px 10px">{Title}</div></div>`
+ `<div><div style="height:100%; width:100%;position:absolute;">{layout}</div><div style="height:25px; width:100%; position:absolute; top: 0; background-color: rgba(0, 0, 0, .4); color: white; padding:2px 10px">{props.Document.title}</div></div>`
);
+ export const Summary = new Template("Title", TemplatePosition.InnerTop,
+ `<div><div style="height:100%; width:100%;position:absolute;">{layout}</div><div style="height:25px; width:100%; position:absolute; top: 0; background-color: rgba(0, 0, 0, .4); color: white; padding:2px 10px">{props.Document.doc1.title}</div></div>`
+ );
+ // export const Summary = new Template("Title", TemplatePosition.InnerTop,
+ // `<div style="height:100%; width:100%;position:absolute; margin:0; padding: 0">
+ // <div style="height:60%; width:100%;position:absolute;background:yellow; padding:0; margin:0">
+ // {layout}
+ // </div>
+ // <div style="bottom:0px; height:40%; width:50%; position:absolute; background-color: rgba(0, 0, 0, .4); color: white;">
+ // <FieldView {...props} fieldKey={"doc1"} />
+ // </div>
+ // <div style="bottom:0; left: 50%; height:40%; width:50%; position:absolute; background-color: rgba(0, 0, 0, .4); color: white;">
+ // <FieldView {...props} fieldKey={"doc2"} />
+ // </div>
+ // </div>`
+ // );
export const TemplateList: Template[] = [Title, OuterCaption, InnerCaption, SideCaption];
diff --git a/src/client/views/collections/CollectionBaseView.tsx b/src/client/views/collections/CollectionBaseView.tsx
index aa8fce923..76adfcdcd 100644
--- a/src/client/views/collections/CollectionBaseView.tsx
+++ b/src/client/views/collections/CollectionBaseView.tsx
@@ -1,13 +1,13 @@
import { action, computed } from 'mobx';
import { observer } from 'mobx-react';
import * as React from 'react';
-import { Document } from '../../../fields/Document';
-import { FieldValue, FieldWaiting } from '../../../fields/Field';
-import { KeyStore } from '../../../fields/KeyStore';
-import { ListField } from '../../../fields/ListField';
-import { NumberField } from '../../../fields/NumberField';
import { ContextMenu } from '../ContextMenu';
import { FieldViewProps } from '../nodes/FieldView';
+import { Cast, FieldValue, PromiseValue, NumCast } from '../../../new_fields/Types';
+import { Doc, FieldResult, Opt } from '../../../new_fields/Doc';
+import { listSpec } from '../../../new_fields/Schema';
+import { List } from '../../../new_fields/List';
+import { Id } from '../../../new_fields/RefField';
import { SelectionManager } from '../../util/SelectionManager';
export enum CollectionViewType {
@@ -19,9 +19,9 @@ export enum CollectionViewType {
}
export interface CollectionRenderProps {
- addDocument: (document: Document, allowDuplicates?: boolean) => boolean;
- removeDocument: (document: Document) => boolean;
- moveDocument: (document: Document, targetCollection: Document, addDocument: (document: Document) => boolean) => boolean;
+ addDocument: (document: Doc, allowDuplicates?: boolean) => boolean;
+ removeDocument: (document: Doc) => boolean;
+ moveDocument: (document: Doc, targetCollection: Doc, addDocument: (document: Doc) => boolean) => boolean;
active: () => boolean;
whenActiveChanged: (isActive: boolean) => void;
}
@@ -38,11 +38,9 @@ export interface CollectionViewProps extends FieldViewProps {
export class CollectionBaseView extends React.Component<CollectionViewProps> {
get collectionViewType(): CollectionViewType | undefined {
let Document = this.props.Document;
- let viewField = Document.GetT(KeyStore.ViewType, NumberField);
- if (viewField === FieldWaiting) {
- return undefined;
- } else if (viewField) {
- return viewField.Data;
+ let viewField = Cast(Document.viewType, "number");
+ if (viewField !== undefined) {
+ return viewField;
} else {
return CollectionViewType.Invalid;
}
@@ -61,100 +59,73 @@ export class CollectionBaseView extends React.Component<CollectionViewProps> {
this.props.whenActiveChanged(isActive);
}
- createsCycle(documentToAdd: Document, containerDocument: Document): boolean {
- if (!(documentToAdd instanceof Document)) {
+ createsCycle(documentToAdd: Doc, containerDocument: Doc): boolean {
+ if (!(documentToAdd instanceof Doc)) {
return false;
}
- let data = documentToAdd.GetList(KeyStore.Data, [] as Document[]);
+ let data = Cast(documentToAdd.data, listSpec(Doc), []);
for (const doc of data.filter(d => d instanceof Document)) {
if (this.createsCycle(doc, containerDocument)) {
return true;
}
}
- let annots = documentToAdd.GetList(KeyStore.Annotations, [] as Document[]);
+ let annots = Cast(documentToAdd.annotations, listSpec(Doc), []);
for (const annot of annots) {
if (this.createsCycle(annot, containerDocument)) {
return true;
}
}
- for (let containerProto: FieldValue<Document> = containerDocument; containerProto && containerProto !== FieldWaiting; containerProto = containerProto.GetPrototype()) {
- if (containerProto.Id === documentToAdd.Id) {
+ for (let containerProto: Opt<Doc> = containerDocument; containerProto !== undefined; containerProto = FieldValue(containerProto.proto)) {
+ if (containerProto[Id] === documentToAdd[Id]) {
return true;
}
}
return false;
}
- @computed get isAnnotationOverlay() { return this.props.fieldKey && this.props.fieldKey.Id === KeyStore.Annotations.Id; } // bcz: ? Why do we need to compare Id's?
+ @computed get isAnnotationOverlay() { return this.props.fieldKey && this.props.fieldKey === "annotations"; }
@action.bound
- addDocument(doc: Document, allowDuplicates: boolean = false): boolean {
- var curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1);
- doc.SetOnPrototype(KeyStore.Page, new NumberField(curPage));
+ addDocument(doc: Doc, allowDuplicates: boolean = false): boolean {
+ let props = this.props;
+ var curPage = Cast(props.Document.curPage, "number", -1);
+ Doc.SetOnPrototype(doc, "page", curPage);
if (curPage >= 0) {
- doc.SetOnPrototype(KeyStore.AnnotationOn, this.props.Document);
+ Doc.SetOnPrototype(doc, "annotationOn", props.Document);
}
- if (!this.createsCycle(doc, this.props.Document)) {
- let value = this.props.Document.Get(this.props.fieldKey) as ListField<Document>;
- if (value) {
- if (!value.Data.some(v => v.Id === doc.Id) || allowDuplicates) {
- value.Data.push(doc);
+ if (!this.createsCycle(doc, props.Document)) {
+ //TODO This won't create the field if it doesn't already exist
+ const value = Cast(props.Document[props.fieldKey], listSpec(Doc));
+ if (value !== undefined) {
+ if (allowDuplicates || !value.some(v => v[Id] === doc[Id])) {
+ value.push(doc);
}
} else {
- this.props.Document.Set(this.props.fieldKey, new ListField([doc]));
+ this.props.Document[this.props.fieldKey] = new List([doc]);
}
// set the ZoomBasis only if hasn't already been set -- bcz: maybe set/resetting the ZoomBasis should be a parameter to addDocument?
if (this.collectionViewType === CollectionViewType.Freeform || this.collectionViewType === CollectionViewType.Invalid) {
- let zoom = this.props.Document.GetNumber(KeyStore.Scale, 1);
- doc.SetNumber(KeyStore.ZoomBasis, zoom);
+ let zoom = NumCast(this.props.Document.scale, 1);
+ doc.zoomBasis = zoom;
}
}
return true;
- // bcz: What is this code trying to do?
- // else {
- // let proto = props.Document.GetPrototype();
- // if (!proto || proto === FieldWaiting || !this.createsCycle(proto, doc)) {
- // const field = new ListField([doc]);
- // // const script = CompileScript(`
- // // if(added) {
- // // console.log("added " + field.Title + " " + doc.Title);
- // // } else {
- // // console.log("removed " + field.Title + " " + doc.Title);
- // // }
- // // `, {
- // // addReturn: false,
- // // params: {
- // // field: Document.name,
- // // added: "boolean"
- // // },
- // // capturedVariables: {
- // // doc: this.props.Document
- // // }
- // // });
- // // if (script.compiled) {
- // // field.addScript(new ScriptField(script));
- // // }
- // props.Document.SetOnPrototype(props.fieldKey, field);
- // return true;
- // }
- // }
- return false;
}
@action.bound
- removeDocument(doc: Document): boolean {
+ removeDocument(doc: Doc): boolean {
const props = this.props;
//TODO This won't create the field if it doesn't already exist
- const value = props.Document.GetData(props.fieldKey, ListField, new Array<Document>());
+ const value = Cast(props.Document[props.fieldKey], listSpec(Doc), []);
let index = -1;
for (let i = 0; i < value.length; i++) {
- if (value[i].Id === doc.Id) {
+ if (value[i][Id] === doc[Id]) {
index = i;
break;
}
}
- doc.GetTAsync(KeyStore.AnnotationOn, Document).then((annotationOn) => {
+ PromiseValue(Cast(doc.annotationOn, Doc)).then((annotationOn) => {
if (annotationOn === props.Document) {
- doc.Set(KeyStore.AnnotationOn, undefined, true);
+ doc.annotationOn = undefined;
}
});
@@ -169,7 +140,7 @@ export class CollectionBaseView extends React.Component<CollectionViewProps> {
}
@action.bound
- moveDocument(doc: Document, targetCollection: Document, addDocument: (doc: Document) => boolean): boolean {
+ moveDocument(doc: Doc, targetCollection: Doc, addDocument: (doc: Doc) => boolean): boolean {
if (this.props.Document === targetCollection) {
return true;
}
diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx
index 2a8191c3a..cfb1aef7d 100644
--- a/src/client/views/collections/CollectionDockingView.tsx
+++ b/src/client/views/collections/CollectionDockingView.tsx
@@ -1,36 +1,37 @@
import * as GoldenLayout from "golden-layout";
import 'golden-layout/src/css/goldenlayout-base.css';
import 'golden-layout/src/css/goldenlayout-dark-theme.css';
-import { action, observable, reaction, trace } from "mobx";
+import { action, observable, reaction, trace, runInAction } from "mobx";
import { observer } from "mobx-react";
import * as ReactDOM from 'react-dom';
-import { Document } from "../../../fields/Document";
-import { KeyStore } from "../../../fields/KeyStore";
import Measure from "react-measure";
-import { FieldId, Opt, Field, FieldWaiting } from "../../../fields/Field";
-import { Utils, returnTrue, emptyFunction, emptyDocFunction, returnOne, returnZero } from "../../../Utils";
-import { Server } from "../../Server";
+import { Utils, returnTrue, emptyFunction, returnOne, returnZero } from "../../../Utils";
import { undoBatch, UndoManager } from "../../util/UndoManager";
import { DocumentView } from "../nodes/DocumentView";
import "./CollectionDockingView.scss";
import React = require("react");
import { SubCollectionViewProps } from "./CollectionSubView";
-import { ServerUtils } from "../../../server/ServerUtil";
import { DragManager, DragLinksAsDocuments } from "../../util/DragManager";
-import { TextField } from "../../../fields/TextField";
-import { ListField } from "../../../fields/ListField";
-import { Transform } from '../../util/Transform'
+import { Transform } from '../../util/Transform';
+import { Doc, Opt, Field } from "../../../new_fields/Doc";
+import { Cast, NumCast, StrCast } from "../../../new_fields/Types";
+import { List } from "../../../new_fields/List";
+import { DocServer } from "../../DocServer";
+import { listSpec } from "../../../new_fields/Schema";
+import { Id, FieldId } from "../../../new_fields/RefField";
+import { faSignInAlt } from "@fortawesome/free-solid-svg-icons";
@observer
export class CollectionDockingView extends React.Component<SubCollectionViewProps> {
public static Instance: CollectionDockingView;
- public static makeDocumentConfig(document: Document) {
+ public static makeDocumentConfig(document: Doc, width?: number) {
return {
type: 'react-component',
component: 'DocumentFrameRenderer',
- title: document.Title,
+ title: document.title,
+ width: width,
props: {
- documentId: document.Id,
+ documentId: document[Id],
//collectionDockingView: CollectionDockingView.Instance
}
};
@@ -38,7 +39,6 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp
private _goldenLayout: any = null;
private _containerRef = React.createRef<HTMLDivElement>();
- private _fullScreen: any = null;
private _flush: boolean = false;
private _ignoreStateChange = "";
@@ -50,7 +50,7 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp
}
hack: boolean = false;
undohack: any = null;
- public StartOtherDrag(dragDocs: Document[], e: any) {
+ public StartOtherDrag(dragDocs: Doc[], e: any) {
this.hack = true;
this.undohack = UndoManager.StartBatch("goldenDrag");
dragDocs.map(dragDoc =>
@@ -59,7 +59,7 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp
}
@action
- public OpenFullScreen(document: Document) {
+ public OpenFullScreen(document: Doc) {
let newItemStackConfig = {
type: 'stack',
content: [CollectionDockingView.makeDocumentConfig(document)]
@@ -68,26 +68,19 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp
this._goldenLayout.root.contentItems[0].addChild(docconfig);
docconfig.callDownwards('_$init');
this._goldenLayout._$maximiseItem(docconfig);
- this._fullScreen = docconfig;
this._ignoreStateChange = JSON.stringify(this._goldenLayout.toConfig());
this.stateChanged();
}
- @action
- public CloseFullScreen() {
- if (this._fullScreen) {
- this._goldenLayout._$minimiseItem(this._fullScreen);
- this._goldenLayout.root.contentItems[0].removeChild(this._fullScreen);
- this._fullScreen = null;
- this._ignoreStateChange = JSON.stringify(this._goldenLayout.toConfig());
- this.stateChanged();
- }
- }
//
// Creates a vertical split on the right side of the docking view, and then adds the Document to that split
//
@action
- public AddRightSplit(document: Document, minimize: boolean = false) {
+ public AddRightSplit(document: Doc, minimize: boolean = false) {
+ let docs = Cast(this.props.Document.data, listSpec(Doc));
+ if (docs) {
+ docs.push(document);
+ }
let newItemStackConfig = {
type: 'stack',
content: [CollectionDockingView.makeDocumentConfig(document)]
@@ -123,7 +116,7 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp
}
setupGoldenLayout() {
- var config = this.props.Document.GetText(KeyStore.Data, "");
+ var config = StrCast(this.props.Document.dockingConfig);
if (config) {
if (!this._goldenLayout) {
this._goldenLayout = new GoldenLayout(JSON.parse(config));
@@ -158,7 +151,7 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp
componentDidMount: () => void = () => {
if (this._containerRef.current) {
reaction(
- () => this.props.Document.GetText(KeyStore.Data, ""),
+ () => StrCast(this.props.Document.dockingConfig),
() => {
if (!this._goldenLayout || this._ignoreStateChange !== JSON.stringify(this._goldenLayout.toConfig())) {
setTimeout(() => this.setupGoldenLayout(), 1);
@@ -206,8 +199,8 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp
let y = e.clientY;
let docid = (e.target as any).DashDocId;
let tab = (e.target as any).parentElement as HTMLElement;
- Server.GetField(docid, action(async (sourceDoc: Opt<Field>) =>
- (sourceDoc instanceof Document) && DragLinksAsDocuments(tab, x, y, sourceDoc)));
+ DocServer.GetRefField(docid).then(action(async (sourceDoc: Opt<Field>) =>
+ (sourceDoc instanceof Doc) && DragLinksAsDocuments(tab, x, y, sourceDoc)));
} else
if ((className === "lm_title" || className === "lm_tab lm_active") && !e.shiftKey) {
e.stopPropagation();
@@ -216,12 +209,12 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp
let y = e.clientY;
let docid = (e.target as any).DashDocId;
let tab = (e.target as any).parentElement as HTMLElement;
- Server.GetField(docid, action((f: Opt<Field>) => {
- if (f instanceof Document) {
+ DocServer.GetRefField(docid).then(action((f: Opt<Field>) => {
+ if (f instanceof Doc) {
DragManager.StartDocumentDrag([tab], new DragManager.DocumentDragData([f]), x, y,
{
handlers: {
- dragComplete: action(emptyFunction),
+ dragComplete: emptyFunction,
},
hideSource: false
});
@@ -239,7 +232,7 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp
@undoBatch
stateChanged = () => {
var json = JSON.stringify(this._goldenLayout.toConfig());
- this.props.Document.SetText(KeyStore.Data, json);
+ this.props.Document.dockingConfig = json;
if (this.undohack && !this.hack) {
this.undohack.end();
this.undohack = undefined;
@@ -260,35 +253,38 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp
tabCreated = (tab: any) => {
if (tab.hasOwnProperty("contentItem") && tab.contentItem.config.type !== "stack") {
- Server.GetField(tab.contentItem.config.props.documentId, action((f: Opt<Field>) => {
- if (f !== undefined && f instanceof Document) {
- f.GetTAsync(KeyStore.Title, TextField, (tfield) => {
- if (tfield !== undefined) {
- tab.titleElement[0].textContent = f.Title;
- }
- });
- f.GetTAsync(KeyStore.LinkedFromDocs, ListField).then(lf =>
- f.GetTAsync(KeyStore.LinkedToDocs, ListField).then(lt => {
- let count = (lf ? lf.Data.length : 0) + (lt ? lt.Data.length : 0);
- let counter: any = this.htmlToElement(`<div class="messageCounter">${count}</div>`);
- tab.element.append(counter);
- counter.DashDocId = tab.contentItem.config.props.documentId;
- tab.reactionDisposer = reaction(() => [f.GetT(KeyStore.LinkedFromDocs, ListField), f.GetT(KeyStore.LinkedToDocs, ListField)],
- (lists) => {
- let count = (lists.length > 0 && lists[0] && lists[0]!.Data ? lists[0]!.Data.length : 0) +
- (lists.length > 1 && lists[1] && lists[1]!.Data ? lists[1]!.Data.length : 0);
- counter.innerHTML = count;
- });
- }));
+ DocServer.GetRefField(tab.contentItem.config.props.documentId).then(async f => {
+ if (f instanceof Doc) {
+ const title = Cast(f.title, "string");
+ if (title !== undefined) {
+ tab.titleElement[0].textContent = title;
+ }
+ const lf = await Cast(f.linkedFromDocs, listSpec(Doc));
+ const lt = await Cast(f.linkedToDocs, listSpec(Doc));
+ let count = (lf ? lf.length : 0) + (lt ? lt.length : 0);
+ let counter: any = this.htmlToElement(`<div class="messageCounter">${count}</div>`);
+ tab.element.append(counter);
+ counter.DashDocId = tab.contentItem.config.props.documentId;
+ tab.reactionDisposer = reaction((): [List<Field> | null | undefined, List<Field> | null | undefined] => [lf, lt],
+ ([linkedFrom, linkedTo]) => {
+ let count = (linkedFrom ? linkedFrom.length : 0) + (linkedTo ? linkedTo.length : 0);
+ counter.innerHTML = count;
+ });
tab.titleElement[0].DashDocId = tab.contentItem.config.props.documentId;
}
- }));
+ });
}
tab.closeElement.off('click') //unbind the current click handler
.click(function () {
if (tab.reactionDisposer) {
tab.reactionDisposer();
}
+ DocServer.GetRefField(tab.contentItem.config.props.documentId).then(async f => runInAction(() => {
+ if (f instanceof Doc) {
+ let docs = Cast(CollectionDockingView.Instance.props.Document.data, listSpec(Doc));
+ docs && docs.indexOf(f) !== -1 && docs.splice(docs.indexOf(f), 1);
+ }
+ }));
tab.contentItem.remove();
});
}
@@ -305,7 +301,7 @@ export class CollectionDockingView extends React.Component<SubCollectionViewProp
stack.header.controlsContainer.find('.lm_popout') //get the close icon
.off('click') //unbind the current click handler
.click(action(function () {
- var url = ServerUtils.prepend("/doc/" + stack.contentItems[0].tab.contentItem.config.props.documentId);
+ var url = DocServer.prepend("/doc/" + stack.contentItems[0].tab.contentItem.config.props.documentId);
let win = window.open(url, stack.contentItems[0].tab.title, "width=300,height=400");
}));
}
@@ -324,36 +320,29 @@ interface DockedFrameProps {
}
@observer
export class DockedFrameRenderer extends React.Component<DockedFrameProps> {
-
_mainCont = React.createRef<HTMLDivElement>();
@observable private _panelWidth = 0;
@observable private _panelHeight = 0;
- @observable private _document: Opt<Document>;
+ @observable private _document: Opt<Doc>;
constructor(props: any) {
super(props);
- Server.GetField(this.props.documentId, action((f: Opt<Field>) => this._document = f as Document));
+ DocServer.GetRefField(this.props.documentId).then(action((f: Opt<Field>) => this._document = f as Doc));
}
- nativeWidth = () => {
- let pw = this._document!.GetNumber(KeyStore.NativeWidth, 0);
- return pw ? pw : this._panelWidth;
- }
- nativeHeight = () => {
- let pw = this._document!.GetNumber(KeyStore.NativeHeight, 0);
- return pw ? pw : this._panelHeight;
- }
+ nativeWidth = () => NumCast(this._document!.nativeWidth, this._panelWidth);
+ nativeHeight = () => NumCast(this._document!.nativeHeight, this._panelHeight);
contentScaling = () => {
- let wscale = this._panelWidth / (this.nativeWidth() ? this.nativeWidth() : this._panelWidth);
- if (wscale * this.nativeHeight() > this._panelHeight)
- return this._panelHeight / (this.nativeHeight() ? this.nativeHeight() : this._panelHeight);
- return wscale;
+ const nativeH = this.nativeHeight();
+ const nativeW = this.nativeWidth();
+ let wscale = this._panelWidth / nativeW;
+ return wscale * nativeH > this._panelHeight ? this._panelHeight / nativeH : wscale;
}
ScreenToLocalTransform = () => {
if (this._mainCont.current && this._mainCont.current.children) {
- let { scale, translateX, translateY } = Utils.GetScreenTransform(this._mainCont.current!.children[0].firstChild as HTMLElement);
- scale = Utils.GetScreenTransform(this._mainCont.current!).scale;
+ let { scale, translateX, translateY } = Utils.GetScreenTransform(this._mainCont.current.children[0].firstChild as HTMLElement);
+ scale = Utils.GetScreenTransform(this._mainCont.current).scale;
return CollectionDockingView.Instance.props.ScreenToLocalTransform().translate(-translateX, -translateY).scale(scale / this.contentScaling());
}
return Transform.Identity();
@@ -361,10 +350,12 @@ export class DockedFrameRenderer extends React.Component<DockedFrameProps> {
get previewPanelCenteringOffset() { return (this._panelWidth - this.nativeWidth() * this.contentScaling()) / 2; }
get content() {
+ if (!this._document)
+ return (null);
return (
<div className="collectionDockingView-content" ref={this._mainCont}
style={{ transform: `translate(${this.previewPanelCenteringOffset}px, 0px)` }}>
- <DocumentView key={this._document!.Id} Document={this._document!}
+ <DocumentView key={this._document![Id]} Document={this._document!}
toggleMinimized={emptyFunction}
addDocument={undefined}
removeDocument={undefined}
@@ -376,15 +367,16 @@ export class DockedFrameRenderer extends React.Component<DockedFrameProps> {
selectOnLoad={false}
parentActive={returnTrue}
whenActiveChanged={emptyFunction}
- focus={emptyDocFunction}
+ focus={emptyFunction}
ContainingCollectionView={undefined} />
- </div>);
+ </div >);
}
render() {
+ let theContent = this.content;
return !this._document ? (null) :
<Measure onResize={action((r: any) => { this._panelWidth = r.entry.width; this._panelHeight = r.entry.height; })}>
- {({ measureRef }) => <div ref={measureRef}> {this.content} </div>}
+ {({ measureRef }) => <div ref={measureRef}> {theContent} </div>}
</Measure>;
}
} \ No newline at end of file
diff --git a/src/client/views/collections/CollectionPDFView.tsx b/src/client/views/collections/CollectionPDFView.tsx
index 497c3ee3c..b3762206a 100644
--- a/src/client/views/collections/CollectionPDFView.tsx
+++ b/src/client/views/collections/CollectionPDFView.tsx
@@ -1,6 +1,5 @@
import { action, observable } from "mobx";
import { observer } from "mobx-react";
-import { KeyStore } from "../../../fields/KeyStore";
import { ContextMenu } from "../ContextMenu";
import "./CollectionPDFView.scss";
import React = require("react");
@@ -8,21 +7,23 @@ import { CollectionFreeFormView } from "./collectionFreeForm/CollectionFreeFormV
import { FieldView, FieldViewProps } from "../nodes/FieldView";
import { CollectionRenderProps, CollectionBaseView, CollectionViewType } from "./CollectionBaseView";
import { emptyFunction } from "../../../Utils";
+import { NumCast } from "../../../new_fields/Types";
+import { Id } from "../../../new_fields/RefField";
@observer
export class CollectionPDFView extends React.Component<FieldViewProps> {
- public static LayoutString(fieldKey: string = "DataKey") {
+ public static LayoutString(fieldKey: string = "data") {
return FieldView.LayoutString(CollectionPDFView, fieldKey);
}
@observable _inThumb = false;
- private get curPage() { return this.props.Document.GetNumber(KeyStore.CurPage, -1); }
- private set curPage(value: number) { this.props.Document.SetNumber(KeyStore.CurPage, value); }
- private get numPages() { return this.props.Document.GetNumber(KeyStore.NumPages, 0); }
- @action onPageBack = () => this.curPage > 1 ? this.props.Document.SetNumber(KeyStore.CurPage, this.curPage - 1) : -1;
- @action onPageForward = () => this.curPage < this.numPages ? this.props.Document.SetNumber(KeyStore.CurPage, this.curPage + 1) : -1;
+ private set curPage(value: number) { this.props.Document.curPage = value; }
+ private get curPage() { return NumCast(this.props.Document.curPage, -1); }
+ private get numPages() { return NumCast(this.props.Document.numPages); }
+ @action onPageBack = () => this.curPage > 1 ? (this.props.Document.curPage = this.curPage - 1) : -1;
+ @action onPageForward = () => this.curPage < this.numPages ? (this.props.Document.curPage = this.curPage + 1) : -1;
@action
onThumbDown = (e: React.PointerEvent) => {
@@ -43,8 +44,8 @@ export class CollectionPDFView extends React.Component<FieldViewProps> {
document.removeEventListener("pointermove", this.onThumbMove);
document.removeEventListener("pointerup", this.onThumbUp);
}
- nativeWidth = () => this.props.Document.GetNumber(KeyStore.NativeWidth, 0);
- nativeHeight = () => this.props.Document.GetNumber(KeyStore.NativeHeight, 0);
+ nativeWidth = () => NumCast(this.props.Document.nativeWidth);
+ nativeHeight = () => NumCast(this.props.Document.nativeHeight);
private get uIButtons() {
let ratio = (this.curPage - 1) / this.numPages * 100;
return (
@@ -59,7 +60,7 @@ export class CollectionPDFView extends React.Component<FieldViewProps> {
}
onContextMenu = (e: React.MouseEvent): void => {
- if (!e.isPropagationStopped() && this.props.Document.Id !== "mainDoc") { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7
+ if (!e.isPropagationStopped() && this.props.Document[Id] !== "mainDoc") { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7
ContextMenu.Instance.addItem({ description: "PDFOptions", event: emptyFunction });
}
}
diff --git a/src/client/views/collections/CollectionSchemaView.tsx b/src/client/views/collections/CollectionSchemaView.tsx
index b3cc3fbd5..67784fa81 100644
--- a/src/client/views/collections/CollectionSchemaView.tsx
+++ b/src/client/views/collections/CollectionSchemaView.tsx
@@ -5,17 +5,11 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { action, computed, observable, untracked, runInAction } from "mobx";
import { observer } from "mobx-react";
import ReactTable, { CellInfo, ComponentPropsGetterR, ReactTableDefaults } from "react-table";
-import { MAX_ROW_HEIGHT } from '../../views/globalCssVariables.scss'
+import { MAX_ROW_HEIGHT } from '../../views/globalCssVariables.scss';
import "react-table/react-table.css";
-import { Document } from "../../../fields/Document";
-import { Field, Opt, FieldWaiting } from "../../../fields/Field";
-import { Key } from "../../../fields/Key";
-import { KeyStore } from "../../../fields/KeyStore";
-import { ListField } from "../../../fields/ListField";
-import { emptyDocFunction, emptyFunction, returnFalse, returnZero } from "../../../Utils";
-import { Server } from "../../Server";
+import { emptyFunction, returnFalse, returnZero } from "../../../Utils";
import { SetupDrag } from "../../util/DragManager";
-import { CompileScript, ToField } from "../../util/Scripting";
+import { CompileScript } from "../../util/Scripting";
import { Transform } from "../../util/Transform";
import { COLLECTION_BORDER_WIDTH } from "../../views/globalCssVariables.scss";
import { anchorPoints, Flyout } from "../DocumentDecorations";
@@ -25,43 +19,46 @@ import { DocumentView } from "../nodes/DocumentView";
import { FieldView, FieldViewProps } from "../nodes/FieldView";
import "./CollectionSchemaView.scss";
import { CollectionSubView } from "./CollectionSubView";
+import { Opt, Field, Doc } from "../../../new_fields/Doc";
+import { Cast, FieldValue, NumCast } from "../../../new_fields/Types";
+import { listSpec } from "../../../new_fields/Schema";
+import { List } from "../../../new_fields/List";
+import { Id } from "../../../new_fields/RefField";
// bcz: need to add drag and drop of rows and columns. This seems like it might work for rows: https://codesandbox.io/s/l94mn1q657
@observer
-class KeyToggle extends React.Component<{ keyId: string, checked: boolean, toggle: (key: Key) => void }> {
- @observable key: Key | undefined;
-
+class KeyToggle extends React.Component<{ keyName: string, checked: boolean, toggle: (key: string) => void }> {
constructor(props: any) {
super(props);
- Server.GetField(this.props.keyId, action((field: Opt<Field>) => field instanceof Key && (this.key = field)));
}
render() {
- return !this.key ? (null) :
- (<div key={this.key.Id}>
- <input type="checkbox" checked={this.props.checked} onChange={() => this.key && this.props.toggle(this.key)} />
- {this.key.Name}
- </div>);
+ return (
+ <div key={this.props.keyName}>
+ <input type="checkbox" checked={this.props.checked} onChange={() => this.props.toggle(this.props.keyName)} />
+ {this.props.keyName}
+ </div>
+ );
}
}
@observer
-export class CollectionSchemaView extends CollectionSubView {
+export class CollectionSchemaView extends CollectionSubView(doc => doc) {
private _mainCont?: HTMLDivElement;
private _startSplitPercent = 0;
private DIVIDER_WIDTH = 4;
- @observable _columns: Array<Key> = [KeyStore.Title, KeyStore.Data, KeyStore.Author];
+ @observable _columns: Array<string> = ["title", "data", "author"];
@observable _selectedIndex = 0;
@observable _columnsPercentage = 0;
- @observable _keys: Key[] = [];
+ @observable _keys: string[] = [];
@observable _newKeyName: string = "";
- @computed get splitPercentage() { return this.props.Document.GetNumber(KeyStore.SchemaSplitPercentage, 0); }
- @computed get columns() { return this.props.Document.GetList(KeyStore.ColumnsKey, [] as Key[]); }
+ @computed get splitPercentage() { return NumCast(this.props.Document.schemaSplitPercentage); }
+ @computed get columns() { return Cast(this.props.Document.schemaColumns, listSpec("string"), []); }
@computed get borderWidth() { return Number(COLLECTION_BORDER_WIDTH); }
renderCell = (rowProps: CellInfo) => {
@@ -74,7 +71,7 @@ export class CollectionSchemaView extends CollectionSubView {
isTopMost: false,
selectOnLoad: false,
ScreenToLocalTransform: Transform.Identity,
- focus: emptyDocFunction,
+ focus: emptyFunction,
active: returnFalse,
whenActiveChanged: emptyFunction,
PanelHeight: returnZero,
@@ -85,34 +82,27 @@ export class CollectionSchemaView extends CollectionSubView {
);
let reference = React.createRef<HTMLDivElement>();
let onItemDown = SetupDrag(reference, () => props.Document, this.props.moveDocument);
- let applyToDoc = (doc: Document, run: (args?: { [name: string]: any }) => any) => {
+ let applyToDoc = (doc: Doc, run: (args?: { [name: string]: any }) => any) => {
const res = run({ this: doc });
if (!res.success) return false;
const field = res.result;
- if (field instanceof Field) {
- doc.Set(props.fieldKey, field);
- return true;
- } else {
- let dataField = ToField(field);
- if (dataField) {
- doc.Set(props.fieldKey, dataField);
- return true;
- }
- }
- return false;
+ doc[props.fieldKey] = field;
+ return true;
};
return (
- <div className="collectionSchemaView-cellContents" onPointerDown={onItemDown} key={props.Document.Id} ref={reference}>
+ <div className="collectionSchemaView-cellContents" onPointerDown={onItemDown} key={props.Document[Id]} ref={reference}>
<EditableView
display={"inline"}
contents={contents}
height={Number(MAX_ROW_HEIGHT)}
GetValue={() => {
- let field = props.Document.Get(props.fieldKey);
- if (field && field instanceof Field) {
- return field.ToScriptString();
+ let field = props.Document[props.fieldKey];
+ if (field) {
+ //TODO Types
+ // return field.ToScriptString();
+ return String(field);
}
- return field || "";
+ return "";
}}
SetValue={(value: string) => {
let script = CompileScript(value, { addReturn: true, params: { this: Document.name } });
@@ -128,14 +118,13 @@ export class CollectionSchemaView extends CollectionSubView {
}
const run = script.run;
//TODO This should be able to be refactored to compile the script once
- this.props.Document.GetTAsync<ListField<Document>>(this.props.fieldKey, ListField).then((val) => {
- if (val) {
- val.Data.forEach(doc => applyToDoc(doc, run));
- }
- });
+ const val = Cast(this.props.Document[this.props.fieldKey], listSpec(Doc));
+ if (val) {
+ val.forEach(doc => applyToDoc(doc, run));
+ }
}}>
</EditableView>
- </div>
+ </div >
);
}
@@ -165,41 +154,38 @@ export class CollectionSchemaView extends CollectionSubView {
super.CreateDropTarget(ele);
}
- toggleKey = (key: Key) => {
- this.props.Document.GetTAsync<ListField<Key>>(KeyStore.ColumnsKey, ListField).then(field =>
- runInAction(() => {
- if (field !== FieldWaiting) {
- if (field) {
- const index = field.Data.indexOf(key);
- if (index === -1) {
- this.columns.push(key);
- } else {
- this.columns.splice(index, 1);
- }
- } else {
- this.props.Document.SetData(KeyStore.ColumnsKey, [key], ListField);
- }
- }
- }));
+ @action
+ toggleKey = (key: string) => {
+ let list = Cast(this.props.Document.schemaColumns, listSpec("string"));
+ if (list === undefined) {
+ this.props.Document.schemaColumns = list = new List<string>([key]);
+ } else {
+ const index = list.indexOf(key);
+ if (index === -1) {
+ list.push(key);
+ } else {
+ list.splice(index, 1);
+ }
+ }
}
//toggles preview side-panel of schema
@action
toggleExpander = (event: React.ChangeEvent<HTMLInputElement>) => {
- this.props.Document.SetNumber(KeyStore.SchemaSplitPercentage, this.splitPercentage === 0 ? 33 : 0);
+ this.props.Document.schemaSplitPercentage = this.splitPercentage === 0 ? 33 : 0;
}
@action
onDividerMove = (e: PointerEvent): void => {
let nativeWidth = this._mainCont!.getBoundingClientRect();
- this.props.Document.SetNumber(KeyStore.SchemaSplitPercentage, Math.max(0, 100 - Math.round((e.clientX - nativeWidth.left) / nativeWidth.width * 100)));
+ this.props.Document.schemaSplitPercentage = Math.max(0, 100 - Math.round((e.clientX - nativeWidth.left) / nativeWidth.width * 100));
}
@action
onDividerUp = (e: PointerEvent): void => {
document.removeEventListener("pointermove", this.onDividerMove);
document.removeEventListener('pointerup', this.onDividerUp);
if (this._startSplitPercent === this.splitPercentage) {
- this.props.Document.SetNumber(KeyStore.SchemaSplitPercentage, this.splitPercentage === 0 ? 33 : 0);
+ this.props.Document.schemaSplitPercentage = this.splitPercentage === 0 ? 33 : 0;
}
}
onDividerDown = (e: React.PointerEvent) => {
@@ -212,8 +198,7 @@ export class CollectionSchemaView extends CollectionSubView {
onPointerDown = (e: React.PointerEvent): void => {
if (e.button === 0 && !e.altKey && !e.ctrlKey && !e.metaKey) {
- if (this.props.isSelected())
- e.stopPropagation();
+ if (this.props.isSelected()) e.stopPropagation();
else e.preventDefault();
}
}
@@ -226,7 +211,7 @@ export class CollectionSchemaView extends CollectionSubView {
@action
addColumn = () => {
- this.columns.push(new Key(this._newKeyName));
+ this.columns.push(this._newKeyName);
this._newKeyName = "";
}
@@ -241,21 +226,22 @@ export class CollectionSchemaView extends CollectionSubView {
this.previewScript = e.currentTarget.value;
}
- get previewDocument(): Document | undefined {
- const children = this.props.Document.GetList(this.props.fieldKey, [] as Document[]);
- const selected = children.length > this._selectedIndex ? children[this._selectedIndex] : undefined;
- return selected ? (this.previewScript ? selected.Get(new Key(this.previewScript)) as Document : selected) : undefined;
+ get previewDocument(): Doc | undefined {
+ const children = Cast(this.props.Document[this.props.fieldKey], listSpec(Doc), []);
+ const selected = children.length > this._selectedIndex ? FieldValue(children[this._selectedIndex]) : undefined;
+ return selected ? (this.previewScript ? FieldValue(Cast(selected[this.previewScript], Doc)) : selected) : undefined;
}
get tableWidth() { return (this.props.PanelWidth() - 2 * this.borderWidth - this.DIVIDER_WIDTH) * (1 - this.splitPercentage / 100); }
get previewRegionHeight() { return this.props.PanelHeight() - 2 * this.borderWidth; }
get previewRegionWidth() { return (this.props.PanelWidth() - 2 * this.borderWidth - this.DIVIDER_WIDTH) * this.splitPercentage / 100; }
- private previewDocNativeWidth = () => this.previewDocument!.GetNumber(KeyStore.NativeWidth, this.previewRegionWidth);
- private previewDocNativeHeight = () => this.previewDocument!.GetNumber(KeyStore.NativeHeight, this.previewRegionHeight);
+ private previewDocNativeWidth = () => Cast(this.previewDocument!.nativeWidth, "number", this.previewRegionWidth);
+ private previewDocNativeHeight = () => Cast(this.previewDocument!.nativeHeight, "number", this.previewRegionHeight);
private previewContentScaling = () => {
let wscale = this.previewRegionWidth / (this.previewDocNativeWidth() ? this.previewDocNativeWidth() : this.previewRegionWidth);
- if (wscale * this.previewDocNativeHeight() > this.previewRegionHeight)
+ if (wscale * this.previewDocNativeHeight() > this.previewRegionHeight) {
return this.previewRegionHeight / (this.previewDocNativeHeight() ? this.previewDocNativeHeight() : this.previewRegionHeight);
+ }
return wscale;
}
private previewPanelWidth = () => this.previewDocNativeWidth() * this.previewContentScaling();
@@ -263,22 +249,23 @@ export class CollectionSchemaView extends CollectionSubView {
get previewPanelCenteringOffset() { return (this.previewRegionWidth - this.previewDocNativeWidth() * this.previewContentScaling()) / 2; }
getPreviewTransform = (): Transform => this.props.ScreenToLocalTransform().translate(
- this.borderWidth - this.DIVIDER_WIDTH - this.tableWidth - this.previewPanelCenteringOffset,
- - this.borderWidth).scale(1 / this.previewContentScaling());
+ - this.borderWidth).scale(1 / this.previewContentScaling())
@computed
get previewPanel() {
// let doc = CompileScript(this.previewScript, { this: selected }, true)();
- return !this.previewDocument ? (null) : (
+ const previewDoc = this.previewDocument;
+ return !previewDoc ? (null) : (
<div className="collectionSchemaView-previewRegion" style={{ width: `${this.previewRegionWidth}px` }}>
<div className="collectionSchemaView-previewDoc" style={{ transform: `translate(${this.previewPanelCenteringOffset}px, 0px)` }}>
- <DocumentView Document={this.previewDocument} isTopMost={false} selectOnLoad={false}
+ <DocumentView Document={previewDoc} isTopMost={false} selectOnLoad={false}
toggleMinimized={emptyFunction}
addDocument={this.props.addDocument} removeDocument={this.props.removeDocument}
ScreenToLocalTransform={this.getPreviewTransform}
ContentScaling={this.previewContentScaling}
PanelWidth={this.previewPanelWidth} PanelHeight={this.previewPanelHeight}
ContainingCollectionView={this.props.CollectionView}
- focus={emptyDocFunction}
+ focus={emptyFunction}
parentActive={this.props.active}
whenActiveChanged={this.props.whenActiveChanged}
/>
@@ -290,24 +277,25 @@ export class CollectionSchemaView extends CollectionSubView {
}
get documentKeysCheckList() {
- const docs = this.props.Document.GetList(this.props.fieldKey, [] as Document[]);
- let keys: { [id: string]: boolean } = {};
+ const docs = Cast(this.props.Document[this.props.fieldKey], listSpec(Doc), []);
+ let keys: { [key: string]: boolean } = {};
// bcz: ugh. this is untracked since otherwise a large collection of documents will blast the server for all their fields.
// then as each document's fields come back, we update the documents _proxies. Each time we do this, the whole schema will be
// invalidated and re-rendered. This workaround will inquire all of the document fields before the options button is clicked.
// then by the time the options button is clicked, all of the fields should be in place. If a new field is added while this menu
// is displayed (unlikely) it won't show up until something else changes.
- untracked(() => docs.map(doc => doc.GetAllPrototypes().map(proto => proto._proxies.forEach((val: any, key: string) => keys[key] = false))));
+ //TODO Types
+ untracked(() => docs.map(doc => Doc.GetAllPrototypes(doc).map(proto => Object.keys(proto).forEach(key => keys[key] = false))));
- this.columns.forEach(key => keys[key.Id] = true);
+ this.columns.forEach(key => keys[key] = true);
return Array.from(Object.keys(keys)).map(item =>
- (<KeyToggle checked={keys[item]} key={item} keyId={item} toggle={this.toggleKey} />));
+ (<KeyToggle checked={keys[item]} key={item} keyName={item} toggle={this.toggleKey} />));
}
get tableOptionsPanel() {
return !this.props.active() ? (null) :
(<Flyout
- anchorPoint={anchorPoints.LEFT_TOP}
+ anchorPoint={anchorPoints.RIGHT_TOP}
content={<div>
<div id="schema-options-header"><h5><b>Options</b></h5></div>
<div id="options-flyout-div">
@@ -335,16 +323,17 @@ export class CollectionSchemaView extends CollectionSubView {
render() {
library.add(faCog);
library.add(faPlus);
- const children = this.props.Document.GetList(this.props.fieldKey, [] as Document[]);
+ //This can't just pass FieldValue to filter because filter passes other arguments to the passed in function, which end up as default values in FieldValue
+ const children = (this.children || []).filter(doc => FieldValue(doc));
return (
<div className="collectionSchemaView-container" onPointerDown={this.onPointerDown} onWheel={this.onWheel}
onDrop={(e: React.DragEvent) => this.onDrop(e, {})} ref={this.createTarget}>
<div className="collectionSchemaView-tableContainer" style={{ width: `${this.tableWidth}px` }}>
<ReactTable data={children} page={0} pageSize={children.length} showPagination={false}
columns={this.columns.map(col => ({
- Header: col.Name,
- accessor: (doc: Document) => [doc, col],
- id: col.Id
+ Header: col,
+ accessor: (doc: Doc) => [doc, col],
+ id: col
}))}
column={{ ...ReactTableDefaults.column, Cell: this.renderCell, }}
getTrProps={this.getTrProps}
diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx
index f9fc7be5a..828ac880a 100644
--- a/src/client/views/collections/CollectionSubView.tsx
+++ b/src/client/views/collections/CollectionSubView.tsx
@@ -1,28 +1,27 @@
import { action, runInAction } from "mobx";
-import { Document } from "../../../fields/Document";
-import { ListField } from "../../../fields/ListField";
import React = require("react");
-import { KeyStore } from "../../../fields/KeyStore";
-import { FieldWaiting, Opt } from "../../../fields/Field";
import { undoBatch, UndoManager } from "../../util/UndoManager";
import { DragManager } from "../../util/DragManager";
-import { Documents, DocumentOptions } from "../../documents/Documents";
+import { Docs, DocumentOptions } from "../../documents/Documents";
import { RouteStore } from "../../../server/RouteStore";
-import { TupleField } from "../../../fields/TupleField";
import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils";
-import { NumberField } from "../../../fields/NumberField";
-import { ServerUtils } from "../../../server/ServerUtil";
-import { Server } from "../../Server";
import { FieldViewProps } from "../nodes/FieldView";
import * as rp from 'request-promise';
import { CollectionView } from "./CollectionView";
import { CollectionPDFView } from "./CollectionPDFView";
import { CollectionVideoView } from "./CollectionVideoView";
+import { Doc, Opt } from "../../../new_fields/Doc";
+import { DocComponent } from "../DocComponent";
+import { listSpec } from "../../../new_fields/Schema";
+import { Cast, PromiseValue, FieldValue } from "../../../new_fields/Types";
+import { List } from "../../../new_fields/List";
+import { DocServer } from "../../DocServer";
+import { ObjectField } from "../../../new_fields/ObjectField";
export interface CollectionViewProps extends FieldViewProps {
- addDocument: (document: Document, allowDuplicates?: boolean) => boolean;
- removeDocument: (document: Document) => boolean;
- moveDocument: (document: Document, targetCollection: Document, addDocument: (document: Document) => boolean) => boolean;
+ addDocument: (document: Doc, allowDuplicates?: boolean) => boolean;
+ removeDocument: (document: Doc) => boolean;
+ moveDocument: (document: Doc, targetCollection: Doc, addDocument: (document: Doc) => boolean) => boolean;
PanelWidth: () => number;
PanelHeight: () => number;
}
@@ -33,176 +32,196 @@ export interface SubCollectionViewProps extends CollectionViewProps {
export type CursorEntry = TupleField<[string, string], [number, number]>;
-export class CollectionSubView extends React.Component<SubCollectionViewProps> {
- private dropDisposer?: DragManager.DragDropDisposer;
- protected createDropTarget = (ele: HTMLDivElement) => {
- if (this.dropDisposer) {
- this.dropDisposer();
+export function CollectionSubView<T>(schemaCtor: (doc: Doc) => T) {
+ class CollectionSubView extends DocComponent<SubCollectionViewProps, T>(schemaCtor) {
+ private dropDisposer?: DragManager.DragDropDisposer;
+ protected createDropTarget = (ele: HTMLDivElement) => {
+ if (this.dropDisposer) {
+ this.dropDisposer();
+ }
+ if (ele) {
+ this.dropDisposer = DragManager.MakeDropTarget(ele, { handlers: { drop: this.drop.bind(this) } });
+ }
}
- if (ele) {
- this.dropDisposer = DragManager.MakeDropTarget(ele, { handlers: { drop: this.drop.bind(this) } });
+ protected CreateDropTarget(ele: HTMLDivElement) {
+ this.createDropTarget(ele);
}
- }
- protected CreateDropTarget(ele: HTMLDivElement) {
- this.createDropTarget(ele);
- }
- @action
- protected setCursorPosition(position: [number, number]) {
- let ind;
- let doc = this.props.Document;
- let id = CurrentUserUtils.id;
- let email = CurrentUserUtils.email;
- if (id && email) {
- let textInfo: [string, string] = [id, email];
- doc.GetTAsync(KeyStore.Prototype, Document).then(proto => {
+ get children() {
+ //TODO tfs: This might not be what we want?
+ //This linter error can't be fixed because of how js arguments work, so don't switch this to filter(FieldValue)
+ return Cast(this.props.Document[this.props.fieldKey], listSpec(Doc), []).filter(doc => FieldValue(doc));
+ }
+
+ @action
+ protected async setCursorPosition(position: [number, number]) {
+ return;
+ let ind;
+ let doc = this.props.Document;
+ let id = CurrentUserUtils.id;
+ let email = CurrentUserUtils.email;
+ if (id && email) {
+ let textInfo: [string, string] = [id, email];
+ const proto = await doc.proto;
if (!proto) {
return;
}
- proto.GetOrCreateAsync<ListField<CursorEntry>>(KeyStore.Cursors, ListField, action((field: ListField<CursorEntry>) => {
- let cursors = field.Data;
- if (cursors.length > 0 && (ind = cursors.findIndex(entry => entry.Data[0][0] === id)) > -1) {
- cursors[ind].Data[1] = position;
- } else {
- let entry = new TupleField<[string, string], [number, number]>([textInfo, position]);
- cursors.push(entry);
- }
- }));
- });
+ let cursors = await Cast(proto.cursors, listSpec(ObjectField));
+ if (!cursors) {
+ proto.cursors = cursors = new List<ObjectField>();
+ }
+ if (cursors.length > 0 && (ind = cursors.findIndex(entry => entry.Data[0][0] === id)) > -1) {
+ cursors[ind].Data[1] = position;
+ } else {
+ let entry = new TupleField<[string, string], [number, number]>([textInfo, position]);
+ cursors.push(entry);
+ }
+ }
}
- }
- @undoBatch
- @action
- protected drop(e: Event, de: DragManager.DropEvent): boolean {
- if (de.data instanceof DragManager.DocumentDragData) {
- if (de.data.aliasOnDrop || de.data.copyOnDrop) {
- [KeyStore.Width, KeyStore.Height, KeyStore.CurPage].map(key =>
- de.data.draggedDocuments.map((draggedDocument: Document, i: number) =>
- draggedDocument.GetTAsync(key, NumberField, (f: Opt<NumberField>) => f ? de.data.droppedDocuments[i].SetNumber(key, f.Data) : null)));
- }
- let added = false;
- if (de.data.aliasOnDrop || de.data.copyOnDrop) {
- added = de.data.droppedDocuments.reduce((added: boolean, d) => {
- let moved = this.props.addDocument(d);
- return moved || added;
- }, false);
- } else if (de.data.moveDocument) {
- const move = de.data.moveDocument;
- added = de.data.droppedDocuments.reduce((added: boolean, d) => {
- let moved = move(d, this.props.Document, this.props.addDocument);
- return moved || added;
- }, false);
- } else {
- added = de.data.droppedDocuments.reduce((added: boolean, d) => {
- let moved = this.props.addDocument(d);
- return moved || added;
- }, false);
+ @undoBatch
+ @action
+ protected drop(e: Event, de: DragManager.DropEvent): boolean {
+ if (de.data instanceof DragManager.DocumentDragData) {
+ if (de.data.dropAction || de.data.userDropAction) {
+ ["width", "height", "curPage"].map(key =>
+ de.data.draggedDocuments.map((draggedDocument: Doc, i: number) =>
+ PromiseValue(Cast(draggedDocument[key], "number")).then(f => f && (de.data.droppedDocuments[i][key] = f))));
+ }
+ let added = false;
+ if (de.data.dropAction || de.data.userDropAction) {
+ added = de.data.droppedDocuments.reduce((added: boolean, d) => {
+ let moved = this.props.addDocument(d);
+ return moved || added;
+ }, false);
+ } else if (de.data.moveDocument) {
+ const move = de.data.moveDocument;
+ added = de.data.droppedDocuments.reduce((added: boolean, d) => {
+ let moved = move(d, this.props.Document, this.props.addDocument);
+ return moved || added;
+ }, false);
+ } else {
+ added = de.data.droppedDocuments.reduce((added: boolean, d) => {
+ let moved = this.props.addDocument(d);
+ return moved || added;
+ }, false);
+ }
+ e.stopPropagation();
+ return added;
}
- e.stopPropagation();
- return added;
+ return false;
}
- return false;
- }
- protected async getDocumentFromType(type: string, path: string, options: DocumentOptions): Promise<Opt<Document>> {
- let ctor: ((path: string, options: DocumentOptions) => (Document | Promise<Document | undefined>)) | undefined = undefined;
- if (type.indexOf("image") !== -1) {
- ctor = Documents.ImageDocument;
- }
- if (type.indexOf("video") !== -1) {
- ctor = Documents.VideoDocument;
- }
- if (type.indexOf("audio") !== -1) {
- ctor = Documents.AudioDocument;
- }
- if (type.indexOf("pdf") !== -1) {
- ctor = Documents.PdfDocument;
- options.nativeWidth = 1200;
- }
- if (type.indexOf("excel") !== -1) {
- ctor = Documents.DBDocument;
- options.copyDraggedItems = true;
- }
- if (type.indexOf("html") !== -1) {
- if (path.includes('localhost')) {
- let s = path.split('/');
- let id = s[s.length - 1];
- Server.GetField(id).then(field => {
- if (field instanceof Document) {
- let alias = field.CreateAlias();
- alias.SetNumber(KeyStore.X, options.x || 0);
- alias.SetNumber(KeyStore.Y, options.y || 0);
- alias.SetNumber(KeyStore.Width, options.width || 300);
- alias.SetNumber(KeyStore.Height, options.height || options.width || 300);
- this.props.addDocument(alias, false);
- }
- });
- return undefined;
+ protected async getDocumentFromType(type: string, path: string, options: DocumentOptions): Promise<Opt<Doc>> {
+ let ctor: ((path: string, options: DocumentOptions) => (Doc | Promise<Doc | undefined>)) | undefined = undefined;
+ if (type.indexOf("image") !== -1) {
+ ctor = Docs.ImageDocument;
+ }
+ if (type.indexOf("video") !== -1) {
+ ctor = Docs.VideoDocument;
+ }
+ if (type.indexOf("audio") !== -1) {
+ ctor = Docs.AudioDocument;
}
- ctor = Documents.WebDocument;
- options = { height: options.width, ...options, title: path, nativeWidth: undefined };
+ if (type.indexOf("pdf") !== -1) {
+ ctor = Docs.PdfDocument;
+ options.nativeWidth = 1200;
+ }
+ if (type.indexOf("excel") !== -1) {
+ ctor = Docs.DBDocument;
+ options.dropAction = "copy";
+ }
+ if (type.indexOf("html") !== -1) {
+ if (path.includes('localhost')) {
+ let s = path.split('/');
+ let id = s[s.length - 1];
+ DocServer.GetRefField(id).then(field => {
+ if (field instanceof Doc) {
+ let alias = Doc.MakeAlias(field);
+ alias.x = options.x || 0;
+ alias.y = options.y || 0;
+ alias.width = options.width || 300;
+ alias.height = options.height || options.width || 300;
+ this.props.addDocument(alias, false);
+ }
+ });
+ return undefined;
+ }
+ ctor = Docs.WebDocument;
+ options = { height: options.width, ...options, title: path, nativeWidth: undefined };
+ }
+ return ctor ? ctor(path, options) : undefined;
}
- return ctor ? ctor(path, options) : undefined;
- }
- @undoBatch
- @action
- protected onDrop(e: React.DragEvent, options: DocumentOptions): void {
- let html = e.dataTransfer.getData("text/html");
- let text = e.dataTransfer.getData("text/plain");
+ @undoBatch
+ @action
+ protected onDrop(e: React.DragEvent, options: DocumentOptions): void {
+ let html = e.dataTransfer.getData("text/html");
+ let text = e.dataTransfer.getData("text/plain");
- if (text && text.startsWith("<div")) {
- return;
- }
- e.stopPropagation();
- e.preventDefault();
+ if (text && text.startsWith("<div")) {
+ return;
+ }
+ e.stopPropagation();
+ e.preventDefault();
- if (html && html.indexOf("<img") !== 0 && !html.startsWith("<a")) {
- this.props.addDocument(Documents.HtmlDocument(html, { ...options, width: 300, height: 300, documentText: text }), false);
- return;
- }
+ if (html && html.indexOf("<img") !== 0 && !html.startsWith("<a")) {
+ let htmlDoc = Docs.HtmlDocument(html, { ...options, width: 300, height: 300, documentText: text });
+ this.props.addDocument(htmlDoc, false);
+ return;
+ }
- let batch = UndoManager.StartBatch("collection view drop");
- let promises: Promise<void>[] = [];
- // tslint:disable-next-line:prefer-for-of
- for (let i = 0; i < e.dataTransfer.items.length; i++) {
- const upload = window.location.origin + RouteStore.upload;
- let item = e.dataTransfer.items[i];
- if (item.kind === "string" && item.type.indexOf("uri") !== -1) {
- let str: string;
- let prom = new Promise<string>(resolve => e.dataTransfer.items[i].getAsString(resolve))
- .then(action((s: string) => rp.head(ServerUtils.prepend(RouteStore.corsProxy + "/" + (str = s)))))
- .then(result => {
- let type = result["content-type"];
- if (type) {
- this.getDocumentFromType(type, str, { ...options, width: 300, nativeWidth: 300 })
- .then(doc => doc && this.props.addDocument(doc, false));
- }
+ let batch = UndoManager.StartBatch("collection view drop");
+ let promises: Promise<void>[] = [];
+ // tslint:disable-next-line:prefer-for-of
+ for (let i = 0; i < e.dataTransfer.items.length; i++) {
+ const upload = window.location.origin + RouteStore.upload;
+ let item = e.dataTransfer.items[i];
+ if (item.kind === "string" && item.type.indexOf("uri") !== -1) {
+ let str: string;
+ let prom = new Promise<string>(resolve => e.dataTransfer.items[i].getAsString(resolve))
+ .then(action((s: string) => rp.head(DocServer.prepend(RouteStore.corsProxy + "/" + (str = s)))))
+ .then(result => {
+ let type = result["content-type"];
+ if (type) {
+ this.getDocumentFromType(type, str, { ...options, width: 300, nativeWidth: 300 })
+ .then(doc => doc && this.props.addDocument(doc, false));
+ }
+ });
+ promises.push(prom);
+ }
+ let type = item.type;
+ if (item.kind === "file") {
+ let file = item.getAsFile();
+ let formData = new FormData();
+
+ if (file) {
+ formData.append('file', file);
+ }
+ let dropFileName = file ? file.name : "-empty-";
+
+ let prom = fetch(upload, {
+ method: 'POST',
+ body: formData
+ }).then(async (res: Response) => {
+ (await res.json()).map(action((file: any) => {
+ let path = window.location.origin + file;
+ let docPromise = this.getDocumentFromType(type, path, { ...options, nativeWidth: 600, width: 300, title: dropFileName });
+
+ docPromise.then(doc => doc && this.props.addDocument(doc));
+ }));
});
- promises.push(prom);
- }
- let type = item.type;
- if (item.kind === "file") {
- let file = item.getAsFile();
- let dropFileName = file ? file.name : "-empty-";
- let formData = new FormData();
- if (file) formData.append('file', file);
-
- promises.push(fetch(upload, {
- method: 'POST',
- body: formData
- }).then(async (res: Response) =>
- (await res.json()).map(action((file: any) =>
- this.getDocumentFromType(type, window.location.origin + file, { ...options, nativeWidth: 600, width: 300, title: dropFileName }).
- then(doc => doc && this.props.addDocument(doc, false))))));
+ promises.push(prom);
+ }
}
- }
- if (promises.length) {
- Promise.all(promises).finally(() => batch.end());
- } else {
- batch.end();
+ if (promises.length) {
+ Promise.all(promises).finally(() => batch.end());
+ } else {
+ batch.end();
+ }
}
}
+ return CollectionSubView;
}
+
diff --git a/src/client/views/collections/CollectionTreeView.scss b/src/client/views/collections/CollectionTreeView.scss
index 8ecc5b67b..19d4abc05 100644
--- a/src/client/views/collections/CollectionTreeView.scss
+++ b/src/client/views/collections/CollectionTreeView.scss
@@ -33,18 +33,24 @@
}
.bullet {
+ position: absolute;
width: 1.5em;
display: inline-block;
color: $intermediate-color;
+ margin-top: 3px;
+ transform: scale(1.3,1.3);
}
.coll-title {
+ width:max-content;
+ display: block;
font-size: 24px;
- margin-bottom: 20px;
}
.docContainer {
- display: inline-table;
+ margin-left: 10px;
+ display: block;
+ width: max-content;
}
.docContainer:hover {
diff --git a/src/client/views/collections/CollectionTreeView.tsx b/src/client/views/collections/CollectionTreeView.tsx
index 905b48db7..b67d6f965 100644
--- a/src/client/views/collections/CollectionTreeView.tsx
+++ b/src/client/views/collections/CollectionTreeView.tsx
@@ -1,24 +1,30 @@
import { IconProp, library } from '@fortawesome/fontawesome-svg-core';
import { faCaretDown, faCaretRight, faTrashAlt } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
-import { action, observable } from "mobx";
+import { action, observable, trace } from "mobx";
import { observer } from "mobx-react";
-import { Document } from "../../../fields/Document";
-import { FieldWaiting } from "../../../fields/Field";
-import { KeyStore } from "../../../fields/KeyStore";
-import { ListField } from "../../../fields/ListField";
-import { DragManager, SetupDrag } from "../../util/DragManager";
+import { DragManager, SetupDrag, dropActionType } from "../../util/DragManager";
import { EditableView } from "../EditableView";
import { CollectionSubView } from "./CollectionSubView";
import "./CollectionTreeView.scss";
import React = require("react");
+import { Document, listSpec } from '../../../new_fields/Schema';
+import { Cast, StrCast, BoolCast, FieldValue } from '../../../new_fields/Types';
+import { Doc } from '../../../new_fields/Doc';
+import { Id } from '../../../new_fields/RefField';
+import { ContextMenu } from '../ContextMenu';
+import { undoBatch } from '../../util/UndoManager';
+import { Main } from '../Main';
+import { CurrentUserUtils } from '../../../server/authentication/models/current_user_utils';
+import { CollectionDockingView } from './CollectionDockingView';
+import { DocumentManager } from '../../util/DocumentManager';
export interface TreeViewProps {
- document: Document;
- deleteDoc: (doc: Document) => void;
+ document: Doc;
+ deleteDoc: (doc: Doc) => void;
moveDocument: DragManager.MoveFunction;
- copyOnDrag: boolean;
+ dropAction: "alias" | "copy" | undefined;
}
export enum BulletType {
@@ -41,11 +47,15 @@ class TreeView extends React.Component<TreeViewProps> {
delete = () => this.props.deleteDoc(this.props.document);
+ get children() {
+ return Cast(this.props.document.data, listSpec(Doc), []); // bcz: needed? .filter(doc => FieldValue(doc));
+ }
+
@action
remove = (document: Document) => {
- var children = this.props.document.GetT<ListField<Document>>(KeyStore.Data, ListField);
- if (children && children !== FieldWaiting) {
- children.Data.splice(children.Data.indexOf(document), 1);
+ let children = Cast(this.props.document.data, listSpec(Doc), []);
+ if (children) {
+ children.splice(children.indexOf(document), 1);
}
}
@@ -74,86 +84,118 @@ class TreeView extends React.Component<TreeViewProps> {
*/
renderTitle() {
let reference = React.createRef<HTMLDivElement>();
- let onItemDown = SetupDrag(reference, () => this.props.document, this.props.moveDocument, this.props.copyOnDrag);
+ let onItemDown = SetupDrag(reference, () => this.props.document, this.props.moveDocument, this.props.dropAction);
let editableView = (titleString: string) =>
(<EditableView
display={"inline"}
contents={titleString}
height={36}
- GetValue={() => this.props.document.Title}
+ GetValue={() => StrCast(this.props.document.title)}
SetValue={(value: string) => {
- this.props.document.SetText(KeyStore.Title, value);
+ let target = this.props.document.proto ? this.props.document.proto : this.props.document;
+ target.title = value;
return true;
}}
/>);
return (
<div className="docContainer" ref={reference} onPointerDown={onItemDown}>
- {editableView(this.props.document.Title)}
- <div className="delete-button" onClick={this.delete}><FontAwesomeIcon icon="trash-alt" size="xs" /></div>
+ {editableView(StrCast(this.props.document.title))}
+ {/* <div className="delete-button" onClick={this.delete}><FontAwesomeIcon icon="trash-alt" size="xs" /></div> */}
</div >);
}
+ onWorkspaceContextMenu = (e: React.MouseEvent): void => {
+ if (!e.isPropagationStopped() && this.props.document[Id] !== CurrentUserUtils.MainDocId) { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7
+ ContextMenu.Instance.addItem({ description: "Open as Workspace", event: undoBatch(() => Main.Instance.openWorkspace(this.props.document)) });
+ ContextMenu.Instance.addItem({ description: "Open Right", event: () => CollectionDockingView.Instance.AddRightSplit(this.props.document) });
+ if (DocumentManager.Instance.getDocumentViews(this.props.document).length) {
+ ContextMenu.Instance.addItem({ description: "Focus", event: () => DocumentManager.Instance.getDocumentViews(this.props.document).map(view => view.props.focus(this.props.document)) });
+ }
+ ContextMenu.Instance.addItem({ description: "Delete", event: undoBatch(() => this.props.deleteDoc(this.props.document)) });
+ ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15);
+ e.stopPropagation();
+ }
+ }
+
+ onPointerEnter = (e: React.PointerEvent): void => { this.props.document.libraryBrush = true; }
+ onPointerLeave = (e: React.PointerEvent): void => { this.props.document.libraryBrush = false; }
+
render() {
let bulletType = BulletType.List;
- let childElements: JSX.Element | undefined = undefined;
- var children = this.props.document.GetT<ListField<Document>>(KeyStore.Data, ListField);
- if (children && children !== FieldWaiting) { // add children for a collection
+ let contentElement: JSX.Element | null = (null);
+ var children = Cast(this.props.document.data, listSpec(Doc));
+ if (children) { // add children for a collection
if (!this._collapsed) {
bulletType = BulletType.Collapsible;
- childElements = <ul>
- {children.Data.map(value => <TreeView key={value.Id} document={value} deleteDoc={this.remove} moveDocument={this.move} copyOnDrag={this.props.copyOnDrag} />)}
+ contentElement = <ul>
+ {TreeView.GetChildElements(children, this.remove, this.move, this.props.dropAction)}
</ul >;
}
else bulletType = BulletType.Collapsed;
}
- return <div className="treeViewItem-container" >
+ return <div className="treeViewItem-container"
+ style={{ background: BoolCast(this.props.document.libraryBrush, false) ? "#06121212" : "0" }}
+ onContextMenu={this.onWorkspaceContextMenu}
+ onPointerEnter={this.onPointerEnter} onPointerLeave={this.onPointerLeave}>
<li className="collection-child">
{this.renderBullet(bulletType)}
{this.renderTitle()}
- {childElements ? childElements : (null)}
+ {contentElement}
</li>
</div>;
}
+ public static GetChildElements(docs: Doc[], remove: ((doc: Doc) => void), move: DragManager.MoveFunction, dropAction: dropActionType) {
+ return docs.filter(child => !child.excludeFromLibrary).filter(doc => FieldValue(doc)).map(child =>
+ <TreeView document={child} key={child[Id]} deleteDoc={remove} moveDocument={move} dropAction={dropAction} />);
+ }
}
@observer
-export class CollectionTreeView extends CollectionSubView {
-
+export class CollectionTreeView extends CollectionSubView(Document) {
@action
remove = (document: Document) => {
- var children = this.props.Document.GetT<ListField<Document>>(KeyStore.Data, ListField);
- if (children && children !== FieldWaiting) {
- children.Data.splice(children.Data.indexOf(document), 1);
+ let children = Cast(this.props.Document.data, listSpec(Doc), []);
+ if (children) {
+ children.splice(children.indexOf(document), 1);
+ }
+ }
+ onContextMenu = (e: React.MouseEvent): void => {
+ if (!e.isPropagationStopped() && this.props.Document[Id] !== CurrentUserUtils.MainDocId) { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7
+ ContextMenu.Instance.addItem({ description: "Create Workspace", event: undoBatch(() => Main.Instance.createNewWorkspace()) });
+ }
+ if (!ContextMenu.Instance.getItems().some(item => item.description === "Delete")) {
+ ContextMenu.Instance.addItem({ description: "Delete", event: undoBatch(() => this.remove(this.props.Document)) });
}
}
-
render() {
- let children = this.props.Document.GetT<ListField<Document>>(KeyStore.Data, ListField);
- let copyOnDrag = this.props.Document.GetBoolean(KeyStore.CopyDraggedItems, false);
- let childrenElement = !children || children === FieldWaiting ? (null) :
- (children.Data.map(value =>
- <TreeView document={value} key={value.Id} deleteDoc={this.remove} moveDocument={this.props.moveDocument} copyOnDrag={copyOnDrag} />)
- );
+ trace();
+ const children = this.children;
+ let dropAction = StrCast(this.props.Document.dropAction, "alias") as dropActionType;
+ if (!children) {
+ return (null);
+ }
+ let childElements = TreeView.GetChildElements(children, this.remove, this.props.moveDocument, dropAction);
return (
<div id="body" className="collectionTreeView-dropTarget"
style={{ borderRadius: "inherit" }}
+ onContextMenu={this.onContextMenu}
onWheel={(e: React.WheelEvent) => e.stopPropagation()}
onDrop={(e: React.DragEvent) => this.onDrop(e, {})} ref={this.createDropTarget}>
<div className="coll-title">
<EditableView
- contents={this.props.Document.Title}
+ contents={this.props.Document.title}
display={"inline"}
height={72}
- GetValue={() => this.props.Document.Title}
+ GetValue={() => StrCast(this.props.Document.title)}
SetValue={(value: string) => {
- this.props.Document.SetText(KeyStore.Title, value);
+ let target = this.props.Document.proto ? this.props.Document.proto : this.props.Document;
+ target.title = value;
return true;
}} />
</div>
- <hr />
<ul className="no-indent">
- {childrenElement}
+ {childElements}
</ul>
</div >
);
diff --git a/src/client/views/collections/CollectionVideoView.tsx b/src/client/views/collections/CollectionVideoView.tsx
index 779dc8fc3..9dee217cb 100644
--- a/src/client/views/collections/CollectionVideoView.tsx
+++ b/src/client/views/collections/CollectionVideoView.tsx
@@ -1,6 +1,5 @@
import { action, observable, trace } from "mobx";
import { observer } from "mobx-react";
-import { KeyStore } from "../../../fields/KeyStore";
import { ContextMenu } from "../ContextMenu";
import { CollectionViewType, CollectionBaseView, CollectionRenderProps } from "./CollectionBaseView";
import React = require("react");
@@ -8,17 +7,18 @@ import "./CollectionVideoView.scss";
import { CollectionFreeFormView } from "./collectionFreeForm/CollectionFreeFormView";
import { FieldView, FieldViewProps } from "../nodes/FieldView";
import { emptyFunction } from "../../../Utils";
+import { Id } from "../../../new_fields/RefField";
+import { VideoBox } from "../nodes/VideoBox";
@observer
export class CollectionVideoView extends React.Component<FieldViewProps> {
- private _intervalTimer: any = undefined;
- private _player: HTMLVideoElement | undefined = undefined;
+ private _videoBox: VideoBox | undefined = undefined;
+ @observable _playTimer?: NodeJS.Timeout = undefined;
@observable _currentTimecode: number = 0;
- @observable _isPlaying: boolean = false;
- public static LayoutString(fieldKey: string = "DataKey") {
+ public static LayoutString(fieldKey: string = "data") {
return FieldView.LayoutString(CollectionVideoView, fieldKey);
}
private get uIButtons() {
@@ -29,7 +29,7 @@ export class CollectionVideoView extends React.Component<FieldViewProps> {
<span style={{ fontSize: 8 }}>{" " + Math.round((this._currentTimecode - Math.trunc(this._currentTimecode)) * 100)}</span>
</div>,
<div className="collectionVideoView-play" key="play" onPointerDown={this.onPlayDown} style={{ transform: `scale(${scaling}, ${scaling})` }}>
- {this._isPlaying ? "\"" : ">"}
+ {this._playTimer ? "\"" : ">"}
</div>,
<div className="collectionVideoView-full" key="full" onPointerDown={this.onFullDown} style={{ transform: `scale(${scaling}, ${scaling})` }}>
F
@@ -37,60 +37,37 @@ export class CollectionVideoView extends React.Component<FieldViewProps> {
]);
}
- _ele: HTMLDivElement | null = null;
@action
- mainCont = (ele: HTMLDivElement | null) => {
- this._ele = ele;
- if (ele) {
- this._player = ele.getElementsByTagName("video")[0];
- console.log(this._player);
- if (this.props.Document.GetNumber(KeyStore.CurPage, -1) >= 0) {
- this._currentTimecode = this.props.Document.GetNumber(KeyStore.CurPage, -1);
- }
+ updateTimecode = () => {
+ if (this._videoBox && this._videoBox.player) {
+ this._currentTimecode = this._videoBox.player.currentTime;
+ this.props.Document.curPage = Math.round(this._currentTimecode);
}
}
- componentDidMount() {
- this._intervalTimer = setInterval(this.updateTimecode, 1000);
- }
+ componentDidMount() { this.updateTimecode(); }
- componentWillUnmount() {
- clearInterval(this._intervalTimer);
- }
-
- @action
- updateTimecode = () => {
- this._player = this._player ? this._player : this._ele ? this._ele.getElementsByTagName("video")[0] : undefined;
- if (this._player) {
- let timecode = (this._player as any).hasOwnProperty("AHackBecauseSomethingResetsTheVideoToZero") ?
- (this._player as any).AHackBecauseSomethingResetsTheVideoToZero : -1;
- if (timecode !== -1 && Object) {
- this._player.currentTime = timecode;
- (this._player as any).AHackBecauseSomethingResetsTheVideoToZero = -1;
- } else {
- this._currentTimecode = this._player.currentTime;
- this.props.Document.SetNumber(KeyStore.CurPage, Math.round(this._currentTimecode));
- }
- }
- }
+ componentWillUnmount() { if (this._playTimer) clearInterval(this._playTimer); }
@action
onPlayDown = () => {
- if (this._player) {
- if (this._player.paused) {
- this._player.play();
- this._isPlaying = true;
+ if (this._videoBox && this._videoBox.player) {
+ if (this._videoBox.player.paused) {
+ this._videoBox.player.play();
+ if (!this._playTimer) this._playTimer = setInterval(this.updateTimecode, 1000);
} else {
- this._player.pause();
- this._isPlaying = false;
+ this._videoBox.player.pause();
+ if (this._playTimer) clearInterval(this._playTimer);
+ this._playTimer = undefined;
+
}
}
}
@action
onFullDown = (e: React.PointerEvent) => {
- if (this._player) {
- this._player.requestFullscreen();
+ if (this._videoBox && this._videoBox.player) {
+ this._videoBox.player.requestFullscreen();
e.stopPropagation();
e.preventDefault();
}
@@ -98,33 +75,34 @@ export class CollectionVideoView extends React.Component<FieldViewProps> {
@action
onResetDown = () => {
- if (this._player) {
- this._player.pause();
- this._player.currentTime = 0;
+ if (this._videoBox && this._videoBox.player) {
+ this._videoBox.player.pause();
+ this._videoBox.player.currentTime = 0;
+ if (this._playTimer) clearInterval(this._playTimer);
+ this._playTimer = undefined;
+ this.updateTimecode();
}
-
}
onContextMenu = (e: React.MouseEvent): void => {
- if (!e.isPropagationStopped() && this.props.Document.Id !== "mainDoc") { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7
+ if (!e.isPropagationStopped() && this.props.Document[Id] !== "mainDoc") { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7
ContextMenu.Instance.addItem({ description: "VideoOptions", event: emptyFunction });
}
}
+ setVideoBox = (player: VideoBox) => { this._videoBox = player; }
+
private subView = (_type: CollectionViewType, renderProps: CollectionRenderProps) => {
let props = { ...this.props, ...renderProps };
- return (
- <>
- <CollectionFreeFormView {...props} CollectionView={this} />
- {this.props.isSelected() ? this.uIButtons : (null)}
- </>
- );
+ return (<>
+ <CollectionFreeFormView {...props} setVideoBox={this.setVideoBox} CollectionView={this} />
+ {this.props.isSelected() ? this.uIButtons : (null)}
+ </>);
}
render() {
- trace();
return (
- <CollectionBaseView {...this.props} className="collectionVideoView-cont" contentRef={this.mainCont} onContextMenu={this.onContextMenu}>
+ <CollectionBaseView {...this.props} className="collectionVideoView-cont" onContextMenu={this.onContextMenu}>
{this.subView}
</CollectionBaseView>);
}
diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx
index 675e720e2..8c1442d38 100644
--- a/src/client/views/collections/CollectionView.tsx
+++ b/src/client/views/collections/CollectionView.tsx
@@ -7,14 +7,15 @@ import { CollectionDockingView } from './CollectionDockingView';
import { CollectionTreeView } from './CollectionTreeView';
import { ContextMenu } from '../ContextMenu';
import { CurrentUserUtils } from '../../../server/authentication/models/current_user_utils';
-import { KeyStore } from '../../../fields/KeyStore';
import { observer } from 'mobx-react';
import { undoBatch } from '../../util/UndoManager';
import { trace } from 'mobx';
+import { Id } from '../../../new_fields/RefField';
+import { Main } from '../Main';
@observer
export class CollectionView extends React.Component<FieldViewProps> {
- public static LayoutString(fieldStr: string = "DataKey") { return FieldView.LayoutString(CollectionView, fieldStr); }
+ public static LayoutString(fieldStr: string = "data") { return FieldView.LayoutString(CollectionView, fieldStr); }
private SubView = (type: CollectionViewType, renderProps: CollectionRenderProps) => {
let props = { ...this.props, ...renderProps };
@@ -29,13 +30,13 @@ export class CollectionView extends React.Component<FieldViewProps> {
return (null);
}
- get isAnnotationOverlay() { return this.props.fieldKey && this.props.fieldKey.Id === KeyStore.Annotations.Id; } // bcz: ? Why do we need to compare Id's?
+ get isAnnotationOverlay() { return this.props.fieldKey && this.props.fieldKey === "annotations"; } // bcz: ? Why do we need to compare Id's?
onContextMenu = (e: React.MouseEvent): void => {
- if (!this.isAnnotationOverlay && !e.isPropagationStopped() && this.props.Document.Id !== CurrentUserUtils.MainDocId) { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7
- ContextMenu.Instance.addItem({ description: "Freeform", event: undoBatch(() => this.props.Document.SetNumber(KeyStore.ViewType, CollectionViewType.Freeform)) });
- ContextMenu.Instance.addItem({ description: "Schema", event: undoBatch(() => this.props.Document.SetNumber(KeyStore.ViewType, CollectionViewType.Schema)) });
- ContextMenu.Instance.addItem({ description: "Treeview", event: undoBatch(() => this.props.Document.SetNumber(KeyStore.ViewType, CollectionViewType.Tree)) });
+ if (!this.isAnnotationOverlay && !e.isPropagationStopped() && this.props.Document[Id] !== CurrentUserUtils.MainDocId) { // need to test this because GoldenLayout causes a parallel hierarchy in the React DOM for its children and the main document view7
+ ContextMenu.Instance.addItem({ description: "Freeform", event: undoBatch(() => this.props.Document.viewType = CollectionViewType.Freeform) });
+ ContextMenu.Instance.addItem({ description: "Schema", event: undoBatch(() => this.props.Document.viewType = CollectionViewType.Schema) });
+ ContextMenu.Instance.addItem({ description: "Treeview", event: undoBatch(() => this.props.Document.viewType = CollectionViewType.Tree) });
}
}
diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx
index 8cd6c7624..3b700b053 100644
--- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx
+++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinkView.tsx
@@ -1,18 +1,18 @@
import { observer } from "mobx-react";
-import { Document } from "../../../../fields/Document";
-import { KeyStore } from "../../../../fields/KeyStore";
import { Utils } from "../../../../Utils";
import "./CollectionFreeFormLinkView.scss";
import React = require("react");
import v5 = require("uuid/v5");
+import { StrCast, NumCast, BoolCast } from "../../../../new_fields/Types";
+import { Doc, WidthSym, HeightSym } from "../../../../new_fields/Doc";
import { InkingControl } from "../../InkingControl";
export interface CollectionFreeFormLinkViewProps {
- A: Document;
- B: Document;
- LinkDocs: Document[];
- addDocument: (document: Document, allowDuplicates?: boolean) => boolean;
- removeDocument: (document: Document) => boolean;
+ A: Doc;
+ B: Doc;
+ LinkDocs: Doc[];
+ addDocument: (document: Doc, allowDuplicates?: boolean) => boolean;
+ removeDocument: (document: Doc) => boolean;
}
@observer
@@ -22,14 +22,14 @@ export class CollectionFreeFormLinkView extends React.Component<CollectionFreeFo
if (e.button === 0 && !InkingControl.Instance.selectedTool) {
let a = this.props.A;
let b = this.props.B;
- let x1 = a.GetNumber(KeyStore.X, 0) + (a.GetBoolean(KeyStore.IsMinimized, false) ? 5 : a.Width() / 2);
- let y1 = a.GetNumber(KeyStore.Y, 0) + (a.GetBoolean(KeyStore.IsMinimized, false) ? 5 : a.Height() / 2);
- let x2 = b.GetNumber(KeyStore.X, 0) + (b.GetBoolean(KeyStore.IsMinimized, false) ? 5 : b.Width() / 2);
- let y2 = b.GetNumber(KeyStore.Y, 0) + (b.GetBoolean(KeyStore.IsMinimized, false) ? 5 : b.Height() / 2);
+ let x1 = NumCast(a.x) + (BoolCast(a.isMinimized, false) ? 5 : a[WidthSym]() / 2);
+ let y1 = NumCast(a.y) + (BoolCast(a.isMinimized, false) ? 5 : a[HeightSym]() / 2);
+ let x2 = NumCast(b.x) + (BoolCast(b.isMinimized, false) ? 5 : b[WidthSym]() / 2);
+ let y2 = NumCast(b.y) + (BoolCast(b.isMinimized, false) ? 5 : b[HeightSym]() / 2);
this.props.LinkDocs.map(l => {
- let width = l.GetNumber(KeyStore.Width, 0);
- l.SetNumber(KeyStore.X, (x1 + x2) / 2 - width / 2);
- l.SetNumber(KeyStore.Y, (y1 + y2) / 2 + 10);
+ let width = l[WidthSym]();
+ l.x = (x1 + x2) / 2 - width / 2;
+ l.y = (y1 + y2) / 2 + 10;
if (!this.props.removeDocument(l)) this.props.addDocument(l, false);
});
e.stopPropagation();
@@ -40,10 +40,10 @@ export class CollectionFreeFormLinkView extends React.Component<CollectionFreeFo
let l = this.props.LinkDocs;
let a = this.props.A;
let b = this.props.B;
- let x1 = a.GetNumber(KeyStore.X, 0) + (a.GetBoolean(KeyStore.IsMinimized, false) ? 5 : a.Width() / 2);
- let y1 = a.GetNumber(KeyStore.Y, 0) + (a.GetBoolean(KeyStore.IsMinimized, false) ? 5 : a.Height() / 2);
- let x2 = b.GetNumber(KeyStore.X, 0) + (b.GetBoolean(KeyStore.IsMinimized, false) ? 5 : b.Width() / 2);
- let y2 = b.GetNumber(KeyStore.Y, 0) + (b.GetBoolean(KeyStore.IsMinimized, false) ? 5 : b.Height() / 2);
+ let x1 = NumCast(a.x) + (BoolCast(a.isMinimized, false) ? 5 : NumCast(a.width) / 2);
+ let y1 = NumCast(a.y) + (BoolCast(a.isMinimized, false) ? 5 : NumCast(a.height) / 2);
+ let x2 = NumCast(b.x) + (BoolCast(b.isMinimized, false) ? 5 : NumCast(b.width) / 2);
+ let y2 = NumCast(b.y) + (BoolCast(b.isMinimized, false) ? 5 : NumCast(b.height) / 2);
return (
<>
<line key={Utils.GenerateGuid()} className="collectionfreeformlinkview-linkLine"
diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx
index b97df7556..b34e0856e 100644
--- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx
+++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLinksView.tsx
@@ -1,8 +1,5 @@
import { computed, IReactionDisposer, reaction } from "mobx";
import { observer } from "mobx-react";
-import { Document } from "../../../../fields/Document";
-import { KeyStore } from "../../../../fields/KeyStore";
-import { ListField } from "../../../../fields/ListField";
import { Utils } from "../../../../Utils";
import { DocumentManager } from "../../../util/DocumentManager";
import { DocumentView } from "../../nodes/DocumentView";
@@ -10,54 +7,67 @@ import { CollectionViewProps } from "../CollectionSubView";
import "./CollectionFreeFormLinksView.scss";
import { CollectionFreeFormLinkView } from "./CollectionFreeFormLinkView";
import React = require("react");
+import { Doc } from "../../../../new_fields/Doc";
+import { Cast, FieldValue, NumCast, StrCast } from "../../../../new_fields/Types";
+import { listSpec } from "../../../../new_fields/Schema";
+import { List } from "../../../../new_fields/List";
+import { Id } from "../../../../new_fields/RefField";
@observer
export class CollectionFreeFormLinksView extends React.Component<CollectionViewProps> {
_brushReactionDisposer?: IReactionDisposer;
componentDidMount() {
- this._brushReactionDisposer = reaction(() => this.props.Document.GetList(this.props.fieldKey, [] as Document[]).map(doc => doc.GetNumber(KeyStore.X, 0)),
+ this._brushReactionDisposer = reaction(() => Cast(this.props.Document[this.props.fieldKey], listSpec(Doc), []).map(doc => NumCast(doc.x)),
() => {
- let views = this.props.Document.GetList(this.props.fieldKey, [] as Document[]).filter(doc => doc.GetText(KeyStore.BackgroundLayout, "").indexOf("istogram") !== -1);
+ let views = Cast(this.props.Document[this.props.fieldKey], listSpec(Doc), []).filter(doc => StrCast(doc.backgroundLayout, "").indexOf("istogram") !== -1);
for (let i = 0; i < views.length; i++) {
for (let j = 0; j < views.length; j++) {
let srcDoc = views[j];
let dstDoc = views[i];
- let x1 = srcDoc.GetNumber(KeyStore.X, 0);
- let x1w = srcDoc.GetNumber(KeyStore.Width, -1);
- let x2 = dstDoc.GetNumber(KeyStore.X, 0);
- let x2w = dstDoc.GetNumber(KeyStore.Width, -1);
+ let x1 = NumCast(srcDoc.x);
+ let x1w = NumCast(srcDoc.width, -1);
+ let x2 = NumCast(dstDoc.x);
+ let x2w = NumCast(dstDoc.width, -1);
if (x1w < 0 || x2w < 0 || i === j) {
continue;
}
let dstTarg = dstDoc;
let srcTarg = srcDoc;
- let findBrush = (field: ListField<Document>) => field.Data.findIndex(brush => {
- let bdocs = brush ? brush.GetList(KeyStore.BrushingDocs, [] as Document[]) : [];
+ let findBrush = (field: List<Doc>) => field.findIndex(brush => {
+ let bdocs = brush ? Cast(brush.brushingDocs, listSpec(Doc), []) : [];
return (bdocs.length && ((bdocs[0] === dstTarg && bdocs[1] === srcTarg)) ? true : false);
});
- let brushAction = (field: ListField<Document>) => {
+ let brushAction = (field: List<Doc>) => {
let found = findBrush(field);
if (found !== -1) {
console.log("REMOVE BRUSH " + srcTarg.Title + " " + dstTarg.Title);
- field.Data.splice(found, 1);
+ field.splice(found, 1);
}
};
if (Math.abs(x1 + x1w - x2) < 20) {
- let linkDoc: Document = new Document();
- linkDoc.SetText(KeyStore.Title, "Histogram Brush");
- linkDoc.SetText(KeyStore.LinkDescription, "Brush between " + srcTarg.Title + " and " + dstTarg.Title);
- linkDoc.SetData(KeyStore.BrushingDocs, [dstTarg, srcTarg], ListField);
+ let linkDoc: Doc = new Doc();
+ linkDoc.title = "Histogram Brush";
+ linkDoc.linkDescription = "Brush between " + StrCast(srcTarg.title) + " and " + StrCast(dstTarg.Title);
+ linkDoc.brushingDocs = new List([dstTarg, srcTarg]);
- brushAction = (field: ListField<Document>) => {
+ brushAction = (field: List<Doc>) => {
if (findBrush(field) === -1) {
console.log("ADD BRUSH " + srcTarg.Title + " " + dstTarg.Title);
- (findBrush(field) === -1) && field.Data.push(linkDoc);
+ (findBrush(field) === -1) && field.push(linkDoc);
}
};
}
- dstTarg.GetOrCreateAsync(KeyStore.BrushingDocs, ListField, brushAction);
- srcTarg.GetOrCreateAsync(KeyStore.BrushingDocs, ListField, brushAction);
+ let dstBrushDocs = Cast(dstTarg.brushingDocs, listSpec(Doc));
+ if (dstBrushDocs === undefined) {
+ dstTarg.brushingDocs = dstBrushDocs = new List<Doc>();
+ }
+ let srcBrushDocs = Cast(srcTarg.brushingDocs, listSpec(Doc));
+ if (srcBrushDocs === undefined) {
+ srcTarg.brushingDocs = srcBrushDocs = new List<Doc>();
+ }
+ brushAction(dstBrushDocs);
+ brushAction(srcBrushDocs);
}
}
@@ -70,15 +80,15 @@ export class CollectionFreeFormLinksView extends React.Component<CollectionViewP
}
documentAnchors(view: DocumentView) {
let equalViews = [view];
- let containerDoc = view.props.Document.GetT(KeyStore.AnnotationOn, Document);
- if (containerDoc && containerDoc instanceof Document) {
- equalViews.push(...DocumentManager.Instance.getDocumentViews(containerDoc.GetPrototype()!));
+ let containerDoc = FieldValue(Cast(view.props.Document.annotationOn, Doc));
+ if (containerDoc) {
+ equalViews = DocumentManager.Instance.getDocumentViews(containerDoc.proto!);
}
if (view.props.ContainingCollectionView) {
- let collid = view.props.ContainingCollectionView.props.Document.Id;
- this.props.Document.GetList(this.props.fieldKey, [] as Document[]).
+ let collid = view.props.ContainingCollectionView.props.Document[Id];
+ Cast(this.props.Document[this.props.fieldKey], listSpec(Doc), []).
filter(child =>
- child.Id === collid).map(view =>
+ child[Id] === collid).map(view =>
DocumentManager.Instance.getDocumentViews(view).map(view =>
equalViews.push(view)));
}
@@ -90,12 +100,12 @@ export class CollectionFreeFormLinksView extends React.Component<CollectionViewP
let connections = DocumentManager.Instance.LinkedDocumentViews.reduce((drawnPairs, connection) => {
let srcViews = this.documentAnchors(connection.a);
let targetViews = this.documentAnchors(connection.b);
- let possiblePairs: { a: Document, b: Document, }[] = [];
+ let possiblePairs: { a: Doc, b: Doc, }[] = [];
srcViews.map(sv => targetViews.map(tv => possiblePairs.push({ a: sv.props.Document, b: tv.props.Document })));
possiblePairs.map(possiblePair =>
drawnPairs.reduce((found, drawnPair) => {
let match = (possiblePair.a === drawnPair.a && possiblePair.b === drawnPair.b);
- if (match && !drawnPair.l.reduce((found, link) => found || link.Id === connection.l.Id, false)) {
+ if (match && !drawnPair.l.reduce((found, link) => found || link[Id] === connection.l[Id], false)) {
drawnPair.l.push(connection.l);
}
return match || found;
@@ -104,7 +114,7 @@ export class CollectionFreeFormLinksView extends React.Component<CollectionViewP
drawnPairs.push({ a: possiblePair.a, b: possiblePair.b, l: [connection.l] })
);
return drawnPairs;
- }, [] as { a: Document, b: Document, l: Document[] }[]);
+ }, [] as { a: Doc, b: Doc, l: Doc[] }[]);
return connections.map(c => <CollectionFreeFormLinkView key={Utils.GenerateGuid()} A={c.a} B={c.b} LinkDocs={c.l}
removeDocument={this.props.removeDocument} addDocument={this.props.addDocument} />);
}
diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx
index cf0a6de00..036745eca 100644
--- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx
+++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormRemoteCursors.tsx
@@ -1,6 +1,5 @@
import { computed } from "mobx";
import { observer } from "mobx-react";
-import { KeyStore } from "../../../../fields/KeyStore";
import { CollectionViewProps, CursorEntry } from "../CollectionSubView";
import "./CollectionFreeFormView.scss";
import React = require("react");
diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
index b931105d8..17c25c9db 100644
--- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
+++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx
@@ -1,7 +1,5 @@
-import { action, computed } from "mobx";
+import { action, computed, trace } from "mobx";
import { observer } from "mobx-react";
-import { Document } from "../../../../fields/Document";
-import { KeyStore } from "../../../../fields/KeyStore";
import { emptyFunction, returnFalse, returnOne } from "../../../../Utils";
import { DocumentManager } from "../../../util/DocumentManager";
import { DragManager } from "../../../util/DragManager";
@@ -12,7 +10,7 @@ import { COLLECTION_BORDER_WIDTH } from "../../../views/globalCssVariables.scss"
import { InkingCanvas } from "../../InkingCanvas";
import { CollectionFreeFormDocumentView } from "../../nodes/CollectionFreeFormDocumentView";
import { DocumentContentsView } from "../../nodes/DocumentContentsView";
-import { DocumentViewProps } from "../../nodes/DocumentView";
+import { DocumentViewProps, positionSchema } from "../../nodes/DocumentView";
import { CollectionSubView } from "../CollectionSubView";
import { CollectionFreeFormLinksView } from "./CollectionFreeFormLinksView";
import { CollectionFreeFormRemoteCursors } from "./CollectionFreeFormRemoteCursors";
@@ -20,10 +18,23 @@ import "./CollectionFreeFormView.scss";
import { MarqueeView } from "./MarqueeView";
import React = require("react");
import v5 = require("uuid/v5");
-import { BooleanField } from "../../../../fields/BooleanField";
+import { createSchema, makeInterface, listSpec } from "../../../../new_fields/Schema";
+import { Doc, WidthSym, HeightSym } from "../../../../new_fields/Doc";
+import { FieldValue, Cast, NumCast } from "../../../../new_fields/Types";
+import { pageSchema } from "../../nodes/ImageBox";
+import { Id } from "../../../../new_fields/RefField";
+
+export const panZoomSchema = createSchema({
+ panX: "number",
+ panY: "number",
+ scale: "number"
+});
+
+type PanZoomDocument = makeInterface<[typeof panZoomSchema, typeof positionSchema, typeof pageSchema]>;
+const PanZoomDocument = makeInterface(panZoomSchema, positionSchema, pageSchema);
@observer
-export class CollectionFreeFormView extends CollectionSubView {
+export class CollectionFreeFormView extends CollectionSubView(PanZoomDocument) {
public static RIGHT_BTN_DRAG = false;
private _selectOnLoaded: string = ""; // id of document that should be selected once it's loaded (used for click-to-type)
private _lastX: number = 0;
@@ -31,42 +42,38 @@ export class CollectionFreeFormView extends CollectionSubView {
private get _pwidth() { return this.props.PanelWidth(); }
private get _pheight() { return this.props.PanelHeight(); }
- @computed get nativeWidth() { return this.props.Document.GetNumber(KeyStore.NativeWidth, 0); }
- @computed get nativeHeight() { return this.props.Document.GetNumber(KeyStore.NativeHeight, 0); }
+ @computed get nativeWidth() { return FieldValue(this.Document.nativeWidth, 0); }
+ @computed get nativeHeight() { return FieldValue(this.Document.nativeHeight, 0); }
private get borderWidth() { return this.isAnnotationOverlay ? 0 : COLLECTION_BORDER_WIDTH; }
- private get isAnnotationOverlay() { return this.props.fieldKey && this.props.fieldKey.Id === KeyStore.Annotations.Id; } // bcz: ? Why do we need to compare Id's?
- private panX = () => this.props.Document.GetNumber(KeyStore.PanX, 0);
- private panY = () => this.props.Document.GetNumber(KeyStore.PanY, 0);
- private zoomScaling = () => this.props.Document.GetNumber(KeyStore.Scale, 1);
+ private get isAnnotationOverlay() { return this.props.fieldKey && this.props.fieldKey === "annotations"; }
+ private panX = () => FieldValue(this.Document.panX, 0);
+ private panY = () => FieldValue(this.Document.panY, 0);
+ private zoomScaling = () => FieldValue(this.Document.scale, 1);
private centeringShiftX = () => !this.nativeWidth ? this._pwidth / 2 : 0; // shift so pan position is at center of window for non-overlay collections
private centeringShiftY = () => !this.nativeHeight ? this._pheight / 2 : 0;// shift so pan position is at center of window for non-overlay collections
private getTransform = (): Transform => this.props.ScreenToLocalTransform().translate(-this.borderWidth, -this.borderWidth).translate(-this.centeringShiftX(), -this.centeringShiftY()).transform(this.getLocalTransform());
private getContainerTransform = (): Transform => this.props.ScreenToLocalTransform().translate(-this.borderWidth, -this.borderWidth);
private getLocalTransform = (): Transform => Transform.Identity().scale(1 / this.zoomScaling()).translate(this.panX(), this.panY());
- private addLiveTextBox = (newBox: Document) => {
- this._selectOnLoaded = newBox.Id;// track the new text box so we can give it a prop that tells it to focus itself when it's displayed
+ private addLiveTextBox = (newBox: Doc) => {
+ this._selectOnLoaded = newBox[Id];// track the new text box so we can give it a prop that tells it to focus itself when it's displayed
this.addDocument(newBox, false);
}
- @action
- private addDocument = (newBox: Document, allowDuplicates: boolean) => {
+ private addDocument = (newBox: Doc, allowDuplicates: boolean) => {
this.props.addDocument(newBox, false);
this.bringToFront(newBox);
return true;
}
- private selectDocuments = (docs: Document[]) => {
+ private selectDocuments = (docs: Doc[]) => {
SelectionManager.DeselectAll;
docs.map(doc => DocumentManager.Instance.getDocumentView(doc)).filter(dv => dv).map(dv =>
SelectionManager.SelectDoc(dv!, true));
}
public getActiveDocuments = () => {
- var curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1);
- return this.props.Document.GetList(this.props.fieldKey, [] as Document[]).reduce((active, doc) => {
- var page = doc.GetNumber(KeyStore.Page, -1);
- if (page === curPage || page === -1) {
- active.push(doc);
- }
- return active;
- }, [] as Document[]);
+ const curPage = FieldValue(this.Document.curPage, -1);
+ return FieldValue(this.children, [] as Doc[]).filter(doc => {
+ var page = NumCast(doc.page, -1);
+ return page === curPage || page === -1;
+ });
}
@undoBatch
@@ -75,22 +82,22 @@ export class CollectionFreeFormView extends CollectionSubView {
if (super.drop(e, de) && de.data instanceof DragManager.DocumentDragData) {
if (de.data.droppedDocuments.length) {
let dragDoc = de.data.droppedDocuments[0];
- let zoom = dragDoc.GetNumber(KeyStore.ZoomBasis, 1);
+ let zoom = NumCast(dragDoc.zoomBasis, 1);
let [xp, yp] = this.getTransform().transformPoint(de.x, de.y);
let x = xp - de.data.xOffset / zoom;
let y = yp - de.data.yOffset / zoom;
- let dropX = de.data.droppedDocuments[0].GetNumber(KeyStore.X, 0);
- let dropY = de.data.droppedDocuments[0].GetNumber(KeyStore.Y, 0);
+ let dropX = NumCast(de.data.droppedDocuments[0].x);
+ let dropY = NumCast(de.data.droppedDocuments[0].y);
de.data.droppedDocuments.map(d => {
- d.SetNumber(KeyStore.X, x + (d.GetNumber(KeyStore.X, 0) - dropX));
- d.SetNumber(KeyStore.Y, y + (d.GetNumber(KeyStore.Y, 0) - dropY));
- if (!d.GetNumber(KeyStore.Width, 0)) {
- d.SetNumber(KeyStore.Width, 300);
+ d.x = x + NumCast(d.x) - dropX;
+ d.y = y + NumCast(d.y) - dropY;
+ if (!NumCast(d.width)) {
+ d.width = 300;
}
- if (!d.GetNumber(KeyStore.Height, 0)) {
- let nw = d.GetNumber(KeyStore.NativeWidth, 0);
- let nh = d.GetNumber(KeyStore.NativeHeight, 0);
- d.SetNumber(KeyStore.Height, nw && nh ? nh / nw * d.Width() : 300);
+ if (!NumCast(d.height)) {
+ let nw = NumCast(d.nativeWidth);
+ let nh = NumCast(d.nativeHeight);
+ d.height = nw && nh ? nh / nw * NumCast(d.width) : 300;
}
this.bringToFront(d);
});
@@ -102,14 +109,8 @@ export class CollectionFreeFormView extends CollectionSubView {
}
@action
- cleanupInteractions = () => {
- document.removeEventListener("pointermove", this.onPointerMove);
- document.removeEventListener("pointerup", this.onPointerUp);
- }
-
- @action
onPointerDown = (e: React.PointerEvent): void => {
- let childSelected = this.props.Document.GetList(this.props.fieldKey, [] as Document[]).filter(doc => doc).reduce((childSelected, doc) => {
+ let childSelected = Cast(this.props.Document[this.props.fieldKey], listSpec(Doc), [] as Doc[]).filter(doc => doc).reduce((childSelected, doc) => {
var dv = DocumentManager.Instance.getDocumentView(doc);
return childSelected || (dv && SelectionManager.IsSelected(dv) ? true : false);
}, false);
@@ -118,7 +119,8 @@ export class CollectionFreeFormView extends CollectionSubView {
(e.button === 0 && e.altKey)) && (childSelected || this.props.active()))) ||
(!CollectionFreeFormView.RIGHT_BTN_DRAG &&
((e.button === 0 && !e.altKey && (!this.isAnnotationOverlay || this.zoomScaling() !== 1)) && (childSelected || this.props.active())))) {
- this.cleanupInteractions();
+ document.removeEventListener("pointermove", this.onPointerMove);
+ document.removeEventListener("pointerup", this.onPointerUp);
document.addEventListener("pointermove", this.onPointerMove);
document.addEventListener("pointerup", this.onPointerUp);
this._lastX = e.pageX;
@@ -127,26 +129,27 @@ export class CollectionFreeFormView extends CollectionSubView {
}
onPointerUp = (e: PointerEvent): void => {
- this.cleanupInteractions();
+ document.removeEventListener("pointermove", this.onPointerMove);
+ document.removeEventListener("pointerup", this.onPointerUp);
}
@action
onPointerMove = (e: PointerEvent): void => {
if (!e.cancelBubble) {
- let x = this.props.Document.GetNumber(KeyStore.PanX, 0);
- let y = this.props.Document.GetNumber(KeyStore.PanY, 0);
- let docs = this.props.Document.GetList(this.props.fieldKey, [] as Document[]);
+ let x = Cast(this.props.Document.panX, "number", 0);
+ let y = Cast(this.props.Document.panY, "number", 0);
+ let docs = this.children || [];
let [dx, dy] = this.getTransform().transformDirection(e.clientX - this._lastX, e.clientY - this._lastY);
if (!this.isAnnotationOverlay) {
- let minx = docs.length ? docs[0].GetNumber(KeyStore.X, 0) : 0;
- let maxx = docs.length ? docs[0].Width() + minx : minx;
- let miny = docs.length ? docs[0].GetNumber(KeyStore.Y, 0) : 0;
- let maxy = docs.length ? docs[0].Height() + miny : miny;
+ let minx = docs.length ? Cast(docs[0].x, "number", 0) : 0;
+ let maxx = docs.length ? Cast(docs[0].width, "number", 0) + minx : minx;
+ let miny = docs.length ? Cast(docs[0].y, "number", 0) : 0;
+ let maxy = docs.length ? Cast(docs[0].height, "number", 0) + miny : miny;
let ranges = docs.filter(doc => doc).reduce((range, doc) => {
- let x = doc.GetNumber(KeyStore.X, 0);
- let xe = x + doc.GetNumber(KeyStore.Width, 0);
- let y = doc.GetNumber(KeyStore.Y, 0);
- let ye = y + doc.GetNumber(KeyStore.Height, 0);
+ let x = Cast(doc.x, "number", 0);
+ let xe = x + Cast(doc.width, "number", 0);
+ let y = Cast(doc.y, "number", 0);
+ let ye = y + Cast(doc.height, "number", 0);
return [[range[0][0] > x ? x : range[0][0], range[0][1] < xe ? xe : range[0][1]],
[range[1][0] > y ? y : range[1][0], range[1][1] < ye ? ye : range[1][1]]];
}, [[minx, maxx], [miny, maxy]]);
@@ -170,10 +173,10 @@ export class CollectionFreeFormView extends CollectionSubView {
// if (!this.props.active()) {
// return;
// }
- let childSelected = this.props.Document.GetList(this.props.fieldKey, [] as Document[]).filter(doc => doc).reduce((childSelected, doc) => {
+ let childSelected = (this.children || []).filter(doc => doc).some(doc => {
var dv = DocumentManager.Instance.getDocumentView(doc);
- return childSelected || (dv && SelectionManager.IsSelected(dv) ? true : false);
- }, false);
+ return dv && SelectionManager.IsSelected(dv) ? true : false;
+ });
if (!this.props.isSelected() && !childSelected && !this.props.isTopMost) {
return;
}
@@ -182,8 +185,8 @@ export class CollectionFreeFormView extends CollectionSubView {
if (e.ctrlKey) {
let deltaScale = (1 - (e.deltaY / coefficient));
- this.props.Document.SetNumber(KeyStore.NativeWidth, this.nativeWidth * deltaScale);
- this.props.Document.SetNumber(KeyStore.NativeHeight, this.nativeHeight * deltaScale);
+ this.props.Document.nativeWidth = this.nativeWidth * deltaScale;
+ this.props.Document.nativeHeight = this.nativeHeight * deltaScale;
e.stopPropagation();
e.preventDefault();
} else {
@@ -198,7 +201,7 @@ export class CollectionFreeFormView extends CollectionSubView {
let localTransform = this.getLocalTransform().inverse().scaleAbout(deltaScale, x, y);
let safeScale = Math.abs(localTransform.Scale);
- this.props.Document.SetNumber(KeyStore.Scale, Math.abs(safeScale));
+ this.props.Document.scale = Math.abs(safeScale);
this.setPan(-localTransform.TranslateX / safeScale, -localTransform.TranslateY / safeScale);
e.stopPropagation();
}
@@ -209,9 +212,8 @@ export class CollectionFreeFormView extends CollectionSubView {
var scale = this.getLocalTransform().inverse().Scale;
const newPanX = Math.min((1 - 1 / scale) * this.nativeWidth, Math.max(0, panX));
const newPanY = Math.min((1 - 1 / scale) * this.nativeHeight, Math.max(0, panY));
- this.props.Document.SetNumber(KeyStore.PanX, this.isAnnotationOverlay ? newPanX : panX);
- this.props.Document.SetNumber(KeyStore.PanY, this.isAnnotationOverlay ? newPanY : panY);
-
+ this.props.Document.panX = this.isAnnotationOverlay ? newPanX : panX;
+ this.props.Document.panY = this.isAnnotationOverlay ? newPanY : panY;
}
@action
@@ -223,30 +225,31 @@ export class CollectionFreeFormView extends CollectionSubView {
onDragOver = (): void => {
}
- @action
- bringToFront(doc: Document) {
- let docs = this.props.Document.GetList(this.props.fieldKey, [] as Document[]).slice();
- docs.sort((doc1, doc2) => {
+ bringToFront = (doc: Doc) => {
+ const docs = (this.children || []);
+ docs.slice().sort((doc1, doc2) => {
if (doc1 === doc) return 1;
if (doc2 === doc) return -1;
- return doc1.GetNumber(KeyStore.ZIndex, 0) - doc2.GetNumber(KeyStore.ZIndex, 0);
- }).map((doc, index) => doc.SetNumber(KeyStore.ZIndex, index + 1));
- doc.SetNumber(KeyStore.ZIndex, docs.length + 1);
+ return NumCast(doc1.zIndex) - NumCast(doc2.zIndex);
+ }).forEach((doc, index) => doc.zIndex = index + 1);
+ doc.zIndex = docs.length + 1;
+ return doc;
}
- focusDocument = (doc: Document) => {
+ focusDocument = (doc: Doc) => {
SelectionManager.DeselectAll();
- this.props.Document.SetText(KeyStore.PanTransformType, "Ease");
+ this.props.Document.panTransformType = "Ease";
this.setPan(
- doc.GetNumber(KeyStore.X, 0) + doc.Width() / 2,
- doc.GetNumber(KeyStore.Y, 0) + doc.Height() / 2);
+ NumCast(doc.x) + NumCast(doc.width) / 2,
+ NumCast(doc.y) + NumCast(doc.height) / 2);
this.props.focus(this.props.Document);
- if (this.props.Document.GetText(KeyStore.PanTransformType, "") === "Ease") {
- setTimeout(() => this.props.Document.SetText(KeyStore.PanTransformType, "None"), 5000); // wait 5 seconds, then reset to false
+ if (this.props.Document.panTransformType === "Ease") {
+ setTimeout(() => this.props.Document.panTransformType = "None", 2000); // wait 3 seconds, then reset to false
}
}
- getDocumentViewProps(document: Document): DocumentViewProps {
+
+ getDocumentViewProps(document: Doc): DocumentViewProps {
return {
Document: document,
toggleMinimized: emptyFunction,
@@ -255,26 +258,29 @@ export class CollectionFreeFormView extends CollectionSubView {
moveDocument: this.props.moveDocument,
ScreenToLocalTransform: this.getTransform,
isTopMost: false,
- selectOnLoad: document.Id === this._selectOnLoaded,
- PanelWidth: document.Width,
- PanelHeight: document.Height,
+ selectOnLoad: document[Id] === this._selectOnLoaded,
+ PanelWidth: document[WidthSym],
+ PanelHeight: document[HeightSym],
ContentScaling: returnOne,
ContainingCollectionView: this.props.CollectionView,
focus: this.focusDocument,
parentActive: this.props.active,
whenActiveChanged: this.props.active,
+ bringToFront: this.bringToFront,
};
}
- @computed
+ @computed.struct
get views() {
- var curPage = this.props.Document.GetNumber(KeyStore.CurPage, -1);
- let docviews = this.props.Document.GetList(this.props.fieldKey, [] as Document[]).filter(doc => doc).reduce((prev, doc) => {
- var page = doc.GetNumber(KeyStore.Page, -1);
+ let curPage = FieldValue(this.Document.curPage, -1);
+ let docviews = (this.children || []).filter(doc => doc).reduce((prev, doc) => {
+ if (!FieldValue(doc)) return prev;
+ var page = NumCast(doc.page, -1);
if (page === curPage || page === -1) {
- let minim = doc.GetT(KeyStore.IsMinimized, BooleanField);
- if (minim === undefined || (minim && !minim.Data))
- prev.push(<CollectionFreeFormDocumentView key={doc.Id} {...this.getDocumentViewProps(doc)} />);
+ let minim = Cast(doc.isMinimized, "boolean");
+ if (minim === undefined || !minim) {
+ prev.push(<CollectionFreeFormDocumentView key={doc[Id]} {...this.getDocumentViewProps(doc)} />);
+ }
}
return prev;
}, [] as JSX.Element[]);
@@ -292,16 +298,11 @@ export class CollectionFreeFormView extends CollectionSubView {
private childViews = () => [...this.views, <CollectionFreeFormBackgroundView key="backgroundView" {...this.props} {...this.getDocumentViewProps(this.props.Document)} />];
render() {
const containerName = `collectionfreeformview${this.isAnnotationOverlay ? "-overlay" : "-container"}`;
- const easing = () => this.props.Document.GetText(KeyStore.PanTransformType, "") === "Ease";
+ const easing = () => this.props.Document.panTransformType === "Ease";
return (
<div className={containerName} ref={this.createDropTarget} onWheel={this.onPointerWheel}
style={{ borderRadius: "inherit" }}
onPointerDown={this.onPointerDown} onPointerMove={this.onCursorMove} onDrop={this.onDrop.bind(this)} onDragOver={this.onDragOver} >
- {/* <svg viewBox="0 0 180 18" style={{ top: "50%", opacity: 0.05, position: "absolute" }}>
- <text y="15" >
- {this.props.Document.Title}
- </text>
- </svg> */}
<MarqueeView container={this} activeDocuments={this.getActiveDocuments} selectDocuments={this.selectDocuments} isSelected={this.props.isSelected}
addDocument={this.addDocument} removeDocument={this.props.removeDocument} addLiveTextDocument={this.addLiveTextBox}
getContainerTransform={this.getContainerTransform} getTransform={this.getTransform}>
@@ -313,7 +314,7 @@ export class CollectionFreeFormView extends CollectionSubView {
{this.childViews}
</InkingCanvas>
</CollectionFreeFormLinksView>
- <CollectionFreeFormRemoteCursors {...this.props} key="remoteCursors" />
+ {/* <CollectionFreeFormRemoteCursors {...this.props} key="remoteCursors" /> */}
</CollectionFreeFormViewPannableContents>
<CollectionFreeFormOverlayView {...this.getDocumentViewProps(this.props.Document)} {...this.props} />
</MarqueeView>
@@ -325,9 +326,9 @@ export class CollectionFreeFormView extends CollectionSubView {
@observer
class CollectionFreeFormOverlayView extends React.Component<DocumentViewProps> {
@computed get overlayView() {
- let overlayLayout = this.props.Document.GetText(KeyStore.OverlayLayout, "");
+ let overlayLayout = Cast(this.props.Document.overlayLayout, "string", "");
return !overlayLayout ? (null) :
- (<DocumentContentsView {...this.props} layoutKey={KeyStore.OverlayLayout}
+ (<DocumentContentsView {...this.props} layoutKey={"overlayLayout"}
isTopMost={this.props.isTopMost} isSelected={returnFalse} select={emptyFunction} />);
}
render() {
@@ -338,9 +339,9 @@ class CollectionFreeFormOverlayView extends React.Component<DocumentViewProps> {
@observer
class CollectionFreeFormBackgroundView extends React.Component<DocumentViewProps & { isSelected: () => boolean }> {
@computed get backgroundView() {
- let backgroundLayout = this.props.Document.GetText(KeyStore.BackgroundLayout, "");
+ let backgroundLayout = Cast(this.props.Document.backgroundLayout, "string", "");
return !backgroundLayout ? (null) :
- (<DocumentContentsView {...this.props} layoutKey={KeyStore.BackgroundLayout}
+ (<DocumentContentsView {...this.props} layoutKey={"backgroundLayout"}
isTopMost={this.props.isTopMost} isSelected={this.props.isSelected} select={emptyFunction} />);
}
render() {
diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx
index da1170759..8c81f6990 100644
--- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx
+++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx
@@ -1,10 +1,6 @@
import { action, computed, observable } from "mobx";
import { observer } from "mobx-react";
-import { Document } from "../../../../fields/Document";
-import { FieldWaiting } from "../../../../fields/Field";
-import { InkField, StrokeData } from "../../../../fields/InkField";
-import { KeyStore } from "../../../../fields/KeyStore";
-import { Documents } from "../../../documents/Documents";
+import { Docs } from "../../../documents/Documents";
import { SelectionManager } from "../../../util/SelectionManager";
import { Transform } from "../../../util/Transform";
import { undoBatch } from "../../../util/UndoManager";
@@ -14,16 +10,21 @@ import { CollectionFreeFormView } from "./CollectionFreeFormView";
import "./MarqueeView.scss";
import React = require("react");
import { Utils } from "../../../../Utils";
+import { Doc } from "../../../../new_fields/Doc";
+import { NumCast, Cast } from "../../../../new_fields/Types";
+import { InkField, StrokeData } from "../../../../new_fields/InkField";
+import { Templates } from "../../Templates";
+import { List } from "../../../../new_fields/List";
interface MarqueeViewProps {
getContainerTransform: () => Transform;
getTransform: () => Transform;
container: CollectionFreeFormView;
- addDocument: (doc: Document, allowDuplicates: false) => boolean;
- activeDocuments: () => Document[];
- selectDocuments: (docs: Document[]) => void;
- removeDocument: (doc: Document) => boolean;
- addLiveTextDocument: (doc: Document) => void;
+ addDocument: (doc: Doc, allowDuplicates: false) => boolean;
+ activeDocuments: () => Doc[];
+ selectDocuments: (docs: Doc[]) => void;
+ removeDocument: (doc: Doc) => boolean;
+ addLiveTextDocument: (doc: Doc) => void;
isSelected: () => boolean;
}
@@ -51,7 +52,7 @@ export class MarqueeView extends React.Component<MarqueeViewProps>
onKeyPress = (e: KeyboardEvent) => {
//make textbox and add it to this collection
let [x, y] = this.props.getTransform().transformPoint(this._downX, this._downY);
- let newBox = Documents.TextDocument({ width: 200, height: 100, x: x, y: y, title: "-typed text-" });
+ let newBox = Docs.TextDocument({ width: 200, height: 100, x: x, y: y, title: "-typed text-" });
this.props.addLiveTextDocument(newBox);
e.stopPropagation();
}
@@ -67,8 +68,9 @@ export class MarqueeView extends React.Component<MarqueeViewProps>
document.addEventListener("pointerup", this.onPointerUp, true);
document.addEventListener("keydown", this.marqueeCommand, true);
}
- if (e.altKey)
+ if (e.altKey) {
e.preventDefault();
+ }
}
@action
@@ -85,8 +87,9 @@ export class MarqueeView extends React.Component<MarqueeViewProps>
e.preventDefault();
}
}
- if (e.altKey)
+ if (e.altKey) {
e.preventDefault();
+ }
}
@action
@@ -99,17 +102,16 @@ export class MarqueeView extends React.Component<MarqueeViewProps>
this.props.selectDocuments(mselect.length ? mselect : [this.props.container.props.Document]);
}
this.cleanupInteractions(true);
- if (e.altKey)
+ if (e.altKey) {
e.preventDefault();
+ }
}
@action
onClick = (e: React.MouseEvent): void => {
if (Math.abs(e.clientX - this._downX) < Utils.DRAG_THRESHOLD &&
Math.abs(e.clientY - this._downY) < Utils.DRAG_THRESHOLD) {
- if (this.props.isSelected()) {
- PreviewCursor.Show(e.clientX, e.clientY, this.onKeyPress);
- }
+ PreviewCursor.Show(e.clientX, e.clientY, this.onKeyPress);
// let the DocumentView stopPropagation of this event when it selects this document
} else { // why do we get a click event when the cursor have moved a big distance?
// let's cut it off here so no one else has to deal with it.
@@ -140,9 +142,9 @@ export class MarqueeView extends React.Component<MarqueeViewProps>
if (e.key === "Backspace" || e.key === "Delete" || e.key == "d") {
this._commandExecuted = true;
this.marqueeSelect().map(d => this.props.removeDocument(d));
- let ink = this.props.container.props.Document.GetT(KeyStore.Ink, InkField);
- if (ink && ink !== FieldWaiting) {
- this.marqueeInkDelete(ink.Data);
+ let ink = Cast(this.props.container.props.Document.ink, InkField);
+ if (ink) {
+ this.marqueeInkDelete(ink.inkData);
}
this.cleanupInteractions(false);
e.stopPropagation();
@@ -152,35 +154,48 @@ export class MarqueeView extends React.Component<MarqueeViewProps>
e.stopPropagation();
let bounds = this.Bounds;
let selected = this.marqueeSelect().map(d => {
- this.props.removeDocument(d);
- d.SetNumber(KeyStore.X, d.GetNumber(KeyStore.X, 0) - bounds.left - bounds.width / 2);
- d.SetNumber(KeyStore.Y, d.GetNumber(KeyStore.Y, 0) - bounds.top - bounds.height / 2);
- d.SetNumber(KeyStore.Page, -1);
+ if (e.key !== "r")
+ this.props.removeDocument(d);
+ d.x = NumCast(d.x) - bounds.left - bounds.width / 2;
+ d.y = NumCast(d.y) - bounds.top - bounds.height / 2;
+ d.page = -1;
return d;
});
- let ink = this.props.container.props.Document.GetT(KeyStore.Ink, InkField);
- let inkData = ink && ink !== FieldWaiting ? ink.Data : undefined;
- let zoomBasis = this.props.container.props.Document.GetNumber(KeyStore.Scale, 1);
- let newCollection = Documents.FreeformDocument(selected, {
+ let ink = Cast(this.props.container.props.Document.ink, InkField);
+ let inkData = ink ? ink.inkData : undefined;
+ let zoomBasis = NumCast(this.props.container.props.Document.scale, 1);
+ let newCollection = Docs.FreeformDocument(selected, {
x: bounds.left,
y: bounds.top,
- panx: 0,
- pany: 0,
+ panX: 0,
+ panY: 0,
borderRounding: e.key === "e" ? -1 : undefined,
scale: zoomBasis,
width: bounds.width * zoomBasis,
height: bounds.height * zoomBasis,
- ink: inkData ? this.marqueeInkSelect(inkData) : undefined,
+ ink: inkData ? new InkField(this.marqueeInkSelect(inkData)) : undefined,
title: "a nested collection"
});
this.marqueeInkDelete(inkData);
// SelectionManager.DeselectAll();
if (e.key === "r") {
- let summary = Documents.TextDocument({ x: bounds.left, y: bounds.top, width: 300, height: 100, backgroundColor: "yellow", title: "-summary-" });
- summary.GetPrototype()!.CreateLink(newCollection.GetPrototype()!);
+ let summary = Docs.TextDocument({ x: bounds.left, y: bounds.top, width: 300, height: 100, backgroundColor: "yellow", title: "-summary-" });
+ summary.maximizedDocs = new List<Doc>(selected);
+ // summary.doc1 = selected[0];
+ // if (selected.length > 1)
+ // summary.doc2 = selected[1];
+ // summary.templates = new List<string>([Templates.Summary.Layout]);
this.props.addLiveTextDocument(summary);
e.preventDefault();
+ let scrpt = this.props.getTransform().inverse().transformPoint(bounds.left, bounds.top);
+ selected.map(maximizedDoc => {
+ let maxx = NumCast(maximizedDoc.x, undefined);
+ let maxy = NumCast(maximizedDoc.y, undefined);
+ let maxw = NumCast(maximizedDoc.width, undefined);
+ let maxh = NumCast(maximizedDoc.height, undefined);
+ maximizedDoc.isIconAnimating = new List<number>([scrpt[0], scrpt[1], maxx, maxy, maxw, maxh, Date.now(), 0])
+ });
}
else {
this.props.addDocument(newCollection, false);
@@ -194,9 +209,9 @@ export class MarqueeView extends React.Component<MarqueeViewProps>
let bounds = this.Bounds;
let selected = this.marqueeSelect();
SelectionManager.DeselectAll();
- let summary = Documents.TextDocument({ x: bounds.left + bounds.width + 25, y: bounds.top, width: 300, height: 100, backgroundColor: "yellow", title: "-summary-" });
+ let summary = Docs.TextDocument({ x: bounds.left + bounds.width + 25, y: bounds.top, width: 300, height: 100, backgroundColor: "yellow", title: "-summary-" });
this.props.addLiveTextDocument(summary);
- selected.map(select => summary.GetPrototype()!.CreateLink(select.GetPrototype()!));
+ selected.forEach(select => Doc.MakeLink(summary.proto!, select.proto!));
this.cleanupInteractions(false);
}
@@ -231,19 +246,19 @@ export class MarqueeView extends React.Component<MarqueeViewProps>
let idata = new Map();
ink.forEach((value: StrokeData, key: string, map: any) =>
!InkingCanvas.IntersectStrokeRect(value, this.Bounds) && idata.set(key, value));
- this.props.container.props.Document.SetDataOnPrototype(KeyStore.Ink, idata, InkField);
+ Doc.SetOnPrototype(this.props.container.props.Document, "ink", new InkField(idata));
}
}
marqueeSelect() {
let selRect = this.Bounds;
- let selection: Document[] = [];
+ let selection: Doc[] = [];
this.props.activeDocuments().map(doc => {
- var z = doc.GetNumber(KeyStore.ZoomBasis, 1);
- var x = doc.GetNumber(KeyStore.X, 0);
- var y = doc.GetNumber(KeyStore.Y, 0);
- var w = doc.Width() / z;
- var h = doc.Height() / z;
+ var z = NumCast(doc.zoomBasis, 1);
+ var x = NumCast(doc.x);
+ var y = NumCast(doc.y);
+ var w = NumCast(doc.width) / z;
+ var h = NumCast(doc.height) / z;
if (this.intersectRect({ left: x, top: y, width: w, height: h }, selRect)) {
selection.push(doc);
}
diff --git a/src/client/views/nodes/AudioBox.tsx b/src/client/views/nodes/AudioBox.tsx
index 1493ff25b..be12dced3 100644
--- a/src/client/views/nodes/AudioBox.tsx
+++ b/src/client/views/nodes/AudioBox.tsx
@@ -1,36 +1,19 @@
import React = require("react");
import { FieldViewProps, FieldView } from './FieldView';
-import { FieldWaiting } from '../../../fields/Field';
import { observer } from "mobx-react";
-import { ContextMenu } from "../../views/ContextMenu";
-import { observable, action } from 'mobx';
-import { KeyStore } from '../../../fields/KeyStore';
-import { AudioField } from "../../../fields/AudioField";
import "./AudioBox.scss";
-import { NumberField } from "../../../fields/NumberField";
+import { Cast } from "../../../new_fields/Types";
+import { AudioField } from "../../../new_fields/URLField";
+const defaultField: AudioField = new AudioField(new URL("http://techslides.com/demos/samples/sample.mp3"));
@observer
export class AudioBox extends React.Component<FieldViewProps> {
public static LayoutString() { return FieldView.LayoutString(AudioBox); }
- constructor(props: FieldViewProps) {
- super(props);
- }
-
-
-
- componentDidMount() {
- }
-
- componentWillUnmount() {
- }
-
-
render() {
- let field = this.props.Document.Get(this.props.fieldKey);
- let path = field === FieldWaiting ? "http://techslides.com/demos/samples/sample.mp3" :
- field instanceof AudioField ? field.Data.href : "http://techslides.com/demos/samples/sample.mp3";
+ let field = Cast(this.props.Document[this.props.fieldKey], AudioField, defaultField);
+ let path = field.url.href;
return (
<div>
diff --git a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx
index bad78cbd5..2ba0458f5 100644
--- a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx
+++ b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx
@@ -1,55 +1,66 @@
-import { computed, trace, action } from "mobx";
+import { computed, trace, action, reaction, IReactionDisposer } from "mobx";
import { observer } from "mobx-react";
-import { KeyStore } from "../../../fields/KeyStore";
-import { NumberField } from "../../../fields/NumberField";
-import { Document } from "../../../fields/Document";
import { Transform } from "../../util/Transform";
-import { DocumentView, DocumentViewProps } from "./DocumentView";
+import { DocumentView, DocumentViewProps, positionSchema } from "./DocumentView";
import "./DocumentView.scss";
import React = require("react");
+import { DocComponent } from "../DocComponent";
+import { createSchema, makeInterface, listSpec } from "../../../new_fields/Schema";
+import { FieldValue, Cast, NumCast, BoolCast } from "../../../new_fields/Types";
import { OmitKeys, Utils } from "../../../Utils";
import { SelectionManager } from "../../util/SelectionManager";
-import { ListField } from "../../../fields/ListField";
-import { BooleanField } from "../../../fields/BooleanField";
-import { matchedData } from "express-validator/filter";
+import { Doc } from "../../../new_fields/Doc";
+import { List } from "../../../new_fields/List";
export interface CollectionFreeFormDocumentViewProps extends DocumentViewProps {
}
+const schema = createSchema({
+ zoomBasis: "number",
+ zIndex: "number"
+});
+
+//TODO Types: The import order is wrong, so positionSchema is undefined
+type FreeformDocument = makeInterface<[typeof schema, typeof positionSchema]>;
+const FreeformDocument = makeInterface(schema, positionSchema);
+
@observer
-export class CollectionFreeFormDocumentView extends React.Component<CollectionFreeFormDocumentViewProps> {
+export class CollectionFreeFormDocumentView extends DocComponent<CollectionFreeFormDocumentViewProps, FreeformDocument>(FreeformDocument) {
private _mainCont = React.createRef<HTMLDivElement>();
private _downX: number = 0;
private _downY: number = 0;
+ _bringToFrontDisposer?: IReactionDisposer;
@computed get transform() {
return `scale(${this.props.ContentScaling()}, ${this.props.ContentScaling()}) translate(${this.X}px, ${this.Y}px) scale(${this.zoom}, ${this.zoom}) `;
}
- @computed get X() { return this.props.Document.GetNumber(KeyStore.X, 0); }
- @computed get Y() { return this.props.Document.GetNumber(KeyStore.Y, 0); }
- @computed get zoom() { return 1 / this.props.Document.GetNumber(KeyStore.ZoomBasis, 1); }
- @computed get nativeWidth() { return this.props.Document.GetNumber(KeyStore.NativeWidth, 0); }
- @computed get nativeHeight() { return this.props.Document.GetNumber(KeyStore.NativeHeight, 0); }
- @computed get width() { return this.props.Document.Width(); }
- @computed get height() { return this.props.Document.Height(); }
- @computed get zIndex() { return this.props.Document.GetNumber(KeyStore.ZIndex, 0); }
+
+ @computed get X() { return FieldValue(this.Document.x, 0); }
+ @computed get Y() { return FieldValue(this.Document.y, 0); }
+ @computed get zoom(): number { return 1 / FieldValue(this.Document.zoomBasis, 1); }
+ @computed get nativeWidth(): number { return FieldValue(this.Document.nativeWidth, 0); }
+ @computed get nativeHeight(): number { return FieldValue(this.Document.nativeHeight, 0); }
+ @computed get width(): number { return FieldValue(this.Document.width, 0); }
+ @computed get height(): number { return FieldValue(this.Document.height, 0); }
+ @computed get zIndex(): number { return FieldValue(this.Document.zIndex, 0); }
+
set width(w: number) {
- this.props.Document.SetData(KeyStore.Width, w, NumberField);
+ this.Document.width = w;
if (this.nativeWidth && this.nativeHeight) {
- this.props.Document.SetNumber(KeyStore.Height, this.nativeHeight / this.nativeWidth * w);
+ this.Document.height = this.nativeHeight / this.nativeWidth * w;
}
}
set height(h: number) {
- this.props.Document.SetData(KeyStore.Height, h, NumberField);
+ this.Document.height = h;
if (this.nativeWidth && this.nativeHeight) {
- this.props.Document.SetNumber(KeyStore.Width, this.nativeWidth / this.nativeHeight * h);
+ this.Document.width = this.nativeWidth / this.nativeHeight * h;
}
}
set zIndex(h: number) {
- this.props.Document.SetData(KeyStore.ZIndex, h, NumberField);
+ this.Document.zIndex = h;
}
- contentScaling = () => (this.nativeWidth > 0 ? this.width / this.nativeWidth : 1);
+ contentScaling = () => this.nativeWidth > 0 ? this.width / this.nativeWidth : 1;
panelWidth = () => this.props.PanelWidth();
panelHeight = () => this.props.PanelHeight();
toggleMinimized = () => this.toggleIcon();
@@ -59,7 +70,7 @@ export class CollectionFreeFormDocumentView extends React.Component<CollectionFr
@computed
get docView() {
- return <DocumentView {...OmitKeys(this.props, ['zoomFade'])}
+ return <DocumentView {...OmitKeys(this.props, ['zoomFade']).omit}
toggleMinimized={this.toggleMinimized}
ContentScaling={this.contentScaling}
ScreenToLocalTransform={this.getTransform}
@@ -68,32 +79,43 @@ export class CollectionFreeFormDocumentView extends React.Component<CollectionFr
/>;
}
- animateBetweenIcon(first: boolean, icon: number[], targ: number[], width: number, height: number, stime: number, target: Document, maximizing: boolean) {
+ componentDidMount() {
+ this._bringToFrontDisposer = reaction(() => this.props.Document.isIconAnimating, (values) => {
+ this.props.bringToFront(this.props.Document);
+ if (values instanceof List) {
+ let scrpt = this.props.ScreenToLocalTransform().transformPoint(values[0], values[1]);
+ this.animateBetweenIcon(true, scrpt, [values[2], values[3]], values[4], values[5], values[6], this.props.Document, values[7] ? true : false);
+ }
+ });
+ }
+
+ componentWillUnmount() {
+ if (this._bringToFrontDisposer) this._bringToFrontDisposer();
+ }
+
+ animateBetweenIcon(first: boolean, icon: number[], targ: number[], width: number, height: number, stime: number, target: Doc, maximizing: boolean) {
setTimeout(() => {
let now = Date.now();
let progress = Math.min(1, (now - stime) / 200);
let pval = maximizing ?
[icon[0] + (targ[0] - icon[0]) * progress, icon[1] + (targ[1] - icon[1]) * progress] :
[targ[0] + (icon[0] - targ[0]) * progress, targ[1] + (icon[1] - targ[1]) * progress];
- target.SetNumber(KeyStore.Width, maximizing ? 25 + (width - 25) * progress : width + (25 - width) * progress);
- target.SetNumber(KeyStore.Height, maximizing ? 25 + (height - 25) * progress : height + (25 - height) * progress);
- target.SetNumber(KeyStore.X, pval[0]);
- target.SetNumber(KeyStore.Y, pval[1]);
- if (first) {
- target.SetBoolean(KeyStore.IsMinimized, false);
- }
+ target.width = maximizing ? 25 + (width - 25) * progress : width + (25 - width) * progress;
+ target.height = maximizing ? 25 + (height - 25) * progress : height + (25 - height) * progress;
+ target.x = pval[0];
+ target.y = pval[1];
if (now < stime + 200) {
this.animateBetweenIcon(false, icon, targ, width, height, stime, target, maximizing);
}
else {
if (!maximizing) {
- target.SetBoolean(KeyStore.IsMinimized, true);
- target.SetNumber(KeyStore.X, targ[0]);
- target.SetNumber(KeyStore.Y, targ[1]);
- target.SetNumber(KeyStore.Width, width);
- target.SetNumber(KeyStore.Height, height);
+ target.isMinimized = true;
+ target.x = targ[0];
+ target.y = targ[1];
+ target.width = width;
+ target.height = height;
}
- (target as any).isIconAnimating = false;
+ target.isIconAnimating = undefined;
}
},
2);
@@ -102,64 +124,70 @@ export class CollectionFreeFormDocumentView extends React.Component<CollectionFr
public toggleIcon = async (): Promise<void> => {
SelectionManager.DeselectAll();
let isMinimized: boolean | undefined;
- let minimizedDocSet = await this.props.Document.GetTAsync(KeyStore.LinkTags, ListField);
- if (!minimizedDocSet) return;
- minimizedDocSet.Data.map(async minimizedDoc => {
- if (minimizedDoc instanceof Document) {
- this.props.addDocument && this.props.addDocument(minimizedDoc, false);
- let maximizedDoc = await minimizedDoc.GetTAsync(KeyStore.MaximizedDoc, Document);
- if (maximizedDoc instanceof Document && !(maximizedDoc as any).isIconAnimating) {
- (maximizedDoc as any).isIconAnimating = true;
+ let maximizedDocs = await Cast(this.props.Document.maximizedDocs, listSpec(Doc));
+ let minimizedDoc: Doc | undefined = this.props.Document;
+ if (!maximizedDocs) {
+ minimizedDoc = await Cast(this.props.Document.minimizedDoc, Doc);
+ if (minimizedDoc) maximizedDocs = await Cast(minimizedDoc.maximizedDocs, listSpec(Doc));
+ }
+ if (minimizedDoc && maximizedDocs && maximizedDocs instanceof List) {
+ let minimizedTarget = minimizedDoc;
+ maximizedDocs.map(maximizedDoc => {
+ let iconAnimating = Cast(maximizedDoc.isIconAnimating, List);
+ if (!iconAnimating || (Date.now() - iconAnimating[6] > 1000)) {
if (isMinimized === undefined) {
- let maximizedDocMinimizedState = await maximizedDoc.GetTAsync(KeyStore.IsMinimized, BooleanField);
- isMinimized = (maximizedDocMinimizedState && maximizedDocMinimizedState.Data) ? true : false;
+ isMinimized = BoolCast(maximizedDoc.isMinimized, false);
}
- let minx = await minimizedDoc.GetTAsync(KeyStore.X, NumberField);
- let miny = await minimizedDoc.GetTAsync(KeyStore.Y, NumberField);
- let maxx = await maximizedDoc.GetTAsync(KeyStore.X, NumberField);
- let maxy = await maximizedDoc.GetTAsync(KeyStore.Y, NumberField);
- let maxw = await maximizedDoc.GetTAsync(KeyStore.Width, NumberField);
- let maxh = await maximizedDoc.GetTAsync(KeyStore.Height, NumberField);
+ let minx = NumCast(minimizedTarget.x, undefined) + NumCast(minimizedTarget.width, undefined) / 2;
+ let miny = NumCast(minimizedTarget.y, undefined) + NumCast(minimizedTarget.height, undefined) / 2;
+ let maxx = NumCast(maximizedDoc.x, undefined);
+ let maxy = NumCast(maximizedDoc.y, undefined);
+ let maxw = NumCast(maximizedDoc.width, undefined);
+ let maxh = NumCast(maximizedDoc.height, undefined);
if (minx !== undefined && miny !== undefined && maxx !== undefined && maxy !== undefined &&
- maxw !== undefined && maxh !== undefined)
- this.animateBetweenIcon(
- true,
- [minx.Data, miny.Data], [maxx.Data, maxy.Data], maxw.Data, maxh.Data,
- Date.now(), maximizedDoc, isMinimized);
+ maxw !== undefined && maxh !== undefined) {
+ let scrpt = this.props.ScreenToLocalTransform().inverse().transformPoint(minx, miny);
+ maximizedDoc.isMinimized = false;
+ maximizedDoc.isIconAnimating = new List<number>([scrpt[0], scrpt[1], maxx, maxy, maxw, maxh, Date.now(), isMinimized ? 1 : 0])
+ }
}
-
- }
- })
+ });
+ }
}
onPointerDown = (e: React.PointerEvent): void => {
this._downX = e.clientX;
this._downY = e.clientY;
e.stopPropagation();
}
- onClick = (e: React.MouseEvent): void => {
+ onClick = async (e: React.MouseEvent) => {
e.stopPropagation();
+ let ctrlKey = e.ctrlKey;
if (Math.abs(e.clientX - this._downX) < Utils.DRAG_THRESHOLD &&
Math.abs(e.clientY - this._downY) < Utils.DRAG_THRESHOLD) {
- this.props.Document.GetTAsync(KeyStore.MaximizedDoc, Document).then(maxdoc => {
- if (maxdoc instanceof Document) { // bcz: need a better way to associate behaviors with click events on widget-documents
- this.props.addDocument && this.props.addDocument(maxdoc, false);
+ if (await BoolCast(this.props.Document.isButton, false)) {
+ let maximizedDocs = await Cast(this.props.Document.maximizedDocs, listSpec(Doc));
+ if (maximizedDocs) { // bcz: need a better way to associate behaviors with click events on widget-documents
+ if (ctrlKey)
+ this.props.addDocument && maximizedDocs.filter(d => d instanceof Doc).map(maxDoc => this.props.addDocument!(maxDoc, false));
this.toggleIcon();
}
- });
+ }
}
}
+ onPointerEnter = (e: React.PointerEvent): void => { this.props.Document.libraryBrush = true; }
+ onPointerLeave = (e: React.PointerEvent): void => { this.props.Document.libraryBrush = false; }
+
borderRounding = () => {
- let br = this.props.Document.GetNumber(KeyStore.BorderRounding, 0);
+ let br = NumCast(this.props.Document.borderRounding);
return br >= 0 ? br :
- this.props.Document.GetNumber(KeyStore.NativeWidth, 0) === 0 ?
+ NumCast(this.props.Document.nativeWidth) === 0 ?
Math.min(this.props.PanelWidth(), this.props.PanelHeight())
- :
- Math.min(this.props.Document.GetNumber(KeyStore.NativeWidth, 0), this.props.Document.GetNumber(KeyStore.NativeHeight, 0));
+ : Math.min(this.Document.nativeWidth || 0, this.Document.nativeHeight || 0);
}
render() {
- let maximizedDoc = this.props.Document.GetT(KeyStore.MaximizedDoc, Document);
+ let maximizedDoc = FieldValue(Cast(this.props.Document.maximizedDocs, listSpec(Doc)));
let zoomFade = 1;
//var zoom = doc.GetNumber(KeyStore.ZoomBasis, 1);
let transform = this.getTransform().scale(this.contentScaling()).inverse();
@@ -167,7 +195,7 @@ export class CollectionFreeFormDocumentView extends React.Component<CollectionFr
let [bptX, bptY] = transform.transformPoint(this.props.PanelWidth(), this.props.PanelHeight());
let w = bptX - sptX;
//zoomFade = area < 100 || area > 800 ? Math.max(0, Math.min(1, 2 - 5 * (zoom < this.scale ? this.scale / zoom : zoom / this.scale))) : 1;
- const screenWidth = 1800;
+ const screenWidth = Math.min(50 * NumCast(this.props.Document.nativeWidth, 0), 1800);
let fadeUp = .75 * screenWidth;
let fadeDown = (maximizedDoc ? .0075 : .075) * screenWidth;
zoomFade = w < fadeDown /* || w > fadeUp */ ? Math.max(0.1, Math.min(1, 2 - (w < fadeDown ? fadeDown / w : w / fadeUp))) : 1;
@@ -175,8 +203,12 @@ export class CollectionFreeFormDocumentView extends React.Component<CollectionFr
return (
<div className="collectionFreeFormDocumentView-container" ref={this._mainCont}
onPointerDown={this.onPointerDown}
+ onPointerEnter={this.onPointerEnter} onPointerLeave={this.onPointerLeave}
onClick={this.onClick}
style={{
+ outlineColor: "black",
+ outlineStyle: "dashed",
+ outlineWidth: BoolCast(this.props.Document.libraryBrush, false) ? `${0.5 / this.contentScaling()}px` : "0px",
opacity: zoomFade,
borderRadius: `${this.borderRounding()}px`,
transformOrigin: "left top",
diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx
index e9c46aa9d..bbc927b5a 100644
--- a/src/client/views/nodes/DocumentContentsView.tsx
+++ b/src/client/views/nodes/DocumentContentsView.tsx
@@ -1,9 +1,5 @@
import { computed } from "mobx";
import { observer } from "mobx-react";
-import { FieldWaiting, Field } from "../../../fields/Field";
-import { Key } from "../../../fields/Key";
-import { KeyStore } from "../../../fields/KeyStore";
-import { ListField } from "../../../fields/ListField";
import { CollectionDockingView } from "../collections/CollectionDockingView";
import { CollectionFreeFormView } from "../collections/collectionFreeForm/CollectionFreeFormView";
import { CollectionPDFView } from "../collections/CollectionPDFView";
@@ -19,55 +15,67 @@ import { IconBox } from "./IconBox";
import { KeyValueBox } from "./KeyValueBox";
import { PDFBox } from "./PDFBox";
import { VideoBox } from "./VideoBox";
+import { FieldView } from "./FieldView";
import { WebBox } from "./WebBox";
import { HistogramBox } from "../../northstar/dash-nodes/HistogramBox";
import React = require("react");
-import { Document } from "../../../fields/Document";
import { FieldViewProps } from "./FieldView";
import { Without, OmitKeys } from "../../../Utils";
+import { Cast, StrCast } from "../../../new_fields/Types";
+import { List } from "../../../new_fields/List";
const JsxParser = require('react-jsx-parser').default; //TODO Why does this need to be imported like this?
type BindingProps = Without<FieldViewProps, 'fieldKey'>;
export interface JsxBindings {
props: BindingProps;
- [keyName: string]: BindingProps | Field;
}
+class ObserverJsxParser1 extends JsxParser {
+ constructor(props: any) {
+ super(props);
+ observer(this as any);
+ }
+}
+
+const ObserverJsxParser: typeof JsxParser = ObserverJsxParser1 as any;
+
@observer
export class DocumentContentsView extends React.Component<DocumentViewProps & {
isSelected: () => boolean,
select: (ctrl: boolean) => void,
- layoutKey: Key
+ layoutKey: string
}> {
- @computed get layout(): string { return this.props.Document.GetText(this.props.layoutKey, "<p>Error loading layout data</p>"); }
- @computed get layoutKeys(): Key[] { return this.props.Document.GetData(KeyStore.LayoutKeys, ListField, new Array<Key>()); }
- @computed get layoutFields(): Key[] { return this.props.Document.GetData(KeyStore.LayoutFields, ListField, new Array<Key>()); }
-
+ @computed get layout(): string { return Cast(this.props.Document[this.props.layoutKey], "string", "<p>Error loading layout data</p>"); }
CreateBindings(): JsxBindings {
- let bindings: JsxBindings = { props: OmitKeys(this.props, ['parentActive'], (obj: any) => obj.active = this.props.parentActive) };
+ return { props: OmitKeys(this.props, ['parentActive'], (obj: any) => obj.active = this.props.parentActive).omit };
+ }
- let keys: Key[] = [];
- keys.push(...this.layoutKeys, KeyStore.Caption) // bcz: hack to get templates to work
- for (const key of keys) {
- bindings[key.Name + "Key"] = key; // this maps string values of the form <keyname>Key to an actual key Kestore.keyname e.g, "DataKey" => KeyStore.Data
- }
- for (const key of this.layoutFields) {
- let field = this.props.Document.Get(key);
- bindings[key.Name] = field && field !== FieldWaiting ? field.GetValue() : field;
+ @computed get templates(): List<string> {
+ let field = this.props.Document.templates;
+ if (field && field instanceof List) {
+ return field;
}
- return bindings;
+ return new List<string>();
+ }
+ set templates(templates: List<string>) { this.props.Document.templates = templates; }
+ get finalLayout() {
+ const baseLayout = this.layout;
+ let base = baseLayout;
+ let layout = baseLayout;
+
+ this.templates.forEach(template => {
+ layout = template.replace("{layout}", base);
+ base = layout;
+ });
+ return layout;
}
render() {
- let lkeys = this.props.Document.GetT(KeyStore.LayoutKeys, ListField);
- if (!lkeys || lkeys === FieldWaiting) {
- return <p>Error loading layout keys</p>;
- }
- return <JsxParser
- components={{ FormattedTextBox, ImageBox, IconBox, CollectionFreeFormView, CollectionDockingView, CollectionSchemaView, CollectionView, CollectionPDFView, CollectionVideoView, WebBox, KeyValueBox, PDFBox, VideoBox, AudioBox, HistogramBox }}
+ return <ObserverJsxParser
+ components={{ FormattedTextBox, ImageBox, IconBox, FieldView, CollectionFreeFormView, CollectionDockingView, CollectionSchemaView, CollectionView, CollectionPDFView, CollectionVideoView, WebBox, KeyValueBox, PDFBox, VideoBox, AudioBox, HistogramBox }}
bindings={this.CreateBindings()}
- jsx={this.layout}
+ jsx={this.finalLayout}
showWarnings={true}
onError={(test: any) => { console.log(test); }}
/>;
diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx
index 40e3c66ae..fd012e7ea 100644
--- a/src/client/views/nodes/DocumentView.tsx
+++ b/src/client/views/nodes/DocumentView.tsx
@@ -1,16 +1,9 @@
import { action, computed, runInAction } from "mobx";
import { observer } from "mobx-react";
-import { Document } from "../../../fields/Document";
-import { Field, FieldWaiting, Opt } from "../../../fields/Field";
-import { Key } from "../../../fields/Key";
-import { KeyStore } from "../../../fields/KeyStore";
-import { ListField } from "../../../fields/ListField";
-import { TemplateField } from "../../../fields/TemplateField";
-import { ServerUtils } from "../../../server/ServerUtil";
import { emptyFunction, Utils } from "../../../Utils";
-import { Documents } from "../../documents/Documents";
+import { Docs } from "../../documents/Documents";
import { DocumentManager } from "../../util/DocumentManager";
-import { DragManager } from "../../util/DragManager";
+import { DragManager, dropActionType } from "../../util/DragManager";
import { SelectionManager } from "../../util/SelectionManager";
import { Transform } from "../../util/Transform";
import { undoBatch, UndoManager } from "../../util/UndoManager";
@@ -23,15 +16,31 @@ import { Template, Templates } from "./../Templates";
import { DocumentContentsView } from "./DocumentContentsView";
import "./DocumentView.scss";
import React = require("react");
-import { PresentationView } from "../PresentationView";
-
+import { Opt, Doc, WidthSym, HeightSym } from "../../../new_fields/Doc";
+import { DocComponent } from "../DocComponent";
+import { createSchema, makeInterface } from "../../../new_fields/Schema";
+import { FieldValue, StrCast, BoolCast } from "../../../new_fields/Types";
+import { List } from "../../../new_fields/List";
import { CollectionFreeFormView } from "../collections/collectionFreeForm/CollectionFreeFormView";
import { CurrentUserUtils } from "../../../server/authentication/models/current_user_utils";
-import { TextField } from "../../../fields/TextField";
+import { DocServer } from "../../DocServer";
+import { Id } from "../../../new_fields/RefField";
+import { PresentationView } from "../PresentationView";
+
+const linkSchema = createSchema({
+ title: "string",
+ linkDescription: "string",
+ linkTags: "string",
+ linkedTo: Doc,
+ linkedFrom: Doc
+});
+
+type LinkDoc = makeInterface<[typeof linkSchema]>;
+const LinkDoc = makeInterface(linkSchema);
export interface DocumentViewProps {
ContainingCollectionView: Opt<CollectionView | CollectionPDFView | CollectionVideoView>;
- Document: Document;
+ Document: Doc;
addDocument?: (doc: Document, allowDuplicates?: boolean) => boolean;
removeDocument?: (doc: Document) => boolean;
moveDocument?: (doc: Document, targetCollection: Document, addDocument: (document: Document) => boolean) => boolean;
@@ -45,49 +54,33 @@ export interface DocumentViewProps {
parentActive: () => boolean;
whenActiveChanged: (isActive: boolean) => void;
toggleMinimized: () => void;
-}
-export interface JsxArgs extends DocumentViewProps {
- Keys: { [name: string]: Key };
- Fields: { [name: string]: Field };
+ bringToFront: (doc: Doc) => void;
}
-/*
-This function is pretty much a hack that lets us fill out the fields in JsxArgs with something that
-jsx-to-string can recover the jsx from
-Example usage of this function:
- public static LayoutString() {
- let args = FakeJsxArgs(["Data"]);
- return jsxToString(
- <CollectionFreeFormView
- doc={args.Document}
- fieldKey={args.Keys.Data}
- DocumentViewForField={args.DocumentView} />,
- { useFunctionCode: true, functionNameOnly: true }
- )
- }
-*/
-export function FakeJsxArgs(keys: string[], fields: string[] = []): JsxArgs {
- let Keys: { [name: string]: any } = {};
- let Fields: { [name: string]: any } = {};
- for (const key of keys) {
- Object.defineProperty(emptyFunction, "name", { value: key + "Key" });
- Keys[key] = emptyFunction;
- }
- for (const field of fields) {
- Object.defineProperty(emptyFunction, "name", { value: field });
- Fields[field] = emptyFunction;
- }
- let args: JsxArgs = {
- Document: function Document() { },
- DocumentView: function DocumentView() { },
- Keys,
- Fields
- } as any;
- return args;
-}
+const schema = createSchema({
+ layout: "string",
+ nativeWidth: "number",
+ nativeHeight: "number",
+ backgroundColor: "string"
+});
+
+export const positionSchema = createSchema({
+ nativeWidth: "number",
+ nativeHeight: "number",
+ width: "number",
+ height: "number",
+ x: "number",
+ y: "number",
+});
+
+export type PositionDocument = makeInterface<[typeof positionSchema]>;
+export const PositionDocument = makeInterface(positionSchema);
+
+type Document = makeInterface<[typeof schema]>;
+const Document = makeInterface(schema);
@observer
-export class DocumentView extends React.Component<DocumentViewProps> {
+export class DocumentView extends DocComponent<DocumentViewProps, Document>(Document) {
private _downX: number = 0;
private _downY: number = 0;
private _mainCont = React.createRef<HTMLDivElement>();
@@ -96,14 +89,14 @@ export class DocumentView extends React.Component<DocumentViewProps> {
public get ContentDiv() { return this._mainCont.current; }
@computed get active(): boolean { return SelectionManager.IsSelected(this) || this.props.parentActive(); }
@computed get topMost(): boolean { return this.props.isTopMost; }
- @computed get layout(): string { return this.props.Document.GetText(KeyStore.Layout, "<p>Error loading layout data</p>"); }
- @computed get layoutKeys(): Key[] { return this.props.Document.GetData(KeyStore.LayoutKeys, ListField, new Array<Key>()); }
- @computed get layoutFields(): Key[] { return this.props.Document.GetData(KeyStore.LayoutFields, ListField, new Array<Key>()); }
- @computed get templates(): Array<Template> {
- let field = this.props.Document.GetT(KeyStore.Templates, TemplateField);
- return !field || field === FieldWaiting ? [] : field.Data;
+ @computed get templates(): List<string> {
+ let field = this.props.Document.templates;
+ if (field && field instanceof List) {
+ return field;
+ }
+ return new List<string>();
}
- set templates(templates: Array<Template>) { this.props.Document.SetData(KeyStore.Templates, templates, TemplateField); }
+ set templates(templates: List<string>) { this.props.Document.templates = templates; }
screenRect = (): ClientRect | DOMRect => this._mainCont.current ? this._mainCont.current.getBoundingClientRect() : new DOMRect();
@action
@@ -138,12 +131,12 @@ export class DocumentView extends React.Component<DocumentViewProps> {
e.stopPropagation();
}
- startDragging(x: number, y: number, dropAliasOfDraggedDoc: boolean) {
+ startDragging(x: number, y: number, dropAction: dropActionType) {
if (this._mainCont.current) {
const [left, top] = this.props.ScreenToLocalTransform().scale(this.props.ContentScaling()).inverse().transformPoint(0, 0);
let dragData = new DragManager.DocumentDragData([this.props.Document]);
const [xoff, yoff] = this.props.ScreenToLocalTransform().scale(this.props.ContentScaling()).transformDirection(x - left, y - top);
- dragData.aliasOnDrop = dropAliasOfDraggedDoc;
+ dragData.dropAction = dropAction;
dragData.xOffset = xoff;
dragData.yOffset = yoff;
dragData.moveDocument = this.props.moveDocument;
@@ -151,13 +144,13 @@ export class DocumentView extends React.Component<DocumentViewProps> {
handlers: {
dragComplete: action(emptyFunction)
},
- hideSource: !dropAliasOfDraggedDoc
+ hideSource: !dropAction
});
}
}
onClick = (e: React.MouseEvent): void => {
- if (CurrentUserUtils.MainDocId != this.props.Document.Id &&
+ if (CurrentUserUtils.MainDocId !== this.props.Document[Id] &&
(Math.abs(e.clientX - this._downX) < Utils.DRAG_THRESHOLD &&
Math.abs(e.clientY - this._downY) < Utils.DRAG_THRESHOLD)) {
SelectionManager.SelectDoc(this, e.ctrlKey);
@@ -171,7 +164,7 @@ export class DocumentView extends React.Component<DocumentViewProps> {
}
if (e.shiftKey && e.buttons === 1) {
if (this.props.isTopMost) {
- this.startDragging(e.pageX, e.pageY, e.altKey || e.ctrlKey);
+ this.startDragging(e.pageX, e.pageY, e.altKey || e.ctrlKey ? "alias" : undefined);
} else {
CollectionDockingView.Instance.StartOtherDrag([this.props.Document], e);
}
@@ -181,7 +174,6 @@ export class DocumentView extends React.Component<DocumentViewProps> {
document.addEventListener("pointermove", this.onPointerMove);
document.removeEventListener("pointerup", this.onPointerUp);
document.addEventListener("pointerup", this.onPointerUp);
- e.preventDefault();
}
}
onPointerMove = (e: PointerEvent): void => {
@@ -190,7 +182,7 @@ export class DocumentView extends React.Component<DocumentViewProps> {
document.removeEventListener("pointermove", this.onPointerMove);
document.removeEventListener("pointerup", this.onPointerUp);
if (!e.altKey && !this.topMost && (!CollectionFreeFormView.RIGHT_BTN_DRAG && e.buttons === 1) || (CollectionFreeFormView.RIGHT_BTN_DRAG && e.buttons === 2)) {
- this.startDragging(this._downX, this._downY, e.ctrlKey || e.altKey);
+ this.startDragging(this._downX, this._downY, e.ctrlKey || e.altKey ? "alias" : undefined);
}
}
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
@@ -206,33 +198,34 @@ export class DocumentView extends React.Component<DocumentViewProps> {
this.props.removeDocument && this.props.removeDocument(this.props.Document);
}
fieldsClicked = (e: React.MouseEvent): void => {
- let kvp = Documents.KVPDocument(this.props.Document, { width: 300, height: 300 });
+ let kvp = Docs.KVPDocument(this.props.Document, { width: 300, height: 300 });
CollectionDockingView.Instance.AddRightSplit(kvp);
}
- fullScreenClicked = (e: React.MouseEvent): void => {
- CollectionDockingView.Instance.OpenFullScreen((this.props.Document.GetPrototype() as Document).MakeDelegate());
- ContextMenu.Instance.clearItems();
- ContextMenu.Instance.addItem({ description: "Close Full Screen", event: this.closeFullScreenClicked });
- ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15);
+ makeButton = (e: React.MouseEvent): void => {
+ this.props.Document.isButton = !BoolCast(this.props.Document.isButton, false);
+ if (this.props.Document.isButton && !this.props.Document.nativeWidth) {
+ this.props.Document.nativeWidth = this.props.Document[WidthSym]();
+ this.props.Document.nativeHeight = this.props.Document[HeightSym]();
+ }
}
- closeFullScreenClicked = (e: React.MouseEvent): void => {
- CollectionDockingView.Instance.CloseFullScreen();
+ fullScreenClicked = (e: React.MouseEvent): void => {
+ const doc = Doc.MakeDelegate(FieldValue(this.Document.proto));
+ if (doc) {
+ CollectionDockingView.Instance.OpenFullScreen(doc);
+ }
ContextMenu.Instance.clearItems();
- ContextMenu.Instance.addItem({ description: "Full Screen", event: this.fullScreenClicked });
- ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15);
+ SelectionManager.DeselectAll();
}
-
@undoBatch
@action
- drop = (e: Event, de: DragManager.DropEvent) => {
+ drop = async (e: Event, de: DragManager.DropEvent) => {
if (de.data instanceof DragManager.LinkDragData) {
let sourceDoc = de.data.linkSourceDocument;
let destDoc = this.props.Document;
- destDoc.GetTAsync(KeyStore.Prototype, Document).then(protoDest =>
- sourceDoc.GetTAsync(KeyStore.Prototype, Document).then(protoSrc =>
- (protoSrc ? protoSrc : sourceDoc).CreateLink(protoDest ? protoDest : destDoc))
- );
+ const protoDest = destDoc.proto;
+ const protoSrc = sourceDoc.proto;
+ Doc.MakeLink(protoSrc ? protoSrc : sourceDoc, protoDest ? protoDest : destDoc);
e.stopPropagation();
}
}
@@ -241,52 +234,30 @@ export class DocumentView extends React.Component<DocumentViewProps> {
onDrop = (e: React.DragEvent) => {
let text = e.dataTransfer.getData("text/plain");
if (!e.isDefaultPrevented() && text && text.startsWith("<div")) {
- let oldLayout = this.props.Document.GetText(KeyStore.Layout, "");
+ let oldLayout = FieldValue(this.Document.layout) || "";
let layout = text.replace("{layout}", oldLayout);
- this.props.Document.SetText(KeyStore.Layout, layout);
+ this.Document.layout = layout;
e.stopPropagation();
e.preventDefault();
}
}
- updateLayout = async () => {
- const baseLayout = await this.props.Document.GetTAsync(KeyStore.BaseLayout, TextField);
- if (baseLayout) {
- let base = baseLayout.Data;
- let layout = baseLayout.Data;
-
- this.templates.forEach(template => {
- let temp = template.Layout;
- layout = temp.replace("{layout}", base);
- base = layout;
- });
-
- this.props.Document.SetText(KeyStore.Layout, layout);
- }
- }
@action
addTemplate = (template: Template) => {
- let templates = this.templates;
- templates.push(template);
- templates = templates.splice(0, templates.length).sort(Templates.sortTemplates);
- this.templates = templates;
- this.updateLayout();
+ this.templates.push(template.Layout);
+ this.templates = this.templates;
}
@action
removeTemplate = (template: Template) => {
- let templates = this.templates;
- for (let i = 0; i < templates.length; i++) {
- let temp = templates[i];
- if (temp.Name === template.Name) {
- templates.splice(i, 1);
+ for (let i = 0; i < this.templates.length; i++) {
+ if (this.templates[i] === template.Layout) {
+ this.templates.splice(i, 1);
break;
}
}
- templates = templates.splice(0, templates.length).sort(Templates.sortTemplates);
- this.templates = templates;
- this.updateLayout();
+ this.templates = this.templates;
}
@action
@@ -300,11 +271,12 @@ export class DocumentView extends React.Component<DocumentViewProps> {
e.preventDefault();
ContextMenu.Instance.addItem({ description: "Full Screen", event: this.fullScreenClicked });
+ ContextMenu.Instance.addItem({ description: this.props.Document.isButton ? "Remove Button" : "Make Button", event: this.makeButton });
ContextMenu.Instance.addItem({ description: "Fields", event: this.fieldsClicked });
ContextMenu.Instance.addItem({ description: "Center", event: () => this.props.focus(this.props.Document) });
ContextMenu.Instance.addItem({ description: "Open Right", event: () => CollectionDockingView.Instance.AddRightSplit(this.props.Document) });
- ContextMenu.Instance.addItem({ description: "Copy URL", event: () => Utils.CopyText(ServerUtils.prepend("/doc/" + this.props.Document.Id)) });
- ContextMenu.Instance.addItem({ description: "Copy ID", event: () => Utils.CopyText(this.props.Document.Id) });
+ ContextMenu.Instance.addItem({ description: "Copy URL", event: () => Utils.CopyText(DocServer.prepend("/doc/" + this.props.Document[Id])) });
+ ContextMenu.Instance.addItem({ description: "Copy ID", event: () => Utils.CopyText(this.props.Document[Id]) });
//ContextMenu.Instance.addItem({ description: "Docking", event: () => this.props.Document.SetNumber(KeyStore.ViewType, CollectionViewType.Docking) })
ContextMenu.Instance.addItem({ description: "Pin to Presentation", event: () => PresentationView.Instance.PinDoc(this.props.Document) });
ContextMenu.Instance.addItem({ description: "Delete", event: this.deleteClicked });
@@ -313,15 +285,18 @@ export class DocumentView extends React.Component<DocumentViewProps> {
e.stopPropagation();
}
ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15);
- if (!SelectionManager.IsSelected(this))
+ if (!SelectionManager.IsSelected(this)) {
SelectionManager.SelectDoc(this, false);
+ }
}
+
isSelected = () => SelectionManager.IsSelected(this);
select = (ctrlPressed: boolean) => SelectionManager.SelectDoc(this, ctrlPressed);
- @computed get nativeWidth() { return this.props.Document.GetNumber(KeyStore.NativeWidth, 0); }
- @computed get nativeHeight() { return this.props.Document.GetNumber(KeyStore.NativeHeight, 0); }
- @computed get contents() { return (<DocumentContentsView {...this.props} isSelected={this.isSelected} select={this.select} layoutKey={KeyStore.Layout} />); }
+
+ @computed get nativeWidth() { return this.Document.nativeWidth || 0; }
+ @computed get nativeHeight() { return this.Document.nativeHeight || 0; }
+ @computed get contents() { return (<DocumentContentsView {...this.props} isSelected={this.isSelected} select={this.select} layoutKey={"layout"} />); }
render() {
var scaling = this.props.ContentScaling();
@@ -333,8 +308,9 @@ export class DocumentView extends React.Component<DocumentViewProps> {
ref={this._mainCont}
style={{
borderRadius: "inherit",
- background: this.props.Document.GetText(KeyStore.BackgroundColor, ""),
- width: nativeWidth, height: nativeHeight,
+ background: this.Document.backgroundColor || "",
+ width: nativeWidth,
+ height: nativeHeight,
transform: `scale(${scaling}, ${scaling})`
}}
onDrop={this.onDrop} onContextMenu={this.onContextMenu} onPointerDown={this.onPointerDown} onClick={this.onClick}
diff --git a/src/client/views/nodes/FieldView.tsx b/src/client/views/nodes/FieldView.tsx
index 9e175b0d1..a1e083b36 100644
--- a/src/client/views/nodes/FieldView.tsx
+++ b/src/client/views/nodes/FieldView.tsx
@@ -1,30 +1,22 @@
import React = require("react");
import { observer } from "mobx-react";
import { computed } from "mobx";
-import { Field, FieldWaiting, FieldValue, Opt } from "../../../fields/Field";
-import { Document } from "../../../fields/Document";
-import { TextField } from "../../../fields/TextField";
-import { NumberField } from "../../../fields/NumberField";
-import { RichTextField } from "../../../fields/RichTextField";
-import { ImageField } from "../../../fields/ImageField";
-import { VideoField } from "../../../fields/VideoField";
-import { Key } from "../../../fields/Key";
import { FormattedTextBox } from "./FormattedTextBox";
import { ImageBox } from "./ImageBox";
-import { WebBox } from "./WebBox";
import { VideoBox } from "./VideoBox";
import { AudioBox } from "./AudioBox";
-import { AudioField } from "../../../fields/AudioField";
-import { ListField } from "../../../fields/ListField";
import { DocumentContentsView } from "./DocumentContentsView";
import { Transform } from "../../util/Transform";
-import { KeyStore } from "../../../fields/KeyStore";
-import { returnFalse, emptyDocFunction, emptyFunction, returnOne, returnZero } from "../../../Utils";
+import { returnFalse, emptyFunction } from "../../../Utils";
import { CollectionView } from "../collections/CollectionView";
import { CollectionPDFView } from "../collections/CollectionPDFView";
import { CollectionVideoView } from "../collections/CollectionVideoView";
-import { IconField } from "../../../fields/IconFIeld";
import { IconBox } from "./IconBox";
+import { Opt, Doc, FieldResult } from "../../../new_fields/Doc";
+import { List } from "../../../new_fields/List";
+import { ImageField, VideoField, AudioField } from "../../../new_fields/URLField";
+import { IconField } from "../../../new_fields/IconField";
+import { RichTextField } from "../../../new_fields/RichTextField";
//
@@ -33,43 +25,44 @@ import { IconBox } from "./IconBox";
// See the LayoutString method on each field view : ImageBox, FormattedTextBox, etc.
//
export interface FieldViewProps {
- fieldKey: Key;
+ fieldKey: string;
ContainingCollectionView: Opt<CollectionView | CollectionPDFView | CollectionVideoView>;
- Document: Document;
+ Document: Doc;
isSelected: () => boolean;
select: (isCtrlPressed: boolean) => void;
isTopMost: boolean;
selectOnLoad: boolean;
- addDocument?: (document: Document, allowDuplicates?: boolean) => boolean;
- removeDocument?: (document: Document) => boolean;
- moveDocument?: (document: Document, targetCollection: Document, addDocument: (document: Document) => boolean) => boolean;
+ addDocument?: (document: Doc, allowDuplicates?: boolean) => boolean;
+ removeDocument?: (document: Doc) => boolean;
+ moveDocument?: (document: Doc, targetCollection: Doc, addDocument: (document: Doc) => boolean) => boolean;
ScreenToLocalTransform: () => Transform;
active: () => boolean;
whenActiveChanged: (isActive: boolean) => void;
- focus: (doc: Document) => void;
+ focus: (doc: Doc) => void;
PanelWidth: () => number;
PanelHeight: () => number;
+ setVideoBox?: (player: VideoBox) => void;
}
@observer
export class FieldView extends React.Component<FieldViewProps> {
- public static LayoutString(fieldType: { name: string }, fieldStr: string = "DataKey") {
- return `<${fieldType.name} {...props} fieldKey={${fieldStr}} />`;
+ public static LayoutString(fieldType: { name: string }, fieldStr: string = "data") {
+ return `<${fieldType.name} {...props} fieldKey={"${fieldStr}"} />`;
}
@computed
- get field(): FieldValue<Field> {
- const { Document: doc, fieldKey } = this.props;
- return doc.Get(fieldKey);
+ get field(): FieldResult {
+ const { Document, fieldKey } = this.props;
+ return Document[fieldKey];
}
render() {
const field = this.field;
- if (!field) {
+ if (field === undefined) {
return <p>{'<null>'}</p>;
}
- if (field instanceof TextField) {
- return <p>{field.Data}</p>;
- }
+ // if (typeof field === "string") {
+ // return <p>{field}</p>;
+ // }
else if (field instanceof RichTextField) {
return <FormattedTextBox {...this.props} />;
}
@@ -85,7 +78,7 @@ export class FieldView extends React.Component<FieldViewProps> {
else if (field instanceof AudioField) {
return <AudioBox {...this.props} />;
}
- else if (field instanceof Document) {
+ else if (field instanceof Doc) {
return (
<DocumentContentsView Document={field}
addDocument={undefined}
@@ -96,30 +89,27 @@ export class FieldView extends React.Component<FieldViewProps> {
PanelHeight={() => 100}
isTopMost={true} //TODO Why is this top most?
selectOnLoad={false}
- focus={emptyDocFunction}
+ focus={emptyFunction}
isSelected={this.props.isSelected}
select={returnFalse}
- layoutKey={KeyStore.Layout}
+ layoutKey={"layout"}
ContainingCollectionView={this.props.ContainingCollectionView}
parentActive={this.props.active}
toggleMinimized={emptyFunction}
whenActiveChanged={this.props.whenActiveChanged} />
);
}
- else if (field instanceof ListField) {
+ else if (field instanceof List) {
return (<div>
- {(field as ListField<Field>).Data.map(f => f instanceof Document ? f.Title : f.GetValue().toString()).join(", ")}
+ {field.map(f => f instanceof Doc ? f.title : f.toString()).join(", ")}
</div>);
}
// bcz: this belongs here, but it doesn't render well so taking it out for now
// else if (field instanceof HtmlField) {
// return <WebBox {...this.props} />
// }
- else if (field instanceof NumberField) {
- return <p>{field.Data}</p>;
- }
- else if (field !== FieldWaiting) {
- return <p>{JSON.stringify(field.GetValue())}</p>;
+ else if (!(field instanceof Promise)) {
+ return <p>{JSON.stringify(field)}</p>;
}
else {
return <p> {"Waiting for server..."} </p>;
diff --git a/src/client/views/nodes/FormattedTextBox.scss b/src/client/views/nodes/FormattedTextBox.scss
index 727d3c0b2..d43aa4e02 100644
--- a/src/client/views/nodes/FormattedTextBox.scss
+++ b/src/client/views/nodes/FormattedTextBox.scss
@@ -30,11 +30,11 @@
pointer-events: none;
}
.formattedTextBox-inner-rounded {
- height: calc(100% - 40px);
+ height: calc(100% - 25px);
width: calc(100% - 40px);
position: absolute;
- overflow: scroll;
- top: 20;
+ overflow: auto;
+ top: 15;
left: 20;
}
diff --git a/src/client/views/nodes/FormattedTextBox.tsx b/src/client/views/nodes/FormattedTextBox.tsx
index 41ee24498..eeb60cb3d 100644
--- a/src/client/views/nodes/FormattedTextBox.tsx
+++ b/src/client/views/nodes/FormattedTextBox.tsx
@@ -4,11 +4,6 @@ import { history } from "prosemirror-history";
import { keymap } from "prosemirror-keymap";
import { EditorState, Plugin, Transaction } from "prosemirror-state";
import { EditorView } from "prosemirror-view";
-import { FieldWaiting, Opt } from "../../../fields/Field";
-import { KeyStore } from "../../../fields/KeyStore";
-import { RichTextField } from "../../../fields/RichTextField";
-import { TextField } from "../../../fields/TextField";
-import { Document } from "../../../fields/Document";
import buildKeymap from "../../util/ProsemirrorKeymap";
import { inpRules } from "../../util/RichTextRules";
import { schema } from "../../util/RichTextSchema";
@@ -20,12 +15,20 @@ import { FieldView, FieldViewProps } from "./FieldView";
import "./FormattedTextBox.scss";
import React = require("react");
import { SelectionManager } from "../../util/SelectionManager";
+import { DocComponent } from "../DocComponent";
+import { createSchema, makeInterface } from "../../../new_fields/Schema";
+import { Opt, Doc, WidthSym, HeightSym } from "../../../new_fields/Doc";
import { observer } from "mobx-react";
import { InkingControl } from "../InkingControl";
+import { StrCast, Cast, NumCast, BoolCast } from "../../../new_fields/Types";
+import { RichTextField } from "../../../new_fields/RichTextField";
+import { Id } from "../../../new_fields/RefField";
+const { buildMenuItems } = require("prosemirror-example-setup");
+const { menuBar } = require("prosemirror-menu");
// FormattedTextBox: Displays an editable plain text node that maps to a specified Key of a Document
//
-// HTML Markup: <FormattedTextBox Doc={Document's ID} FieldKey={Key's name + "Key"}
+// HTML Markup: <FormattedTextBox Doc={Document's ID} FieldKey={Key's name}
//
// In Code, the node's HTML is specified in the document's parameterized structure as:
// document.SetField(KeyStore.Layout, "<FormattedTextBox doc={doc} fieldKey={<KEYNAME>Key} />");
@@ -44,9 +47,16 @@ export interface FormattedTextBoxOverlay {
isOverlay?: boolean;
}
+const richTextSchema = createSchema({
+ documentText: "string"
+});
+
+type RichTextDocument = makeInterface<[typeof richTextSchema]>;
+const RichTextDocument = makeInterface(richTextSchema);
+
@observer
-export class FormattedTextBox extends React.Component<(FieldViewProps & FormattedTextBoxOverlay)> {
- public static LayoutString(fieldStr: string = "DataKey") {
+export class FormattedTextBox extends DocComponent<(FieldViewProps & FormattedTextBoxOverlay), RichTextDocument>(RichTextDocument) {
+ public static LayoutString(fieldStr: string = "data") {
return FieldView.LayoutString(FormattedTextBox, fieldStr);
}
private _ref: React.RefObject<HTMLDivElement>;
@@ -62,7 +72,6 @@ export class FormattedTextBox extends React.Component<(FieldViewProps & Formatte
this._ref = React.createRef();
this._proseRef = React.createRef();
- this.onChange = this.onChange.bind(this);
}
_applyingChange: boolean = false;
@@ -73,17 +82,15 @@ export class FormattedTextBox extends React.Component<(FieldViewProps & Formatte
const state = this._lastState = this._editorView.state.apply(tx);
this._editorView.updateState(state);
this._applyingChange = true;
- this.props.Document.SetDataOnPrototype(
- this.props.fieldKey,
- JSON.stringify(state.toJSON()),
- RichTextField
- );
- this.props.Document.SetDataOnPrototype(KeyStore.DocumentText, state.doc.textBetween(0, state.doc.content.size, "\n\n"), TextField);
+ Doc.SetOnPrototype(this.props.Document, this.props.fieldKey, new RichTextField(JSON.stringify(state.toJSON())));
+ Doc.SetOnPrototype(this.props.Document, "documentText", state.doc.textBetween(0, state.doc.content.size, "\n\n"));
this._applyingChange = false;
- if (this.props.Document.Title.startsWith("-") && this._editorView) {
+ let title = StrCast(this.props.Document.title);
+ if (title && title.startsWith("-") && this._editorView) {
let str = this._editorView.state.doc.textContent;
let titlestr = str.substr(0, Math.min(40, str.length));
- this.props.Document.SetText(KeyStore.Title, "-" + titlestr + (str.length > 40 ? "..." : ""));
+ let target = this.props.Document.proto ? this.props.Document.proto : this.props.Document;
+ target.title = "-" + titlestr + (str.length > 40 ? "..." : "");
};
}
}
@@ -111,7 +118,7 @@ export class FormattedTextBox extends React.Component<(FieldViewProps & Formatte
};
if (this.props.isOverlay) {
- this._inputReactionDisposer = reaction(() => MainOverlayTextBox.Instance.TextDoc && MainOverlayTextBox.Instance.TextDoc.Id,
+ this._inputReactionDisposer = reaction(() => MainOverlayTextBox.Instance.TextDoc && MainOverlayTextBox.Instance.TextDoc[Id],
() => {
if (this._editorView) {
this._editorView.destroy();
@@ -121,14 +128,14 @@ export class FormattedTextBox extends React.Component<(FieldViewProps & Formatte
);
} else {
this._proxyReactionDisposer = reaction(() => this.props.isSelected(),
- () => this.props.isSelected() && MainOverlayTextBox.Instance.SetTextDoc(this.props.Document, this.props.fieldKey, this._ref.current!, this.props.ScreenToLocalTransform));
+ () => this.props.isSelected() && !BoolCast(this.props.Document.isButton, false) && MainOverlayTextBox.Instance.SetTextDoc(this.props.Document, this.props.fieldKey, this._ref.current!, this.props.ScreenToLocalTransform));
}
this._reactionDisposer = reaction(
() => {
- const field = this.props.Document ? this.props.Document.GetT(this.props.fieldKey, RichTextField) : undefined;
- return field && field !== FieldWaiting ? field.Data : undefined;
+ const field = this.props.Document ? Cast(this.props.Document[this.props.fieldKey], RichTextField) : undefined;
+ return field ? field.Data : undefined;
},
field => field && this._editorView && !this._applyingChange &&
this._editorView.updateState(EditorState.fromJSON(config, JSON.parse(field)))
@@ -136,10 +143,10 @@ export class FormattedTextBox extends React.Component<(FieldViewProps & Formatte
this.setupEditor(config, this.props.Document);
}
- private setupEditor(config: any, doc?: Document) {
- let field = doc ? doc.GetT(this.props.fieldKey, RichTextField) : undefined;
- if (this._ref.current) {
- this._editorView = new EditorView(this._ref.current, {
+ private setupEditor(config: any, doc?: Doc) {
+ let field = doc ? Cast(doc[this.props.fieldKey], RichTextField) : undefined;
+ if (this._proseRef.current) {
+ this._editorView = new EditorView(this._proseRef.current, {
state: field && field.Data ? EditorState.fromJSON(config, JSON.parse(field.Data)) : EditorState.create(config),
dispatchTransaction: this.dispatchTransaction
});
@@ -166,13 +173,6 @@ export class FormattedTextBox extends React.Component<(FieldViewProps & Formatte
}
}
- @action
- onChange(e: React.ChangeEvent<HTMLInputElement>) {
- const { fieldKey, Document } = this.props;
- Document.SetOnPrototype(fieldKey, new RichTextField(e.target.value));
- // doc.SetData(fieldKey, e.target.value, RichTextField);
- }
- @action
onPointerDown = (e: React.PointerEvent): void => {
if (e.button === 0 && this.props.isSelected() && !e.altKey && !e.ctrlKey && !e.metaKey) {
e.stopPropagation();
@@ -196,22 +196,30 @@ export class FormattedTextBox extends React.Component<(FieldViewProps & Formatte
if (!this.props.isOverlay) {
MainOverlayTextBox.Instance.SetTextDoc(this.props.Document, this.props.fieldKey, this._ref.current!, this.props.ScreenToLocalTransform);
} else {
- if (this._ref.current) {
- this._ref.current.scrollTop = MainOverlayTextBox.Instance.TextScroll;
+ if (this._proseRef.current) {
+ this._proseRef.current.scrollTop = MainOverlayTextBox.Instance.TextScroll;
}
}
}
//REPLACE THIS WITH CAPABILITIES SPECIFIC TO THIS TYPE OF NODE
- textCapability = (e: React.MouseEvent): void => { };
+ textCapability = (e: React.MouseEvent): void => {
+ if (NumCast(this.props.Document.nativeWidth)) {
+ this.props.Document.nativeWidth = undefined;
+ this.props.Document.nativeHeight = undefined;
+ } else {
+ this.props.Document.nativeWidth = this.props.Document[WidthSym]();
+ this.props.Document.nativeHeight = this.props.Document[HeightSym]();
+ }
+ }
specificContextMenu = (e: React.MouseEvent): void => {
if (!this._gotDown) {
e.preventDefault();
return;
}
ContextMenu.Instance.addItem({
- description: "Text Capability",
+ description: NumCast(this.props.Document.nativeWidth) ? "Unfreeze" : "Freeze",
event: this.textCapability
});
@@ -238,6 +246,11 @@ export class FormattedTextBox extends React.Component<(FieldViewProps & Formatte
onClick = (e: React.MouseEvent): void => {
this._proseRef.current!.focus();
}
+ onMouseDown = (e: React.MouseEvent): void => {
+ if (!this.props.isSelected()) { // preventing default allows the onClick to be generated instead of being swallowed by the text box itself
+ e.preventDefault(); // bcz: this would normally be in OnPointerDown - however, if done there, no mouse move events will be generated which makes transititioning to GoldenLayout's drag interactions impossible
+ }
+ }
tooltipTextMenuPlugin() {
let myprops = this.props;
@@ -259,9 +272,8 @@ export class FormattedTextBox extends React.Component<(FieldViewProps & Formatte
});
}
- @action
onKeyPress = (e: React.KeyboardEvent) => {
- if (e.key == "Escape") {
+ if (e.key === "Escape") {
SelectionManager.DeselectAll();
}
e.stopPropagation();
@@ -269,14 +281,20 @@ export class FormattedTextBox extends React.Component<(FieldViewProps & Formatte
// stop propagation doesn't seem to stop propagation of native keyboard events.
// so we set a flag on the native event that marks that the event's been handled.
(e.nativeEvent as any).DASHFormattedTextBoxHandled = true;
+ if (StrCast(this.props.Document.title).startsWith("-") && this._editorView) {
+ let str = this._editorView.state.doc.textContent;
+ let titlestr = str.substr(0, Math.min(40, str.length));
+ let target = this.props.Document.proto ? this.props.Document.proto : this.props.Document;
+ target.title = "-" + titlestr + (str.length > 40 ? "..." : "");
+ }
}
render() {
- let style = this.props.isOverlay ? "-scroll" : "-hidden";
- let rounded = this.props.Document.GetNumber(KeyStore.BorderRounding, 0) < 0 ? "-rounded" : "";
- let color = this.props.Document.GetText(KeyStore.BackgroundColor, "");
- let interactive = InkingControl.Instance.selectedTool ? "" : "-interactive";
+ let style = this.props.isOverlay ? "scroll" : "hidden";
+ let rounded = NumCast(this.props.Document.borderRounding) < 0 ? "-rounded" : "";
+ let color = StrCast(this.props.Document.backgroundColor);
+ let interactive = InkingControl.Instance.selectedTool ? "" : "interactive";
return (
- <div className={`formattedTextBox-cont${style}`} ref={this._ref}
+ <div className={`formattedTextBox-cont-${style}`} ref={this._ref}
style={{
pointerEvents: interactive ? "all" : "none",
background: color,
@@ -287,11 +305,12 @@ export class FormattedTextBox extends React.Component<(FieldViewProps & Formatte
onClick={this.onClick}
onPointerUp={this.onPointerUp}
onPointerDown={this.onPointerDown}
+ onMouseDown={this.onMouseDown}
onContextMenu={this.specificContextMenu}
// tfs: do we need this event handler
onWheel={this.onPointerWheel}
>
- <div className={`formattedTextBox-inner${rounded}`} ref={this._proseRef} />
+ <div className={`formattedTextBox-inner${rounded}`} style={{ pointerEvents: this.props.Document.isButton ? "none" : "all" }} ref={this._proseRef} />
</div>
);
}
diff --git a/src/client/views/nodes/IconBox.scss b/src/client/views/nodes/IconBox.scss
index ce0ee2e09..85bbdeb59 100644
--- a/src/client/views/nodes/IconBox.scss
+++ b/src/client/views/nodes/IconBox.scss
@@ -4,9 +4,19 @@
position: absolute;
left:0;
top:0;
+ height: 100%;
+ width: max-content;
+ // overflow: hidden;
+ pointer-events: all;
svg {
- width: 100% !important;
+ width: $MINIMIZED_ICON_SIZE !important;
height: 100%;
background: white;
}
+ .iconBox-label {
+ position: inherit;
+ width:max-content;
+ font-size: 14px;
+ margin-top: 3px;
+ }
} \ No newline at end of file
diff --git a/src/client/views/nodes/IconBox.tsx b/src/client/views/nodes/IconBox.tsx
index 9c90c0a0e..3fab10df4 100644
--- a/src/client/views/nodes/IconBox.tsx
+++ b/src/client/views/nodes/IconBox.tsx
@@ -2,14 +2,18 @@ import React = require("react");
import { library } from '@fortawesome/fontawesome-svg-core';
import { faCaretUp, faFilePdf, faFilm, faImage, faObjectGroup, faStickyNote } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import { action, computed } from "mobx";
+import { action, computed, observable, runInAction } from "mobx";
import { observer } from "mobx-react";
-import { Document } from '../../../fields/Document';
-import { IconField } from "../../../fields/IconFIeld";
-import { KeyStore } from "../../../fields/KeyStore";
import { SelectionManager } from "../../util/SelectionManager";
import { FieldView, FieldViewProps } from './FieldView';
import "./IconBox.scss";
+import { Cast, StrCast, BoolCast } from "../../../new_fields/Types";
+import { Doc, WidthSym, HeightSym } from "../../../new_fields/Doc";
+import { IconField } from "../../../new_fields/IconField";
+import { ContextMenu } from "../ContextMenu";
+import Measure from "react-measure";
+import { MINIMIZED_ICON_SIZE } from "../../views/globalCssVariables.scss";
+import { listSpec } from "../../../new_fields/Schema";
library.add(faCaretUp);
@@ -22,8 +26,7 @@ library.add(faFilm);
export class IconBox extends React.Component<FieldViewProps> {
public static LayoutString() { return FieldView.LayoutString(IconBox); }
- @computed get maximized() { return this.props.Document.GetT(KeyStore.MaximizedDoc, Document); }
- @computed get layout(): string { return this.props.Document.GetData(this.props.fieldKey, IconField, "<p>Error loading layout data</p>" as string); }
+ @computed get layout(): string { const field = Cast(this.props.Document[this.props.fieldKey], IconField); return field ? field.icon : "<p>Error loading icon data</p>"; }
@computed get minimizedIcon() { return IconBox.DocumentIcon(this.layout); }
public static DocumentIcon(layout: string) {
@@ -33,13 +36,34 @@ export class IconBox extends React.Component<FieldViewProps> {
layout.indexOf("Video") !== -1 ? faFilm :
layout.indexOf("Collection") !== -1 ? faObjectGroup :
faCaretUp;
- return <FontAwesomeIcon icon={button} className="documentView-minimizedIcon" />
+ return <FontAwesomeIcon icon={button} className="documentView-minimizedIcon" />;
}
+ setLabelField = (e: React.MouseEvent): void => {
+ this.props.Document.hideLabel = !BoolCast(this.props.Document.hideLabel);
+ }
+
+ specificContextMenu = (e: React.MouseEvent): void => {
+ ContextMenu.Instance.addItem({
+ description: BoolCast(this.props.Document.hideLabel) ? "show label" : "hide label",
+ event: this.setLabelField
+ });
+ }
+ @observable _panelWidth: number = 0;
+ @observable _panelHeight: number = 0;
render() {
+ let labelField = StrCast(this.props.Document.labelField);
+ let hideLabel = BoolCast(this.props.Document.hideLabel);
+ let maxDoc = Cast(this.props.Document.maximizedDocs, listSpec(Doc), []);
+ let label = !hideLabel && maxDoc && labelField ? (maxDoc.length === 1 ? maxDoc[0][labelField] : this.props.Document[labelField]) : "";
return (
- <div className="iconBox-container">
+ <div className="iconBox-container" onContextMenu={this.specificContextMenu}>
{this.minimizedIcon}
+ <Measure onResize={(r) => runInAction(() => { if (r.entry.width || BoolCast(this.props.Document.hideLabel)) this.props.Document.nativeWidth = this.props.Document.width = (r.entry.width + Number(MINIMIZED_ICON_SIZE)); })}>
+ {({ measureRef }) =>
+ <span ref={measureRef} className="iconBox-label">{label}</span>
+ }
+ </Measure>
</div>);
}
} \ No newline at end of file
diff --git a/src/client/views/nodes/ImageBox.scss b/src/client/views/nodes/ImageBox.scss
index 9fe211df0..2316a050e 100644
--- a/src/client/views/nodes/ImageBox.scss
+++ b/src/client/views/nodes/ImageBox.scss
@@ -10,6 +10,8 @@
}
.imageBox-cont-interactive {
pointer-events: all;
+ width:100%;
+ height:auto;
}
.imageBox-dot {
diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx
index 2cbb0fa90..0e9e904a8 100644
--- a/src/client/views/nodes/ImageBox.tsx
+++ b/src/client/views/nodes/ImageBox.tsx
@@ -3,11 +3,6 @@ import { action, observable } from 'mobx';
import { observer } from "mobx-react";
import Lightbox from 'react-image-lightbox';
import 'react-image-lightbox/style.css'; // This only needs to be imported once in your app
-import { Document } from '../../../fields/Document';
-import { FieldWaiting } from '../../../fields/Field';
-import { ImageField } from '../../../fields/ImageField';
-import { KeyStore } from '../../../fields/KeyStore';
-import { ListField } from '../../../fields/ListField';
import { Utils } from '../../../Utils';
import { DragManager } from '../../util/DragManager';
import { undoBatch } from '../../util/UndoManager';
@@ -15,14 +10,27 @@ import { ContextMenu } from "../../views/ContextMenu";
import { FieldView, FieldViewProps } from './FieldView';
import "./ImageBox.scss";
import React = require("react");
+import { createSchema, makeInterface, listSpec } from '../../../new_fields/Schema';
+import { DocComponent } from '../DocComponent';
+import { positionSchema } from './DocumentView';
+import { FieldValue, Cast, StrCast } from '../../../new_fields/Types';
+import { ImageField } from '../../../new_fields/URLField';
+import { List } from '../../../new_fields/List';
import { InkingControl } from '../InkingControl';
-import { NumberField } from '../../../fields/NumberField';
+import { Doc } from '../../../new_fields/Doc';
+
+export const pageSchema = createSchema({
+ curPage: "number"
+});
+
+type ImageDocument = makeInterface<[typeof pageSchema, typeof positionSchema]>;
+const ImageDocument = makeInterface(pageSchema, positionSchema);
@observer
-export class ImageBox extends React.Component<FieldViewProps> {
+export class ImageBox extends DocComponent<FieldViewProps, ImageDocument>(ImageDocument) {
public static LayoutString() { return FieldView.LayoutString(ImageBox); }
- private _imgRef: React.RefObject<HTMLImageElement>;
+ private _imgRef: React.RefObject<HTMLImageElement> = React.createRef();
private _downX: number = 0;
private _downY: number = 0;
private _lastTap: number = 0;
@@ -30,20 +38,13 @@ export class ImageBox extends React.Component<FieldViewProps> {
@observable private _isOpen: boolean = false;
private dropDisposer?: DragManager.DragDropDisposer;
- constructor(props: FieldViewProps) {
- super(props);
-
- this._imgRef = React.createRef();
- }
-
@action
onLoad = (target: any) => {
var h = this._imgRef.current!.naturalHeight;
var w = this._imgRef.current!.naturalWidth;
if (this._photoIndex === 0) {
- this.props.Document.SetNumber(KeyStore.NativeHeight, this.props.Document.GetNumber(KeyStore.NativeWidth, 0) * h / w);
- this.props.Document.GetTAsync(KeyStore.Width, NumberField, field =>
- field && this.props.Document.SetNumber(KeyStore.Height, field.Data * h / w));
+ this.Document.nativeHeight = FieldValue(this.Document.nativeWidth, 0) * h / w;
+ this.Document.height = FieldValue(this.Document.width, 0) * h / w;
}
}
@@ -66,19 +67,18 @@ export class ImageBox extends React.Component<FieldViewProps> {
@undoBatch
drop = (e: Event, de: DragManager.DropEvent) => {
if (de.data instanceof DragManager.DocumentDragData) {
- de.data.droppedDocuments.map(action((drop: Document) => {
- let layout = drop.GetText(KeyStore.BackgroundLayout, "");
+ de.data.droppedDocuments.forEach(action((drop: Doc) => {
+ let layout = StrCast(drop.backgroundLayout);
if (layout.indexOf(ImageBox.name) !== -1) {
- let imgData = this.props.Document.Get(KeyStore.Data);
- if (imgData instanceof ImageField && imgData) {
- this.props.Document.SetOnPrototype(KeyStore.Data, new ListField([imgData]));
+ let imgData = this.props.Document[this.props.fieldKey];
+ if (imgData instanceof ImageField) {
+ Doc.SetOnPrototype(this.props.Document, "data", new List([imgData]));
}
- let imgList = this.props.Document.GetList(KeyStore.Data, [] as any[]);
+ let imgList = Cast(this.props.Document[this.props.fieldKey], listSpec(ImageField), [] as any[]);
if (imgList) {
- let field = drop.Get(KeyStore.Data);
- if (field === FieldWaiting) { }
- else if (field instanceof ImageField) imgList.push(field);
- else if (field instanceof ListField) imgList.push(field.Data);
+ let field = drop.data;
+ if (field instanceof ImageField) imgList.push(field);
+ else if (field instanceof List) imgList.concat(field);
}
e.stopPropagation();
}
@@ -128,9 +128,9 @@ export class ImageBox extends React.Component<FieldViewProps> {
}
specificContextMenu = (e: React.MouseEvent): void => {
- let field = this.props.Document.GetT(this.props.fieldKey, ImageField);
- if (field && field !== FieldWaiting) {
- let url = field.Data.href;
+ let field = Cast(this.Document[this.props.fieldKey], ImageField);
+ if (field) {
+ let url = field.url.href;
ContextMenu.Instance.addItem({
description: "Copy path", event: () => {
Utils.CopyText(url);
@@ -142,27 +142,26 @@ export class ImageBox extends React.Component<FieldViewProps> {
@action
onDotDown(index: number) {
this._photoIndex = index;
- this.props.Document.SetNumber(KeyStore.CurPage, index);
+ this.Document.curPage = index;
}
dots(paths: string[]) {
- let nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 1);
+ let nativeWidth = FieldValue(this.Document.nativeWidth, 1);
let dist = Math.min(nativeWidth / paths.length, 40);
let left = (nativeWidth - paths.length * dist) / 2;
return paths.map((p, i) =>
<div className="imageBox-placer" key={i} >
- <div className="imageBox-dot" style={{ background: (i == this._photoIndex ? "black" : "gray"), transform: `translate(${i * dist + left}px, 0px)` }} onPointerDown={(e: React.PointerEvent) => { e.stopPropagation(); this.onDotDown(i); }} />
+ <div className="imageBox-dot" style={{ background: (i === this._photoIndex ? "black" : "gray"), transform: `translate(${i * dist + left}px, 0px)` }} onPointerDown={(e: React.PointerEvent) => { e.stopPropagation(); this.onDotDown(i); }} />
</div>
);
}
render() {
- let field = this.props.Document.Get(this.props.fieldKey);
+ let field = this.Document[this.props.fieldKey];
let paths: string[] = ["http://www.cs.brown.edu/~bcz/face.gif"];
- if (field === FieldWaiting) paths = ["https://image.flaticon.com/icons/svg/66/66163.svg"];
- else if (field instanceof ImageField) paths = [field.Data.href];
- else if (field instanceof ListField) paths = field.Data.filter(val => val as ImageField).map(p => (p as ImageField).Data.href);
- let nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 1);
+ if (field instanceof ImageField) paths = [field.url.href];
+ else if (field instanceof List) paths = field.filter(val => val instanceof ImageField).map(p => (p as ImageField).url.href);
+ let nativeWidth = FieldValue(this.Document.nativeWidth, 1);
let interactive = InkingControl.Instance.selectedTool ? "" : "-interactive";
return (
<div className={`imageBox-cont${interactive}`} onPointerDown={this.onPointerDown} onDrop={this.onDrop} ref={this.createDropTarget} onContextMenu={this.specificContextMenu}>
diff --git a/src/client/views/nodes/KeyValueBox.tsx b/src/client/views/nodes/KeyValueBox.tsx
index ddbec014b..876a3c173 100644
--- a/src/client/views/nodes/KeyValueBox.tsx
+++ b/src/client/views/nodes/KeyValueBox.tsx
@@ -2,24 +2,22 @@
import { action, computed, observable } from "mobx";
import { observer } from "mobx-react";
import 'react-image-lightbox/style.css'; // This only needs to be imported once in your app
-import { Document } from '../../../fields/Document';
-import { Field, FieldWaiting } from '../../../fields/Field';
-import { Key } from '../../../fields/Key';
-import { KeyStore } from '../../../fields/KeyStore';
-import { CompileScript, ToField } from "../../util/Scripting";
+import { CompileScript } from "../../util/Scripting";
import { FieldView, FieldViewProps } from './FieldView';
import "./KeyValueBox.scss";
import { KeyValuePair } from "./KeyValuePair";
import React = require("react");
+import { NumCast, Cast, FieldValue } from "../../../new_fields/Types";
+import { Doc, IsField } from "../../../new_fields/Doc";
@observer
export class KeyValueBox extends React.Component<FieldViewProps> {
private _mainCont = React.createRef<HTMLDivElement>();
- public static LayoutString(fieldStr: string = "DataKey") { return FieldView.LayoutString(KeyValueBox, fieldStr); }
+ public static LayoutString(fieldStr: string = "data") { return FieldView.LayoutString(KeyValueBox, fieldStr); }
@observable private _keyInput: string = "";
@observable private _valueInput: string = "";
- @computed get splitPercentage() { return this.props.Document.GetNumber(KeyStore.SchemaSplitPercentage, 50); }
+ @computed get splitPercentage() { return NumCast(this.props.Document.schemaSplitPercentage, 50); }
constructor(props: FieldViewProps) {
@@ -30,8 +28,8 @@ export class KeyValueBox extends React.Component<FieldViewProps> {
onEnterKey = (e: React.KeyboardEvent): void => {
if (e.key === 'Enter') {
if (this._keyInput && this._valueInput) {
- let doc = this.props.Document.GetT(KeyStore.Data, Document);
- if (!doc || doc === FieldWaiting) {
+ let doc = FieldValue(Cast(this.props.Document.data, Doc));
+ if (!doc) {
return;
}
let realDoc = doc;
@@ -43,13 +41,8 @@ export class KeyValueBox extends React.Component<FieldViewProps> {
let res = script.run();
if (!res.success) return;
const field = res.result;
- if (field instanceof Field) {
- realDoc.Set(new Key(this._keyInput), field);
- } else {
- let dataField = ToField(field);
- if (dataField) {
- realDoc.Set(new Key(this._keyInput), dataField);
- }
+ if (IsField(field)) {
+ realDoc[this._keyInput] = field;
}
this._keyInput = "";
this._valueInput = "";
@@ -67,16 +60,16 @@ export class KeyValueBox extends React.Component<FieldViewProps> {
}
createTable = () => {
- let doc = this.props.Document.GetT(KeyStore.Data, Document);
- if (!doc || doc === FieldWaiting) {
+ let doc = FieldValue(Cast(this.props.Document.data, Doc));
+ if (!doc) {
return <tr><td>Loading...</td></tr>;
}
let realDoc = doc;
let ids: { [key: string]: string } = {};
- let protos = doc.GetAllPrototypes();
+ let protos = Doc.GetAllPrototypes(doc);
for (const proto of protos) {
- proto._proxies.forEach((val: any, key: string) => {
+ Object.keys(proto).forEach(key => {
if (!(key in ids)) {
ids[key] = key;
}
@@ -86,7 +79,7 @@ export class KeyValueBox extends React.Component<FieldViewProps> {
let rows: JSX.Element[] = [];
let i = 0;
for (let key in ids) {
- rows.push(<KeyValuePair doc={realDoc} keyWidth={100 - this.splitPercentage} rowStyle={"keyValueBox-" + (i++ % 2 ? "oddRow" : "evenRow")} fieldId={key} key={key} />);
+ rows.push(<KeyValuePair doc={realDoc} keyWidth={100 - this.splitPercentage} rowStyle={"keyValueBox-" + (i++ % 2 ? "oddRow" : "evenRow")} key={key} keyName={key} />);
}
return rows;
}
@@ -116,7 +109,7 @@ export class KeyValueBox extends React.Component<FieldViewProps> {
@action
onDividerMove = (e: PointerEvent): void => {
let nativeWidth = this._mainCont.current!.getBoundingClientRect();
- this.props.Document.SetNumber(KeyStore.SchemaSplitPercentage, Math.max(0, 100 - Math.round((e.clientX - nativeWidth.left) / nativeWidth.width * 100)));
+ this.props.Document.schemaSplitPercentage = Math.max(0, 100 - Math.round((e.clientX - nativeWidth.left) / nativeWidth.width * 100));
}
@action
onDividerUp = (e: PointerEvent): void => {
diff --git a/src/client/views/nodes/KeyValuePair.tsx b/src/client/views/nodes/KeyValuePair.tsx
index d480eb5af..235792cbe 100644
--- a/src/client/views/nodes/KeyValuePair.tsx
+++ b/src/client/views/nodes/KeyValuePair.tsx
@@ -1,48 +1,33 @@
import { action, observable } from 'mobx';
import { observer } from "mobx-react";
import 'react-image-lightbox/style.css'; // This only needs to be imported once in your app
-import { Document } from '../../../fields/Document';
-import { Field, Opt } from '../../../fields/Field';
-import { Key } from '../../../fields/Key';
-import { emptyDocFunction, emptyFunction, returnFalse } from '../../../Utils';
-import { Server } from "../../Server";
-import { CompileScript, ToField } from "../../util/Scripting";
+import { emptyFunction, returnFalse, returnZero } from '../../../Utils';
+import { CompileScript } from "../../util/Scripting";
import { Transform } from '../../util/Transform';
import { EditableView } from "../EditableView";
import { FieldView, FieldViewProps } from './FieldView';
import "./KeyValueBox.scss";
import "./KeyValuePair.scss";
import React = require("react");
+import { Doc, Opt, IsField } from '../../../new_fields/Doc';
+import { FieldValue } from '../../../new_fields/Types';
// Represents one row in a key value plane
export interface KeyValuePairProps {
rowStyle: string;
- fieldId: string;
- doc: Document;
+ keyName: string;
+ doc: Doc;
keyWidth: number;
}
@observer
export class KeyValuePair extends React.Component<KeyValuePairProps> {
- @observable private key: Opt<Key>;
-
- constructor(props: KeyValuePairProps) {
- super(props);
- Server.GetField(this.props.fieldId,
- action((field: Opt<Field>) => field instanceof Key && (this.key = field)));
-
- }
-
-
render() {
- if (!this.key) {
- return <tr><td>error</td><td /></tr>;
- }
let props: FieldViewProps = {
Document: this.props.doc,
ContainingCollectionView: undefined,
- fieldKey: this.key,
+ fieldKey: this.props.keyName,
isSelected: returnFalse,
select: emptyFunction,
isTopMost: false,
@@ -50,7 +35,9 @@ export class KeyValuePair extends React.Component<KeyValuePairProps> {
active: returnFalse,
whenActiveChanged: emptyFunction,
ScreenToLocalTransform: Transform.Identity,
- focus: emptyDocFunction,
+ focus: emptyFunction,
+ PanelWidth: returnZero,
+ PanelHeight: returnZero,
};
let contents = <FieldView {...props} />;
return (
@@ -58,21 +45,23 @@ export class KeyValuePair extends React.Component<KeyValuePairProps> {
<td className="keyValuePair-td-key" style={{ width: `${this.props.keyWidth}%` }}>
<div className="keyValuePair-td-key-container">
<button className="keyValuePair-td-key-delete" onClick={() => {
- let field = props.Document.Get(props.fieldKey);
- field && field instanceof Field && props.Document.Set(props.fieldKey, undefined);
+ let field = FieldValue(props.Document[props.fieldKey]);
+ field && (props.Document[props.fieldKey] = undefined);
}}>
X
</button>
- <div className="keyValuePair-keyField">{this.key.Name}</div>
+ <div className="keyValuePair-keyField">{this.props.keyName}</div>
</div>
</td>
<td className="keyValuePair-td-value" style={{ width: `${100 - this.props.keyWidth}%` }}>
<EditableView contents={contents} height={36} GetValue={() => {
- let field = props.Document.Get(props.fieldKey);
- if (field && field instanceof Field) {
- return field.ToScriptString();
+ let field = FieldValue(props.Document[props.fieldKey]);
+ if (field) {
+ //TODO Types
+ return String(field);
+ // return field.ToScriptString();
}
- return field || "";
+ return "";
}}
SetValue={(value: string) => {
let script = CompileScript(value, { addReturn: true });
@@ -82,15 +71,9 @@ export class KeyValuePair extends React.Component<KeyValuePairProps> {
let res = script.run();
if (!res.success) return false;
const field = res.result;
- if (field instanceof Field) {
- props.Document.Set(props.fieldKey, field);
+ if (IsField(field)) {
+ props.Document[props.fieldKey] = field;
return true;
- } else {
- let dataField = ToField(field);
- if (dataField) {
- props.Document.Set(props.fieldKey, dataField);
- return true;
- }
}
return false;
}}>
diff --git a/src/client/views/nodes/LinkBox.tsx b/src/client/views/nodes/LinkBox.tsx
index 8f979fdd7..08cfa590b 100644
--- a/src/client/views/nodes/LinkBox.tsx
+++ b/src/client/views/nodes/LinkBox.tsx
@@ -2,16 +2,15 @@ import { library } from '@fortawesome/fontawesome-svg-core';
import { faEdit, faEye, faTimes } from '@fortawesome/free-solid-svg-icons';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { observer } from "mobx-react";
-import { Document } from "../../../fields/Document";
-import { KeyStore } from '../../../fields/KeyStore';
-import { ListField } from "../../../fields/ListField";
-import { NumberField } from "../../../fields/NumberField";
import { DocumentManager } from "../../util/DocumentManager";
import { undoBatch } from "../../util/UndoManager";
import { CollectionDockingView } from "../collections/CollectionDockingView";
import './LinkBox.scss';
import React = require("react");
-import { runInAction } from 'mobx';
+import { Doc } from '../../../new_fields/Doc';
+import { Cast, NumCast } from '../../../new_fields/Types';
+import { listSpec } from '../../../new_fields/Schema';
+import { action } from 'mobx';
library.add(faEye);
@@ -19,9 +18,9 @@ library.add(faEdit);
library.add(faTimes);
interface Props {
- linkDoc: Document;
+ linkDoc: Doc;
linkName: String;
- pairedDoc: Document;
+ pairedDoc: Doc;
type: String;
showEditor: () => void;
}
@@ -30,65 +29,54 @@ interface Props {
export class LinkBox extends React.Component<Props> {
@undoBatch
- onViewButtonPressed = (e: React.PointerEvent): void => {
+ onViewButtonPressed = async (e: React.PointerEvent): Promise<void> => {
e.stopPropagation();
let docView = DocumentManager.Instance.getDocumentView(this.props.pairedDoc);
if (docView) {
docView.props.focus(docView.props.Document);
} else {
- this.props.pairedDoc.GetAsync(KeyStore.AnnotationOn, (contextDoc: any) => {
- if (!contextDoc) {
- CollectionDockingView.Instance.AddRightSplit(this.props.pairedDoc.MakeDelegate());
- } else if (contextDoc instanceof Document) {
- this.props.pairedDoc.GetTAsync(KeyStore.Page, NumberField).then((pfield: any) => {
- contextDoc.GetTAsync(KeyStore.CurPage, NumberField).then((cfield: any) => {
- if (pfield !== cfield) {
- contextDoc.SetNumber(KeyStore.CurPage, pfield.Data);
- }
- let contextView = DocumentManager.Instance.getDocumentView(contextDoc);
- if (contextView) {
- contextDoc.SetText(KeyStore.PanTransformType, "Ease");
- contextView.props.focus(contextDoc);
- } else {
- CollectionDockingView.Instance.AddRightSplit(contextDoc);
- }
- });
- });
+ const contextDoc = await Cast(this.props.pairedDoc.annotationOn, Doc);
+ if (!contextDoc) {
+ CollectionDockingView.Instance.AddRightSplit(Doc.MakeDelegate(this.props.pairedDoc));
+ } else {
+ const page = NumCast(this.props.pairedDoc.page, undefined);
+ const curPage = NumCast(contextDoc.curPage, undefined);
+ if (page !== curPage) {
+ contextDoc.curPage = page;
}
- });
+ let contextView = DocumentManager.Instance.getDocumentView(contextDoc);
+ if (contextView) {
+ contextDoc.panTransformType = "Ease";
+ contextView.props.focus(contextDoc);
+ } else {
+ CollectionDockingView.Instance.AddRightSplit(contextDoc);
+ }
+ }
}
}
onEditButtonPressed = (e: React.PointerEvent): void => {
- console.log("edit down");
e.stopPropagation();
this.props.showEditor();
}
- onDeleteButtonPressed = (e: React.PointerEvent): void => {
- console.log("delete down");
+ @action
+ onDeleteButtonPressed = async (e: React.PointerEvent): Promise<void> => {
e.stopPropagation();
- this.props.linkDoc.GetTAsync(KeyStore.LinkedFromDocs, Document, field => {
- if (field) {
- field.GetTAsync<ListField<Document>>(KeyStore.LinkedToDocs, ListField, field =>
- runInAction(() => {
- if (field) {
- field.Data.splice(field.Data.indexOf(this.props.linkDoc));
- }
- }));
+ const [linkedFrom, linkedTo] = await Promise.all([Cast(this.props.linkDoc.linkedFrom, Doc), Cast(this.props.linkDoc.linkedTo, Doc)]);
+ if (linkedFrom) {
+ const linkedToDocs = Cast(linkedFrom.linkedToDocs, listSpec(Doc));
+ if (linkedToDocs) {
+ linkedToDocs.splice(linkedToDocs.indexOf(this.props.linkDoc), 1);
}
- });
- this.props.linkDoc.GetTAsync(KeyStore.LinkedToDocs, Document, field => {
- if (field) {
- field.GetTAsync<ListField<Document>>(KeyStore.LinkedFromDocs, ListField, field =>
- runInAction(() => {
- if (field) {
- field.Data.splice(field.Data.indexOf(this.props.linkDoc));
- }
- }));
+ }
+ if (linkedTo) {
+ const linkedFromDocs = Cast(linkedTo.linkedFromDocs, listSpec(Doc));
+ if (linkedFromDocs) {
+ linkedFromDocs.splice(linkedFromDocs.indexOf(this.props.linkDoc), 1);
}
- });
+ }
}
render() {
diff --git a/src/client/views/nodes/LinkEditor.tsx b/src/client/views/nodes/LinkEditor.tsx
index bde50fed8..f82c6e9cb 100644
--- a/src/client/views/nodes/LinkEditor.tsx
+++ b/src/client/views/nodes/LinkEditor.tsx
@@ -3,31 +3,29 @@ import React = require("react");
import { SelectionManager } from "../../util/SelectionManager";
import { observer } from "mobx-react";
import './LinkEditor.scss';
-import { KeyStore } from '../../../fields/KeyStore';
import { props } from "bluebird";
import { DocumentView } from "./DocumentView";
-import { Document } from "../../../fields/Document";
-import { TextField } from "../../../fields/TextField";
import { link } from "fs";
+import { StrCast } from "../../../new_fields/Types";
+import { Doc } from "../../../new_fields/Doc";
interface Props {
- linkDoc: Document;
+ linkDoc: Doc;
showLinks: () => void;
}
@observer
export class LinkEditor extends React.Component<Props> {
- @observable private _nameInput: string = this.props.linkDoc.GetText(KeyStore.Title, "");
- @observable private _descriptionInput: string = this.props.linkDoc.GetText(KeyStore.LinkDescription, "");
+ @observable private _nameInput: string = StrCast(this.props.linkDoc.title);
+ @observable private _descriptionInput: string = StrCast(this.props.linkDoc.linkDescription);
onSaveButtonPressed = (e: React.PointerEvent): void => {
- console.log("view down");
e.stopPropagation();
- this.props.linkDoc.SetData(KeyStore.Title, this._nameInput, TextField);
- this.props.linkDoc.SetData(KeyStore.LinkDescription, this._descriptionInput, TextField);
+ this.props.linkDoc.title = this._nameInput;
+ this.props.linkDoc.linkDescription = this._descriptionInput;
this.props.showLinks();
}
diff --git a/src/client/views/nodes/LinkMenu.tsx b/src/client/views/nodes/LinkMenu.tsx
index ac09da305..e21adebbc 100644
--- a/src/client/views/nodes/LinkMenu.tsx
+++ b/src/client/views/nodes/LinkMenu.tsx
@@ -1,15 +1,14 @@
import { action, observable } from "mobx";
import { observer } from "mobx-react";
-import { Document } from "../../../fields/Document";
-import { FieldWaiting } from "../../../fields/Field";
-import { Key } from "../../../fields/Key";
-import { KeyStore } from '../../../fields/KeyStore';
-import { ListField } from "../../../fields/ListField";
import { DocumentView } from "./DocumentView";
import { LinkBox } from "./LinkBox";
import { LinkEditor } from "./LinkEditor";
import './LinkMenu.scss';
import React = require("react");
+import { Doc } from "../../../new_fields/Doc";
+import { Cast, FieldValue } from "../../../new_fields/Types";
+import { listSpec } from "../../../new_fields/Schema";
+import { Id } from "../../../new_fields/RefField";
interface Props {
docView: DocumentView;
@@ -19,28 +18,28 @@ interface Props {
@observer
export class LinkMenu extends React.Component<Props> {
- @observable private _editingLink?: Document;
+ @observable private _editingLink?: Doc;
- renderLinkItems(links: Document[], key: Key, type: string) {
+ renderLinkItems(links: Doc[], key: string, type: string) {
return links.map(link => {
- let doc = link.GetT(key, Document);
- if (doc && doc !== FieldWaiting) {
- return <LinkBox key={doc.Id} linkDoc={link} linkName={link.Title} pairedDoc={doc} showEditor={action(() => this._editingLink = link)} type={type} />;
+ let doc = FieldValue(Cast(link[key], Doc));
+ if (doc) {
+ return <LinkBox key={doc[Id]} linkDoc={link} linkName={Cast(link.title, "string", "")} pairedDoc={doc} showEditor={action(() => this._editingLink = link)} type={type} />;
}
});
}
render() {
//get list of links from document
- let linkFrom: Document[] = this.props.docView.props.Document.GetData(KeyStore.LinkedFromDocs, ListField, []);
- let linkTo: Document[] = this.props.docView.props.Document.GetData(KeyStore.LinkedToDocs, ListField, []);
+ let linkFrom: Doc[] = Cast(this.props.docView.props.Document.linkedFromDocs, listSpec(Doc), []);
+ let linkTo: Doc[] = Cast(this.props.docView.props.Document.linkedToDocs, listSpec(Doc), []);
if (this._editingLink === undefined) {
return (
<div id="linkMenu-container">
<input id="linkMenu-searchBar" type="text" placeholder="Search..."></input>
<div id="linkMenu-list">
- {this.renderLinkItems(linkTo, KeyStore.LinkedToDocs, "Destination: ")}
- {this.renderLinkItems(linkFrom, KeyStore.LinkedFromDocs, "Source: ")}
+ {this.renderLinkItems(linkTo, "linkedTo", "Destination: ")}
+ {this.renderLinkItems(linkFrom, "linkedFrom", "Source: ")}
</div>
</div>
);
diff --git a/src/client/views/nodes/PDFBox.tsx b/src/client/views/nodes/PDFBox.tsx
index 226dfba11..eb45ea273 100644
--- a/src/client/views/nodes/PDFBox.tsx
+++ b/src/client/views/nodes/PDFBox.tsx
@@ -6,10 +6,6 @@ import Measure from "react-measure";
//@ts-ignore
import { Document, Page } from "react-pdf";
import 'react-pdf/dist/Page/AnnotationLayer.css';
-import { FieldWaiting, Opt } from '../../../fields/Field';
-import { ImageField } from '../../../fields/ImageField';
-import { KeyStore } from '../../../fields/KeyStore';
-import { PDFField } from '../../../fields/PDFField';
import { RouteStore } from "../../../server/RouteStore";
import { Utils } from '../../../Utils';
import { Annotation } from './Annotation';
@@ -17,6 +13,13 @@ import { FieldView, FieldViewProps } from './FieldView';
import "./PDFBox.scss";
import React = require("react");
import { SelectionManager } from "../../util/SelectionManager";
+import { Cast, FieldValue, NumCast } from "../../../new_fields/Types";
+import { Opt } from "../../../new_fields/Doc";
+import { DocComponent } from "../DocComponent";
+import { makeInterface } from "../../../new_fields/Schema";
+import { positionSchema } from "./DocumentView";
+import { pageSchema } from "./ImageBox";
+import { ImageField, PdfField } from "../../../new_fields/URLField";
import { InkingControl } from "../InkingControl";
/** ALSO LOOK AT: Annotation.tsx, Sticky.tsx
@@ -41,8 +44,12 @@ import { InkingControl } from "../InkingControl";
*
* written by: Andrew Kim
*/
+
+type PdfDocument = makeInterface<[typeof positionSchema, typeof pageSchema]>;
+const PdfDocument = makeInterface(positionSchema, pageSchema);
+
@observer
-export class PDFBox extends React.Component<FieldViewProps> {
+export class PDFBox extends DocComponent<FieldViewProps, PdfDocument>(PdfDocument) {
public static LayoutString() { return FieldView.LayoutString(PDFBox); }
private _mainDiv = React.createRef<HTMLDivElement>();
@@ -58,8 +65,8 @@ export class PDFBox extends React.Component<FieldViewProps> {
@observable private _interactive: boolean = false;
@observable private _loaded: boolean = false;
- @computed private get curPage() { return this.props.Document.GetNumber(KeyStore.CurPage, 1); }
- @computed private get thumbnailPage() { return this.props.Document.GetNumber(KeyStore.ThumbnailPage, -1); }
+ @computed private get curPage() { return FieldValue(this.Document.curPage, 1); }
+ @computed private get thumbnailPage() { return Cast(this.props.Document.thumbnailPage, "number", -1); }
componentDidMount() {
this._reactionDisposer = reaction(
@@ -240,14 +247,13 @@ export class PDFBox extends React.Component<FieldViewProps> {
saveThumbnail = () => {
this._renderAsSvg = false;
setTimeout(() => {
- var me = this;
- let nwidth = me.props.Document.GetNumber(KeyStore.NativeWidth, 0);
- let nheight = me.props.Document.GetNumber(KeyStore.NativeHeight, 0);
+ let nwidth = FieldValue(this.Document.nativeWidth, 0);
+ let nheight = FieldValue(this.Document.nativeHeight, 0);
htmlToImage.toPng(this._mainDiv.current!, { width: nwidth, height: nheight, quality: 1 })
.then(action((dataUrl: string) => {
- me.props.Document.SetData(KeyStore.Thumbnail, new URL(dataUrl), ImageField);
- me.props.Document.SetNumber(KeyStore.ThumbnailPage, me.props.Document.GetNumber(KeyStore.CurPage, -1));
- me._renderAsSvg = true;
+ this.props.Document.thumbnail = new ImageField(new URL(dataUrl));
+ this.props.Document.thumbnailPage = FieldValue(this.Document.curPage, -1);
+ this._renderAsSvg = true;
}))
.catch(function (error: any) {
console.error('oops, something went wrong!', error);
@@ -258,7 +264,7 @@ export class PDFBox extends React.Component<FieldViewProps> {
@action
onLoaded = (page: any) => {
// bcz: the number of pages should really be set when the document is imported.
- this.props.Document.SetNumber(KeyStore.NumPages, page._transport.numPages);
+ this.props.Document.numPages = page._transport.numPages;
if (this._perPageInfo.length === 0) { //Makes sure it only runs once
this._perPageInfo = [...Array(page._transport.numPages)];
}
@@ -270,11 +276,11 @@ export class PDFBox extends React.Component<FieldViewProps> {
// bcz: the nativeHeight should really be set when the document is imported.
// also, the native dimensions could be different for different pages of the canvas
// so this design is flawed.
- var nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 0);
- if (!this.props.Document.GetNumber(KeyStore.NativeHeight, 0)) {
+ var nativeWidth = FieldValue(this.Document.nativeWidth, 0);
+ if (!FieldValue(this.Document.nativeHeight, 0)) {
var nativeHeight = nativeWidth * r.entry.height / r.entry.width;
- this.props.Document.SetNumber(KeyStore.Height, nativeHeight / nativeWidth * this.props.Document.GetNumber(KeyStore.Width, 0));
- this.props.Document.SetNumber(KeyStore.NativeHeight, nativeHeight);
+ this.props.Document.height = nativeHeight / nativeWidth * FieldValue(this.Document.width, 0);
+ this.props.Document.nativeHeight = nativeHeight;
}
}
renderHeight = 2400;
@@ -284,9 +290,11 @@ export class PDFBox extends React.Component<FieldViewProps> {
}
@computed
get pdfContent() {
- let pdfUrl = this.props.Document.GetT(this.props.fieldKey, PDFField);
- let xf = this.props.Document.GetNumber(KeyStore.NativeHeight, 0) / this.renderHeight;
- let body = (this.props.Document.GetNumber(KeyStore.NativeHeight, 0)) ?
+ let page = this.curPage;
+ const renderHeight = 2400;
+ let pdfUrl = Cast(this.props.Document[this.props.fieldKey], PdfField);
+ let xf = FieldValue(this.Document.nativeHeight, 0) / renderHeight;
+ let body = NumCast(this.props.Document.nativeHeight) ?
this.pdfPage :
<Measure onResize={this.setScaling}>
{({ measureRef }) =>
@@ -305,8 +313,8 @@ export class PDFBox extends React.Component<FieldViewProps> {
@computed
get pdfRenderer() {
let proxy = this._loaded ? (null) : this.imageProxyRenderer;
- let pdfUrl = this.props.Document.GetT(this.props.fieldKey, PDFField);
- if ((!this._interactive && proxy) || !pdfUrl || pdfUrl === FieldWaiting) {
+ let pdfUrl = Cast(this.props.Document[this.props.fieldKey], PdfField);
+ if ((!this._interactive && proxy) || !pdfUrl) {
return proxy;
}
return [
@@ -319,10 +327,10 @@ export class PDFBox extends React.Component<FieldViewProps> {
@computed
get imageProxyRenderer() {
- let thumbField = this.props.Document.Get(KeyStore.Thumbnail);
+ let thumbField = this.props.Document.thumbnail;
if (thumbField) {
- let path = thumbField === FieldWaiting || this.thumbnailPage !== this.curPage ? "https://image.flaticon.com/icons/svg/66/66163.svg" :
- thumbField instanceof ImageField ? thumbField.Data.href : "http://cs.brown.edu/people/bcz/prairie.jpg";
+ let path = this.thumbnailPage !== this.curPage ? "https://image.flaticon.com/icons/svg/66/66163.svg" :
+ thumbField instanceof ImageField ? thumbField.url.href : "http://cs.brown.edu/people/bcz/prairie.jpg";
return <img src={path} width="100%" />;
}
return (null);
diff --git a/src/client/views/nodes/VideoBox.tsx b/src/client/views/nodes/VideoBox.tsx
index 3bb930ba7..422508f90 100644
--- a/src/client/views/nodes/VideoBox.tsx
+++ b/src/client/views/nodes/VideoBox.tsx
@@ -1,75 +1,80 @@
import React = require("react");
-import { action, computed, IReactionDisposer, trace } from "mobx";
import { observer } from "mobx-react";
-import Measure from "react-measure";
-import { FieldWaiting, Opt } from '../../../fields/Field';
-import { KeyStore } from "../../../fields/KeyStore";
-import { VideoField } from '../../../fields/VideoField';
import { FieldView, FieldViewProps } from './FieldView';
import "./VideoBox.scss";
+import { action, computed, trace } from "mobx";
+import { DocComponent } from "../DocComponent";
+import { positionSchema } from "./DocumentView";
+import { makeInterface } from "../../../new_fields/Schema";
+import { pageSchema } from "./ImageBox";
+import { Cast, FieldValue, NumCast, ToConstructor, ListSpec } from "../../../new_fields/Types";
+import { VideoField } from "../../../new_fields/URLField";
+import Measure from "react-measure";
+import "./VideoBox.scss";
+import { Field, FieldResult, Opt } from "../../../new_fields/Doc";
+
+type VideoDocument = makeInterface<[typeof positionSchema, typeof pageSchema]>;
+const VideoDocument = makeInterface(positionSchema, pageSchema);
@observer
-export class VideoBox extends React.Component<FieldViewProps> {
+export class VideoBox extends DocComponent<FieldViewProps, VideoDocument>(VideoDocument) {
- private _videoRef = React.createRef<HTMLVideoElement>();
+ private _videoRef: HTMLVideoElement | null = null;
+ private _loaded: boolean = false;
+ private get initialTimecode() { return FieldValue(this.Document.curPage, -1); }
public static LayoutString() { return FieldView.LayoutString(VideoBox); }
- constructor(props: FieldViewProps) {
- super(props);
+ public get player(): HTMLVideoElement | undefined {
+ if (this._videoRef) {
+ return this._videoRef;
+ }
}
-
- @computed private get curPage() { return this.props.Document.GetNumber(KeyStore.CurPage, -1); }
-
-
- _loaded: boolean = false;
-
@action
setScaling = (r: any) => {
if (this._loaded) {
// bcz: the nativeHeight should really be set when the document is imported.
- // also, the native dimensions could be different for different pages of the PDF
- // so this design is flawed.
- var nativeWidth = this.props.Document.GetNumber(KeyStore.NativeWidth, 0);
- var nativeHeight = this.props.Document.GetNumber(KeyStore.NativeHeight, 0);
+ var nativeWidth = FieldValue(this.Document.nativeWidth, 0);
+ var nativeHeight = FieldValue(this.Document.nativeHeight, 0);
var newNativeHeight = nativeWidth * r.entry.height / r.entry.width;
if (!nativeHeight && newNativeHeight !== nativeHeight && !isNaN(newNativeHeight)) {
- this.props.Document.SetNumber(KeyStore.Height, newNativeHeight / nativeWidth * this.props.Document.GetNumber(KeyStore.Width, 0));
- this.props.Document.SetNumber(KeyStore.NativeHeight, newNativeHeight);
+ this.Document.height = newNativeHeight / nativeWidth * FieldValue(this.Document.width, 0);
+ this.Document.nativeHeight = newNativeHeight;
}
} else {
this._loaded = true;
}
}
- get player(): HTMLVideoElement | undefined {
- return this._videoRef.current ? this._videoRef.current.getElementsByTagName("video")[0] : undefined;
+ componentDidMount() {
+ if (this.props.setVideoBox) this.props.setVideoBox(this);
}
@action
setVideoRef = (vref: HTMLVideoElement | null) => {
- if (this.curPage >= 0 && vref) {
- vref.currentTime = this.curPage;
- (vref as any).AHackBecauseSomethingResetsTheVideoToZero = this.curPage;
+ this._videoRef = vref;
+ if (this.initialTimecode >= 0 && vref) {
+ vref.currentTime = this.initialTimecode;
}
}
videoContent(path: string) {
return <video className="videobox-cont" ref={this.setVideoRef}>
<source src={path} type="video/mp4" />
Not supported.
- </video>;
+ </video>;
}
render() {
- let field = this.props.Document.GetT(this.props.fieldKey, VideoField);
- if (!field || field === FieldWaiting) {
+ let field = Cast(this.Document[this.props.fieldKey], VideoField);
+ if (!field) {
return <div>Loading</div>;
}
- return (this.props.Document.GetNumber(KeyStore.NativeHeight, 0)) ?
- this.videoContent(field.Data.href) :
+ let content = this.videoContent(field.url.href);
+ return NumCast(this.props.Document.nativeHeight) ?
+ content :
<Measure onResize={this.setScaling}>
{({ measureRef }) =>
<div style={{ width: "100%", height: "auto" }} ref={measureRef}>
- {this.videoContent(field!.Data.href)}
+ {content}
</div>
}
</Measure>;
diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx
index a7c6fda8b..2239a8e38 100644
--- a/src/client/views/nodes/WebBox.tsx
+++ b/src/client/views/nodes/WebBox.tsx
@@ -1,11 +1,10 @@
import "./WebBox.scss";
import React = require("react");
-import { WebField } from '../../../fields/WebField';
import { FieldViewProps, FieldView } from './FieldView';
-import { FieldWaiting, Opt } from '../../../fields/Field';
+import { HtmlField } from "../../../new_fields/HtmlField";
+import { WebField } from "../../../new_fields/URLField";
import { observer } from "mobx-react";
import { computed, reaction, IReactionDisposer } from 'mobx';
-import { KeyStore } from '../../../fields/KeyStore';
import { DocumentDecorations } from "../DocumentDecorations";
import { InkingControl } from "../InkingControl";
@@ -14,8 +13,6 @@ export class WebBox extends React.Component<FieldViewProps> {
public static LayoutString() { return FieldView.LayoutString(WebBox); }
- @computed get html(): string { return this.props.Document.GetHtml(KeyStore.Data, ""); }
-
_ignore = 0;
onPreWheel = (e: React.WheelEvent) => {
this._ignore = e.timeStamp;
@@ -34,14 +31,18 @@ export class WebBox extends React.Component<FieldViewProps> {
}
}
render() {
- let field = this.props.Document.Get(this.props.fieldKey);
- let path = field === FieldWaiting ? "https://image.flaticon.com/icons/svg/66/66163.svg" :
- field instanceof WebField ? field.Data.href : "https://crossorigin.me/" + "https://cs.brown.edu";
-
+ let field = this.props.Document[this.props.fieldKey];
+ let view;
+ if (field instanceof HtmlField) {
+ view = <span id="webBox-htmlSpan" dangerouslySetInnerHTML={{ __html: field.html }} />;
+ } else if (field instanceof WebField) {
+ view = <iframe src={field.url.href} style={{ position: "absolute", width: "100%", height: "100%" }} />;
+ } else {
+ view = <iframe src={"https://crossorigin.me/https://cs.brown.edu"} style={{ position: "absolute", width: "100%", height: "100%" }} />;
+ }
let content =
<div style={{ width: "100%", height: "100%", position: "absolute" }} onWheel={this.onPostWheel} onPointerDown={this.onPostPointer} onPointerMove={this.onPostPointer} onPointerUp={this.onPostPointer}>
- {this.html ? <span id="webBox-htmlSpan" dangerouslySetInnerHTML={{ __html: this.html }} /> :
- <iframe src={path} style={{ position: "absolute", width: "100%", height: "100%" }} />}
+ {view}
</div>;
let frozen = !this.props.isSelected() || DocumentDecorations.Instance.Interacting;