diff options
author | Sam Wilkins <abdullah_ahmed@brown.edu> | 2019-03-08 00:11:04 -0500 |
---|---|---|
committer | Sam Wilkins <abdullah_ahmed@brown.edu> | 2019-03-08 00:11:04 -0500 |
commit | f4a01b9b394a5bdc48e57923567249bb05cb71ff (patch) | |
tree | e7e3c26c82c00f0a5b5255932710fdbab4651749 /src | |
parent | 6ca68333303d97ce35d4118bacdd21f410bdd017 (diff) |
Close to refactor
Diffstat (limited to 'src')
-rw-r--r-- | src/client/SocketStub.ts | 1 | ||||
-rw-r--r-- | src/client/documents/Documents.ts | 6 | ||||
-rw-r--r-- | src/client/views/Main.tsx | 79 | ||||
-rw-r--r-- | src/server/authentication/controllers/WorkspacesMenu.tsx | 56 | ||||
-rw-r--r-- | src/server/database.ts | 10 | ||||
-rw-r--r-- | src/server/index.ts | 88 |
6 files changed, 116 insertions, 124 deletions
diff --git a/src/client/SocketStub.ts b/src/client/SocketStub.ts index 18df4ca0a..c48f21f63 100644 --- a/src/client/SocketStub.ts +++ b/src/client/SocketStub.ts @@ -48,6 +48,7 @@ export class SocketStub { public static SEND_FIELDS_REQUEST(fieldIds: FieldId[], callback: (fields: { [key: string]: Field }) => any) { Utils.EmitCallback(Server.Socket, MessageStore.GetFields, fieldIds, (fields: any[]) => { + console.log(fieldIds); let fieldMap: any = {}; for (let field of fields) { fieldMap[field._id] = ServerUtils.FromJson(field); diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 1d24ff7d2..596652cf0 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -44,14 +44,14 @@ export namespace Documents { const collProtoId = "collectionProto"; const kvpProtoId = "kvpProto"; - export function initProtos(mainDocId: string, callback: (mainDoc?: Document) => void) { - Server.GetFields([collProtoId, textProtoId, imageProtoId, mainDocId], (fields) => { + export function initProtos(callback: () => void) { + Server.GetFields([collProtoId, textProtoId, imageProtoId], (fields) => { collProto = fields[collProtoId] as Document; imageProto = fields[imageProtoId] as Document; textProto = fields[textProtoId] as Document; webProto = fields[webProtoId] as Document; kvpProto = fields[kvpProtoId] as Document; - callback(fields[mainDocId] as Document) + callback(); }); } function assignOptions(doc: Document, options: DocumentOptions): Document { diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index 2f4264ad9..da7e17f1f 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -19,13 +19,14 @@ import { DocumentDecorations } from './DocumentDecorations'; import { DocumentView } from './nodes/DocumentView'; import "./Main.scss"; import { observer } from 'mobx-react'; +import { Field, Opt } from '../../fields/Field'; @observer export class Main extends React.Component { // dummy initializations keep the compiler happy - @observable private mainDocId = ""; - @observable private mainContainer: Document = new Document; - @observable private mainfreeform: Document = new Document; + @observable private mainContainer?: Document; + @observable private mainfreeform?: Document; + @observable private userWorkspaces: Document[] = []; constructor(props: Readonly<{}>) { super(props); @@ -33,7 +34,9 @@ export class Main extends React.Component { configure({ enforceActions: "observed" }); this.initEventListeners(); - this.initAuthenticationRouters(); + Documents.initProtos(() => { + this.initAuthenticationRouters(); + }); } initEventListeners = () => { @@ -50,46 +53,49 @@ export class Main extends React.Component { initAuthenticationRouters = () => { // Load the user's active workspace, or create a new one if initial session after signup request.get(this.contextualize("getActiveWorkspaceId"), (error, response, body) => { - this.requestWorkspace(body ? body : this.getNewWorkspace()); + if (body) { + Server.GetField(body, field => { + if (field instanceof Document) { + this.openDocument(field); + } else { + this.createNewWorkspace(); + } + }); + } else { + this.createNewWorkspace(); + } }); } - getNewWorkspace = (): string => { - let newId = Utils.GenerateGuid(); + @action + createNewWorkspace = (): void => { + let mainDoc = Documents.DockDocument(JSON.stringify({ content: [{ type: 'row', content: [] }] }), { title: "main container" }); + let newId = mainDoc.Id; request.post(this.contextualize("addWorkspaceId"), { body: { target: newId }, json: true - }) - return newId; + }); + + // bcz: strangely, we need a timeout to prevent exceptions/issues initializing GoldenLayout (the rendering engine for Main Container) + setTimeout(() => { + let freeformDoc = Documents.FreeformDocument([], { x: 0, y: 400, title: "mini collection" }); + + var dockingLayout = { content: [{ type: 'row', content: [CollectionDockingView.makeDocumentConfig(freeformDoc)] }] }; + mainDoc.SetText(KeyStore.Data, JSON.stringify(dockingLayout)); + mainDoc.Set(KeyStore.ActiveFrame, freeformDoc); + this.openDocument(mainDoc); + }, 0); + this.userWorkspaces.push(mainDoc); } @action - requestWorkspace = (activeWorkspaceId: string) => { + openDocument = (doc: Document): void => { request.post(this.contextualize("setActiveWorkspaceId"), { - body: { target: activeWorkspaceId }, + body: { target: doc.Id }, json: true - }) - Documents.initProtos(activeWorkspaceId, this.prepareWorkspace); - } - - @action.bound - prepareWorkspace = (res?: Document) => { - if (res instanceof Document) { - this.mainContainer = res; - this.mainContainer.GetAsync(KeyStore.ActiveFrame, field => this.mainfreeform = field as Document); - } - else { - this.mainContainer = Documents.DockDocument(JSON.stringify({ content: [{ type: 'row', content: [] }] }), { title: "main container" }, this.mainDocId); - - // bcz: strangely, we need a timeout to prevent exceptions/issues initializing GoldenLayout (the rendering engine for Main Container) - setTimeout(() => { - this.mainfreeform = Documents.FreeformDocument([], { x: 0, y: 400, title: "mini collection" }); - - var dockingLayout = { content: [{ type: 'row', content: [CollectionDockingView.makeDocumentConfig(this.mainfreeform)] }] }; - this.mainContainer.SetText(KeyStore.Data, JSON.stringify(dockingLayout)); - this.mainContainer.Set(KeyStore.ActiveFrame, this.mainfreeform); - }, 0); - } + }); + this.mainContainer = doc; + this.mainContainer.GetAsync(KeyStore.ActiveFrame, field => this.mainfreeform = field as Document); } toggleWorkspaces = () => { @@ -117,8 +123,11 @@ export class Main extends React.Component { let addImageNode = action(() => Documents.ImageDocument(imgurl, { width: 200, height: 200, title: "an image of a cat" })); let addWebNode = action(() => Documents.WebDocument(weburl, { width: 200, height: 200, title: "a sample web page" })); - let addClick = (creator: () => Document) => action(() => this.mainfreeform.GetList<Document>(KeyStore.Data, []).push(creator())); + let addClick = (creator: () => Document) => action(() => this.mainfreeform!.GetList<Document>(KeyStore.Data, []).push(creator())); + if (!this.mainContainer) { + return <div></div> + } return ( <div style={{ position: "absolute", width: "100%", height: "100%" }}> <DocumentView Document={this.mainContainer} @@ -131,7 +140,7 @@ export class Main extends React.Component { ContainingCollectionView={undefined} /> <DocumentDecorations /> <ContextMenu /> - <WorkspacesMenu active={this.mainDocId} load={this.requestWorkspace} new={this.getNewWorkspace} /> + <WorkspacesMenu active={this.mainContainer} open={this.openDocument} new={this.createNewWorkspace} allWorkspaces={this.userWorkspaces} /> <div className="main-buttonDiv" style={{ bottom: '0px' }} ref={imgRef} > <button onPointerDown={setupDrag(imgRef, addImageNode)} onClick={addClick(addImageNode)}>Add Image</button></div> <div className="main-buttonDiv" style={{ bottom: '25px' }} ref={webRef} > diff --git a/src/server/authentication/controllers/WorkspacesMenu.tsx b/src/server/authentication/controllers/WorkspacesMenu.tsx index b565af193..ebc4f5a10 100644 --- a/src/server/authentication/controllers/WorkspacesMenu.tsx +++ b/src/server/authentication/controllers/WorkspacesMenu.tsx @@ -4,62 +4,37 @@ import { observable, action, configure, reaction, computed, ObservableMap, runIn import { observer } from "mobx-react"; import * as request from 'request' import './WorkspacesMenu.css' +import { Document } from '../../../fields/Document'; +import { Server } from '../../../client/Server'; +import { Field } from '../../../fields/Field'; export interface WorkspaceMenuProps { - active: string; - load: (workspaceId: string) => void; - new: () => string; + active: Document; + open: (workspace: Document) => void; + new: () => void; + allWorkspaces: Document[]; } @observer export class WorkspacesMenu extends React.Component<WorkspaceMenuProps> { static Instance: WorkspacesMenu; @observable private workspacesExposed: boolean = false; - @observable private workspaceIds: Array<string> = []; - @observable private selectedWorkspaceId: string = ""; constructor(props: WorkspaceMenuProps) { super(props); WorkspacesMenu.Instance = this; - this.loadExistingWorkspace = this.loadExistingWorkspace.bind(this); this.addNewWorkspace = this.addNewWorkspace.bind(this); - this.selectedWorkspaceId = this.props.active; } @action addNewWorkspace() { - let newId = this.props.new(); - this.selectedWorkspaceId = newId; - this.props.load(newId); + this.props.new(); this.toggle(); } @action - loadExistingWorkspace = (e: React.MouseEvent<HTMLLIElement, MouseEvent>) => { - let id = e.currentTarget.innerHTML; - this.props.load(id); - this.selectedWorkspaceId = id; - } - - @action toggle() { - if (this.workspacesExposed) { - this.workspacesExposed = !this.workspacesExposed; - } else { - request.get(window.location.origin + "/getAllWorkspaceIds", this.idCallback) - } - } - - @action.bound - idCallback: request.RequestCallback = (error, response, body) => { - this.workspaceIds = []; - let ids: Array<string> = JSON.parse(body) as Array<string>; - if (ids) { - for (let i = 0; i < ids.length; i++) { - this.workspaceIds.push(ids[i]); - } - this.workspacesExposed = !this.workspacesExposed; - } + this.workspacesExposed = !this.workspacesExposed; } render() { @@ -78,8 +53,7 @@ export class WorkspacesMenu extends React.Component<WorkspaceMenuProps> { transition: "all 1s ease", zIndex: 15, padding: 10, - }} - > + }}> <img src="https://bit.ly/2IBBkxk" style={{ @@ -90,16 +64,16 @@ export class WorkspacesMenu extends React.Component<WorkspaceMenuProps> { }} onClick={this.addNewWorkspace} /> - {this.workspaceIds.map(s => + {this.props.allWorkspaces.map(s => <li className={"ids"} - key={s} + key={s.Id} style={{ listStyleType: "none", - color: s === this.selectedWorkspaceId ? "darkblue" : "black", + color: s.Id === this.props.active.Id ? "darkblue" : "black", cursor: "grab" }} - onClick={this.loadExistingWorkspace} - >{s}</li> + onClick={() => this.props.open(s)} + >{s.Title}</li> )} </div> ); diff --git a/src/server/database.ts b/src/server/database.ts index 07c5819ab..1553dd94e 100644 --- a/src/server/database.ts +++ b/src/server/database.ts @@ -70,6 +70,16 @@ export class Database { let collection = this.db.collection('documents'); let cursor = collection.find({ _id: { "$in": ids } }) cursor.toArray((err, docs) => { + if (err) { + console.log("Error"); + console.log(err.message); + console.log(err.errmsg); + console.log(ids); + console.log(["afca93a8-c6bd-4b58-967e-07784c5b12c8"]); + console.log("MAKES SENSE: " + (ids instanceof Array)); + } + console.log(typeof ids); + console.log("DATABASE: " + docs); fn(docs); }) }; diff --git a/src/server/index.ts b/src/server/index.ts index e6f08bc29..40e1f6686 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -80,60 +80,58 @@ app.use((req, res, next) => { // AUTHENTICATION ROUTING +enum Method { + Get, + Post +} + +function addSecureRoute(method: Method, + route: string, + handler: (user: DashUserModel, req: express.Request, res: express.Response) => void, + nope: (res: express.Response) => any) { + route = "/" + route; + switch (method) { + case Method.Get: + app.get(route, (req, res) => { + const dashUser: DashUserModel = req.user; + if (!dashUser) return nope(res); + handler(dashUser, req, res); + }); + break; + case Method.Post: + app.post(route, (req, res) => { + const dashUser: DashUserModel = req.user; + if (!dashUser) return nope(res); + handler(dashUser, req, res); + }); + break; + } +} + // *** // Look for the definitions of these get and post // functions in the exports of user.ts -// /home defines destination after a successful log in -app.get("/home", (req, res) => { - // if user is not logged in, redirect to log in page - const dashUser: DashUserModel = req.user; - if (!dashUser) { - return res.redirect("/login"); - } - // otherwise, connect them to Dash - // TODO: store and manage users' workspaces - // if (dashUser.allWorkspaceIds.length > 0) { - // if (!dashUser.didSelectSessionWorkspace) { - // return res.redirect("/workspaces"); - // } - // } +addSecureRoute(Method.Get, "home", (user, req, res) => { res.sendFile(path.join(__dirname, '../../deploy/index.html')); -}); - -// app.get("/workspaces", getWorkspaces); +}, res => res.redirect("/login")) -app.get("/getActiveWorkspaceId", (req, res) => { - const dashUser: DashUserModel = req.user; - if (!dashUser) { - return; - } - res.send(dashUser.activeWorkspaceId || ""); -}); +addSecureRoute(Method.Get, "getActiveWorkspaceId", (user, req, res) => { + console.log(`/getActiveWorkspaceId in index.ts ${user.activeWorkspaceId}`); + res.send(user.activeWorkspaceId || ""); +}, () => { }); -app.get("/getAllWorkspaceIds", (req, res) => { - const dashUser: DashUserModel = req.user; - if (!dashUser) { - return; - } - res.send(JSON.stringify(dashUser.allWorkspaceIds as Array<String>)); -}) +addSecureRoute(Method.Get, "getAllWorkspaceIds", (user, req, res) => { + res.send(JSON.stringify(user.allWorkspaceIds as Array<String>)); +}, () => { }); -app.post("/setActiveWorkspaceId", (req, res) => { - const dashUser: DashUserModel = req.user; - if (!dashUser) { - return; - } - dashUser.update({ $set: { activeWorkspaceId: req.body.target } }, () => { }); -}) +addSecureRoute(Method.Post, "setActiveWorkspaceId", (user, req) => { + user.update({ $set: { activeWorkspaceId: req.body.target } }, () => { }); +}, () => { }); -app.post("/addWorkspaceId", (req, res) => { - const dashUser: DashUserModel = req.user; - if (!dashUser) { - return; - } - dashUser.update({ $push: { allWorkspaceIds: req.body.target } }, () => { }); -}) +addSecureRoute(Method.Post, "addWorkspaceId", (user, req) => { + user.update({ $push: { allWorkspaceIds: req.body.target } }, () => { }); +}, () => { }); // anyone attempting to navigate to localhost at this port will // first have to login |