From e678ac7f21e0c44eaa8ad88577093cdb313e21bb Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 19 Apr 2019 23:13:17 -0400 Subject: Deleted more old fields and split new stuff into multiple files --- src/new_fields/Doc.ts | 90 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 src/new_fields/Doc.ts (limited to 'src/new_fields/Doc.ts') diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts new file mode 100644 index 000000000..c67170573 --- /dev/null +++ b/src/new_fields/Doc.ts @@ -0,0 +1,90 @@ +import { observable, action } from "mobx"; +import { serializable, primitive, map, alias, list } from "serializr"; +import { autoObject, SerializationHelper, Deserializable } from "../client/util/SerializationHelper"; +import { Utils } from "../Utils"; +import { DocServer } from "../client/DocServer"; +import { setter, getter, getField } from "./util"; +import { Cast, FieldCtor } from "./Types"; + +export const HandleUpdate = Symbol("HandleUpdate"); +export const Id = Symbol("Id"); +export abstract class RefField { + @serializable(alias("id", primitive())) + private __id: string; + readonly [Id]: string; + + constructor(id?: string) { + this.__id = id || Utils.GenerateGuid(); + this[Id] = this.__id; + } + + protected [HandleUpdate]?(diff: any): void; +} + +export const Update = Symbol("Update"); +export const OnUpdate = Symbol("OnUpdate"); +export const Parent = Symbol("Parent"); +export class ObjectField { + protected [OnUpdate]?: (diff?: any) => void; + private [Parent]?: Doc; +} + +export type Field = number | string | boolean | ObjectField | RefField; +export type Opt = T | undefined; +export type FieldWaiting = null; +export const FieldWaiting: FieldWaiting = null; + +export const Self = Symbol("Self"); + +@Deserializable("doc").withFields(["id"]) +export class Doc extends RefField { + constructor(id?: string, forceSave?: boolean) { + super(id); + const doc = new Proxy(this, { + set: setter, + get: getter, + deleteProperty: () => { throw new Error("Currently properties can't be deleted from documents, assign to undefined instead"); }, + defineProperty: () => { throw new Error("Currently properties can't be defined on documents using Object.defineProperty"); }, + }); + if (!id || forceSave) { + DocServer.CreateField(SerializationHelper.Serialize(doc)); + } + return doc; + } + + [key: string]: Field | null | undefined; + + @serializable(alias("fields", map(autoObject()))) + @observable + private __fields: { [key: string]: Field | null | undefined } = {}; + + private [Update] = (diff: any) => { + DocServer.UpdateField(this[Id], diff); + } + + private [Self] = this; +} + +export namespace Doc { + export function GetAsync(doc: Doc, key: string, ignoreProto: boolean = false): Promise { + const self = doc[Self]; + return new Promise(res => getField(self, key, ignoreProto, res)); + } + export function GetTAsync(doc: Doc, key: string, ctor: FieldCtor, ignoreProto: boolean = false): Promise { + const self = doc[Self]; + return new Promise(async res => { + const field = await GetAsync(doc, key, ignoreProto); + return Cast(field, ctor); + }); + } + export function Get(doc: Doc, key: string, ignoreProto: boolean = false): Field | null | undefined { + const self = doc[Self]; + return getField(self, key, ignoreProto); + } + export function GetT(doc: Doc, key: string, ctor: FieldCtor, ignoreProto: boolean = false): Field | null | undefined { + return Cast(Get(doc, key, ignoreProto), ctor); + } + export const Prototype = Symbol("Prototype"); +} + +export const GetAsync = Doc.GetAsync; \ No newline at end of file -- cgit v1.2.3-70-g09d2 From e3ad2c2c8f920a5538541b8e495af52815e36dc6 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Fri, 19 Apr 2019 23:52:34 -0400 Subject: Started fixing stuff --- src/client/views/DocComponent.tsx | 14 ++++++ src/client/views/nodes/DocumentView.tsx | 87 ++++++++++----------------------- src/new_fields/Doc.ts | 8 +++ src/new_fields/Schema.ts | 7 +-- src/new_fields/Types.ts | 2 +- 5 files changed, 54 insertions(+), 64 deletions(-) create mode 100644 src/client/views/DocComponent.tsx (limited to 'src/new_fields/Doc.ts') diff --git a/src/client/views/DocComponent.tsx b/src/client/views/DocComponent.tsx new file mode 100644 index 000000000..31282744b --- /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

(schemaCtor: (doc: Doc) => T) { + class Component extends React.Component

{ + //TODO This might be pretty inefficient if doc isn't observed, because computed doesn't cache then + @computed + get Document() { + return schemaCtor(this.props.Document); + } + } + return Component; +} \ No newline at end of file diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index b99e449be..4f7909692 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -1,12 +1,5 @@ import { action, computed, runInAction } from "mobx"; import { observer } from "mobx-react"; -import { BooleanField } from "../../../fields/BooleanField"; -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 { TextField } from "../../../fields/TextField"; import { ServerUtils } from "../../../server/ServerUtil"; import { emptyFunction, Utils } from "../../../Utils"; import { Documents } from "../../documents/Documents"; @@ -23,11 +16,15 @@ import { ContextMenu } from "../ContextMenu"; import { DocumentContentsView } from "./DocumentContentsView"; import "./DocumentView.scss"; import React = require("react"); +import { Field, Opt, Doc, Id } from "../../../new_fields/Doc"; +import { DocComponent } from "../DocComponent"; +import { createSchema, makeInterface } from "../../../new_fields/Schema"; +import { FieldValue } from "../../../new_fields/Types"; export interface DocumentViewProps { ContainingCollectionView: Opt; - Document: Document; + Document: Doc; addDocument?: (doc: Document, allowDuplicates?: boolean) => boolean; removeDocument?: (doc: Document) => boolean; moveDocument?: (doc: Document, targetCollection: Document, addDocument: (document: Document) => boolean) => boolean; @@ -41,48 +38,20 @@ export interface DocumentViewProps { parentActive: () => boolean; onActiveChanged: (isActive: boolean) => void; } -export interface JsxArgs extends DocumentViewProps { - Keys: { [name: string]: Key }; - Fields: { [name: string]: Field }; -} -/* -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( - , - { 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", + minimized: "boolean", + nativeWidth: "number", + nativeHeight: "number", + backgroundColor: "string" +}); + +type Document = makeInterface; +const Document = makeInterface(schema); @observer -export class DocumentView extends React.Component { +export class DocumentView extends DocComponent(Document) { private _downX: number = 0; private _downY: number = 0; private _mainCont = React.createRef(); @@ -91,9 +60,6 @@ export class DocumentView extends React.Component { 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, "

Error loading layout data

"); } - @computed get layoutKeys(): Key[] { return this.props.Document.GetData(KeyStore.LayoutKeys, ListField, new Array()); } - @computed get layoutFields(): Key[] { return this.props.Document.GetData(KeyStore.LayoutFields, ListField, new Array()); } onPointerDown = (e: React.PointerEvent): void => { this._downX = e.clientX; @@ -200,7 +166,7 @@ export class DocumentView extends React.Component { } } fullScreenClicked = (e: React.MouseEvent): void => { - CollectionDockingView.Instance.OpenFullScreen((this.props.Document.GetPrototype() as Document).MakeDelegate()); + CollectionDockingView.Instance.OpenFullScreen(Doc.MakeDelegate(this.Document.prototype)); ContextMenu.Instance.clearItems(); ContextMenu.Instance.addItem({ description: "Close Full Screen", event: this.closeFullScreenClicked }); ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); @@ -266,9 +232,9 @@ export class DocumentView extends React.Component { onDrop = (e: React.DragEvent) => { let text = e.dataTransfer.getData("text/plain"); if (!e.isDefaultPrevented() && text && text.startsWith(" { 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 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: "Delete", event: this.deleteClicked }); ContextMenu.Instance.displayMenu(e.pageX - 15, e.pageY - 15); - if (!SelectionManager.IsSelected(this)) + if (!SelectionManager.IsSelected(this)) { SelectionManager.SelectDoc(this, false); + } } @action - expand = () => this.props.Document.SetBoolean(KeyStore.Minimized, false) - isMinimized = () => this.props.Document.GetBoolean(KeyStore.Minimized, false); + expand = () => this.Document.minimized = false + isMinimized = () => FieldValue(this.Document.minimized) || 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 nativeWidth() { return FieldValue(this.Document.nativeWidth) || 0; } + @computed get nativeHeight() { return FieldValue(this.Document.nativeHeight) || 0; } @computed get contents() { return (); } render() { @@ -321,7 +288,7 @@ export class DocumentView extends React.Component {
(doc: Doc, key: string, ctor: FieldCtor, ignoreProto: boolean = false): Field | null | undefined { return Cast(Get(doc, key, ignoreProto), ctor); } + export function MakeDelegate(doc: Opt): Opt { + if (!doc) { + return undefined; + } + const delegate = new Doc(); + delegate.prototype = doc; + return delegate; + } export const Prototype = Symbol("Prototype"); } diff --git a/src/new_fields/Schema.ts b/src/new_fields/Schema.ts index c7d2f0801..27b9635af 100644 --- a/src/new_fields/Schema.ts +++ b/src/new_fields/Schema.ts @@ -1,4 +1,4 @@ -import { Interface, ToInterface, Cast } from "./Types"; +import { Interface, ToInterface, Cast, FieldCtor, ToConstructor } from "./Types"; import { Doc } from "./Doc"; export type makeInterface = Partial> & Doc; @@ -42,6 +42,7 @@ export function makeStrictInterface(schema: T): (doc: Doc) }; } -export function createSchema(schema: T): T { - return schema; +export function createSchema(schema: T): T & { prototype: ToConstructor } { + schema.prototype = Doc; + return schema as any; } diff --git a/src/new_fields/Types.ts b/src/new_fields/Types.ts index 416298a64..cafb208ce 100644 --- a/src/new_fields/Types.ts +++ b/src/new_fields/Types.ts @@ -53,6 +53,6 @@ export function Cast>(field: Field | null | undefined return undefined; } -export function FieldValue(field: Opt | Promise>): Opt { +export function FieldValue(field: Opt | Promise>): Opt { return field instanceof Promise ? undefined : field; } -- cgit v1.2.3-70-g09d2 From 1eb965a5d9c8aaebf1970bc645edecfb7017b601 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Sat, 20 Apr 2019 03:29:35 -0400 Subject: Made the switch in a couple more classes --- src/Utils.ts | 3 -- src/client/views/nodes/DocumentContentsView.tsx | 26 ++------------ src/client/views/nodes/DocumentView.tsx | 16 +++++++-- src/client/views/nodes/FieldView.tsx | 45 ++++++++++--------------- src/client/views/nodes/ImageBox.tsx | 41 +++++++++++++--------- src/debug/Test.tsx | 4 +-- src/new_fields/Doc.ts | 5 +-- src/new_fields/HtmlField.ts | 2 +- src/new_fields/Schema.ts | 24 +++++++++++-- src/new_fields/Types.ts | 19 +++++++---- 10 files changed, 98 insertions(+), 87 deletions(-) (limited to 'src/new_fields/Doc.ts') diff --git a/src/Utils.ts b/src/Utils.ts index 98f75d3b9..066d653f5 100644 --- a/src/Utils.ts +++ b/src/Utils.ts @@ -2,7 +2,6 @@ import v4 = require('uuid/v4'); import v5 = require("uuid/v5"); import { Socket } from 'socket.io'; import { Message } from './server/Message'; -import { Document } from './fields/Document'; export class Utils { @@ -108,6 +107,4 @@ export function returnZero() { return 0; } export function emptyFunction() { } -export function emptyDocFunction(doc: Document) { } - export type Without = Pick>; \ No newline at end of file diff --git a/src/client/views/nodes/DocumentContentsView.tsx b/src/client/views/nodes/DocumentContentsView.tsx index 07599c345..273401111 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"; @@ -22,46 +18,30 @@ import { VideoBox } from "./VideoBox"; 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 } from "../../../new_fields/Types"; const JsxParser = require('react-jsx-parser').default; //TODO Why does this need to be imported like this? type BindingProps = Without; export interface JsxBindings { props: BindingProps; - [keyName: string]: BindingProps | Field; } @observer export class DocumentContentsView extends React.Component boolean, select: (ctrl: boolean) => void, - layoutKey: Key + layoutKey: string }> { - @computed get layout(): string { return this.props.Document.GetText(this.props.layoutKey, "

Error loading layout data

"); } - @computed get layoutKeys(): Key[] { return this.props.Document.GetData(KeyStore.LayoutKeys, ListField, new Array()); } - @computed get layoutFields(): Key[] { return this.props.Document.GetData(KeyStore.LayoutFields, ListField, new Array()); } - + @computed get layout(): string { return Cast(this.props.Document[this.props.layoutKey], "string", "

Error loading layout data

"); } CreateBindings(): JsxBindings { let bindings: JsxBindings = { props: OmitKeys(this.props, ['parentActive'], (obj: any) => obj.active = this.props.parentActive) }; - - for (const key of this.layoutKeys) { - bindings[key.Name + "Key"] = key; // this maps string values of the form 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; - } return bindings; } render() { - let lkeys = this.props.Document.GetT(KeyStore.LayoutKeys, ListField); - if (!lkeys || lkeys === FieldWaiting) { - return

Error loading layout keys

; - } return ; -const Document = makeInterface(schema); +export const positionSchema = createSchema({ + nativeWidth: "number", + nativeHeight: "number", + width: "number", + height: "number", + x: "number", + y: "number", +}); + +type Document = makeInterface<[typeof schema]>; +const Document = makeInterface([schema]); @observer export class DocumentView extends DocComponent(Document) { @@ -146,7 +155,7 @@ export class DocumentView extends DocComponent(Docu document.removeEventListener("pointermove", this.onPointerMove); document.removeEventListener("pointerup", this.onPointerUp); e.stopPropagation(); - if (!SelectionManager.IsSelected(this) && e.button !== 2) + if (!SelectionManager.IsSelected(this) && e.button !== 2) { if (Math.abs(e.clientX - this._downX) < 4 && Math.abs(e.clientY - this._downY) < 4) { if (this.props.Document.Get(KeyStore.MaximizedDoc) instanceof Document) { this.props.Document.GetAsync(KeyStore.MaximizedDoc, maxdoc => { @@ -159,6 +168,7 @@ export class DocumentView extends DocComponent(Docu SelectionManager.SelectDoc(this, e.ctrlKey); } } + } } stopPropagation = (e: React.SyntheticEvent) => { e.stopPropagation(); diff --git a/src/client/views/nodes/FieldView.tsx b/src/client/views/nodes/FieldView.tsx index 93e385821..d8de5afec 100644 --- a/src/client/views/nodes/FieldView.tsx +++ b/src/client/views/nodes/FieldView.tsx @@ -1,30 +1,21 @@ 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 } from "../../../Utils"; +import { returnFalse, emptyFunction, returnOne } 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, Field, FieldValue, FieldWaiting } from "../../../new_fields/Doc"; +import { List } from "../../../new_fields/List"; // @@ -33,9 +24,9 @@ import { IconBox } from "./IconBox"; // See the LayoutString method on each field view : ImageBox, FormattedTextBox, etc. // export interface FieldViewProps { - fieldKey: Key; + fieldKey: string; ContainingCollectionView: Opt; - Document: Document; + Document: Doc; isSelected: () => boolean; select: (isCtrlPressed: boolean) => void; isTopMost: boolean; @@ -56,17 +47,17 @@ export class FieldView extends React.Component { } @computed - get field(): FieldValue { - const { Document: doc, fieldKey } = this.props; - return doc.Get(fieldKey); + get field(): FieldValue { + const { Document, fieldKey } = this.props; + return Document[fieldKey]; } render() { const field = this.field; if (!field) { return

{''}

; } - if (field instanceof TextField) { - return

{field.Data}

; + if (typeof field === "string") { + return

{field}

; } else if (field instanceof RichTextField) { return ; @@ -83,7 +74,7 @@ export class FieldView extends React.Component { else if (field instanceof AudioField) { return ; } - else if (field instanceof Document) { + else if (field instanceof Doc) { return ( { PanelHeight={() => 100} isTopMost={true} //TODO Why is this top most? selectOnLoad={false} - focus={emptyDocFunction} + focus={emptyFunction} isSelected={returnFalse} select={returnFalse} - layoutKey={KeyStore.Layout} + layoutKey={"layout"} ContainingCollectionView={this.props.ContainingCollectionView} parentActive={this.props.active} whenActiveChanged={this.props.whenActiveChanged} /> ); } - else if (field instanceof ListField) { + else if (field instanceof List) { return (
- {(field as ListField).Data.map(f => f instanceof Document ? f.Title : f.GetValue().toString()).join(", ")} + {field.map(f => f instanceof Doc ? f.title : f.toString()).join(", ")}
); } // bcz: this belongs here, but it doesn't render well so taking it out for now // else if (field instanceof HtmlField) { // return // } - else if (field instanceof NumberField) { - return

{field.Data}

; + else if (typeof field === "number") { + return

{field}

; } else if (field !== FieldWaiting) { - return

{JSON.stringify(field.GetValue())}

; + return

{JSON.stringify(field)}

; } else { return

{"Waiting for server..."}

; diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index fd5381b77..3b72e9f39 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,9 +10,23 @@ import { ContextMenu } from "../../views/ContextMenu"; import { FieldView, FieldViewProps } from './FieldView'; import "./ImageBox.scss"; import React = require("react"); +import { createSchema, makeInterface } from '../../../new_fields/Schema'; +import { DocComponent } from '../DocComponent'; +import { positionSchema } from './DocumentView'; +import { FieldValue, Cast } from '../../../new_fields/Types'; +import { URLField } from '../../../new_fields/URLField'; +import { Doc, FieldWaiting } from '../../../new_fields/Doc'; +import { List } from '../../../new_fields/List'; + +const schema = createSchema({ + curPage: "number" +}); + +type ImageDocument = makeInterface<[typeof schema, typeof positionSchema]>; +const ImageDocument = makeInterface([schema, positionSchema]); @observer -export class ImageBox extends React.Component { +export class ImageBox extends DocComponent(ImageDocument) { public static LayoutString() { return FieldView.LayoutString(ImageBox); } private _imgRef: React.RefObject; @@ -39,8 +48,8 @@ export class ImageBox extends React.Component { 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.SetNumber(KeyStore.Height, this.props.Document.Width() * h / w); + this.Document.nativeHeight = FieldValue(this.Document.nativeWidth, 0) * h / w; + this.Document.height = FieldValue(this.Document.width, 0) * h / w; } } @@ -126,9 +135,9 @@ export class ImageBox extends React.Component { } specificContextMenu = (e: React.MouseEvent): void => { - let field = this.props.Document.GetT(this.props.fieldKey, ImageField); + let field = Cast(this.Document[this.props.fieldKey], URLField); if (field && field !== FieldWaiting) { - let url = field.Data.href; + let url = field.url.href; ContextMenu.Instance.addItem({ description: "Copy path", event: () => { Utils.CopyText(url); @@ -140,11 +149,11 @@ export class ImageBox extends React.Component { @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) => @@ -155,12 +164,12 @@ export class ImageBox extends React.Component { } 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); + else if (field instanceof URLField) paths = [field.url.href]; + else if (field instanceof List) paths = field.filter(val => val instanceof URLField).map(p => (p as URLField).url.href); + let nativeWidth = FieldValue(this.Document.nativeWidth, 1); return (
Image not found diff --git a/src/debug/Test.tsx b/src/debug/Test.tsx index 8b9c9fa0b..81c69ca8e 100644 --- a/src/debug/Test.tsx +++ b/src/debug/Test.tsx @@ -16,8 +16,8 @@ const schema1 = createSchema({ testDoc: Doc }); -const TestDoc = makeInterface(schema1); -type TestDoc = makeInterface; +const TestDoc = makeInterface([schema1]); +type TestDoc = makeInterface<[typeof schema1]>; const schema2 = createSchema({ hello: URLField, diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 23a8c05cc..e0eb44ee9 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -33,6 +33,7 @@ export type Field = number | string | boolean | ObjectField | RefField; export type Opt = T | undefined; export type FieldWaiting = null; export const FieldWaiting: FieldWaiting = null; +export type FieldValue = Opt | FieldWaiting; export const Self = Symbol("Self"); @@ -81,8 +82,8 @@ export namespace Doc { const self = doc[Self]; return getField(self, key, ignoreProto); } - export function GetT(doc: Doc, key: string, ctor: FieldCtor, ignoreProto: boolean = false): Field | null | undefined { - return Cast(Get(doc, key, ignoreProto), ctor); + export function GetT(doc: Doc, key: string, ctor: FieldCtor, ignoreProto: boolean = false): T | null | undefined { + return Cast(Get(doc, key, ignoreProto), ctor) as T | null | undefined; } export function MakeDelegate(doc: Opt): Opt { if (!doc) { diff --git a/src/new_fields/HtmlField.ts b/src/new_fields/HtmlField.ts index f8e54ade5..76fdb1f62 100644 --- a/src/new_fields/HtmlField.ts +++ b/src/new_fields/HtmlField.ts @@ -3,7 +3,7 @@ import { serializable, primitive } from "serializr"; import { ObjectField } from "./Doc"; @Deserializable("html") -export class URLField extends ObjectField { +export class HtmlField extends ObjectField { @serializable(primitive()) readonly html: string; diff --git a/src/new_fields/Schema.ts b/src/new_fields/Schema.ts index 1607d4c15..1d1f56844 100644 --- a/src/new_fields/Schema.ts +++ b/src/new_fields/Schema.ts @@ -1,8 +1,26 @@ -import { Interface, ToInterface, Cast, FieldCtor, ToConstructor } from "./Types"; +import { Interface, ToInterface, Cast, FieldCtor, ToConstructor, HasTail, Head, Tail } from "./Types"; import { Doc } from "./Doc"; -export type makeInterface = Partial> & U; -export function makeInterface(schema: T): (doc: U) => makeInterface { +type All = { + 1: makeInterface, U> & All, U>, + 0: makeInterface, U> +}[HasTail extends true ? 1 : 0]; + +type AllToInterface = { + 1: ToInterface> & AllToInterface>, + 0: ToInterface> +}[HasTail extends true ? 1 : 0]; + +export type makeInterface = Partial> & U; +// export function makeInterface(schemas: T): (doc: U) => All; +// export function makeInterface(schema: T): (doc: U) => makeInterface; +export function makeInterface(schemas: T): (doc: U) => All { + let schema: Interface = {}; + for (const s of schemas) { + for (const key in s) { + schema[key] = s[key]; + } + } return function (doc: any) { return new Proxy(doc, { get(target, prop) { diff --git a/src/new_fields/Types.ts b/src/new_fields/Types.ts index cafb208ce..6ffb3e02f 100644 --- a/src/new_fields/Types.ts +++ b/src/new_fields/Types.ts @@ -27,14 +27,17 @@ export type Tail = ((...t: T) => any) extends ((_: any, ...tail: infer TT) => any) ? TT : []; export type HasTail = T extends ([] | [any]) ? false : true; +//TODO Allow you to optionally specify default values for schemas, which should then make that field not be partial export interface Interface { [key: string]: ToConstructor | ListSpec; // [key: string]: ToConstructor | ListSpec; } -export type FieldCtor = ToConstructor | ListSpec; +export type FieldCtor = T extends List ? ListSpec : ToConstructor; -export function Cast>(field: Field | null | undefined, ctor: T): ToType | null | undefined { +export function Cast>(field: Field | null | undefined, ctor: T): ToType | null | undefined; +export function Cast>(field: Field | null | undefined, ctor: T, defaultVal: ToType): ToType; +export function Cast>(field: Field | null | undefined, ctor: T, defaultVal?: ToType): ToType | null | undefined { if (field !== undefined && field !== null) { if (typeof ctor === "string") { if (typeof field === ctor) { @@ -42,17 +45,19 @@ export function Cast>(field: Field | null | undefined } } else if (typeof ctor === "object") { if (field instanceof List) { - return field as ToType; + return field as any; } } else if (field instanceof (ctor as any)) { return field as ToType; } } else { - return field; + return defaultVal; } - return undefined; + return defaultVal; } -export function FieldValue(field: Opt | Promise>): Opt { - return field instanceof Promise ? undefined : field; +export function FieldValue(field: Opt | Promise>, defaultValue: U): T; +export function FieldValue(field: Opt | Promise>): Opt; +export function FieldValue(field: Opt | Promise>, defaultValue?: T): Opt { + return field instanceof Promise ? defaultValue : field; } -- cgit v1.2.3-70-g09d2 From 8ddec1c70c01b3d7d919908299e1168b75698dc7 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Sat, 20 Apr 2019 19:06:28 -0400 Subject: More refactoring --- .../views/collections/CollectionDockingView.tsx | 65 +++++++++++----------- src/new_fields/Doc.ts | 13 +++-- src/new_fields/List.ts | 2 +- src/new_fields/Proxy.ts | 20 +++---- src/new_fields/Types.ts | 2 - src/new_fields/URLField.ts | 12 ++-- src/new_fields/util.ts | 4 +- 7 files changed, 59 insertions(+), 59 deletions(-) (limited to 'src/new_fields/Doc.ts') diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index e4c647635..b6c87231f 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -4,11 +4,8 @@ import 'golden-layout/src/css/goldenlayout-dark-theme.css'; import { action, observable, reaction, trace } 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 } from "../../../Utils"; +import { Utils, returnTrue, emptyFunction, returnOne } from "../../../Utils"; import { Server } from "../../Server"; import { undoBatch } from "../../util/UndoManager"; import { DocumentView } from "../nodes/DocumentView"; @@ -17,20 +14,22 @@ 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, Id, Opt, Field, FieldId } from "../../../new_fields/Doc"; +import { Cast, FieldValue } from "../../../new_fields/Types"; +import { List } from "../../../new_fields/List"; +import { DocServer } from "../../DocServer"; @observer export class CollectionDockingView extends React.Component { public static Instance: CollectionDockingView; - public static makeDocumentConfig(document: Document) { + public static makeDocumentConfig(document: Doc) { return { type: 'react-component', component: 'DocumentFrameRenderer', - title: document.Title, + title: document.title, props: { - documentId: document.Id, + documentId: document[Id], //collectionDockingView: CollectionDockingView.Instance } }; @@ -48,14 +47,14 @@ export class CollectionDockingView extends React.Component this.AddRightSplit(dragDoc, true).contentItems[0].tab._dragListener. onMouseDown({ pageX: e.pageX, pageY: e.pageY, preventDefault: emptyFunction, button: 0 })); } @action - public OpenFullScreen(document: Document) { + public OpenFullScreen(document: Doc) { let newItemStackConfig = { type: 'stack', content: [CollectionDockingView.makeDocumentConfig(document)] @@ -83,7 +82,7 @@ export class CollectionDockingView extends React.Component void = () => { if (this._containerRef.current) { reaction( - () => this.props.Document.GetText(KeyStore.Data, ""), + () => Cast(this.props.Document.data, "string", ""), () => { if (!this._goldenLayout || this._ignoreStateChange !== JSON.stringify(this._goldenLayout.toConfig())) { setTimeout(() => this.setupGoldenLayout(), 1); @@ -203,7 +202,7 @@ export class CollectionDockingView extends React.Component) => - (sourceDoc instanceof Document) && DragLinksAsDocuments(tab, x, y, sourceDoc))); + (sourceDoc instanceof Doc) && DragLinksAsDocuments(tab, x, y, sourceDoc))); } else if ((className === "lm_title" || className === "lm_tab lm_active") && !e.shiftKey) { e.stopPropagation(); @@ -213,11 +212,11 @@ export class CollectionDockingView extends React.Component) => { - if (f instanceof Document) { + if (f instanceof Doc) { DragManager.StartDocumentDrag([tab], new DragManager.DocumentDragData([f]), x, y, { handlers: { - dragComplete: action(emptyFunction), + dragComplete: emptyFunction, }, hideSource: false }); @@ -235,7 +234,7 @@ export class CollectionDockingView extends React.Component { var json = JSON.stringify(this._goldenLayout.toConfig()); - this.props.Document.SetText(KeyStore.Data, json); + this.props.Document.data = json; } itemDropped = () => { @@ -264,10 +263,9 @@ export class CollectionDockingView extends React.Component${count}
`); 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); + tab.reactionDisposer = reaction((): [List | null | undefined, List | null | undefined] => [Cast(f.linkedFromDocs, List), Cast(f.linkedToDocs, List)], + ([linkedFrom, linkedTo]) => { + let count = (linkedFrom ? linkedFrom.length : 0) + (linkedTo ? linkedTo.length : 0); counter.innerHTML = count; }); })); @@ -319,19 +317,22 @@ export class DockedFrameRenderer extends React.Component { _mainCont = React.createRef(); @observable private _panelWidth = 0; @observable private _panelHeight = 0; - @observable private _document: Opt; + @observable private _document: Opt; constructor(props: any) { super(props); - Server.GetField(this.props.documentId, action((f: Opt) => this._document = f as Document)); + DocServer.GetRefField(this.props.documentId).then(action((f: Opt) => this._document = f as Doc)); } - nativeWidth = () => this._document!.GetNumber(KeyStore.NativeWidth, this._panelWidth); - nativeHeight = () => this._document!.GetNumber(KeyStore.NativeHeight, this._panelHeight); + nativeWidth = () => Cast(this._document!.nativeWidth, "number", this._panelWidth); + nativeHeight = () => Cast(this._document!.nativeHeight, "number", 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); + const nativeH = this.nativeHeight(); + const nativeW = this.nativeWidth(); + let wscale = this._panelWidth / nativeW; + if (wscale * nativeH > this._panelHeight) { + return this._panelHeight / nativeH; + } return wscale; } @@ -349,7 +350,7 @@ export class DockedFrameRenderer extends React.Component { return (
- { selectOnLoad={false} parentActive={returnTrue} whenActiveChanged={emptyFunction} - focus={emptyDocFunction} + focus={emptyFunction} ContainingCollectionView={undefined} />
); } diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index e0eb44ee9..8cbd8cf38 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -6,14 +6,15 @@ import { DocServer } from "../client/DocServer"; import { setter, getter, getField } from "./util"; import { Cast, FieldCtor } from "./Types"; +export type FieldId = string; export const HandleUpdate = Symbol("HandleUpdate"); export const Id = Symbol("Id"); export abstract class RefField { @serializable(alias("id", primitive())) - private __id: string; - readonly [Id]: string; + private __id: FieldId; + readonly [Id]: FieldId; - constructor(id?: string) { + constructor(id?: FieldId) { this.__id = id || Utils.GenerateGuid(); this[Id] = this.__id; } @@ -39,7 +40,7 @@ export const Self = Symbol("Self"); @Deserializable("doc").withFields(["id"]) export class Doc extends RefField { - constructor(id?: string, forceSave?: boolean) { + constructor(id?: FieldId, forceSave?: boolean) { super(id); const doc = new Proxy(this, { set: setter, @@ -53,7 +54,7 @@ export class Doc extends RefField { return doc; } - [key: string]: Field | null | undefined; + [key: string]: Field | FieldWaiting | undefined; @serializable(alias("fields", map(autoObject()))) @observable @@ -72,7 +73,6 @@ export namespace Doc { return new Promise(res => getField(self, key, ignoreProto, res)); } export function GetTAsync(doc: Doc, key: string, ctor: FieldCtor, ignoreProto: boolean = false): Promise { - const self = doc[Self]; return new Promise(async res => { const field = await GetAsync(doc, key, ignoreProto); return Cast(field, ctor); @@ -90,6 +90,7 @@ export namespace Doc { return undefined; } const delegate = new Doc(); + //TODO Does this need to be doc[Self]? delegate.prototype = doc; return delegate; } diff --git a/src/new_fields/List.ts b/src/new_fields/List.ts index a1a623f83..58b252f7b 100644 --- a/src/new_fields/List.ts +++ b/src/new_fields/List.ts @@ -9,7 +9,7 @@ class ListImpl extends ObjectField { constructor() { super(); const list = new Proxy(this, { - set: function (a, b, c, d) { return setter(a, b, c, d); }, + set: setter, get: getter, deleteProperty: () => { throw new Error("Currently properties can't be deleted from documents, assign to undefined instead"); }, defineProperty: () => { throw new Error("Currently properties can't be defined on documents using Object.defineProperty"); }, diff --git a/src/new_fields/Proxy.ts b/src/new_fields/Proxy.ts index 3b4b2e452..6a78388c1 100644 --- a/src/new_fields/Proxy.ts +++ b/src/new_fields/Proxy.ts @@ -1,7 +1,8 @@ import { Deserializable } from "../client/util/SerializationHelper"; -import { RefField, Id, ObjectField } from "./Doc"; +import { RefField, Id, ObjectField, FieldWaiting } from "./Doc"; import { primitive, serializable } from "serializr"; -import { observable } from "mobx"; +import { observable, action } from "mobx"; +import { DocServer } from "../client/DocServer"; @Deserializable("proxy") export class ProxyField extends ObjectField { @@ -32,7 +33,7 @@ export class ProxyField extends ObjectField { private failed = false; private promise?: Promise; - value(callback?: ((field: T | undefined) => void)): T | undefined | null { + value(callback?: ((field: T | undefined) => void)): T | undefined | FieldWaiting { if (this.cache) { callback && callback(this.cache); return this.cache; @@ -41,13 +42,12 @@ export class ProxyField extends ObjectField { return undefined; } if (!this.promise) { - // this.promise = Server.GetField(this.fieldId).then(action((field: any) => { - // this.promise = undefined; - // this.cache = field; - // if (field === undefined) this.failed = true; - // return field; - // })); - this.promise = new Promise(r => r()); + this.promise = DocServer.GetRefField(this.fieldId).then(action((field: any) => { + this.promise = undefined; + this.cache = field; + if (field === undefined) this.failed = true; + return field; + })); } callback && this.promise.then(callback); return null; diff --git a/src/new_fields/Types.ts b/src/new_fields/Types.ts index 6ffb3e02f..0fbd8984c 100644 --- a/src/new_fields/Types.ts +++ b/src/new_fields/Types.ts @@ -50,8 +50,6 @@ export function Cast>(field: Field | null | undefined } else if (field instanceof (ctor as any)) { return field as ToType; } - } else { - return defaultVal; } return defaultVal; } diff --git a/src/new_fields/URLField.ts b/src/new_fields/URLField.ts index d27a2b692..e456a7d16 100644 --- a/src/new_fields/URLField.ts +++ b/src/new_fields/URLField.ts @@ -1,16 +1,16 @@ import { Deserializable } from "../client/util/SerializationHelper"; -import { serializable } from "serializr"; +import { serializable, custom } from "serializr"; import { ObjectField } from "./Doc"; function url() { - return { - serializer: function (value: URL) { + return custom( + function (value: URL) { return value.href; }, - deserializer: function (jsonValue: string, done: (err: any, val: any) => void) { - done(undefined, new URL(jsonValue)); + function (jsonValue: string) { + return new URL(jsonValue); } - }; + ); } @Deserializable("url") diff --git a/src/new_fields/util.ts b/src/new_fields/util.ts index 0f08ecf03..3806044bd 100644 --- a/src/new_fields/util.ts +++ b/src/new_fields/util.ts @@ -22,6 +22,7 @@ export function setter(target: any, prop: string | symbol | number, value: any, value = new ProxyField(value); } if (value instanceof ObjectField) { + //TODO Instead of target, maybe use target[Self] if (value[Parent] && value[Parent] !== target) { throw new Error("Can't put the same object in multiple documents at the same time"); } @@ -51,7 +52,7 @@ export function getter(target: any, prop: string | symbol | number, receiver: an if (SerializationHelper.IsSerializing()) { return target[prop]; } - return getField(target, prop, receiver); + return getField(target, prop); } export function getField(target: any, prop: string | number, ignoreProto: boolean = false, callback?: (field: Field | undefined) => void): any { @@ -69,5 +70,4 @@ export function getField(target: any, prop: string | number, ignoreProto: boolea } callback && callback(field); return field; - } -- cgit v1.2.3-70-g09d2 From 3556aae6d063d8b654509330e70bc67606f16613 Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Sun, 21 Apr 2019 00:39:09 -0400 Subject: More changes --- .../views/collections/CollectionDockingView.tsx | 38 +++++++++---------- .../views/nodes/CollectionFreeFormDocumentView.tsx | 43 +++++++++++++--------- src/new_fields/Doc.ts | 9 ++--- src/new_fields/Proxy.ts | 2 +- src/new_fields/Types.ts | 22 ++++++++--- 5 files changed, 65 insertions(+), 49 deletions(-) (limited to 'src/new_fields/Doc.ts') diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index b6c87231f..7b204cbdc 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -250,28 +250,26 @@ export class CollectionDockingView extends React.Component { if (tab.hasOwnProperty("contentItem") && tab.contentItem.config.type !== "stack") { - Server.GetField(tab.contentItem.config.props.documentId, action((f: Opt) => { - if (f !== undefined && f instanceof Document) { - f.GetTAsync(KeyStore.Title, TextField, (tfield) => { - if (tfield !== undefined) { - tab.titleElement[0].textContent = f.Title; - } - }); - 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(`
${count}
`); - tab.element.append(counter); - counter.DashDocId = tab.contentItem.config.props.documentId; - tab.reactionDisposer = reaction((): [List | null | undefined, List | null | undefined] => [Cast(f.linkedFromDocs, List), Cast(f.linkedToDocs, List)], - ([linkedFrom, linkedTo]) => { - let count = (linkedFrom ? linkedFrom.length : 0) + (linkedTo ? linkedTo.length : 0); - counter.innerHTML = count; - }); - })); + DocServer.GetRefField(tab.contentItem.config.props.documentId).then(async f => { + if (f instanceof Doc) { + const tfield = await Cast(f.title, "string"); + if (tfield !== undefined) { + tab.titleElement[0].textContent = f.Title; + } + const lf = await Cast(f.linkedFromDocs, List); + const lt = await Cast(f.linkedToDocs, List); + let count = (lf ? lf.length : 0) + (lt ? lt.length : 0); + let counter: any = this.htmlToElement(`
${count}
`); + tab.element.append(counter); + counter.DashDocId = tab.contentItem.config.props.documentId; + tab.reactionDisposer = reaction((): [List | null | undefined, List | 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 () { diff --git a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx index 1d42b3899..27fd25b5c 100644 --- a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx +++ b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx @@ -1,18 +1,27 @@ import { computed, trace } from "mobx"; import { observer } from "mobx-react"; -import { KeyStore } from "../../../fields/KeyStore"; -import { NumberField } from "../../../fields/NumberField"; import { Transform } from "../../util/Transform"; -import { DocumentView, DocumentViewProps } from "./DocumentView"; +import { DocumentView, DocumentViewProps, positionSchema } from "./DocumentView"; import "./DocumentView.scss"; import React = require("react"); import { OmitKeys } from "../../../Utils"; +import { DocComponent } from "../DocComponent"; +import { createSchema, makeInterface } from "../../../new_fields/Schema"; +import { FieldValue } from "../../../new_fields/Types"; export interface CollectionFreeFormDocumentViewProps extends DocumentViewProps { } +const schema = createSchema({ + zoom: "number", + zIndex: "number" +}); + +type FreeformDocument = makeInterface<[typeof schema, typeof positionSchema]>; +const FreeformDocument = makeInterface([schema, positionSchema]); + @observer -export class CollectionFreeFormDocumentView extends React.Component { +export class CollectionFreeFormDocumentView extends DocComponent(FreeformDocument) { private _mainCont = React.createRef(); @computed @@ -20,36 +29,36 @@ export class CollectionFreeFormDocumentView extends React.Component this.props.ScreenToLocalTransform() diff --git a/src/new_fields/Doc.ts b/src/new_fields/Doc.ts index 8cbd8cf38..10e8fe7ec 100644 --- a/src/new_fields/Doc.ts +++ b/src/new_fields/Doc.ts @@ -32,9 +32,8 @@ export class ObjectField { export type Field = number | string | boolean | ObjectField | RefField; export type Opt = T | undefined; -export type FieldWaiting = null; -export const FieldWaiting: FieldWaiting = null; -export type FieldValue = Opt | FieldWaiting; +export type FieldWaiting = Promise; +export type FieldValue = Opt | FieldWaiting; export const Self = Symbol("Self"); @@ -58,7 +57,7 @@ export class Doc extends RefField { @serializable(alias("fields", map(autoObject()))) @observable - private __fields: { [key: string]: Field | null | undefined } = {}; + private __fields: { [key: string]: Field | FieldWaiting | undefined } = {}; private [Update] = (diff: any) => { DocServer.UpdateField(this[Id], diff); @@ -78,7 +77,7 @@ export namespace Doc { return Cast(field, ctor); }); } - export function Get(doc: Doc, key: string, ignoreProto: boolean = false): Field | null | undefined { + export function Get(doc: Doc, key: string, ignoreProto: boolean = false): FieldValue { const self = doc[Self]; return getField(self, key, ignoreProto); } diff --git a/src/new_fields/Proxy.ts b/src/new_fields/Proxy.ts index 6a78388c1..2aa78731e 100644 --- a/src/new_fields/Proxy.ts +++ b/src/new_fields/Proxy.ts @@ -50,6 +50,6 @@ export class ProxyField extends ObjectField { })); } callback && this.promise.then(callback); - return null; + return this.promise; } } diff --git a/src/new_fields/Types.ts b/src/new_fields/Types.ts index 0fbd8984c..0392dc2fb 100644 --- a/src/new_fields/Types.ts +++ b/src/new_fields/Types.ts @@ -1,4 +1,4 @@ -import { Field, Opt } from "./Doc"; +import { Field, Opt, FieldWaiting, FieldValue } from "./Doc"; import { List } from "./List"; export type ToType = @@ -6,7 +6,7 @@ export type ToType = T extends "number" ? number : T extends "boolean" ? boolean : T extends ListSpec ? List : - T extends { new(...args: any[]): infer R } ? R : never; + T extends { new(...args: any[]): infer R } ? (R | Promise) : never; export type ToConstructor = T extends string ? "string" : @@ -35,10 +35,13 @@ export interface Interface { export type FieldCtor = T extends List ? ListSpec : ToConstructor; -export function Cast>(field: Field | null | undefined, ctor: T): ToType | null | undefined; -export function Cast>(field: Field | null | undefined, ctor: T, defaultVal: ToType): ToType; -export function Cast>(field: Field | null | undefined, ctor: T, defaultVal?: ToType): ToType | null | undefined { - if (field !== undefined && field !== null) { +export function Cast>(field: Field | FieldWaiting | undefined, ctor: T): FieldValue>; +export function Cast>(field: Field | FieldWaiting | undefined, ctor: T, defaultVal: ToType): ToType; +export function Cast>(field: Field | FieldWaiting | undefined, ctor: T, defaultVal?: ToType): FieldValue> | undefined { + if (field instanceof Promise) { + return defaultVal === undefined ? field.then(f => Cast(f, ctor) as any) : defaultVal; + } + if (field !== undefined && !(field instanceof Promise)) { if (typeof ctor === "string") { if (typeof field === ctor) { return field as ToType; @@ -59,3 +62,10 @@ export function FieldValue(field: Opt | Promise>): Op export function FieldValue(field: Opt | Promise>, defaultValue?: T): Opt { return field instanceof Promise ? defaultValue : field; } + +export interface PromiseLike { + then(callback: (field: Opt | PromiseLike) => void): void; +} +export function PromiseValue(field: FieldValue): PromiseLike> { + return field instanceof Promise ? field : { then(cb: ((field: Opt) => void)) { return cb(field); } }; +} \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 393d351420b3a0d28f4cd1ea8b674fa5d04bfcde Mon Sep 17 00:00:00 2001 From: Tyler Schicke Date: Sun, 21 Apr 2019 23:40:48 -0400 Subject: More fixes --- .../views/collections/CollectionDockingView.tsx | 6 ++-- .../views/nodes/CollectionFreeFormDocumentView.tsx | 2 +- src/client/views/nodes/DocumentView.tsx | 2 +- src/client/views/nodes/FieldView.tsx | 8 ++--- src/client/views/nodes/ImageBox.tsx | 15 +++++----- src/client/views/nodes/VideoBox.tsx | 35 ++++++++++++---------- src/client/views/nodes/WebBox.tsx | 4 +-- src/debug/Test.tsx | 12 ++++---- src/new_fields/Doc.ts | 4 +-- src/new_fields/Schema.ts | 22 +++----------- src/new_fields/Types.ts | 11 +++---- src/new_fields/URLField.ts | 9 ++++-- 12 files changed, 62 insertions(+), 68 deletions(-) (limited to 'src/new_fields/Doc.ts') diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 7b204cbdc..86ee7cea9 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -16,7 +16,7 @@ import { ServerUtils } from "../../../server/ServerUtil"; import { DragManager, DragLinksAsDocuments } from "../../util/DragManager"; import { Transform } from '../../util/Transform'; import { Doc, Id, Opt, Field, FieldId } from "../../../new_fields/Doc"; -import { Cast, FieldValue } from "../../../new_fields/Types"; +import { Cast } from "../../../new_fields/Types"; import { List } from "../../../new_fields/List"; import { DocServer } from "../../DocServer"; @@ -336,8 +336,8 @@ export class DockedFrameRenderer extends React.Component { 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(); diff --git a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx index 27fd25b5c..c6eea5623 100644 --- a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx +++ b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx @@ -18,7 +18,7 @@ const schema = createSchema({ }); type FreeformDocument = makeInterface<[typeof schema, typeof positionSchema]>; -const FreeformDocument = makeInterface([schema, positionSchema]); +const FreeformDocument = makeInterface(schema, positionSchema); @observer export class CollectionFreeFormDocumentView extends DocComponent(FreeformDocument) { diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index f1a12e6db..c0afc192e 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -56,7 +56,7 @@ export const positionSchema = createSchema({ }); type Document = makeInterface<[typeof schema]>; -const Document = makeInterface([schema]); +const Document = makeInterface(schema); @observer export class DocumentView extends DocComponent(Document) { diff --git a/src/client/views/nodes/FieldView.tsx b/src/client/views/nodes/FieldView.tsx index 845213366..b11a87d75 100644 --- a/src/client/views/nodes/FieldView.tsx +++ b/src/client/views/nodes/FieldView.tsx @@ -3,19 +3,19 @@ import { observer } from "mobx-react"; import { computed } from "mobx"; import { FormattedTextBox } from "./FormattedTextBox"; import { ImageBox } from "./ImageBox"; -import { WebBox } from "./WebBox"; import { VideoBox } from "./VideoBox"; import { AudioBox } from "./AudioBox"; import { DocumentContentsView } from "./DocumentContentsView"; import { Transform } from "../../util/Transform"; -import { returnFalse, emptyFunction, returnOne } 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, Field, FieldValue, FieldWaiting } from "../../../new_fields/Doc"; +import { Opt, Doc, FieldResult } from "../../../new_fields/Doc"; import { List } from "../../../new_fields/List"; +import { ImageField, VideoField, AudioField } from "../../../new_fields/URLField"; // @@ -47,7 +47,7 @@ export class FieldView extends React.Component { } @computed - get field(): FieldValue { + get field(): FieldResult { const { Document, fieldKey } = this.props; return Document[fieldKey]; } diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index 3b72e9f39..c11aee56e 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -14,16 +14,15 @@ import { createSchema, makeInterface } from '../../../new_fields/Schema'; import { DocComponent } from '../DocComponent'; import { positionSchema } from './DocumentView'; import { FieldValue, Cast } from '../../../new_fields/Types'; -import { URLField } from '../../../new_fields/URLField'; -import { Doc, FieldWaiting } from '../../../new_fields/Doc'; +import { ImageField } from '../../../new_fields/URLField'; import { List } from '../../../new_fields/List'; -const schema = createSchema({ +export const pageSchema = createSchema({ curPage: "number" }); -type ImageDocument = makeInterface<[typeof schema, typeof positionSchema]>; -const ImageDocument = makeInterface([schema, positionSchema]); +type ImageDocument = makeInterface<[typeof pageSchema, typeof positionSchema]>; +const ImageDocument = makeInterface(pageSchema, positionSchema); @observer export class ImageBox extends DocComponent(ImageDocument) { @@ -135,7 +134,7 @@ export class ImageBox extends DocComponent(ImageD } specificContextMenu = (e: React.MouseEvent): void => { - let field = Cast(this.Document[this.props.fieldKey], URLField); + let field = Cast(this.Document[this.props.fieldKey], ImageField); if (field && field !== FieldWaiting) { let url = field.url.href; ContextMenu.Instance.addItem({ @@ -167,8 +166,8 @@ export class ImageBox extends DocComponent(ImageD 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 URLField) paths = [field.url.href]; - else if (field instanceof List) paths = field.filter(val => val instanceof URLField).map(p => (p as URLField).url.href); + else 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); return (
diff --git a/src/client/views/nodes/VideoBox.tsx b/src/client/views/nodes/VideoBox.tsx index 9d7c2bc56..7b922b620 100644 --- a/src/client/views/nodes/VideoBox.tsx +++ b/src/client/views/nodes/VideoBox.tsx @@ -1,18 +1,22 @@ import React = require("react"); import { observer } from "mobx-react"; -import { FieldWaiting, Opt } from '../../../fields/Field'; -import { VideoField } from '../../../fields/VideoField'; import { FieldView, FieldViewProps } from './FieldView'; import "./VideoBox.scss"; import Measure from "react-measure"; -import { action, trace, observable, IReactionDisposer, computed, reaction } from "mobx"; -import { KeyStore } from "../../../fields/KeyStore"; -import { number } from "prop-types"; +import { action, computed } from "mobx"; +import { DocComponent } from "../DocComponent"; +import { positionSchema } from "./DocumentView"; +import { makeInterface } from "../../../new_fields/Schema"; +import { pageSchema } from "./ImageBox"; +import { Cast, FieldValue } from "../../../new_fields/Types"; +import { VideoField } from "../../../new_fields/URLField"; + +type VideoDocument = makeInterface<[typeof positionSchema, typeof pageSchema]>; +const VideoDocument = makeInterface(positionSchema, pageSchema); @observer -export class VideoBox extends React.Component { +export class VideoBox extends DocComponent(VideoDocument) { - private _reactionDisposer: Opt; private _videoRef = React.createRef(); public static LayoutString() { return FieldView.LayoutString(VideoBox); } @@ -20,7 +24,7 @@ export class VideoBox extends React.Component { super(props); } - @computed private get curPage() { return this.props.Document.GetNumber(KeyStore.CurPage, -1); } + @computed private get curPage() { return FieldValue(this.Document.curPage, -1); } _loaded: boolean = false; @@ -31,12 +35,12 @@ export class VideoBox extends React.Component { // 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; @@ -56,12 +60,11 @@ export class VideoBox extends React.Component { } render() { - let field = this.props.Document.GetT(this.props.fieldKey, VideoField); - if (!field || field === FieldWaiting) { + let field = FieldValue(Cast(this.Document[this.props.fieldKey], VideoField)); + if (!field) { return
Loading
; } - let path = field.Data.href; - trace(); + let path = field.url.href; return ( {({ measureRef }) => diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx index e3b6e1c05..63778fa50 100644 --- a/src/client/views/nodes/WebBox.tsx +++ b/src/client/views/nodes/WebBox.tsx @@ -4,7 +4,7 @@ import { FieldViewProps, FieldView } from './FieldView'; import { observer } from "mobx-react"; import { computed } from 'mobx'; import { HtmlField } from "../../../new_fields/HtmlField"; -import { URLField } from "../../../new_fields/URLField"; +import { WebField } from "../../../new_fields/URLField"; @observer export class WebBox extends React.Component { @@ -37,7 +37,7 @@ export class WebBox extends React.Component { let view; if (field instanceof HtmlField) { view = - } else if (field instanceof URLField) { + } else if (field instanceof WebField) { view =